コード例 #1
0
ファイル: decom.py プロジェクト: t-lark/DEP-Notify-Decom
def get_apps(tag, removal):
    """use spotlight to find apps by custom tag"""
    # main dictionary
    removals = {}
    # set NSMetaDatQuery predicate by your custom tag with value of true
    predicate = "%s = 'true'" % tag
    # build and execute the spotlight query
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(NSPredicate.predicateWithFormat_(predicate))
    query.setSearchScopes_(['/Applications'])
    query.startQuery()
    start_time = 0
    max_time = 20
    while query.isGathering() and start_time <= max_time:
        start_time += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()
    # iterate through the results to grab spotlight attributes
    for item in query.results():
        app = item.valueForAttribute_('kMDItemFSName')
        path = item.valueForAttribute_('kMDItemPath')
        customtag = item.valueForAttribute_(removal)
        if customtag:
            # build nested dictionary of tagged apps and attribute values
            removals[app] = {}
            removals[app]['path'] = path
            removals[app]['method'] = customtag

    return removals
コード例 #2
0
 def __init__(self, image):
     NSBundle.loadNibNamed_owner_("ScreensharingPreviewPanel", self)
     self.view.setImage_(image)
     self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5.0, self, "closeTimer:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
     self.window.orderFront_(None)
コード例 #3
0
ファイル: info.py プロジェクト: y010204025/munki
def find_apps_in_dirs(dirlist):
    """Do spotlight search for type applications within the
    list of directories provided. Returns a list of paths to applications
    these appear to always be some form of unicode string.
    """
    applist = []
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")'))
    query.setSearchScopes_(dirlist)
    query.startQuery()
    # Spotlight isGathering phase - this is the initial search. After the
    # isGathering phase Spotlight keeps running returning live results from
    # filesystem changes, we are not interested in that phase.
    # Run for 0.3 seconds then check if isGathering has completed.
    runtime = 0
    maxruntime = 20
    while query.isGathering() and runtime <= maxruntime:
        runtime += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()

    if runtime >= maxruntime:
        display.display_warning(
            'Spotlight search for applications terminated due to excessive '
            'time. Possible causes: Spotlight indexing is turned off for a '
            'volume; Spotlight is reindexing a volume.')

    for item in query.results():
        pathname = item.valueForAttribute_('kMDItemPath')
        if pathname and not is_excluded_filesystem(pathname):
            applist.append(pathname)

    return applist
コード例 #4
0
    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)
コード例 #5
0
def notify(title, subtitle, text, bundleid=None, url=None):
    if bundleid:
        # fake our bundleid
        set_fake_bundleid(bundleid)

    # create a new user notification
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(text)
    if url:
        userInfo = NSDictionary.dictionaryWithDictionary_({
            'action': u'open_url',
            'value': unicode(url)
        })
        notification.setUserInfo_(userInfo)
    notification.setHasActionButton_(True)
    notification.setActionButtonTitle_('Details')

    # get the default User Notification Center
    nc = NSUserNotificationCenter.defaultUserNotificationCenter()

    # create a delegate object that implements our delegate methods
    my_delegate = NotificationCenterDelegate.alloc().init()
    nc.setDelegate_(my_delegate)

    nc.removeAllDeliveredNotifications()
    # deliver the notification
    nc.deliverNotification_(notification)

    # keep running until the notification is activated
    while (my_delegate.keepRunning):
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.1))
コード例 #6
0
def get_apps():
    # credit to the Munki project for borrowing code, thanks Munki!
    apps_dict = {}
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_(
            "(kMDItemContentType = 'com.apple.application-bundle')"))
    query.setSearchScopes_(['/Applications'])
    query.startQuery()
    start_time = 0
    max_time = 20
    while query.isGathering() and start_time <= max_time:
        start_time += 0.3
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()
    # check if the app returns a None value for this query, some apps may have embedded Applescripts
    # that will return a None value and will be set to blank
    for app in query.results():
        name = app.valueForAttribute_('kMDItemDisplayName')
        if name:
            version = app.valueForAttribute_('kMDItemVersion') or ''
            apps_dict[name] = version

    return apps_dict
コード例 #7
0
def notify(title, subtitle, text, bundleid=None):
    if bundleid:
        # fake our bundleid
        set_fake_bundleid(bundleid)

    # create a new user notification
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(title)
    notification.setSubtitle_(subtitle)
    notification.setInformativeText_(text)

    # get the default User Notification Center
    nc = NSUserNotificationCenter.defaultUserNotificationCenter()

    # create a delegate object that implements our delegate methods
    my_delegate = NotificationCenterDelegate.alloc().init()
    nc.setDelegate_(my_delegate)

    # deliver the notification
    nc.deliverNotification_(notification)

    # keep running until the notification is activated
    while (my_delegate.keepRunning):
        NSRunLoop.currentRunLoop().runUntilDate_(
            NSDate.dateWithTimeIntervalSinceNow_(0.1))
コード例 #8
0
ファイル: BtBatStat.py プロジェクト: zhangcheng/btbatstat
  def applicationDidFinishLaunching_(self, notification):
    self.noDevice = None

    #Create menu
    self.menu = NSMenu.alloc().init()

    self.barItem = dict()

    # Load images
    self.noDeviceImage = NSImage.alloc().initByReferencingFile_('icons/no_device.png')
    self.barImage = dict(kb = NSImage.alloc().initByReferencingFile_('icons/kb.png'),
			 magicMouse = NSImage.alloc().initByReferencingFile_('icons/magic_mouse.png'),
			 mightyMouse = NSImage.alloc().initByReferencingFile_('icons/mighty_mouse.png'),
			 magicTrackpad = NSImage.alloc().initByReferencingFile_('icons/TrackpadIcon.png'))

    #Define menu items
    self.statusbar = NSStatusBar.systemStatusBar()
    self.menuAbout = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About BtBatStat', 'about:', '')
    self.separator_menu_item = NSMenuItem.separatorItem()
    self.menuQuit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')

    # Get the timer going
    self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 10.0, self, 'tick:', None, True)
    NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
    self.timer.fire()

    #Add menu items
    self.menu.addItem_(self.menuAbout)
    self.menu.addItem_(self.separator_menu_item)
    self.menu.addItem_(self.menuQuit)

    #Check for updates
    checkForUpdates()
コード例 #9
0
ファイル: info.py プロジェクト: chrisgrande/munki
def find_apps_in_dirs(dirlist):
    """Do spotlight search for type applications within the
    list of directories provided. Returns a list of paths to applications
    these appear to always be some form of unicode string.
    """
    applist = []
    query = NSMetadataQuery.alloc().init()
    query.setPredicate_(
        NSPredicate.predicateWithFormat_('(kMDItemKind = "Application")'))
    query.setSearchScopes_(dirlist)
    query.startQuery()
    # Spotlight isGathering phase - this is the initial search. After the
    # isGathering phase Spotlight keeps running returning live results from
    # filesystem changes, we are not interested in that phase.
    # Run for 0.3 seconds then check if isGathering has completed.
    runtime = 0
    maxruntime = 20
    while query.isGathering() and runtime <= maxruntime:
        runtime += 0.3
        NSRunLoop.currentRunLoop(
            ).runUntilDate_(NSDate.dateWithTimeIntervalSinceNow_(0.3))
    query.stopQuery()

    if runtime >= maxruntime:
        display.display_warning(
            'Spotlight search for applications terminated due to excessive '
            'time. Possible causes: Spotlight indexing is turned off for a '
            'volume; Spotlight is reindexing a volume.')

    for item in query.results():
        pathname = item.valueForAttribute_('kMDItemPath')
        if pathname and not is_excluded_filesystem(pathname):
            applist.append(pathname)

    return applist
コード例 #10
0
ファイル: rumps.py プロジェクト: mjhea0/rumps
 def __init__(self, callback, interval):
     self.set_callback(callback)
     self._nsdate = NSDate.date()
     self._nstimer = NSTimer.alloc(
     ).initWithFireDate_interval_target_selector_userInfo_repeats_(
         self._nsdate, interval, self, 'callback:', None, True)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self._nstimer,
                                                  NSDefaultRunLoopMode)
コード例 #11
0
ファイル: rumps.py プロジェクト: philippeowagner/rumps
 def start(self):
     if not self._status:
         self._nsdate = NSDate.date()
         self._nstimer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(
             self._nsdate, self._interval, self, 'callback:', None, True)
         NSRunLoop.currentRunLoop().addTimer_forMode_(self._nstimer, NSDefaultRunLoopMode)
         _TIMERS.add(self)
         self._status = True
コード例 #12
0
    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:")
コード例 #13
0
 def start(self):
     if not self._status:
         self._nsdate = NSDate.date()
         self._nstimer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(
             self._nsdate, self._interval, self, 'callback:', None, True)
         NSRunLoop.currentRunLoop().addTimer_forMode_(self._nstimer, NSDefaultRunLoopMode)
         _TIMERS.add(self)
         self._status = True
コード例 #14
0
    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:")
コード例 #15
0
 def startDeallocTimer(self):
     # workaround to keep the object alive as cocoa still sends delegate tableview messages after close
     self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
         2.0, self, "deallocTimer:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer,
                                                  NSRunLoopCommonModes)
     NSRunLoop.currentRunLoop().addTimer_forMode_(
         self.dealloc_timer, NSEventTrackingRunLoopMode)
コード例 #16
0
ファイル: gurl.py プロジェクト: SteveKueng/munki
 def isDone(self):
     '''Check if the connection request is complete. As a side effect,
     allow the delegates to work by letting the run loop run for a bit'''
     if self.done:
         return self.done
     # let the delegates do their thing
     NSRunLoop.currentRunLoop().runUntilDate_(
         NSDate.dateWithTimeIntervalSinceNow_(.1))
     return self.done
コード例 #17
0
ファイル: gurl.py プロジェクト: zippyy/munki
 def isDone(self):
     '''Check if the connection request is complete. As a side effect,
     allow the delegates to work by letting the run loop run for a bit'''
     if self.done:
         return self.done
     # let the delegates do their thing
     NSRunLoop.currentRunLoop().runUntilDate_(
         NSDate.dateWithTimeIntervalSinceNow_(.1))
     return self.done
コード例 #18
0
 def start_auto_close_timer(self):
     if not self.close_timer:
         # auto-close everything in 5s
         self.close_timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
             5, self, "closeWindows:", None, False)
         NSRunLoop.currentRunLoop().addTimer_forMode_(
             self.close_timer, NSRunLoopCommonModes)
         NSRunLoop.currentRunLoop().addTimer_forMode_(
             self.close_timer, NSEventTrackingRunLoopMode)
コード例 #19
0
ファイル: AlertPanel.py プロジェクト: bitsworking/blink-cocoa
 def enableAutoAnswer(self, view, session, delay=30):
     if session not in self.autoAnswerTimers:
         label = view.viewWithTag_(15)
         info = dict(delay = delay, session = session, label = label, time = time.time())
         timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "timerTickAutoAnswer:", info, True)
         NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSRunLoopCommonModes)
         NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSEventTrackingRunLoopMode)
         self.autoAnswerTimers[session] = timer
         self.timerTickAutoAnswer_(timer)
         label.setHidden_(False)
コード例 #20
0
 def __init__(self, image):
     NSBundle.loadNibNamed_owner_("ScreensharingPreviewPanel", self)
     self.view.setImage_(image)
     self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
         5.0, self, "closeTimer:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer,
                                                  NSModalPanelRunLoopMode)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer,
                                                  NSDefaultRunLoopMode)
     self.window.orderFront_(None)
コード例 #21
0
def do_it():
    delegate = BluetoothDelegate.alloc().init()
    manager = CBCentralManager.alloc().initWithDelegate_queue_(delegate, None)
    manager.scanForPeripheralsWithServices_options_(None, None)
    while True:
        try:
            NSRunLoop.currentRunLoop().runUntilDate_(
                NSDate.dateWithTimeIntervalSinceNow_(0.5))
        except (KeyboardInterrupt, SystemExit):
            break
コード例 #22
0
ファイル: ChatOTR.py プロジェクト: uditha-atukorala/blink
 def _finish(self):
     self.smp_running = False
     self.finished = True
     self.secretText.setEnabled_(False)
     self.questionText.setEnabled_(False)
     self.progressBar.setDoubleValue_(9)
     self.continueButton.setEnabled_(True)
     self.continueButton.setTitle_('Finish')
     self.cancelButton.setHidden_(True)
     self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(5, self, "verificationFinished:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
コード例 #23
0
    def _NH_SIPApplicationDidStart(self, notification):
        settings = SIPSimpleSettings()
        if settings.presence_state.timestamp is None:
            settings.presence_state.timestamp = ISOTimestamp.now()
            settings.save()

        self.get_location([account for account in AccountManager().iter_accounts() if account is not BonjourAccount()])
        self.publish()

        idle_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateIdleTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSEventTrackingRunLoopMode)
コード例 #24
0
 def __init__(self, start_val, end_val, k, damp, duration, update_period, value_cb, done_cb):
     self.last_time = self.start_time = time.time()
     self.start_val = self.cur_val = start_val
     self.end_val = end_val
     self.cur_velocity = 0
     self.damp = damp
     self.k = k
     self.duration = duration
     self.value_cb = value_cb
     self.done_cb = done_cb
     self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(update_period, self, selector(self.period, signature='v@:'), None, True)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode)
コード例 #25
0
    def _NH_SIPApplicationDidStart(self, notification):
        settings = SIPSimpleSettings()
        if settings.presence_state.timestamp is None:
            settings.presence_state.timestamp = ISOTimestamp.now()
            settings.save()

        self.get_location([account for account in AccountManager().iter_accounts() if account is not BonjourAccount()])
        self.publish()

        idle_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateIdleTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(idle_timer, NSEventTrackingRunLoopMode)
コード例 #26
0
 def initWithStartVal_endVal_duration_interval_valueCb_doneCb_(self, start_val, end_val, duration, update_period, value_callback, done_callback):
     self = super(LinearAnimator, self).init()
     if not self:
         return
     self.start_time = time.time()
     self.duration = duration
     self.end_val = end_val
     self.start_val = start_val
     self.value_callback = value_callback
     self.done_callback = done_callback
     self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(update_period, self, 'period:', None, True)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSEventTrackingRunLoopMode)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
コード例 #27
0
    def start(self):
        notification_center = NotificationCenter()
        notification_center.add_observer(self, name="BlinkFileTransferDidEnd")
        notification_center.add_observer(self, name="AudioStreamDidChangeHoldState")
        notification_center.add_observer(self, name="CFGSettingsObjectDidChange")
        notification_center.add_observer(self, name="ChatViewControllerDidDisplayMessage")
        notification_center.add_observer(self, name="ConferenceHasAddedAudio")
        notification_center.add_observer(self, name="BlinkWillCancelProposal")

        self.cleanupTimer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(3, self, "cleanupTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer, NSEventTrackingRunLoopMode)
        self.started = True
コード例 #28
0
    def finishLaunching(self):
        self._setup_menuBar()

        # Create a timer which fires the update_ method every 1second,
        # and add it to the runloop
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            NSTimer.
            scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(
                1, self, 'update:', '', True), NSEventTrackingRunLoopMode)

        print('Simon is now running.')
        print('CTRL+C does not work here.')
        print('You can quit through the menubar (Simon -> Quit).')
コード例 #29
0
ファイル: menu.py プロジェクト: andreoliwa/python-dontforget
    def finishLaunching(self):
        """Setup the menu and run the app loop."""
        self._setup_menu_bar()

        # Create a timer which fires the update_ method every 1second,
        # and add it to the runloop
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "update:", "", True),
            NSEventTrackingRunLoopMode,
        )

        print("Sentinel is now running.")
        print("CTRL+C does not work here.")
        print("You can quit through the menu bar (Sentinel -> Quit).")
コード例 #30
0
ファイル: ChatOTR.py プロジェクト: ronaldoussoren/blink-cocoa
 def _finish(self, result=False):
     self.finished = True
     self.smp_running = False
     self.requested_by_remote = False
     self.secretText.setEnabled_(False)
     self.questionText.setEnabled_(False)
     self.progressBar.setDoubleValue_(9)
     self.continueButton.setEnabled_(False)
     self.continueButton.setTitle_(NSLocalizedString("Finish", "Button Title"))
     self.cancelButton.setHidden_(True)
     self.continueButton.setEnabled_(True)
     wait_interval = 5 if result else 10
     self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(wait_interval, self, "verificationFinished:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSRunLoopCommonModes)
コード例 #31
0
    def _NH_MediaStreamDidStart(self, sender, data):
        super(VideoController, self)._NH_MediaStreamDidStart(sender, data)
        self.started = True
        sample_rate = self.stream.clock_rate/1000
        codec = beautify_video_codec(self.stream.codec)
        self.sessionController.log_info("Video stream established to %s:%s using %s %0.fkHz codec" % (self.stream.remote_rtp_address, self.stream.remote_rtp_port, codec, sample_rate))

        self.videoWindowController.show()
        self.changeStatus(STREAM_CONNECTED)

        if self.sessionController.hasStreamOfType("chat") and self.videoWindowController.always_on_top:
            self.videoWindowController.toogleAlwaysOnTop()

        self.statistics_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(STATISTICS_INTERVAL, self, "updateStatisticsTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer, NSEventTrackingRunLoopMode)
コード例 #32
0
def runConsoleEventLoop(argv=None,
                        installInterrupt=False,
                        mode=NSDefaultRunLoopMode,
                        maxTimeout=3.0):
    if argv is None:
        argv = sys.argv
    if installInterrupt:
        installMachInterrupt()
    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
    PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(
        stopper, runLoop)
    try:

        while stopper.shouldRun():
            nextfire = runLoop.limitDateForMode_(mode)
            if not stopper.shouldRun():
                break

            soon = NSDate.dateWithTimeIntervalSinceNow_(maxTimeout)
            if nextfire is not None:
                nextfire = soon.earlierDate_(nextfire)
            if not runLoop.runMode_beforeDate_(mode, nextfire):
                stopper.stop()

    finally:
        PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
コード例 #33
0
def apple_music_loop():
    AppleMusicHandler(command=on_song_detected)
    while True:
        loop = NSRunLoop.currentRunLoop()
        loop.run()
        if not run_thread:
            break
コード例 #34
0
ファイル: AlertPanel.py プロジェクト: bitsworking/blink-cocoa
 def enableAnsweringMachine(self, view, session, run_now=False):
     try:
         timer = self.answeringMachineTimers[session]
     except KeyError:
         settings = SIPSimpleSettings()
         amLabel = view.viewWithTag_(15)
         delay = 0 if run_now else settings.answering_machine.answer_delay
         info = dict(delay = delay, session = session, label = amLabel, time = time.time())
         timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "timerTickAnsweringMachine:", info, True)
         NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSRunLoopCommonModes)
         NSRunLoop.currentRunLoop().addTimer_forMode_(timer, NSEventTrackingRunLoopMode)
         self.answeringMachineTimers[session] = timer
         self.timerTickAnsweringMachine_(timer)
         amLabel.setHidden_(False)
     else:
         if run_now:
             self.acceptAudioStreamAnsweringMachine(session)
コード例 #35
0
def findDomains(serviceName, seconds=5.0):
    runloop = NSRunLoop.currentRunLoop()
    browser = NSNetServiceBrowser.new()
    pbd = PrintingBrowserDelegate.new()
    browser.setDelegate_(pbd)
    browser.searchForServicesOfType_inDomain_(serviceName, "")
    untilWhen = NSDate.dateWithTimeIntervalSinceNow_(seconds)
    runloop.runUntilDate_(untilWhen)
コード例 #36
0
ファイル: __init__.py プロジェクト: tlongeri/bleak
    def __init__(self):
        self.main_loop = asyncio.get_event_loop()
        self.main_loop.create_task(self._handle_nsrunloop())
        self.main_loop.create_task(self._central_manager_delegate_ready())

        self.nsrunloop = NSRunLoop.currentRunLoop()

        self.central_manager_delegate = CentralManagerDelegate.alloc().init()
コード例 #37
0
ファイル: rendezvous.py プロジェクト: benoit-pierre/pyobjc
def findDomains(serviceName, seconds=5.0):
    runloop = NSRunLoop.currentRunLoop()
    browser = NSNetServiceBrowser.new()
    pbd = PrintingBrowserDelegate.new()
    browser.setDelegate_(pbd)
    browser.searchForServicesOfType_inDomain_(serviceName, "")
    untilWhen = NSDate.dateWithTimeIntervalSinceNow_(seconds)
    runloop.runUntilDate_(untilWhen)
コード例 #38
0
    def end(self):
        if self.ended:
            return

        self.sessionController.log_debug("End %s" % self)
        self.ended = True

        if self.sessionController.waitingForLocalVideo:
            self.stop_wait_for_camera_timer()
            self.sessionController.cancelBeforeDNSLookup()

        if self.sessionController.video_consumer == "audio":
            NSApp.delegate().contactsWindowController.detachVideo(
                self.sessionController)
        elif self.sessionController.video_consumer == "chat":
            NSApp.delegate().chatWindowController.detachVideo(
                self.sessionController)

        status = self.status
        if status in [STREAM_IDLE, STREAM_FAILED]:
            self.changeStatus(STREAM_IDLE)
        elif status == STREAM_PROPOSING:
            self.sessionController.cancelProposal(self)
            self.changeStatus(STREAM_CANCELLING)
        else:
            self.sessionController.endStream(self)
            self.changeStatus(STREAM_IDLE)

        self.removeFromSession()

        self.videoRecorder.stop()

        self.videoWindowController.close()

        self.notification_center.remove_observer(
            self,
            sender=self.sessionController,
            name='VideoRemovedByRemoteParty')

        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)
コード例 #39
0
    def captureButtonClicked_(self, sender):
        if self.countdownCheckbox.state() == NSOnState:
            self.countdown_counter = 10
            self.previewButton.setHidden_(True)
            self.captureButton.setHidden_(True)
            self.countdownCheckbox.setHidden_(True)
            self.countdownProgress.setHidden_(False)
            self.countdownProgress.startAnimation_(None)
            self.countdownProgress.setIndeterminate_(False)
            self.countdownProgress.setDoubleValue_(self.countdown_counter)

            self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1, self, "executeTimerCapture:", None, True)
            NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode)
            NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
        else:
            self.countdownCheckbox.setHidden_(True)
            self.countdownProgress.setHidden_(True)
            self.executeCapture()
コード例 #40
0
 def applicationDidFinishLaunching_(self, notification):
     global start_time
     statusbar = NSStatusBar.systemStatusBar()
     # Create the statusbar item
     self.statusitem = statusbar.statusItemWithLength_(70.0)
     # Set initial image
     self.statusitem.setTitle_(self.updateGeektime())
     # Let it highlight upon clicking
     self.statusitem.setHighlightMode_(1)
     
     self.menu = NSMenu.alloc().init()
     menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '')
     self.menu.addItem_(menuitem)
     self.statusitem.setMenu_(self.menu)
     
     self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 0.65, self, 'tick:', None, True)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
     self.timer.fire()
コード例 #41
0
    def _NH_MediaStreamDidStart(self, sender, data):
        self.started = True
        sample_rate = self.stream.sample_rate / 1000
        codec = beautify_video_codec(self.stream.codec)
        self.sessionController.log_info(
            "Video stream established to %s:%s using %s codec" %
            (self.stream.remote_rtp_address, self.stream.remote_rtp_port,
             codec))

        self.changeStatus(STREAM_CONNECTED)
        self.sessionController.setVideoConsumer(
            self.sessionController.video_consumer)

        self.statistics_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
            STATISTICS_INTERVAL, self, "updateStatisticsTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.statistics_timer,
                                                     NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            self.statistics_timer, NSEventTrackingRunLoopMode)
コード例 #42
0
class ReverseLookup(object):
    def myCompletionHandler(placemarks, error):
        if error is not None:
            print error
        else:
            print placemarks

    # Convert coordinates to address
    geocoder = CLGeocoder.alloc().init()
    geocoder.reverseGeocodeLocation_completionHandler_(location,
                                                       myCompletionHandler)
    NSRunLoop.currentRunLoop().runUntilDate_(
        NSDate.dateWithTimeIntervalSinceNow_(1))

    # Convert street address into coordinates
    geocoder.geocodeAddressString_completionHandler_(address,
                                                     myCompletionHandler)
    NSRunLoop.currentRunLoop().runUntilDate_(
        NSDate.dateWithTimeIntervalSinceNow_(1))
コード例 #43
0
    def __init__(self, owner):
        BlinkLogger().log_debug('Starting Ringtone Manager')
        self.owner = owner
        notification_center = NotificationCenter()
        notification_center.add_observer(self, name="BlinkFileTransferDidEnd")
        notification_center.add_observer(self,
                                         name="RTPStreamDidChangeHoldState")
        notification_center.add_observer(self,
                                         name="CFGSettingsObjectDidChange")
        notification_center.add_observer(
            self, name="ChatViewControllerDidDisplayMessage")
        notification_center.add_observer(self, name="ConferenceHasAddedAudio")
        notification_center.add_observer(self, name="BlinkWillCancelProposal")

        self.cleanupTimer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
            3, self, "cleanupTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.cleanupTimer,
                                                     NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            self.cleanupTimer, NSEventTrackingRunLoopMode)
        self.update_ringtones()
コード例 #44
0
    def startOutgoing(self, is_update):
        if self.videoWindowController:
            self.videoWindowController.initLocalVideoWindow()

        self.ended = False
        self.notification_center.add_observer(self, sender=self.stream)
        self.notification_center.add_observer(self,
                                              sender=self.sessionController)
        self.notification_center.add_observer(self,
                                              sender=self.sessionController,
                                              name='VideoRemovedByRemoteParty')
        if is_update and self.sessionController.canProposeMediaStreamChanges():
            self.changeStatus(STREAM_PROPOSING)
        else:
            self.changeStatus(STREAM_WAITING_DNS_LOOKUP)

        self.wait_for_camera_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
            5.0, self, "localVideoReadyTimer:", None, False)
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            self.wait_for_camera_timer, NSRunLoopCommonModes)
        NSRunLoop.currentRunLoop().addTimer_forMode_(
            self.wait_for_camera_timer, NSEventTrackingRunLoopMode)
コード例 #45
0
    def __init__(self, sessionController):

        self.notification_center = NotificationCenter()

        self.sessionController = None
        self.audio_stream = None
        self.chat_stream = None

        self.add_session(sessionController)
        self.add_audio_stream()
        self.add_chat_stream()

        self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateTimer:", None, True)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode)
        NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
        NSBundle.loadNibNamed_owner_("SessionInfoPanel", self)

        sessionBoxTitle = NSAttributedString.alloc().initWithString_attributes_("SIP Session", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.sessionBox.setTitle_(sessionBoxTitle)

        audioBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Audio Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.audioBox.setTitle_(audioBoxTitle)

        chatBoxTitle = NSAttributedString.alloc().initWithString_attributes_("Chat Stream", NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName))
        self.chatBox.setTitle_(chatBoxTitle)

        self.audio_rtt_graph.setLineWidth_(1.0)
        self.audio_rtt_graph.setLineSpacing_(1.0)
        self.audio_rtt_graph.setAboveLimit_(200) # if higher than 200 ms show red color
        self.audio_rtt_graph.setMinimumHeigth_(200)

        self.audio_packet_loss_graph.setLineWidth_(1.0)
        self.audio_packet_loss_graph.setLineSpacing_(1.0)
        self.audio_packet_loss_graph.setAboveLimit_(3) # if higher than 3% show red color
        self.audio_packet_loss_graph.setLineColor_(NSColor.greenColor())
        self.audio_packet_loss_graph.setMinimumHeigth_(5)

        self.resetSession()
        self.updatePanelValues()
コード例 #46
0
ファイル: Task.py プロジェクト: mnabeelp/PyGUI
 def start(self):
     self.stop()
     #ns_timer = \
     #	NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
     #		self._interval, self._target, '_ns_fire', None, self._repeat)
     ns_timer = \
      NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
       self._interval, trigger, 'fire:', None, self._repeat)
     self._ns_timer = ns_timer
     ns_timer_to_task[ns_timer] = self
     ns_run_loop = NSRunLoop.currentRunLoop()
     ns_run_loop.addTimer_forMode_(ns_timer, NSDefaultRunLoopMode)
     ns_run_loop.addTimer_forMode_(ns_timer, NSEventTrackingRunLoopMode)
     ns_run_loop.addTimer_forMode_(ns_timer, NSModalPanelRunLoopMode)
コード例 #47
0
    def captureButtonClicked_(self, sender):
        if self.countdownCheckbox.state() == NSOnState:
            self.countdown_counter = 5
            self.previewButton.setHidden_(True)
            self.captureButton.setHidden_(True)
            self.countdownCheckbox.setHidden_(True)
            self.mirrorButton.setHidden_(True)
            self.countdownProgress.setHidden_(False)
            self.countdownProgress.startAnimation_(None)
            self.countdownProgress.setIndeterminate_(False)
            self.countdownProgress.setDoubleValue_(self.countdown_counter)

            self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
                1, self, "executeTimerCapture:", None, True)
            NSRunLoop.currentRunLoop().addTimer_forMode_(
                self.timer, NSModalPanelRunLoopMode)
            NSRunLoop.currentRunLoop().addTimer_forMode_(
                self.timer, NSDefaultRunLoopMode)
        else:
            self.countdownCheckbox.setHidden_(True)
            self.mirrorButton.setHidden_(True)
            self.countdownProgress.setHidden_(True)
            self.executeCapture()
コード例 #48
0
ファイル: Task.py プロジェクト: karlmatthew/pygtk-craigslist
 def start(self):
     self.stop()
     #ns_timer = \
     #	NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
     #		self._interval, self._target, '_ns_fire', None, self._repeat)
     ns_timer = \
         NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(
             self._interval, trigger, 'fire:', None, self._repeat)
     self._ns_timer = ns_timer
     ns_timer_to_task[ns_timer] = self
     ns_run_loop = NSRunLoop.currentRunLoop()
     ns_run_loop.addTimer_forMode_(
         ns_timer, NSDefaultRunLoopMode)
     ns_run_loop.addTimer_forMode_(
         ns_timer, NSEventTrackingRunLoopMode)
     ns_run_loop.addTimer_forMode_(
         ns_timer, NSModalPanelRunLoopMode)
コード例 #49
0
ファイル: AppHelper.py プロジェクト: BMXE/music-player
def runConsoleEventLoop(argv=None, installInterrupt=False, mode=NSDefaultRunLoopMode):
    if argv is None:
        argv = sys.argv
    if installInterrupt:
        installMachInterrupt()
    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
    PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)
    try:

        while stopper.shouldRun():
            nextfire = runLoop.limitDateForMode_(mode)
            if not stopper.shouldRun():
                break
            if not runLoop.runMode_beforeDate_(mode, nextfire):
                stopper.stop()

    finally:
        PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
コード例 #50
0
ファイル: AppHelper.py プロジェクト: ivanmolera/Raspberry
def runConsoleEventLoop(argv=None, installInterrupt=False, mode=NSDefaultRunLoopMode):
    if argv is None:
        argv = sys.argv
    if installInterrupt:
        installMachInterrupt()
    runLoop = NSRunLoop.currentRunLoop()
    stopper = PyObjCAppHelperRunLoopStopper.alloc().init()
    PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop)
    try:

        while stopper.shouldRun():
            nextfire = runLoop.limitDateForMode_(mode)
            if not stopper.shouldRun():
                break
            if not runLoop.runMode_beforeDate_(mode, nextfire):
                stopper.stop()

    finally:
        PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
コード例 #51
0
    def __init__(self):
        ds = SCDynamicStoreCreate(None, "foo", self.callback, self)
        self.delegate = SCDelegate.alloc().init()
#        ds.setDelegate_(self.delegate)
#        ds.addToCurrentRunLoop()
        self.runloop = NSRunLoop.currentRunLoop()
        
        dnspattern = u"State:/Network/global/DNS"
        pattern = r'State:/Network/Global/IPv[46]'
#        keys = list(ds.keyListForPattern_(pattern))
#        keys.extend(list(ds.keyListForPattern_(dnspattern)))
#        ds.notifyValuesForKeys_matchingPatterns_(None, [pattern, dnspattern])
        keys = []
        keys.append(dnspattern)
        keys.append(pattern)
        SCDynamicStoreSetNotificationKeys(ds, None, keys)
#        self.delegate.keysChanged_inDynamicStore_(keys, ds)
        for key in keys:
            print "Watching key " + str(key)
        self.ds = ds
コード例 #52
0
def search(path, searchValue):
    '''
    List records that match the given query.
    '''
    node = _get_node(path)

    if not node:
        log.error('Query not possible, cannot get reference to node at path: {}'.format(path))
        return None

    # @objc.callbackFor("CFOpenDirectory.ODQuerySetCallback")
    # def query_callback(query, value, context, error, info):
    #     log.warning('got callback')
    #     pass

    query, err = ODQuery.queryWithNode_forRecordTypes_attribute_matchType_queryValues_returnAttributes_maximumResults_error_(
        node,
        kODRecordTypeUsers,
        kODAttributeTypeRecordName,
        kODMatchContains,
        searchValue,
        kODAttributeTypeStandardOnly,
        0,
        None
    )

    if err:
        log.error('Failed to construct query: {}'.format(err))
        return None

    ODQueryDelegate = objc.protocolNamed('ODQueryDelegate')

    class QueryDelegate(NSObject, ODQueryDelegate):
        def query_foundResults_error_(self, inQuery, inResults, inError):
            log.error('FOUND RESULTS')

    qd = QueryDelegate()
    query.setDelegate_(qd)
    query.scheduleInRunLoop_forMode_(NSRunLoop.currentRunLoop(), NSDefaultRunLoopMode)
コード例 #53
0
ファイル: spotify.py プロジェクト: szhu/spotify-hax
def wait(time):
    from Foundation import NSDate
    from Foundation import NSRunLoop
    NSRunLoop.mainRunLoop().runBeforeDate_(NSDate.dateWithTimeIntervalSinceNow_(time))
コード例 #54
0
 def startDeallocTimer(self):
     # workaround to keep the object alive as cocoa still sends delegate tableview messages after close
     self.dealloc_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(2.0, self, "deallocTimer:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSRunLoopCommonModes)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.dealloc_timer, NSEventTrackingRunLoopMode)
コード例 #55
0
ファイル: spotify.py プロジェクト: szhu/spotify-hax
def loop():
    from Foundation import NSRunLoop
    NSRunLoop.mainRunLoop().run()
コード例 #56
0
ファイル: AlertPanel.py プロジェクト: bitsworking/blink-cocoa
 def startSpeechSynthesizerTimer(self):
     self.speech_synthesizer_timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(2, self, "startSpeaking:", None, False)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.speech_synthesizer_timer, NSRunLoopCommonModes)
     NSRunLoop.currentRunLoop().addTimer_forMode_(self.speech_synthesizer_timer, NSEventTrackingRunLoopMode)
コード例 #57
0
ファイル: AppHelper.py プロジェクト: BMXE/music-player
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)
コード例 #58
0
ファイル: cfreactor.py プロジェクト: jsober/twisted
 def getRunLoop(self, runLoop=None):
     if self.runLoop is None:
         self.nsRunLoop = runLoop or NSRunLoop.currentRunLoop()
         self.runLoop = cf.PyCFRunLoop(self.nsRunLoop.getCFRunLoop())
     return self.runLoop
コード例 #59
0
ファイル: AppHelper.py プロジェクト: BMXE/music-player
 def currentRunLoopStopper(cls):
     runLoop = NSRunLoop.currentRunLoop()
     return cls.singletons.get(runLoop)