def loadDisplaySettings(self): controller = NSApp().RoboHUD needsInactiveOpacity = self.fadeLayer.opacity( ) == self._inactiveOpacity self._inactiveOpacity = controller.getInactiveOpacity() if needsInactiveOpacity: self._setOpacity_(self._inactiveOpacity)
def _NH_BlinkFileTransferDidEnd(self, sender, data): self.listView.relayout() # jump dock icon and bring window to front if not (isinstance(sender, IncomingFileTransferHandler) and sender.file_name.startswith("xscreencapture")): self.window.orderFront_(None) NSApp.requestUserAttention_(NSInformationalRequest) self.refresh_transfer_rate()
def openMessageWindow(self, target, target_name, account, create_if_needed=True, note_new_message=True): for window in self.windows: for viewer in window.viewers: if viewer.matchesTargetAccount(target, account): break else: continue break else: window, viewer = None, None if not viewer and create_if_needed: viewer = SMSViewController.alloc().initWithAccount_target_name_(account, target, target_name) if not self.windows: window = SMSWindowController.alloc().initWithOwner_(self) self.windows.append(window) else: window = self.windows[0] viewer.windowController = window window.addViewer_(viewer) elif viewer: window = self.windowForViewer(viewer) if window: if note_new_message: window.window().makeKeyAndOrderFront_(None) NSApp.delegate().noteNewMessage(window) return viewer
def openMessageWindow(self, target, target_name, account, create_if_needed=True, note_new_message=True): for window in self.windows: for viewer in window.viewers: if viewer.matchesTargetAccount(target, account): break else: continue break else: window, viewer = None, None if not viewer and create_if_needed: viewer = SMSViewController.alloc().initWithAccount_target_name_( account, target, target_name) if not self.windows: window = SMSWindowController.alloc().initWithOwner_(self) self.windows.append(window) else: window = self.windows[0] viewer.windowController = window window.addViewer_(viewer) elif viewer: window = self.windowForViewer(viewer) if window: if note_new_message: window.window().makeKeyAndOrderFront_(None) NSApp.delegate().noteNewMessage(window) return viewer
def main(): try: import objc from PyObjCTools import AppHelper from AppKit import NSApplication, NSApp, NSObject, NSApplicationActivationPolicyRegular # from Foundation import * class AppDelegate(NSObject): def init(self): self = objc.super(AppDelegate, self).init() if self is None: return None return self def runjava_(self, arg): runAwtStuff() # we need to terminate explicitly, or it'll hang when # the wrapped code exits NSApp().terminate_(self) def applicationDidFinishLaunching_(self, aNotification): self.performSelectorInBackground_withObject_("runjava:", 0) app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) # this is necessary to have keyboard events sent to the UI; # basically this call makes the script act like an OS X application, # with Dock icon and everything NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular) AppHelper.runEventLoop() except ModuleNotFoundError: print("Skipping OSXAWTwrapper - module 'objc' is not installed")
def run(self): contactsWindow = NSApp.delegate().contactsWindowController.window() worksWhenModal = contactsWindow.worksWhenModal() contactsWindow.setWorksWhenModal_(True) if not self.autostart: self.window.makeKeyAndOrderFront_(None) rc = NSApp.runModalForWindow_(self.window) self.window.orderOut_(self) contactsWindow.setWorksWhenModal_(worksWhenModal) if (self.autostart and self.validateConference()) or rc == NSOKButton: if self.audio.state() == NSOnState and self.chat.state() == NSOnState: media_type = ("chat", "audio") elif self.chat.state() == NSOnState: media_type = "chat" else: media_type = "audio" # make a copy of the participants and reset the table data source, participants = self._participants # Cocoa crashes if something is selected in the table view when clicking OK or Cancel button # reseting the data source works around this self._participants = [] self.participantsTable.reloadData() # prevent loops if self.target in participants: participants.remove(self.target) return ServerConferenceRoom(self.target, media_type=media_type, participants=participants, nickname=self.nickname, start_when_participants_available=bool(self.startWhenParticipantsAvailable.state())) else: return None
def init(self): if self: NSBundle.loadNibNamed_owner_("EnrollmentWindow", self) icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled) self.selectRadio_(self.radioMatrix) if not SIPManager().validateAddAccountAction(): self.nextButton.setEnabled_(False) self.purchaseProLabel.setHidden_(False) if NSApp.delegate().contactsWindowController.first_run: NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount') if NSApp.delegate().applicationName == 'SIP2SIP': self.allowed_domains = ['sip2sip.info'] self.syncWithiCloudCheckbox.setHidden_(True) self.syncWithiCloudCheckbox.setState_(NSOffState) self.domainButton.setHidden_(True) self.addressText.cell().setPlaceholderString_('*****@*****.**') if NSApp.delegate().applicationName == 'Blink': self.syncWithiCloudCheckbox.setHidden_(True) return self
def get_modified(self, obj): with self.lock: try: if self.dirty.get(obj, False): pool = NSAutoreleasePool.alloc().init() old_password = self.oldvalues.get(obj, self.default) new_password = self.values.get(obj, self.default) account = (account for account, group in chain(*(attr.values.iteritems() for attr in Account.__dict__.itervalues() if isinstance(attr, SettingsGroupMeta))) if group is obj).next() if self.label is None: label = '%s (%s)' % (NSApp.delegate().applicationName, account.id) else: label = '%s %s (%s)' % (NSApp.delegate().applicationName, self.label, account.id) k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id) if k is None and new_password: EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(label, account.id, new_password) elif k is not None: if new_password: k.setPassword_(new_password) else: k.removeFromKeychain() return ModifiedValue(old=old_password, new=new_password) else: return None finally: try: self.oldvalues[obj] = self.values[obj] except KeyError: self.oldvalues.pop(obj, None) self.dirty[obj] = False
def makeMainMenu(): # http://www.cocoawithlove.com/2010/09/minimalist-cocoa-programming.html # http://www.cocoabuilder.com/archive/cocoa/192181-initializing-the-menubar-without-interface-builder.html # By Robert Nikander via. https://github.com/albertz/music-player/blob/master/guiCocoa.py appName = NSProcessInfo.processInfo().processName() mainMenu = NSMenu.alloc().initWithTitle_('MainMenu') appleMenuItem = mainMenu.addItemWithTitle_action_keyEquivalent_( 'Apple', None, '') appleMenu = NSMenu.alloc().initWithTitle_('Apple') # strange hack (their comment, not mine -jon) NSApp.setAppleMenu_(appleMenu) mainMenu.setSubmenu_forItem_(appleMenu, appleMenuItem) NSApp.setMainMenu_(mainMenu) # Otto menu appleMenu.addItemWithTitle_action_keyEquivalent_('About ' + appName, 'about:', '') appleMenu.addItem_(NSMenuItem.separatorItem()) #appleMenu.addItemWithTitle_action_keyEquivalent_('Preferences...', 'preferences:', ',') #appleMenu.addItem_(NSMenuItem.separatorItem()) appleMenu.addItemWithTitle_action_keyEquivalent_('Quit ' + appName, 'terminate:', 'q')
def retryTransfer_(self, sender): if self.oldTransferInfo: try: account = next( (account for account in AccountManager().iter_accounts() if account.id == self.oldTransferInfo.local_uri)) except StopIteration: account = AccountManager().default_account target_uri = normalize_sip_uri_for_outgoing_session( self.oldTransferInfo.remote_uri, AccountManager().default_account) filenames = [ unicodedata.normalize('NFC', self.oldTransferInfo.file_path) ] NSApp.delegate( ).contactsWindowController.sessionControllersManager.send_files_to_contact( account, target_uri, filenames) else: self.failed = False self.done = False self.updateProgressInfo() self.progressBar.setIndeterminate_(True) self.progressBar.startAnimation_(None) self.progressBar.setHidden_(True) self.updateChecksumProgressInfo(0) self.checksumProgressBar.setIndeterminate_(False) self.checksumProgressBar.startAnimation_(None) self.checksumProgressBar.setHidden_(False) self.sizeText.setTextColor_(NSColor.grayColor()) self.relayoutForRetry() self.transfer.retry()
def end(self): if self.ended: return self.sessionController.log_debug(u"End %s" % self) self.ended = True NSApp.delegate().contactsWindowController.hideLocalVideoWindow() status = self.status if status in [STREAM_IDLE, STREAM_FAILED]: self.changeStatus(STREAM_IDLE) elif status == STREAM_PROPOSING: self.sessionController.cancelProposal(self.stream) self.changeStatus(STREAM_CANCELLING) else: self.sessionController.endStream(self) self.changeStatus(STREAM_IDLE) self.removeFromSession() self.videoWindowController.close() self.notification_center.discard_observer(self, sender=self.sessionController) dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "deallocTimer:", None, False) NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSRunLoopCommonModes) NSRunLoop.currentRunLoop().addTimer_forMode_(dealloc_timer, NSEventTrackingRunLoopMode)
def userButtonClicked_(self, sender): self.window.close() if sender.tag() == 1: NSApp.stopModalWithCode_(1) else: NSApp.stopModalWithCode_(0)
def setupUI(self): self.statusbar = NSStatusBar.systemStatusBar() self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) #NSSquareStatusItemLength #NSVariableStatusItemLength # Set initial image icon icon_path = os.path.join(current_path, "../trayicon.ico") image = NSImage.alloc().initByReferencingFile_(icon_path) image.setScalesWhenResized_(True) image.setSize_((20, 20)) self.statusitem.setImage_(image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_("ZeroNet") # Build a very simple menu self.menu = NSMenu.alloc().init() self.menu.setAutoenablesItems_(False) #self.create_menu_item( 'ip_external', 'IP: %s' % INFO['ip_external'], 'info:') self.menu.addItem_( NSMenuItem.separatorItem() ) # Links self.create_menu_item( 'open_zeronet', 'Open ZeroNet', 'open:') self.create_menu_item( 'open_reddit', 'Zeronet Reddit Community', 'openreddit:') self.create_menu_item( 'open_gh', 'Report issues/feature requests', 'opengithub:') self.menu.addItem_( NSMenuItem.separatorItem() ) self.create_menu_item( 'quit_zeronet', 'Quit ZeroNet', 'windowWillClose:' ) # Bind it to the status item and hide dock icon self.statusitem.setMenu_(self.menu) NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
def init(self): if self: NSBundle.loadNibNamed_owner_("EnrollmentWindow", self) icloud_sync_enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled") self.syncWithiCloudCheckbox.setHidden_(not icloud_sync_enabled) self.selectRadio_(self.radioMatrix) if not SIPManager().validateAddAccountAction(): self.nextButton.setEnabled_(False) self.purchaseProLabel.setHidden_(False) if NSApp.delegate().contactsWindowController.first_run: NotificationCenter().add_observer(self, name='SIPAccountManagerDidAddAccount') if NSApp.delegate().allowed_domains: self.allowed_domains = NSApp.delegate().allowed_domains self.syncWithiCloudCheckbox.setHidden_(True) self.syncWithiCloudCheckbox.setState_(NSOffState) self.domainButton.setHidden_(True) self.addressText.cell().setPlaceholderString_('user@' + self.allowed_domains[0]) if not NSApp.delegate().icloud_enabled: self.syncWithiCloudCheckbox.setHidden_(True) return self
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def __init__(self): wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title='wxPython example') self.ShowFullScreen(True) self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) # Set wx.WANTS_CHARS style for the keyboard to work. # This style also needs to be set for all parent controls. self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS) self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if MAC: try: # noinspection PyUnresolvedReferences from AppKit import NSApp # Make the content view for the window have a layer. # This will make all sub-views have layers. This is # necessary to ensure correct layer ordering of all # child views and their layers. This fixes Window # glitchiness during initial loading on Mac (Issue #371). NSApp.windows()[0].contentView().setWantsLayer_(True) except ImportError: print( "[wxpython.py] Warning: PyObjC package is missing, " "cannot fix Issue #371") print( "[wxpython.py] To install PyObjC type: " "pip install -U pyobjc") if LINUX: # On Linux must show before embedding browser, so that handle # is available (Issue #347). self.Show() # In wxPython 3.0 and wxPython 4.0 on Linux handle is # still not yet available, so must delay embedding browser # (Issue #349). if wx.version().startswith("3.") or wx.version().startswith("4."): wx.CallLater(100, self.embed_browser) else: # This works fine in wxPython 2.8 on Linux self.embed_browser() else: self.embed_browser() self.Show()
def get_state(account, obj=None, skip=[]): state = {} if obj is None: obj = account for name in dir(obj.__class__): attribute = getattr(obj.__class__, name, None) if name in skip: continue if isinstance(attribute, SettingsGroupMeta): state[name] = get_state(account, getattr(obj, name), skip) elif isinstance(attribute, Setting): value = attribute.__getstate__(obj) if value is DefaultValue: value = attribute.default if name == 'password': if isinstance(obj, AuthSettings): label = '%s (%s)' % (NSApp.delegate().applicationName, account.id) keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id) value = unicode(keychain_item.password()) if keychain_item is not None else '' elif isinstance(obj, LDAPSettingsExtension): label = '%s LDAP (%s)' % (NSApp.delegate().applicationName, account.id) keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id) value = unicode(keychain_item.password()) if keychain_item is not None else '' if name == 'web_password': label = '%s WEB (%s)' % (NSApp.delegate().applicationName, account.id) keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id) value = unicode(keychain_item.password()) if keychain_item is not None else '' if name == 'replication_password': label = '%s ChatReplication (%s)' % (NSApp.delegate().applicationName, account.id) keychain_item = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id) value = unicode(keychain_item.password()) if keychain_item is not None else '' state[name] = value return state
def runModal(self): BlinkLogger().log_info('Starting Enrollment') self.newDisplayNameText.setStringValue_(NSFullUserName() or "") self.displayNameText.setStringValue_(NSFullUserName() or "") self.window.center() NSApp.runModalForWindow_(self.window) self.window.orderOut_(self)
def call_in_gui_thread(func, *args, **kwargs): if NSThread.isMainThread(): func(*args, **kwargs) else: pool = NSAutoreleasePool.alloc().init() NSApp.delegate().performSelectorOnMainThread_withObject_waitUntilDone_( "callObject:", lambda: func(*args, **kwargs), False) del pool
def matchesTargetAccount(self, target, account): that_contact = NSApp.delegate( ).contactsWindowController.getFirstContactMatchingURI(target) this_contact = NSApp.delegate( ).contactsWindowController.getFirstContactMatchingURI(self.target_uri) return (self.target_uri == target or (this_contact and that_contact and this_contact == that_contact)) and self.account == account
def muteBeforeSpeechWillStart(self): hasAudio = any(sess.hasStreamOfType("audio") for sess in self.sessionControllersManager.sessionControllers) if hasAudio: if not SIPManager().is_muted(): NSApp.delegate().contactsWindowController.muteClicked_(None) self.muted_by_synthesizer = True if self.speech_recognizer: self.speech_recognizer.stopListening()
def do_init(): for x in list(sys.argv): if x.startswith("-psn_"): sys.argv.remove(x) if os.environ.get("XPRA_HIDE_DOCK", "") == "1": from AppKit import NSApp #@UnresolvedImport #NSApplicationActivationPolicyAccessory = 1 NSApp.setActivationPolicy_(1)
def makeDockMenu(): dockMenu = NSMenu.alloc().initWithTitle_('DockMenu') dockMenu.addItemWithTitle_action_keyEquivalent_('Play', 'play:', '') dockMenu.addItemWithTitle_action_keyEquivalent_('Stop', 'pauseifnot:', '') dockMenu.addItemWithTitle_action_keyEquivalent_('Next', 'next:', '') #NSApp.delegate().setDockMenu_(dockMenu) # why were they doing this? (albertz/music-player) NSApp.setDockMenu_(dockMenu)
def checkProcess_(self, timer): if not comm_queue.empty(): # We Get Signal, Take Off Every Zig - er, time to shut down this forked process # Clear the queue while not comm_queue.empty(): ignore = comm_queue.get_nowait() NSApp.stop_(None) # After you stop the runloop, the app has to receive another event to determine the runloop stopped ... self.kickRunLoop()
def show(self, contact): NSApp.activateIgnoringOtherApps_(True) self.contact = contact self.window.setTitle_(u'Availability Information published by %s' % contact.name) self.name.setStringValue_(self.contact.name) self.addresses.setStringValue_(', '.join(uri.uri for uri in self.contact.uris)) self.window.orderFront_(None) self.icon.setImage_(self.contact.avatar.icon) self.render_pidf()
def addContactPanelClicked_(self, sender): if sender.tag() == 1: NSApp.delegate().contactsWindowController.addContact(self.target_uri) self.addContactView.removeFromSuperview() frame = self.chatViewController.outputView.frame() frame.origin.y = 0 frame.size = self.outputContainer.frame().size self.chatViewController.outputView.setFrame_(frame)
def show(self, contact): NSApp.activateIgnoringOtherApps_(True) self.contact = contact self.window.setTitle_(NSLocalizedString("Availability Information published by %s", "Window title") % contact.name) self.name.setStringValue_(self.contact.name) self.addresses.setStringValue_(', '.join(uri.uri for uri in self.contact.uris)) self.window.orderFront_(None) self.icon.setImage_(self.contact.avatar.icon) self.render_pidf()
def observeValueForKeyPath_ofObject_change_context_(self, key_path, object, change, context): NSLog("KEY_PATH: %@", key_path) if key_path == "spotify.login_state": if self.spotify.login_state == "login_failed": self.display_login_window() NSApp.presentError_modalForWindow_delegate_didPresentSelector_contextInfo_( self.spotify.login_error, self.login_window, None, None, None) elif key_path == "spotify.current_track": self.search_window.setTitle_(self.spotify.current_track.name())
def machInterrupt(signum): stopper = PyObjCAppHelperRunLoopStopper.currentRunLoopStopper() if stopper is not None: stopper.stop() elif NSApp() is not None: NSApp().terminate_(None) else: import os os._exit(1)
def __init__(self, url, icon, title, size): self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: cef.WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 if WINDOWS: # noinspection PyUnresolvedReferences, PyArgumentList logging.debug("[wxpython.py] System DPI settings: %s" % str(cef.DpiAware.GetSystemDpi())) if hasattr(wx, "GetDisplayPPI"): logging.debug("[wxpython.py] wx.GetDisplayPPI = %s" % wx.GetDisplayPPI()) logging.debug("[wxpython.py] wx.GetDisplaySize = %s" % wx.GetDisplaySize()) logging.debug("[wxpython.py] MainFrame DPI scaled size: %s" % str(size)) wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title=title) # wxPython will set a smaller size when it is bigger # than desktop size. logging.debug("[wxpython.py] MainFrame actual size: %s" % self.GetSize()) ic = wx.Icon(icon, wx.BITMAP_TYPE_ICO) self.SetIcon(ic) self.Bind(wx.EVT_CLOSE, self.OnClose) # Set wx.WANTS_CHARS style for the keyboard to work. # This style also needs to be set for all parent controls. self.browser_panel = wx.Panel(self, size=tuple(size)) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) wx.Window.Fit(self) if MAC: # Make the content view for the window have a layer. # This will make all sub-views have layers. This is # necessary to ensure correct layer ordering of all # child views and their layers. This fixes Window # glitchiness during initial loading on Mac (Issue #371). NSApp.windows()[0].contentView().setWantsLayer_(True) if LINUX: self.Show() self.embed_browser(url) else: self.embed_browser(url) self.Show()
def setupUI(self): self.statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) # Set initial image raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines())) self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data)) self.image = NSImage.alloc().initWithData_(self.image_data) self.statusitem.setImage_(self.image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) # Set a tooltip self.statusitem.setToolTip_(GOAGENT_TITLE) # Build a very simple menu self.menu = NSMenu.alloc().init() # Show Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '') self.menu.addItem_(menuitem) # Hide Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide2:', '') self.menu.addItem_(menuitem) # Rest Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reload', 'reset:', '') self.menu.addItem_(menuitem) # Default event menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'exit:', '') self.menu.addItem_(menuitem) # Bind it to the status item self.statusitem.setMenu_(self.menu) # Console window frame = NSMakeRect(0,0,550,350) self.console_window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(frame, NSClosableWindowMask|NSTitledWindowMask, NSBackingStoreBuffered, False) self.console_window.setTitle_(GOAGENT_TITLE) self.console_window.setDelegate_(self) # Console view inside a scrollview self.scroll_view = NSScrollView.alloc().initWithFrame_(frame) self.scroll_view.setBorderType_(NSNoBorder) self.scroll_view.setHasVerticalScroller_(True) self.scroll_view.setHasHorizontalScroller_(False) self.scroll_view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable) self.console_view = NSTextView.alloc().initWithFrame_(frame) self.console_view.setVerticallyResizable_(True) self.console_view.setHorizontallyResizable_(True) self.console_view.setAutoresizingMask_(NSViewWidthSizable) self.scroll_view.setDocumentView_(self.console_view) contentView = self.console_window.contentView() contentView.addSubview_(self.scroll_view) # Hide dock icon NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
def displayAlert(message, info, buttons): alert = NSAlert.alloc().init() alert.setMessageText_(message) alert.setInformativeText_(info) alert.setAlertStyle_(NSInformationalAlertStyle) for button in buttons: alert.addButtonWithTitle_(button) NSApp.activateIgnoringOtherApps_(True) buttonPressed = alert.runModal() return buttonPressed
def decideForSessionRequest(self, action, session): sessionController = self.sessionControllersManager.sessionControllerForSession(session) if action == ACCEPT: NSApp.activateIgnoringOtherApps_(True) try: sessionController.log_info(u"Accepting session from %s" % format_identity_to_string(session.remote_identity)) self.acceptStreams(session) except Exception, exc: sessionController.log_info(u"Error accepting session: %s" % exc) self.removeSession(session)
def addContactPanelClicked_(self, sender): if sender.tag() == 1: NSApp.delegate().contactsWindowController.addContact( uris=[(self.target_uri, 'sip')]) self.addContactView.removeFromSuperview() frame = self.chatViewController.outputView.frame() frame.origin.y = 0 frame.size = self.outputContainer.frame().size self.chatViewController.outputView.setFrame_(frame)
def okClicked_(self, sender): if not len(self._participants): NSRunAlertPanel( NSLocalizedString("Add Participants to the Conference", "Window title"), NSLocalizedString("Please add at least one participant. ", "Label"), NSLocalizedString("OK", "Button title"), None, None) else: NSApp.stopModalWithCode_(NSOKButton)
def windowWillClose_(self, notification): self.captureView.hide() NSApp.stopModalWithCode_(0) settings = SIPSimpleSettings() try: settings.video.auto_rotate_cameras = self.previous_auto_rotate_cameras settings.save() except AttributeError: pass
def serverReady(self): print 'OttoDelegate#serverReady' closeSplash() #openWebBrowser() cookies = getSessionCookie() openSocketIO(cookies) NSApp.activateIgnoringOtherApps_(True) openMainWindow() # uses cookies directy from the shared cookie storage, Safari does too return
def __init__(self): wx.Frame.__init__(self, parent=None, id=wx.ID_ANY, title='wxPython example', size=(WIDTH, HEIGHT)) self.browser = None # Must ignore X11 errors like 'BadWindow' and others by # installing X11 error handlers. This must be done after # wx was intialized. if LINUX: WindowUtils.InstallX11ErrorHandlers() global g_count_windows g_count_windows += 1 self.setup_icon() self.create_menu() self.Bind(wx.EVT_CLOSE, self.OnClose) # Set wx.WANTS_CHARS style for the keyboard to work. # This style also needs to be set for all parent controls. self.browser_panel = wx.Panel(self, style=wx.WANTS_CHARS) self.browser_panel.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus) self.browser_panel.Bind(wx.EVT_SIZE, self.OnSize) if MAC: try: # noinspection PyUnresolvedReferences from AppKit import NSApp # Make the content view for the window have a layer. # This will make all sub-views have layers. This is # necessary to ensure correct layer ordering of all # child views and their layers. This fixes Window # glitchiness during initial loading on Mac (Issue #371). NSApp.windows()[0].contentView().setWantsLayer_(True) except ImportError: print("[wxpython.py] Warning: PyObjC package is missing, " "cannot fix Issue #371") print("[wxpython.py] To install PyObjC type: " "pip install -U pyobjc") if LINUX: # On Linux must show before embedding browser, so that handle # is available (Issue #347). self.Show() # In wxPython 3.0 and wxPython 4.0 on Linux handle is # still not yet available, so must delay embedding browser # (Issue #349). if wx.version().startswith("3.") or wx.version().startswith("4."): wx.CallLater(1000, self.embed_browser) else: # This works fine in wxPython 2.8 on Linux self.embed_browser() else: self.embed_browser() self.Show()
def makeMainMenu(): # http://www.cocoawithlove.com/2010/09/minimalist-cocoa-programming.html # http://www.cocoabuilder.com/archive/cocoa/192181-initializing-the-menubar-without-interface-builder.html # By Robert Nikander via. https://github.com/albertz/music-player/blob/master/guiCocoa.py appName = NSProcessInfo.processInfo().processName() mainMenu = NSMenu.alloc().initWithTitle_('MainMenu') appleMenuItem = mainMenu.addItemWithTitle_action_keyEquivalent_('Apple', None, '') appleMenu = NSMenu.alloc().initWithTitle_('Apple') # strange hack (their comment, not mine -jon) NSApp.setAppleMenu_(appleMenu) mainMenu.setSubmenu_forItem_(appleMenu, appleMenuItem) NSApp.setMainMenu_(mainMenu) # Otto menu appleMenu.addItemWithTitle_action_keyEquivalent_('About '+appName, 'about:', '') appleMenu.addItem_(NSMenuItem.separatorItem()) #appleMenu.addItemWithTitle_action_keyEquivalent_('Preferences...', 'preferences:', ',') #appleMenu.addItem_(NSMenuItem.separatorItem()) appleMenu.addItemWithTitle_action_keyEquivalent_('Quit '+appName, 'terminate:', 'q') # File menu fileMenu = NSMenu.alloc().initWithTitle_('File') fileMenuItem = mainMenu.addItemWithTitle_action_keyEquivalent_('File', None, '') mainMenu.setSubmenu_forItem_(fileMenu, fileMenuItem) fileMenu.addItemWithTitle_action_keyEquivalent_('Main Window', 'mainWindow:', '1') fileMenu.addItemWithTitle_action_keyEquivalent_('Browser Window', 'browser:', 'n') fileMenu.addItem_(NSMenuItem.separatorItem()) fileMenu.addItemWithTitle_action_keyEquivalent_('Play', 'play:', 'p') fileMenu.addItemWithTitle_action_keyEquivalent_('Stop', 'pauseifnot:', '.') # does 'stop:' have a special meaning? fileMenu.addItemWithTitle_action_keyEquivalent_('Next', 'next:', NSRightArrowFunctionKey) fileMenu.addItem_(NSMenuItem.separatorItem()) fileMenu.addItemWithTitle_action_keyEquivalent_('Scan Music', 'loadMusic:', '') # # Edit menu # editMenu = NSMenu.alloc().initWithTitle_('Edit') # editMenuItem = mainMenu.addItemWithTitle_action_keyEquivalent_('Edit', None, '') # mainMenu.setSubmenu_forItem_(editMenu, editMenuItem) # editMenu.addItemWithTitle_action_keyEquivalent_('Cut', 'cut:', 'x') # editMenu.addItemWithTitle_action_keyEquivalent_('Copy', 'copy:', 'c') # editMenu.addItemWithTitle_action_keyEquivalent_('Paste', 'paste:', 'v') # editMenu.addItemWithTitle_action_keyEquivalent_('Select all', 'selectText:', 'a') # View menu viewMenu = NSMenu.alloc().initWithTitle_('View') viewMenuItem = mainMenu.addItemWithTitle_action_keyEquivalent_('View', None, '') mainMenu.setSubmenu_forItem_(viewMenu, viewMenuItem) viewMenu.addItemWithTitle_action_keyEquivalent_('Full Screen', 'toggleFullScreen:', 'F')
def _NH_BlinkFileTransferDidEnd(self, sender, data): self.listView.relayout() self.refresh_transfer_rate() if not data.error: # jump dock icon and bring window to front if isinstance(sender, IncomingFileTransferHandler): self.window.orderFront_(None) NSApp.requestUserAttention_(NSInformationalRequest) elif 'screencapture' not in sender.file_path: self.window.orderFront_(None) NSApp.requestUserAttention_(NSInformationalRequest)
def _NH_SIPApplicationWillStart(self, sender, data): settings = SIPSimpleSettings() _version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString")) settings.user_agent = "%s %s (MacOSX)" % (NSApp.delegate().applicationName, _version) BlinkLogger().log_debug("SIP User Agent: %s" % settings.user_agent) settings.save() self.migratePasswordsToKeychain() self.cleanupIcons() # Set audio settings compatible with AEC and Noise Suppression settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled else 48000 if NSApp.delegate().service_provider_help_url and settings.service_provider.help_url != NSApp.delegate().service_provider_help_url: settings.service_provider.help_url = NSApp.delegate().service_provider_help_url settings.save() if NSApp.delegate().service_provider_name and settings.service_provider.name != NSApp.delegate().service_provider_name: settings.service_provider.name = NSApp.delegate().service_provider_name settings.save() BlinkLogger().log_debug("Audio engine sampling rate %dKHz covering 0-%dKHz spectrum" % (settings.audio.sample_rate/1000, settings.audio.sample_rate/1000/2)) BlinkLogger().log_debug("Acoustic Echo Canceller is %s" % ('enabled' if settings.audio.echo_canceller.enabled else 'disabled')) account_manager = AccountManager() for account in account_manager.iter_accounts(): must_save = False if account is not BonjourAccount() and account.sip.primary_proxy is None and account.sip.outbound_proxy and not account.sip.selected_proxy: account.sip.primary_proxy = account.sip.outbound_proxy if account is not BonjourAccount() and settings.tls.verify_server != account.tls.verify_server: account.tls.verify_server = settings.tls.verify_server if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt': account.tls.certificate = DefaultValue if account.rtp.encryption_type == '': account.rtp.encryption.enabled = False elif account.rtp.encryption_type == 'opportunistic': account.rtp.encryption.enabled = True account.rtp.encryption.key_negotiation = 'opportunistic' elif account.rtp.encryption_type == 'sdes_optional': account.rtp.encryption.enabled = True account.rtp.encryption.key_negotiation = 'sdes_optional' elif account.rtp.encryption_type == 'sdes_mandatory': account.rtp.encryption.enabled = True account.rtp.encryption.key_negotiation = 'sdes_mandatory' elif account.rtp.encryption_type == 'zrtp': account.rtp.encryption.enabled = True account.rtp.encryption.key_negotiation = 'zrtp' account.save() logger = FileLogger() logger.start() self.ip_address_monitor.start()
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() def handler(signal, frame): AppHelper.stopEventLoop() signal.signal(signal.SIGINT, handler) AppHelper.runEventLoop()
def display(self, sender): # Initiate the controller with a XIB self._controller = PreferencesController.alloc() \ .initWithWindowNibName_('preferences') # self._controller.loadWindow() # Show the window self._controller.showWindow_(sender) # Bring app to top NSApp.activateIgnoringOtherApps_(True)
def run(self): if self.hidden: psn = ProcessSerialNumber(0, kCurrentProcess) ApplicationServices.TransformProcessType(psn, kProcessTransformToUIElementAppication) else: psn = ProcessSerialNumber(0, kCurrentProcess) ApplicationServices.TransformProcessType(psn, kProcessTransformToForegroundApplication) self.win.makeKeyAndOrderFront_(None) self.win.display() NSApp.activateIgnoringOtherApps_(True) NSApp.run()
def _NH_BlinkSessionDidStart(self, sender, data): if self.status != STREAM_CONNECTED: if self.videoWindowController: if not self.media_received: self.videoWindowController.showStatusLabel( NSLocalizedString("Waiting for Media...", "Label")) audio_stream = self.sessionController.streamHandlerOfType("audio") if audio_stream and audio_stream.status in ( STREAM_CONNECTING, STREAM_CONNECTED ) and self.sessionController.video_consumer == 'audio': NSApp.delegate().contactsWindowController.showAudioDrawer()
def display_alert(title, message): """Display a warning alert with the given ``title`` and ``message``. :param str title: the big bold title :param str message: the body of the alert """ alert = NSAlert.alloc().init() alert.setAlertStyle_(NSWarningAlertStyle) alert.setMessageText_(title) alert.setInformativeText_(message) NSApp.activateIgnoringOtherApps_(True) alert.runModal()
def doubleClick_(self, sender): row = self.contactTable.selectedRow() if row < 2: return try: contact = self.contacts[row] except IndexError: return NSApp.delegate().contactsWindowController.startSessionWithTarget(contact.uri)
def save_dialog(directory, filename): panel = NSSavePanel.savePanel() panel.setTitle_("Save PDF booklet") myUrl = NSURL.fileURLWithPath_isDirectory_(directory, True) panel.setDirectoryURL_(myUrl) panel.setNameFieldStringValue_(filename) NSApp.activateIgnoringOtherApps_(True) ret_value = panel.runModal() if ret_value: return panel.filename() else: return ''
def main(): session_id = 'mac-{:x}'.format(uuid.getnode()) session = Session(session_id) repository_path = os.path.join( os.environ['HOME'], 'Dropbox (Personal)', 'Earth Reader' ) # FIXME repository = FileSystemRepository(repository_path) # FIXME stage = Stage(session, repository) app = NSApplication.sharedApplication() viewController = MainController(stage) viewController.showWindow_(viewController) NSApp.activateIgnoringOtherApps_(True) return app
def openFileTransferSelectionDialog(account, dest_uri): if not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported("file-transfer"): return panel = NSOpenPanel.openPanel() panel.setTitle_(u"Send File") panel.setAllowsMultipleSelection_(True) if panel.runModal() != NSOKButton: return filenames = [unicodedata.normalize("NFC", file) for file in panel.filenames()] NSApp.delegate().contactsWindowController.sessionControllersManager.send_files_to_contact( account, dest_uri, filenames )
def windowDidExitFullScreen_(self, notification): self.sessionController.log_debug('windowDidExitFullScreen %s' % self) self.full_screen_in_progress = False self.full_screen = False NSApp.delegate().contactsWindowController.hideLocalVideoWindow() NotificationCenter().post_notification("BlinkVideoWindowFullScreenChanged", sender=self) if self.show_window_after_full_screen_ends is not None: self.show_window_after_full_screen_ends.makeKeyAndOrderFront_(None) self.show_window_after_full_screen_ends = None else: if self.window: self.window.orderFront_(self) self.window.setLevel_(NSFloatingWindowLevel if self.always_on_top else NSNormalWindowLevel)
def openFileTransferSelectionDialog(account, dest_uri, filename=None): if not NSApp.delegate().contactsWindowController.sessionControllersManager.isMediaTypeSupported('file-transfer'): return panel = NSOpenPanel.openPanel() panel.setTitle_(NSLocalizedString("Select Files or Folders and Click Open to Send", "Window title")) panel.setDirectoryURL_(NSURL.URLWithString_(filename)) panel.setAllowsMultipleSelection_(True) panel.setCanChooseDirectories_(True) if panel.runModal() != NSOKButton: return filenames = [unicodedata.normalize('NFC', file) for file in panel.filenames()] NSApp.delegate().contactsWindowController.sessionControllersManager.send_files_to_contact(account, dest_uri, filenames)
def renderMessage(self, message): if message.direction == 'outgoing': icon = NSApp.delegate().contactsWindowController.iconPathForSelf() else: sender_uri = sipuri_components_from_string(message.cpim_from)[0] # TODO: How to render the icons from Address Book? Especially in sandbox mode we do not have access to other folders icon = NSApp.delegate().contactsWindowController.iconPathForURI(sender_uri) try: timestamp=ISOTimestamp(message.cpim_timestamp) except Exception: pass else: is_html = False if message.content_type == 'text' else True private = True if message.private == "1" else False self.chatViewController.showMessage(message.sip_callid, message.msgid, message.direction, message.cpim_from, icon, message.body, timestamp, is_private=private, recipient=message.cpim_to, state=message.status, is_html=is_html, history_entry=True, media_type=message.media_type, encryption=message.encryption if message.media_type == 'chat' else None)
def migratePasswordsToKeychain(self): if NSApp.delegate().applicationName == 'SIP2SIP': return account_manager = AccountManager() configuration_manager = ConfigurationManager() bonjour_account = BonjourAccount() for account in (account for account in account_manager.iter_accounts() if account is not bonjour_account): try: stored_auth_password = configuration_manager.get(account.__key__ + ['auth', 'password']) except ObjectNotFoundError: stored_auth_password = None try: stored_ldap_password = configuration_manager.get(account.__key__ + ['ldap', 'password']) except ObjectNotFoundError: stored_ldap_password = None try: stored_web_password = configuration_manager.get(account.__key__ + ['server', 'web_password']) except ObjectNotFoundError: stored_web_password = None if (stored_auth_password, stored_ldap_password, stored_web_password) != ('keychain', 'keychain', 'keychain'): Account.auth.password.dirty[account.auth] = True Account.ldap.password.dirty[account.ldap] = True Account.server.web_password.dirty[account.server] = True account.save()
def runModal(self): self.window.makeKeyAndOrderFront_(None) rc = NSApp.runModalForWindow_(self.window) self.window.orderOut_(self) if rc == NSOKButton: return unicode(self.nameText.stringValue()) return None
def buttonClicked_(self, sender): if self.attention is not None: NSApp.cancelUserAttentionRequest_(self.attention) self.attention = None action = sender.cell().representedObject().integerValue() try: (session, view) = ((sess, view) for sess, view in self.sessions.iteritems() if view == sender.superview().superview()).next() except StopIteration: return if self.proposals.has_key(session): self.decideForProposalRequest(action, session, self.proposals[session]) else: self.decideForSessionRequest(action, session)