Beispiel #1
0
    def dealloc(self):
        # Observers added in init
        NSNotificationCenter.defaultCenter().removeObserver_(self)
        notification_center = NotificationCenter()
        notification_center.discard_observer(self, name="SIPSessionDidStart")
        notification_center.discard_observer(self, name="SIPSessionDidRenegotiateStreams")
        notification_center.discard_observer(self, name="AudioSessionHasQualityIssues")
        notification_center.discard_observer(self, name="AudioSessionQualityRestored")
        notification_center.discard_observer(self, name="AudioStreamICENegotiationDidSucceed")
        notification_center.discard_observer(self, name="AudioStreamICENegotiationDidFail")
        notification_center.discard_observer(self, name="VideoStreamICENegotiationDidSucceed")
        notification_center.discard_observer(self, name="VideoStreamICENegotiationDidFail")

        # Observers added when settings change
        notification_center.discard_observer(self, name="SIPEngineSIPTrace")
        notification_center.discard_observer(self, name="DNSLookupTrace")
        notification_center.discard_observer(self, name="MSRPLibraryLog")
        notification_center.discard_observer(self, name="MSRPTransportTrace")
        notification_center.discard_observer(self, name="XCAPManagerDidDiscoverServerCapabilities")
        notification_center.discard_observer(self, name="XCAPSubscriptionGotNotify")
        notification_center.discard_observer(self, name="XCAPManagerDidChangeState")
        notification_center.discard_observer(self, name="SIPEngineLog")
        notification_center.discard_observer(self)

        super(DebugWindow, self).dealloc()
Beispiel #2
0
 def initWithFrame_(self, frame):
     self = super(ListView, self).initWithFrame_(frame)
     if self:
         self.setBackgroundColor_(NSColor.whiteColor())
         NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "windowChangedKey:", NSWindowDidBecomeKeyNotification, None)
         NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "windowChangedKey:", NSWindowDidResignKeyNotification, None)
     return self
    def awakeFromNib(self):
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "contactSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.contactTable)

        timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(0.3, self, "refreshContactsTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSModalPanelRunLoopMode)
        NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSDefaultRunLoopMode)

        self.contactTable.setDoubleAction_("doubleClick:")
    def awakeFromNib(self):
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "contactSelectionChanged:", NSTableViewSelectionDidChangeNotification, self.contactTable)

        timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "refreshContactsTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSModalPanelRunLoopMode)
        NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSDefaultRunLoopMode)

        self.contactTable.setDoubleAction_("doubleClick:")
 def dealloc(self):
     if self.typingTimer:
         self.typingTimer.invalidate()
         self.typingTimer = None
     if self.scrollingTimer:
         self.scrollingTimer.invalidate()
         self.scrollingTimer = None
     NSNotificationCenter.defaultCenter().removeObserver_(self)
     objc.super(ChatViewController, self).dealloc()
 def dealloc(self):
     if self.typingTimer:
         self.typingTimer.invalidate()
         self.typingTimer = None
     if self.scrollingTimer:
         self.scrollingTimer.invalidate()
         self.scrollingTimer = None
     NSNotificationCenter.defaultCenter().removeObserver_(self)
     super(ChatViewController, self).dealloc()
Beispiel #7
0
 def __init__(self, controller):
     NSBundle.loadNibNamed_owner_("ChatOtrSmp", self)
     self.controller = controller
     self.statusText.setStringValue_('')
     self.progressBar.startAnimation_(None)
     self.window.setTitle_(NSLocalizedString("Identity Verification for %s", "Window title") % self.controller.sessionController.titleShort)
     self.stream = self.controller.stream
     self.remote_address = self.controller.sessionController.remoteAOR
 
     NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "controlTextDidChange:", NSControlTextDidChangeNotification, self.secretText)
    def awakeFromNib(self):
        self.outputView.setShouldCloseWithWindow_(True)
        self.outputView.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "webviewFinishedLoading:", WebViewProgressFinishedNotification, self.outputView)
        if self.inputText:
            self.inputText.registerForDraggedTypes_(NSArray.arrayWithObject_(NSFilenamesPboardType))
            self.inputText.setOwner(self)
            NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "textDidChange:", NSTextDidChangeNotification, self.inputText)

        self.messageQueue = []
    def stop(self):
        self.cloud_storage = None
        self.notification_center.remove_observer(self, name='SIPAccountManagerDidAddAccount')
        self.notification_center.remove_observer(self, name='SIPAccountManagerDidRemoveAccount')
        self.notification_center.remove_observer(self, name='SIPApplicationDidStart')
        self.notification_center.remove_observer(self, name='CFGSettingsObjectDidChange')

        NSNotificationCenter.defaultCenter().removeObserver_name_object_(self, u"NSUbiquitousKeyValueStoreDidChangeExternallyNotification", self.cloud_storage)

        self.first_sync_completed = False
        BlinkLogger().log_info(u"iCloud Manager stopped")
    def start(self):
        BlinkLogger().log_debug(u"Starting iCloud Manager")
        self.cloud_storage = Foundation.NSUbiquitousKeyValueStore.defaultStore()
        self.cloud_storage.synchronize()
        BlinkLogger().log_debug(u"%.1f out of 64.0 KB of iCloud storage space used" % (self.storage_size/1024))

        self.notification_center.add_observer(self, name='SIPAccountManagerDidAddAccount')
        self.notification_center.add_observer(self, name='SIPAccountManagerDidRemoveAccount')
        self.notification_center.add_observer(self, name='SIPApplicationDidStart')
        self.notification_center.add_observer(self, name='CFGSettingsObjectDidChange')

        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "cloudStorgeDidChange:", u"NSUbiquitousKeyValueStoreDidChangeExternallyNotification", self.cloud_storage)
Beispiel #11
0
 def initWithFrame_(self, frame):
     self = objc.super(ListView, self).initWithFrame_(frame)
     if self:
         self.setBackgroundColor_(NSColor.whiteColor())
         NSNotificationCenter.defaultCenter(
         ).addObserver_selector_name_object_(
             self, "windowChangedKey:", NSWindowDidBecomeKeyNotification,
             None)
         NSNotificationCenter.defaultCenter(
         ).addObserver_selector_name_object_(
             self, "windowChangedKey:", NSWindowDidResignKeyNotification,
             None)
     return self
Beispiel #12
0
    def __init__(self):
        major, minor = platform.mac_ver()[0].split('.')[0:2]
        if NSApp.delegate().applicationName in ('Blink Lite', 'SIP2SIP'):
            return

        if (int(major) == 10 and int(minor) >= 7) or int(major) > 10:
            self.notification_center = NotificationCenter()
            enabled = NSUserDefaults.standardUserDefaults().stringForKey_("iCloudSyncEnabled")
            if enabled is None:
                NSUserDefaults.standardUserDefaults().setObject_forKey_("Enabled", "iCloudSyncEnabled")
                self.start()
            elif enabled == "Enabled" :
                self.start()

            NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(self, "userDefaultsDidChange:", "NSUserDefaultsDidChangeNotification", NSUserDefaults.standardUserDefaults())
Beispiel #13
0
 def awakeFromNib(self):
     """awakeFromNib"""
     
     self._common_init()
     
     # Start the IPython engine
     self.engine.startService()
     NSLog('IPython engine started')
     
     # Register for app termination
     nc = NSNotificationCenter.defaultCenter()
     nc.addObserver_selector_name_object_(
                                 self,
                                 'appWillTerminate:',
                                 NSApplicationWillTerminateNotification,
                                 None)
     
     self.textView.setDelegate_(self)
     self.textView.enclosingScrollView().setHasVerticalRuler_(True)
     r = NSRulerView.alloc().initWithScrollView_orientation_(
                                     self.textView.enclosingScrollView(),
                                     NSVerticalRuler)
     self.verticalRulerView = r
     self.verticalRulerView.setClientView_(self.textView)
     self._start_cli_banner()
     self.start_new_block()
Beispiel #14
0
	def setValue_forKey_(self, v, k):
		# print "Setting", k, "to", v
		self.__dict__[k]=v
		# If it's run, send a notification
		if k == 'shouldRun':
			nc=NSNotificationCenter.defaultCenter()
			nc.postNotificationName_object_("RUN_CHECKED", self)
 def connect(self):
     # NSLog(u'connect')
     self.serverSocket = bind_and_listen((self.host, self.port))
     self.serverFileHandle = NSFileHandle.alloc().initWithFileDescriptor_(
         self.serverSocket.fileno())
     nc = NSNotificationCenter.defaultCenter()
     nc.addObserver_selector_name_object_(
         self,
         "remoteSocketAccepted:",
         NSFileHandleConnectionAcceptedNotification,
         self.serverFileHandle,
     )
     self.serverFileHandle.acceptConnectionInBackgroundAndNotify()
     self.remoteFileHandle = None
     for k in os.environ.keys():
         if k.startswith("PYTHON"):
             del os.environ[k]
     self.childTask = NSTask.launchedTaskWithLaunchPath_arguments_(
         self.interpreterPath,
         [self.scriptPath,
          repr(self.serverSocket.getsockname())],
     )
     nc.addObserver_selector_name_object_(self, "childTaskTerminated:",
                                          NSTaskDidTerminateNotification,
                                          self.childTask)
     return self
Beispiel #16
0
    def stop(self):
        self.cloud_storage = None
        self.notification_center.remove_observer(
            self, name='SIPAccountManagerDidAddAccount')
        self.notification_center.remove_observer(
            self, name='SIPAccountManagerDidRemoveAccount')
        self.notification_center.remove_observer(self,
                                                 name='SIPApplicationDidStart')
        self.notification_center.remove_observer(
            self, name='CFGSettingsObjectDidChange')

        NSNotificationCenter.defaultCenter().removeObserver_name_object_(
            self, "NSUbiquitousKeyValueStoreDidChangeExternallyNotification",
            self.cloud_storage)

        self.first_sync_completed = False
        BlinkLogger().log_info("iCloud Manager stopped")
    def awakeFromNib(self):
        self.outputView.setShouldCloseWithWindow_(True)
        self.outputView.registerForDraggedTypes_(
            NSArray.arrayWithObject_(NSFilenamesPboardType))
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "webviewFinishedLoading:",
            WebViewProgressFinishedNotification, self.outputView)
        if self.inputText:
            self.inputText.registerForDraggedTypes_(
                NSArray.arrayWithObject_(NSFilenamesPboardType))
            self.inputText.setOwner(self)
            NSNotificationCenter.defaultCenter(
            ).addObserver_selector_name_object_(self, "textDidChange:",
                                                NSTextDidChangeNotification,
                                                self.inputText)

        self.messageQueue = []
Beispiel #18
0
 def initWithManager_Asset_(self, manager, asset):
     self = objc.super(LivePhotoRequest, self).init()
     if self is None:
         return None
     self.manager = manager
     self.asset = asset
     self.nc = NSNotificationCenter.defaultCenter()
     return self
 def remoteSocketAccepted_(self, notification):
     # NSLog(u'remoteSocketAccepted_')
     self.serverFileHandle.closeFile()
     self.serverFileHandle = None
     ui = notification.userInfo()
     self.remoteFileHandle = ui.objectForKey_(
         NSFileHandleNotificationFileHandleItem)
     nc = NSNotificationCenter.defaultCenter()
     nc.addObserver_selector_name_object_(
         self,
         "remoteFileHandleReadCompleted:",
         NSFileHandleReadCompletionNotification,
         self.remoteFileHandle,
     )
     self.writeBytes_(SOURCE)
     self.remoteFileHandle.readInBackgroundAndNotify()
     self.commandReactor.connectionEstablished_(self)
     NSNotificationCenter.defaultCenter().postNotificationName_object_(
         "AsyncPythonInterpreterOpened", self)
Beispiel #20
0
    def finishLaunching(self):
        # Make statusbar item
        statusbar = NSStatusBar.systemStatusBar()
        self.statusitem = statusbar.statusItemWithLength_(
            NSVariableStatusItemLength)
        # Thanks Matthias Kretschmann
        # at http://kremalicious.com/coffee-cup-icon/
        icon_path = NSBundle.mainBundle()\
                            .pathForResource_ofType_(
                                ICON_BASE, ICON_EXT)
        if not icon_path:
            icon_path = ICON_FILE
        self.icon = NSImage.alloc()\
                           .initByReferencingFile_(icon_path)
        self.icon.setScalesWhenResized_(True)
        self.icon.setSize_((20, 20))
        self.statusitem.setImage_(self.icon)

        # Make the menu
        self.menubarMenu = NSMenu.alloc().init()

        self.menuItem = NSMenuItem.alloc()\
                                  .initWithTitle_action_keyEquivalent_(
                                      'Connect', 'connectAndCloseCNA:', '')
        self.menubarMenu.addItem_(self.menuItem)

        self.quit = NSMenuItem.alloc()\
                              .initWithTitle_action_keyEquivalent_(
                                  'Quit', 'terminate:', '')
        self.menubarMenu.addItem_(self.quit)

        # Add menu to statusitem
        self.statusitem.setMenu_(self.menubarMenu)
        self.statusitem.setToolTip_('Cartel')
        self.statusitem.setHighlightMode_(True)

        # Get the default notification center.
        self.workspace = NSWorkspace.sharedWorkspace()
        self.default_center = NSNotificationCenter.defaultCenter()

        # Create the handler
        self.rhandler = ReachabilityHandler.new()
        self.rhandler.app = self

        self.default_center.addObserver_selector_name_object_(
            self.rhandler,
            "handleChange:",
            kReachabilityChangedNotification,
            None)

        # Create the reachability object and start notifactions.
        self.reachability = Reachability()
        self.reachability.startNotifier()
    def setTool(self, tool):
        """Replace the tool in the image with a new Tool.

setTool(tool)

The argument "tool" should be an instance of a Tool object.
        """
        if not isinstance(tool, PythonCAD.Generic.tools.Tool):
            raise TypeError, "Invalid tool: " + str(tool)
        self.__tool = tool
        _nc = NSNotificationCenter.defaultCenter()
        _nc.postNotificationName_object_userInfo_(Globals.ToolChangedNotification, self, {"tool" : tool})
Beispiel #22
0
    def start(self):
        BlinkLogger().log_debug("Starting iCloud Manager")
        self.cloud_storage = NSUbiquitousKeyValueStore.defaultStore()
        self.cloud_storage.synchronize()
        BlinkLogger().log_debug(
            "%.1f out of 64.0 KB of iCloud storage space used" %
            (self.storage_size / 1024))

        self.notification_center.add_observer(
            self, name='SIPAccountManagerDidAddAccount')
        self.notification_center.add_observer(
            self, name='SIPAccountManagerDidRemoveAccount')
        self.notification_center.add_observer(self,
                                              name='SIPApplicationDidStart')
        self.notification_center.add_observer(
            self, name='CFGSettingsObjectDidChange')

        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "cloudStorageDidChange:",
            "NSUbiquitousKeyValueStoreDidChangeExternallyNotification",
            self.cloud_storage)
Beispiel #23
0
    def setTool(self, tool):
        """Replace the tool in the image with a new Tool.

setTool(tool)

The argument "tool" should be an instance of a Tool object.
        """
        if not isinstance(tool, PythonCAD.Generic.tools.Tool):
            raise TypeError, "Invalid tool: " + str(tool)
        self.__tool = tool
        _nc = NSNotificationCenter.defaultCenter()
        _nc.postNotificationName_object_userInfo_(
            Globals.ToolChangedNotification, self, {"tool": tool})
Beispiel #24
0
    def __init__(self):
        if not NSApp.delegate().icloud_enabled:
            NSUserDefaults.standardUserDefaults().setObject_forKey_(
                "Disabled", "iCloudSyncEnabled")
            return

        if Version.parse(platform.mac_ver()[0]) >= Version.parse("10.7"):
            self.notification_center = NotificationCenter()
            enabled = NSUserDefaults.standardUserDefaults().stringForKey_(
                "iCloudSyncEnabled")
            if enabled is None:
                NSUserDefaults.standardUserDefaults().setObject_forKey_(
                    "Enabled", "iCloudSyncEnabled")
                self.start()
            elif enabled == "Enabled":
                self.start()

            NSNotificationCenter.defaultCenter(
            ).addObserver_selector_name_object_(
                self, "userDefaultsDidChange:",
                "NSUserDefaultsDidChangeNotification",
                NSUserDefaults.standardUserDefaults())
def test_console():
    from PyObjCTools import AppHelper
    from ConsoleReactor import ConsoleReactor

    host = "127.0.0.1"
    port = 0
    interpreterPath = sys.executable
    scriptPath = os.path.abspath("tcpinterpreter.py")
    commandReactor = ConsoleReactor.alloc().init()
    interp = AsyncPythonInterpreter.alloc(
    ).initWithHost_port_interpreterPath_scriptPath_commandReactor_(  # noqa: B950
        host, port, interpreterPath, scriptPath, commandReactor)
    interp.connect()

    class ThisEventLoopStopper(NSObject):
        def interpFinished_(self, notification):
            AppHelper.stopEventLoop()

    stopper = ThisEventLoopStopper.alloc().init()
    NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
        stopper, "interpFinished:", "AsyncPythonInterpreterClosed", interp)
    AppHelper.runConsoleEventLoop(installInterrupt=True)
Beispiel #26
0
    def initWithAVAsset_path_(self, avasset, path):
        """ init helper class for exporting slow-mo video

        Args:
            avasset: AVAsset
            path: python str; path to export to
        """
        self = objc.super(SlowMoVideoExporter, self).init()
        if self is None:
            return None
        self.avasset = avasset
        self.url = path_to_NSURL(path)
        self.nc = NSNotificationCenter.defaultCenter()
        return self
Beispiel #27
0
	def awakeFromNib(self):
		print "Awakened from NIB"
		NSApplication.sharedApplication().setDelegate_(self)
		self.window().setFrameAutosaveName_("mainWindow")
		self.pids={}
		nc=NSNotificationCenter.defaultCenter()
		nc.addObserver_selector_name_object_(self,
			'deadProcess:',
			"NSTaskDidTerminateNotification",
			None)
		nc.addObserver_selector_name_object_(self,
			'runChecked:',
			"RUN_CHECKED",
			None)

		self.initDefaults()
Beispiel #28
0
 def initWithFileDescriptor_readCallback_errorCallback_(
         self, fileDescriptor, readCallback, errorCallback):
     self = self.init()
     self.readCallback = readCallback
     self.errorCallback = errorCallback
     self.fileHandle = NSFileHandle.alloc().initWithFileDescriptor_(
         fileDescriptor)
     self.nc = NSNotificationCenter.defaultCenter()
     self.nc.addObserver_selector_name_object_(
         self,
         "fileHandleReadCompleted:",
         NSFileHandleReadCompletionNotification,
         self.fileHandle,
     )
     self.fileHandle.readInBackgroundAndNotify()
     return self
 def windowDidLoad(self):
     _doc = self.document()
     _sv = _doc.getSplitView()
     _ov = _doc.getOutlineView()
     _text = _doc.getEntry()
     _win = self.window()
     _text.setDelegate_(self)
     _sv.setDelegate_(self)
     _win.setDelegate_(self)
     _win.setFrameUsingName_(WinFrameName)
     _ov.setDataSource_(self)
     _ov.setDelegate_(self)
     _ov.sizeLastColumnToFit()
     _ov.setAutoresizesOutlineColumn_(True)
     _da = _doc.getDA()
     _scrv = _da.enclosingScrollView()
     _scrvSize = _scrv.contentSize()
     _scrv.setCopiesOnScroll_(False)
     _da.setFrameSize_(_scrvSize)
     #
     # ensure selected layer is active
     #
     _item = _ov.itemAtRow_(0)
     _ov.expandItem_expandChildren_(_item, True)
     _endRow = _ov.numberOfRows() - 1
     _ov.selectRow_byExtendingSelection_(_endRow, False)
     _ov.selectRow_byExtendingSelection_(0, False)
     #
     # Register for notifications of changes to the document
     #
     _img = _doc.getImage()
     _obj = Globals.wrap(_img)
     _nc = NSNotificationCenter.defaultCenter()
     _nc.addObserver_selector_name_object_(self, "layerChanged:",
                                           LayerAddedNotification, _obj)
     _nc.addObserver_selector_name_object_(self, "layerChanged:",
                                           LayerDeletedNotification, _obj)
     _nc.addObserver_selector_name_object_(self, "toolChanged:",
                                           ToolChangedNotification, _doc)
Beispiel #30
0
    def awakeFromNib(self):
        """awakeFromNib"""

        self._common_init()

        # Start the IPython engine
        self.engine.startService()
        NSLog('IPython engine started')

        # Register for app termination
        nc = NSNotificationCenter.defaultCenter()
        nc.addObserver_selector_name_object_(
            self, 'appWillTerminate:', NSApplicationWillTerminateNotification,
            None)

        self.textView.setDelegate_(self)
        self.textView.enclosingScrollView().setHasVerticalRuler_(True)
        r = NSRulerView.alloc().initWithScrollView_orientation_(
            self.textView.enclosingScrollView(), NSVerticalRuler)
        self.verticalRulerView = r
        self.verticalRulerView.setClientView_(self.textView)
        self._start_cli_banner()
        self.start_new_block()
 def windowDidLoad(self):
     _doc = self.document()
     _sv = _doc.getSplitView()
     _ov = _doc.getOutlineView()
     _text = _doc.getEntry()
     _win = self.window()
     _text.setDelegate_(self)
     _sv.setDelegate_(self)
     _win.setDelegate_(self)
     _win.setFrameUsingName_(WinFrameName)
     _ov.setDataSource_(self)
     _ov.setDelegate_(self)
     _ov.sizeLastColumnToFit()
     _ov.setAutoresizesOutlineColumn_(True)
     _da = _doc.getDA()
     _scrv = _da.enclosingScrollView()
     _scrvSize = _scrv.contentSize()
     _scrv.setCopiesOnScroll_(False)
     _da.setFrameSize_(_scrvSize)
     #
     # ensure selected layer is active
     #
     _item = _ov.itemAtRow_(0)
     _ov.expandItem_expandChildren_(_item, True)
     _endRow = _ov.numberOfRows() - 1
     _ov.selectRow_byExtendingSelection_(_endRow, False)
     _ov.selectRow_byExtendingSelection_(0, False)
     #
     # Register for notifications of changes to the document
     #
     _img = _doc.getImage()
     _obj = Globals.wrap(_img)
     _nc = NSNotificationCenter.defaultCenter()
     _nc.addObserver_selector_name_object_(self, "layerChanged:", LayerAddedNotification, _obj)
     _nc.addObserver_selector_name_object_(self, "layerChanged:", LayerDeletedNotification, _obj)
     _nc.addObserver_selector_name_object_(self, "toolChanged:", ToolChangedNotification, _doc)
Beispiel #32
0
 def dealloc(self):
     NSNotificationCenter.defaultCenter().removeObserver_(self)
     VerticalBoxView.dealloc(self)
Beispiel #33
0
    def setup_observers(self):
        # reaction to layout changes
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "layoutChanged:", "QSXLayoutChanged", None)

        # new, destroyed or focused windows are passed to the layout
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "newWindow:", "QSXNewWindow", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "windowDestroyed:", "QSXWindowDestroyed", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "windowFocusedExternal:", "QSXWindowFocusedExternal", None)

        # new or destroyed apps are handled here
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "newApp:", "QSXNewApp", None)
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            self, "appDestroyed:", "QSXAppDestroyed", None)
Beispiel #34
0
def runEventLoop(
    argv=None,
    unexpectedErrorAlert=None,
    installInterrupt=None,
    pdb=None,
    main=NSApplicationMain,
):
    """Run the event loop, ask the user if we should continue if an
    exception is caught. Use this function instead of NSApplicationMain().
    """
    if argv is None:
        argv = sys.argv

    if pdb is None:
        pdb = "USE_PDB" in os.environ

    if pdb:
        from PyObjCTools import Debugging

        Debugging.installVerboseExceptionHandler()
        # bring it to the front, starting from terminal
        # often won't
        activator = PyObjCAppHelperApplicationActivator.alloc().init()
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            activator, "activateNow:", NSApplicationDidFinishLaunchingNotification, None
        )
    else:
        Debugging = None

    if installInterrupt is None and pdb:
        installInterrupt = True

    if unexpectedErrorAlert is None:
        if pdb:
            unexpectedErrorAlert = unexpectedErrorAlertPdb
        else:
            unexpectedErrorAlert = unexpectedErrorAlertPanel

    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
    PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)

    firstRun = NSApp() is None
    try:

        while stopper.shouldRun():
            try:
                if firstRun:
                    firstRun = False
                    if installInterrupt:
                        installMachInterrupt()
                    main(argv)
                else:
                    NSApp().run()
            except RAISETHESE:
                traceback.print_exc()
                break
            except:  # noqa: E722, B001
                exctype, e, tb = sys.exc_info()
                if isinstance(e, objc.error):
                    error_str = str(e)

                    NSLog("%@", error_str)
                elif not unexpectedErrorAlert():
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
                    sys.exit(0)
                else:
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
            else:
                break

    finally:
        if Debugging is not None:
            Debugging.removeExceptionHandler()
        PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
Beispiel #35
0
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain):
    """Run the event loop, ask the user if we should continue if an
    exception is caught. Use this function instead of NSApplicationMain().
    """
    if argv is None:
        argv = sys.argv

    if pdb is None:
        pdb = 'USE_PDB' in os.environ

    if pdb:
        from PyObjCTools import Debugging
        Debugging.installVerboseExceptionHandler()
        # bring it to the front, starting from terminal
        # often won't
        activator = PyObjCAppHelperApplicationActivator.alloc().init()
        NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
            activator,
            'activateNow:',
            NSApplicationDidFinishLaunchingNotification,
            None,
        )
    else:
        Debugging = None

    if installInterrupt is None and pdb:
        installInterrupt = True

    if unexpectedErrorAlert is None:
        if pdb:
            unexpectedErrorAlert = unexpectedErrorAlertPdb
        else:
            unexpectedErrorAlert = unexpectedErrorAlertPanel

    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
    PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)

    firstRun = NSApp() is None
    try:

        while stopper.shouldRun():
            try:
                if firstRun:
                    firstRun = False
                    if installInterrupt:
                        installMachInterrupt()
                    main(argv)
                else:
                    NSApp().run()
            except RAISETHESE:
                traceback.print_exc()
                break
            except:
                exctype, e, tb = sys.exc_info()
                objc_exception = False
                if isinstance(e, objc.error):
                    NSLog("%@", unicode(str(e), 'utf-8', 'replace'))
                elif not unexpectedErrorAlert():
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
                    sys.exit(0)
                else:
                    NSLog("%@", "An exception has occured:")
                    traceback.print_exc()
            else:
                break

    finally:
        if Debugging is not None:
            Debugging.removeExceptionHandler()
        PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
 def windowWillClose_(self, note):
     _nc = NSNotificationCenter.defaultCenter()
     _nc.removeObserver_(self)
Beispiel #37
0
# from ConsoleReactor import ConsoleReactor
# host = '127.0.0.1'
# port = 0
# interpreterPath = sys.executable
# scriptPath = unicode(os.path.abspath('tcpinterpreter.py'))
# commandReactor = ConsoleReactor.alloc().init()
# interp = AsyncPythonInterpreter.alloc().initWithHost_port_interpreterPath_scriptPath_commandReactor_(host, port, interpreterPath, scriptPath, commandReactor)
# interp.connect()

query = NSMetadataQuery.alloc().init()
query.setPredicate_(NSPredicate.predicateWithFormat_( 'kMDItemKind = "Aperture Library"' ))
scopes = [NSMetadataQueryUserHomeScope]             
query.setSearchScopes_( scopes )


class ThisEventLoopStopper(NSObject):
    def interpFinished_(self, notification):
        AppHelper.stopEventLoop()
stopper = ThisEventLoopStopper.alloc().init()

NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', NSMetadataQueryDidFinishGatheringNotification, query)
query.startQuery()

# NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(stopper, 'interpFinished:', u'AsyncPythonInterpreterClosed', interp)
AppHelper.runConsoleEventLoop(installInterrupt=True)

query.stopQuery()
print "count: ", len(query.results())
for item in query.results():
    print "item: ", item.valueForAttribute_("kMDItemPath")
 def close(self):
     # NSLog(u'close')
     NSNotificationCenter.defaultCenter().removeObserver_(self)
     self.finalClose()
     NSNotificationCenter.defaultCenter().postNotificationName_object_(
         "AsyncPythonInterpreterClosed", self)
 def windowWillClose_(self, note):
     _nc = NSNotificationCenter.defaultCenter()
     _nc.removeObserver_(self)
Beispiel #40
0
def notify(msg, sender, user_info=None):
    NSNotificationCenter.defaultCenter().postNotificationName_object_userInfo_(msg, sender, user_info)
Beispiel #41
0
 def dealloc(self):
     NSNotificationCenter.defaultCenter().removeObserver_(self)
     VerticalBoxView.dealloc(self)