def stop_event_loop(self): if self.notificationCenter: self.notificationCenter = None if self.blocking: AppHelper.stopEventLoop() if self.handler: self.handler = None
def init(): print "init ui cocoa" global browserwindow app = NSApplication.sharedApplication() app.setActivationPolicy_(1) start_taskbar() app.finishLaunching() _browserwindow = NSWindow.alloc() icon = NSImage.alloc().initByReferencingFile_(settings.mainicon) app.setApplicationIconImage_(icon) deleg = Delegate.alloc() deleg.init() app.setDelegate_(deleg) signal.signal(signal.SIGINT, mac_sigint) from .input import BrowserDelegate bd = BrowserDelegate.alloc() bd.init() browserwindow = draw_browser(_browserwindow, bd) from .... import ui ui.log.debug('using cocoa') atexit.register(exit) gevent_timer(deleg) ui.module_initialized.set() sys.exit = exit AppHelper.runEventLoop()
def main(): #NSLog(u"main()") serviceProvider = ServiceTest.alloc().init() #NSLog(u"serviceProvider = %s", serviceProvider) NSRegisterServicesProvider(serviceProvider, u"PyObjCSimpleService") #NSLog(u"registered as PyObjCSimpleService") AppHelper.runConsoleEventLoop()
def run(self, **options): """Performs various setup tasks including creating the underlying Objective-C application, starting the timers, and registering callback functions for click events. Then starts the application run loop. .. versionchanged:: 0.2.1 Accepts `debug` keyword argument. :param debug: determines if application should log information useful for debugging. Same effect as calling :func:`rumps.debug_mode`. """ dont_change = object() debug = options.get('debug', dont_change) if debug is not dont_change: debug_mode(debug) nsapplication = NSApplication.sharedApplication() nsapplication.activateIgnoringOtherApps_(True) # NSAlerts in front self._nsapp = NSApp.alloc().init() self._nsapp._app = self.__dict__ # allow for dynamic modification based on this App instance nsapplication.setDelegate_(self._nsapp) if _NOTIFICATIONS: NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self._nsapp) setattr(App, '*app_instance', self) # class level ref to running instance (for passing self to App subclasses) t = b = None for t in getattr(timer, '*timers', []): t.start() for b in getattr(clicked, '*buttons', []): b(self) # we waited on registering clicks so we could pass self to access _menu attribute del t, b self._nsapp.initializeStatusBar() AppHelper.runEventLoop()
def gui_main(): IEDLog.IEDLogToController = True IEDLog.IEDLogToSyslog = True IEDLog.IEDLogToStdOut = True IEDLog.IEDLogStdOutLogLevel = IEDLog.IEDLogLevelDebug logFile = os.path.join(get_log_dir(), u"AutoDMG-%s.log" % get_date_string()) try: IEDLog.IEDLogFileHandle = open(logFile, u"a", buffering=1) IEDLog.IEDLogToFile = True except IOError as e: IEDLog.IEDLogToFile = False LogWarning(u"Couldn't open %s for writing" % (logFile)) import AppKit from PyObjCTools import AppHelper # import modules containing classes required to start application and load MainMenu.nib import IEDAppDelegate import IEDController import IEDSourceSelector import IEDAddPkgController import IEDAppVersionController # pass control to AppKit AppHelper.runEventLoop(unexpectedErrorAlert=gui_unexpected_error_alert) return os.EX_OK
def start(self, pipe): self.pipe = pipe self.start_time = NSDate.date() app = NSApplication.sharedApplication() delegate = self.alloc().init() app.setDelegate_(delegate) AppHelper.runEventLoop()
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def trackChanged_iTunesTrack_(self, noteInfo, iTunesTrack): trackData = {"title": noteInfo["Name"]} if self.secretKey: trackData["key"] = self.secretKey if "Artist" in noteInfo: trackData["artist"] = noteInfo["Artist"] if "Album" in noteInfo: trackData["album"] = noteInfo["Album"] if "Store URL" in noteInfo: trackData["url"] = noteInfo["Store URL"] iTunesArtworks = iTunesTrack.artworks() if len(iTunesArtworks) >= 1: artwork = iTunesArtworks[0] artworkTIFF = artwork.data().TIFFRepresentation() artworkPNG = NSBitmapImageRep.imageRepWithData_(artworkTIFF).representationUsingType_properties_(NSPNGFileType, None) trackData["artpng"] = b64encode(artworkPNG.bytes()) try: urlopen(self.handlerURL, urlencode(trackData)) except URLError: description = (u"PostTunes encountered an error when attempting to post the track \"%s\" to your Handler URL." % trackData["title"]) NSLog(u"%s Handler URL: %s" % (description, self.handlerURL)) if self.warnFailure: alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_("PostTunes Could Not Post Track", "OK", "Configure PostTunes", "Quit PostTunes", description) alert.setAlertStyle_(NSCriticalAlertStyle) alert.setShowsSuppressionButton_(True) alertReturn = alert.runModal() if alert.suppressionButton().state() == NSOnState: self.warnFailure = False if alertReturn == NSAlertAlternateReturn: self.runConfigurationAlert_title_description_(None, (u"%s Please confirm your Handler URL." % description)) elif alertReturn == NSAlertOtherReturn: AppHelper.stopEventLoop()
def gotLine(observer, aLine): if aLine: print "you wrote:", aLine.rstrip() prompt() else: print "" AppHelper.stopEventLoop()
def openURL_withReplyEvent_(self, event, replyEvent): keyDirectObject = struct.unpack(">i", "----")[0] url = (event.paramDescriptorForKeyword_(keyDirectObject) .stringValue().decode('utf8')) show_in_host = False for exception in self.exception_list : url_re = re.compile(exception) ret = url_re.search(url) if ret: show_in_host = True break if show_in_host: #NSLog("EXCEPTION MATCHED, opening in host: %s"%(url)) ##Hardcode to open in a host broswer bypassing the default handler ret = subprocess.check_output(["open", "-b", self.host_browser, url]) else: #NSLog("Opening in guest: %s"%(url)) self.vmr(url) ##Kill ourselves so the proc doesn't continue to run for * AppHelper.stopEventLoop()
def main(): ##Kick off an app with the event handlers to deal with the GURL Apple events app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() delegate.dirty_init() app.setDelegate_(delegate) AppHelper.runEventLoop()
def run(self): NSApplication.sharedApplication() self.delegate = AppDelegate.alloc().init() self.delegate.event_sniffer = self NSApp().setDelegate_(self.delegate) self.workspace = NSWorkspace.sharedWorkspace() nc = self.workspace.notificationCenter() # This notification needs OS X v10.6 or later nc.addObserver_selector_name_object_( self.delegate, 'applicationActivated:', 'NSWorkspaceDidActivateApplicationNotification', None) nc.addObserver_selector_name_object_( self.delegate, 'screenSleep:', 'NSWorkspaceScreensDidSleepNotification', None) # I don't think we need to track when the screen comes awake, but in case # we do we can listen for NSWorkspaceScreensDidWakeNotification NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( self.options.active_window_time, self.delegate, 'writeActiveApp:', None, True) # Start the application. This doesn't return. AppHelper.runEventLoop()
def handler(self, event): try: activeApps = self.workspace.runningApplications() for app in activeApps: if app.isActive(): if app.localizedName() != self.currentApp: self.currentApp = app.localizedName() options = kCGWindowListOptionOnScreenOnly windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) for window in windowList: if window['kCGWindowOwnerName'] == self.currentApp: geom = window['kCGWindowBounds'] self.screen_hook( event=event, name = window['kCGWindowName'], owner = window['kCGWindowOwnerName'], x = geom['X'], y = geom['Y'], w = geom['Width'], h = geom['Height']) break break loc = NSEvent.mouseLocation() # mouse clicky buttons if event.type() in ( NSLeftMouseDown, NSRightMouseDown, NSLeftMouseUp, NSRightMouseUp): self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # mouse scrolly buttons elif event.type() == NSScrollWheel: if event.deltaY() > 0 and event.deltaY() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) if event.deltaX() > 0 and event.deltaX() < 0: self.mouse_button_hook(event=event, x=loc.x, y=loc.y) # keys down elif event.type() in ( NSKeyDown, NSKeyUp ): flags = event.modifierFlags() modifiers = [] # OS X api doesn't care it if is left or right if (flags & NSControlKeyMask): modifiers.append('CONTROL') if (flags & NSAlternateKeyMask): modifiers.append('ALTERNATE') if (flags & NSCommandKeyMask): modifiers.append('COMMAND') self.key_hook(event=event, key=event.keyCode(), char=keycode.tostring( event.keyCode() ), mods=modifiers, is_repeat=event.isARepeat()) # Mouse moved elif event.type() == NSMouseMoved: self.mouse_move_hook(event=event, x=loc.x, y=loc.y) else: pass except ( KeyboardInterrupt ) as e: print 'handler', e AppHelper.stopEventLoop()
def eol_flush(self): if self.queue: self.do_play() if self.playing: self.loop = True AppHelper.runConsoleEventLoop() self.loop = False
def run_mainloop_with(self, target): """Start the OS's main loop to process asyncronous BLE events and then run the specified target function in a background thread. Target function should be a function that takes no parameters and optionally return an integer response code. When the target function stops executing or returns with value then the main loop will be stopped and the program will exit with the returned code. Note that an OS main loop is required to process asyncronous BLE events and this function is provided as a convenience for writing simple tools and scripts that don't need to be full-blown GUI applications. If you are writing a GUI application that has a main loop (a GTK glib main loop on Linux, or a Cocoa main loop on OSX) then you don't need to call this function. """ # Create background thread to run user code. self._user_thread = threading.Thread(target=self._user_thread_main, args=(target,)) self._user_thread.daemon = True self._user_thread.start() # Run main loop. This call will never return! try: AppHelper.runConsoleEventLoop(installInterrupt=True) except KeyboardInterrupt: AppHelper.stopEventLoop() sys.exit(0)
def _runInMainThread(self, f): """ Schedule function to run in main cocoa/Twisted thread. Called by the select() thread. """ AppHelper.callAfter(f)
def applicationDidFinishLaunching_(self, aNotification): """ Create a toolbar and menu for the mac application that can be used to close shut down the application. """ self.statusItem = NSStatusBar\ .systemStatusBar()\ .statusItemWithLength_(NSVariableStatusItemLength) self.statusItem.setTitle_(u"M") self.statusItem.setHighlightMode_(TRUE) self.statusItem.setEnabled_(TRUE) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Quit", "terminate:", "") # ugly but... it provides the information. self.port = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Listening on localhost:{0}".format(_PORT), "", "") self.menubarMenu = NSMenu.alloc().init() self.menubarMenu.addItem_(self.port) self.menubarMenu.addItem_(self.quit) # add the menu to status bar item self.statusItem.setMenu_(self.menubarMenu) self.statusItem.setToolTip_(u"mimic - rackspace mock api") AppHelper.callLater(1, startMimic)
def __call__(self, *args, **kwargs): try: evt = kwargs.get('event') del kwargs['event'] items = [ x[0]+"="+unicode(x[1]) for x in kwargs.iteritems()] current_key = 0 items_len = len(items) if items_len >= 3: current_key = str(items[2]).strip("key=") # block out unwanted keys typed if self.__class__.__name__ == "KeyHooker": if current_key not in wanted_keys and items_len >= 3: items[0] = 'char=$$' items[2] = 'key=$$' # stop enter/return key from causing new line if current_key == '36': items[0] = 'char=$$' items = ' '.join(items) print "%s | %20s | %22s | %s" % ( datetime.datetime.now(), self.__class__.__name__, evtypes_rev[evt.type()], items) except Exception as e: print 'Horrific error!', e AppHelper.stopEventLoop() sys.exit(0)
def observerCallback(cls, element, contextData): axObj = contextData cb_fn = contextData.callbackFn cb_args = contextData.callbackArgs cb_kwargs = contextData.callbackKwargs if cb_fn is not None: retElem = cls.with_ref(element) if retElem is None: raise RuntimeError('Could not create new AX UI Element.') cb_args = (retElem,) + cb_args callbackRes = cb_fn(cb_args, cb_kwargs) if callbackRes is None: raise RuntimeError('Python callback failed.') if callbackRes in (-1, 1): AppHelper.stopEventLoop() temp = axObj.observerRes axObj.observerRes = callbackRes else: AppHelper.stopEventLoop() temp = axObj.observerRes axObj.observerRes = True
def _exportFrame(self): if self.session.next(): # step to the proper FRAME value self._meta.frame = self.session.next() # run the draw() function if it exists (or the whole top-level if not) result = self.run(method="draw" if self.animated else None) # let the delegate draw to the screen self.delegate.exportFrame(result, self.canvas) # pass the frame content to the file-writer if result.ok: self.session.add(self.canvas) # know when to fold 'em if result.ok in (False, 'HALTED'): self.session.cancel() # give the runloop a chance to collect events between frames AppHelper.callLater(0.001, self._exportFrame) else: # we've drawn the final frame in the export result = self.call("stop") self.delegate.exportFrame(result, canvas=None) self.session.done()
def _loop(self): request = WAIT if not self.isbusy and self._pipe.poll(): # Coreからのメッセージ取得 try: request = self._pipe.recv() except: pass if request == CONNECT: self.isbusy = True self._state = CONNECT self._timer = Timer(self._timeout_sec, self._timeout, args=["CONNECT"]) self._timer.start() self._ble_delegate.bleConnect(self.callback) elif request == DISCONNECT: self.isbusy = True self._state = DISCONNECT self._timer = Timer(self._timeout_sec, self._timeout, args=["DISCONNECT"]) self._timer.start() self._ble_delegate.bleDisconnect(self.callback) else: self.isbusy = True self._state = WRITE self._timer = Timer(self._timeout_sec, self._timeout, args=["WRITE"]) self._timer.start() self._ble_delegate.send(request, self.callback) AppHelper.callLater(0.1, self._loop)
def applicationDidFinishLaunching_(self, note): pth = self.opts["file"] if self.mode == "windowed": # load the viewer ui from the nib in plotdevice/rsrc nib = NSData.dataWithContentsOfFile_(rsrc_path("viewer.nib")) ui = NSNib.alloc().initWithNibData_bundle_(nib, None) ok, objs = ui.instantiateNibWithOwner_topLevelObjects_(self, None) NSApp().setMainMenu_(self.menu) # configure the window script-controller, and update-watcher self.script.setScript_options_(pth, self.opts) self.window.setTitleWithRepresentedFilename_(pth) # self.script.setWindowFrameAutosaveName_('plotdevice:%s'%self.opts['file']) # foreground the window (if -b wasn't passed) and run the script if opts["activate"]: NSApp().activateIgnoringOtherApps_(True) self.script.showWindow_(self) AppHelper.callAfter(self.script.scriptedRun) elif self.mode == "headless": # create a window-less WindowController self.script = ConsoleScript.alloc().init() self.script.setScript_options_(pth, self.opts) # BUG? FEATURE? (it's a mystery!) # exports will stall if `last` isn't an int. this should probably # be handled by the command line arg-parser though, no? if not opts.get("last", None): opts["last"] = opts.get("first", 1) # kick off an export session format = self.opts["export"].rsplit(".", 1)[1] kind = "movie" if format in ("mov", "gif") else "image" self.script.exportInit(kind, self.opts["export"], self.opts)
def handler(self, event): try: if event.type() == NSLeftMouseDown: self.mouse_button_hook(1, True) # elif event.type() == NSLeftMouseUp: # self.mouse_button_hook(1, False) elif event.type() == NSRightMouseDown: self.mouse_button_hook(2, True) # elif event.type() == NSRightMouseUp: # self.mouse_button_hook(2, False) elif event.type() == NSKeyDown: self.key_hook(event.keyCode(), None, event.characters(), True, event.isARepeat()) elif event.type() == NSMouseMoved: loc = NSEvent.mouseLocation() self.mouse_move_hook(loc.x, loc.y) if event.type() in [NSLeftMouseDown, NSRightMouseDown, NSMouseMoved]: windowNumber = event.windowNumber() windowList = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly, kCGNullWindowID) for window in windowList: if window['kCGWindowNumber'] == windowNumber: self.focus.wm_name = window['kCGWindowName'] self.fucus.app_name = window['kCGWindowOwnerName'] break except KeyboardInterrupt: AppHelper.stopEventLoop()
def notify(self, title, subtitle, text): """Create a user notification and display it.""" # if appImage: # source_img = AppKit.NSImage.alloc().initByReferencingFile_(appImage) # notification.set_identityImage_(source_img) # if contentImage: # source_img = AppKit.NSImage.alloc().initBy # notification.setContentImage_(source_img) notification = NSUserNotification.alloc().init() notification.setTitle_(str(title)) notification.setSubtitle_(str(subtitle)) notification.setInformativeText_(str(text)) notification.setSoundName_("NSUserNotificationDefaultSoundName") # notification.set_showsButtons_(True) # notification.setHasActionButton_(True) # notification.setHasReplyButton_ (True) # this will allow the user to enter text to "reply" # notification.setActionButtonTitle_("View") # notification.setUserInfo_({"action":"open_url", "value":url}) NSUserNotificationCenter.defaultUserNotificationCenter().setDelegate_(self) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_(notification) # Note that the notification center saves a *copy* of our object. AppHelper.runConsoleEventLoop()
def main(self): app = NSApplication.sharedApplication() self._controller.start() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) win = NSWindow.alloc() frame = ((200.0, 300.0), (250.0, 100.0)) win.initWithContentRect_styleMask_backing_defer_ (frame, 15, 2, 0) win.setTitle_ ('BinDownloader') win.setLevel_ (3) hel = NSButton.alloc().initWithFrame_ (((10.0, 10.0), (80.0, 80.0))) win.contentView().addSubview_ (hel) hel.setBezelStyle_( 4 ) hel.setTitle_( 'Hello!' ) hel.setTarget_( app.delegate() ) hel.setAction_( "sayHello:" ) win.display() win.orderFrontRegardless() AppHelper.runEventLoop()
def about(self, sender): #rumps.alert("My quit message") if self.apiServer: self.apiServer.shutdown() AppHelper.stopEventLoop() rumps.quit_application() sys.exit()
def run(self): osxVersion, _, _ = platform.mac_ver() majorVersion = int(osxVersion.split(".")[0]) minorVersion = int(osxVersion.split(".")[1]) logging.debug("major: %s; minor: %s", majorVersion, minorVersion) app = NSApplication.sharedApplication() guiApp = GuiApplicationOSX.alloc().init() app.setDelegate_(guiApp) guiApp.setMembers(self.executable, self.iconPath) messenger = None # OSX 10.8 and greater has a built-in notification system we can take advantage of if minorVersion >= 8: messenger = MessengerOSXMountainLion.alloc().init() else: messenger = MessengerOSXLegacy.alloc().init() # Multiple inheritance not working with NSObject?? messenger.setMembers(self.notificationTimeout, MESSAGE_TITLE) self.initialize(messenger, guiApp) AppHelper.runEventLoop()
def invalidate_size_request(self): # don't figure out the size immediately, this could lead to weirdness # and could be inefficent if we do something else to invalidate the # size request in the current event. if not self._will_invalidate_size_request: AppHelper.callAfter(self._invalidate_size_request) self._will_invalidate_size_request = True
def run(self): # set up the application self.app = NSApplication.sharedApplication() self.delegate = self.createAppDelegate().alloc().init() self.delegate.activity_tracker = self.activity_tracker self.app.setDelegate_(self.delegate) self.app.setActivationPolicy_(NSApplicationActivationPolicyAccessory) self.workspace = NSWorkspace.sharedWorkspace() # start listeners for event recorders self.cr = ClickRecorder(self) self.cr.start_click_listener() self.kr = KeyRecorder(self) self.kr.start_key_listener() self.mr = MoveRecorder(self) self.mr.start_move_listener() self.sr = ScrollRecorder(self) self.sr.start_scroll_listener() self.clr = ClipboardRecorder(self) # AppRecorder starts accessibility listeners that need to be on a # separate thread self.ar = AppRecorder(self) self.art = threading.Thread(target=self.ar.start_app_observers) self.art.start() #TODO add file system tracking # https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/UsingtheFSEventsFramework/UsingtheFSEventsFramework.html # run the Traces application AppHelper.runEventLoop()
def load_html(self, content, base_uri): def load(content, url): url = Foundation.NSURL.URLWithString_(BrowserView.quote(url)) self.webkit.loadHTMLString_baseURL_(content, url) self.loaded.clear() AppHelper.callAfter(load, content, base_uri)
def handler(signal, frame): log.debug("Got signal termination") release_lock() AppHelper.stopEventLoop() os._exit(1)
def handler(self, event): try: check_windows = False event_type = event.type() todo = lambda: None if ( time.time() - self.last_check_windows > FORCE_SCREEN_CHANGE and event_type != NSKeyUp ): self.last_check_windows = time.time() check_windows = True loc = NSEvent.mouseLocation() if event_type == NSLeftMouseDown: check_windows = True todo = lambda: self.mouse_button_hook(1, loc.x, loc.y) elif event_type == NSRightMouseDown: check_windows = True todo = lambda: self.mouse_button_hook(3, loc.x, loc.y) elif event_type == NSScrollWheel: if event.deltaY() > 0: todo = lambda: self.mouse_button_hook(4, loc.x, loc.y) elif event.deltaY() < 0: todo = lambda: self.mouse_button_hook(5, loc.x, loc.y) if event.deltaX() > 0: todo = lambda: self.mouse_button_hook(6, loc.x, loc.y) elif event.deltaX() < 0: todo = lambda: self.mouse_button_hook(7, loc.x, loc.y) elif event_type == NSKeyDown: flags = event.modifierFlags() modifiers = [] # OS X api doesn't care it if is left or right if flags & NSControlKeyMask: modifiers.append('Ctrl') if flags & NSAlternateKeyMask: modifiers.append('Alt') if flags & NSCommandKeyMask: modifiers.append('Cmd') if flags & (NSShiftKeyMask | NSAlphaShiftKeyMask): modifiers.append('Shift') character = event.charactersIgnoringModifiers() # these two get a special case because I am unsure of # their unicode value if event.keyCode() == 36: character = "Enter" elif event.keyCode() == 51: character = "Backspace" todo = lambda: self.key_hook(event.keyCode(), modifiers, keycodes.get(character, character), event.isARepeat()) elif event_type == NSMouseMoved: todo = lambda: self.mouse_move_hook(loc.x, loc.y) elif event_type == NSFlagsChanged: # Register leaving this window after animations are done # approx (1 second) self.last_check_windows = (time.time() - FORCE_SCREEN_CHANGE + WAIT_ANIMATION) check_windows = True if check_windows: activeApps = self.workspace.runningApplications() for app in activeApps: if app.isActive(): app_name = app.localizedName() options = kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements windowList = CGWindowListCopyWindowInfo(options, kCGNullWindowID) windowListLowPrio = [ w for w in windowList if w['kCGWindowLayer'] or not w.get('kCGWindowName', u'') ] windowList = [ w for w in windowList if not w['kCGWindowLayer'] and w.get('kCGWindowName', u'') ] windowList = windowList + windowListLowPrio for window in windowList: if window['kCGWindowOwnerName'] == app_name: geometry = window['kCGWindowBounds'] self.screen_hook(window['kCGWindowOwnerName'], window.get('kCGWindowName', u''), geometry['X'], geometry['Y'], geometry['Width'], geometry['Height']) break break todo() except (SystemExit, KeyboardInterrupt): AppHelper.stopEventLoop() return except: AppHelper.stopEventLoop() raise
pass delegate = SessionDelegate.alloc().init() if hasattr(SUSession, 'initWithProducts_options_delegate_'): # Mac OS X 10.8 session = SUSession.alloc().initWithProducts_options_delegate_( products, 0, delegate) elif hasattr(SUSession, 'initWithProducts_downloadDirectory_options_delegate_' ): # Mac OS X 10.6 session = SUSession.alloc( ).initWithProducts_downloadDirectory_options_delegate_( products, '/Library/Updates', 0, delegate) else: raise Exception("SUSession.initWithProducts_ not found") session.start() AppHelper.runConsoleEventLoop(installInterrupt=True) #while True: # print session.doesInstall(), session.didFail(), session.sessionDidBegin() # print session._estimatedTimeRemainingForCurrentState(), session._currentAverageBytesPerSecond() # time.sleep(2) #sessionimpl = SUSessionImpl.alloc().init() #sessionimpl.installAllProductsSync_(products) #while True: # time.sleep(2) #if sessionimpl.didFail() != 0: # raise Exception("Installation failed: %s" % sessionimpl.combinedErrorMessage()) time.sleep(2) installlog_stop = True
def doBadThingsNow_(self, aTimer): AppHelper.stopEventLoop() raise ValueError, "doing bad things"
#!/usr/bin/env python """ This script shows how to use PyObjCTools.Debugging to show a dump of all (Cocoa) exceptions (handled and unhandled). """ from PyObjCTools import AppHelper from PyObjCTools import Debugging from Foundation import * class FooTester(NSObject): def doBadThingsNow_(self, aTimer): AppHelper.stopEventLoop() raise ValueError, "doing bad things" foo = FooTester.alloc().init() NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, foo, 'doBadThingsNow:', None, False ) # we need to catch everything, because NSTimer handles this one Debugging.installVerboseExceptionHandler() AppHelper.runConsoleEventLoop()
def liveNotification_(self, note): if note.name() == PHOTOKIT_NOTIFICATION_FINISHED_REQUEST: AppHelper.stopEventLoop()
def main(): app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
def handler(event): try: activeApps = NSWorkspace.sharedWorkspace().runningApplications() for app in activeApps: if app.isActive() and app.localizedName() != "Google Chrome": return if event.type() == NSKeyDown and keycode.tostring( event.keyCode()) in string.printable: if event.keyCode() == 48: global delay sp.capture(region=region) currPiece = getPiece( sp.pixel(topLeftCenterx + 4 * squareWidth, topLeftCentery)) holdPiece = None isFirstHold = True while (1): colHeights = [0 for i in range(10)] grid = [[0 for i in range(23)] for i in range(10)] for i in range(10): centerx = topLeftCenterx + i * squareWidth for j in range(1, 20): centery = topLeftCentery + j * squareWidth if (not (isEmpty(sp.pixel(centerx, centery)))): grid[i][19 - j] = True if colHeights[i] == 0: colHeights[i] = 20 - j nextPiece = getPiece(sp.pixel(nextBoxx, nextBoxy)) if isFirstHold: holdPiece = nextPiece currMovementInfo = calculateBestPlacement( currPiece, nextPiece, colHeights) holdMovementInfo = None if isFirstHold: holdMovementInfo = calculateBestPlacement( holdPiece, None, colHeights) else: holdMovementInfo = calculateBestPlacement( holdPiece, nextPiece, colHeights) if currMovementInfo[2] <= holdMovementInfo[2]: placePiece(currPiece, currMovementInfo[0], currMovementInfo[1], colHeights, grid) executeMovement(currPiece, currMovementInfo[0], currMovementInfo[1]) else: pressNTimes("c", 1) if isFirstHold: sleep(0.07) sp.capture(region=region) nextPiece = getPiece(sp.pixel(nextBoxx, nextBoxy)) isFirstHold = False placePiece(holdPiece, holdMovementInfo[0], holdMovementInfo[1], colHeights, grid) executeMovement(holdPiece, holdMovementInfo[0], holdMovementInfo[1]) holdPiece = currPiece if lineCleared(grid): sleep(0.3) else: sleep(0.07) sp.capture(region=region) currPiece = nextPiece except (KeyboardInterrupt) as e: print 'Ending', e AppHelper.stopEventLoop()
self.p_interacting = v def isAutoScroll(self): return self.p_autoScroll def setAutoScroll_(self, v): self.p_autoScroll = v def characterIndexForInput(self): return self.p_characterIndexForInput def setCharacterIndexForInput_(self, idx): self.p_characterIndexForInput = idx self.moveAndScrollToIndex_(idx) def historyView(self): return self.p_historyView def setHistoryView_(self, v): self.p_historyView = v def singleLineInteraction(self): return self.p_singleLineInteraction def setSingleLineInteraction_(self, v): self.p_singleLineInteraction = v if __name__ == '__main__': AppHelper.runEventLoop(installInterrupt=True)
def cancel(self): AppHelper.stopEventLoop()
def stop(self): if self.event_loop_started: self.event_loop_started = False import PyObjCTools.AppHelper as AppHelper #@UnresolvedImport AppHelper.stopEventLoop()
def shutdownGuiEnvironment(): if sys.platform == 'darwin': from PyObjCTools import AppHelper AppHelper.stopEventLoop()
def move(x, y, uid): AppHelper.callAfter(BrowserView.instances[uid].move, x, y)
def main(): clientsocket.connect(('localhost', 8089)) app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
def create_file_dialog(self, dialog_type, directory, allow_multiple, save_filename, file_filter, main_thread=False): def create_dialog(*args): dialog_type = args[0] if dialog_type == SAVE_DIALOG: save_filename = args[2] save_dlg = AppKit.NSSavePanel.savePanel() save_dlg.setTitle_(localization['global.saveFile']) if directory: # set initial directory save_dlg.setDirectoryURL_( Foundation.NSURL.fileURLWithPath_(directory)) if save_filename: # set file name save_dlg.setNameFieldStringValue_(save_filename) if save_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: self._file_name = save_dlg.filename() else: self._file_name = None else: allow_multiple = args[1] open_dlg = AppKit.NSOpenPanel.openPanel() # Enable the selection of files in the dialog. open_dlg.setCanChooseFiles_(dialog_type != FOLDER_DIALOG) # Enable the selection of directories in the dialog. open_dlg.setCanChooseDirectories_(dialog_type == FOLDER_DIALOG) # Enable / disable multiple selection open_dlg.setAllowsMultipleSelection_(allow_multiple) # Set allowed file extensions if file_filter: open_dlg.setAllowedFileTypes_(file_filter[0][1]) # Add a menu to choose between multiple file filters if len(file_filter) > 1: filter_chooser = BrowserView.FileFilterChooser.alloc( ).initWithFilter_(file_filter) open_dlg.setAccessoryView_(filter_chooser) open_dlg.setAccessoryViewDisclosed_(True) if directory: # set initial directory open_dlg.setDirectoryURL_( Foundation.NSURL.fileURLWithPath_(directory)) if open_dlg.runModal() == AppKit.NSFileHandlingPanelOKButton: files = open_dlg.filenames() self._file_name = tuple(files) else: self._file_name = None if not main_thread: self._file_name_semaphore.release() if main_thread: create_dialog(dialog_type, allow_multiple, save_filename) else: AppHelper.callAfter(create_dialog, dialog_type, allow_multiple, save_filename) self._file_name_semaphore.acquire() return self._file_name
def run(self): #this is for running standalone log("starting console event loop") self.event_loop_started = True import PyObjCTools.AppHelper as AppHelper #@UnresolvedImport AppHelper.runConsoleEventLoop(installInterrupt=True)
def destroy(self): AppHelper.callAfter(self.window.close)
def set_on_top(uid, top): def _set_on_top(): level = AppKit.NSStatusWindowLevel if top else AppKit.NSNormalWindowLevel BrowserView.instances[uid].window.setLevel_(level) AppHelper.callAfter(_set_on_top)
def show(self): def _show(): self.window.makeKeyAndOrderFront_(self.window) AppHelper.callAfter(_show)
def set_title(self, title): def _set_title(): self.window.setTitle_(title) AppHelper.callAfter(_set_title)
def startLoop(self): NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, self, 'onPumpFirst:', None, False) AppHelper.runConsoleEventLoop()
def hide(self): def _hide(): self.window.orderOut_(self.window) AppHelper.callAfter(_hide)
def main(): app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.callLater(_BUCKET_SIZE_SECONDS, record) AppHelper.runEventLoop()
def endLoop(self): AppHelper.stopEventLoop()
def show_alert(title, body): AppHelper.callAfter(showAlert_, title, body)
def serve_forever(): app = NSApplication.sharedApplication() delegate = MacTrayObject.alloc().init() app.setDelegate_(delegate) AppHelper.runEventLoop()
""" Display the useful contents of /var/db/dhcpd_leases This lets you see what IP addresses are leased out when using Internet Connection Sharing """ from PyObjCTools import AppHelper # import classes required to start application import TableModelAppDelegate # start the event loop AppHelper.runEventLoop(argv=[], installInterrupt=False)
def runLoopAndExit(): AppHelper.stopEventLoop()
self.model_name = re.findall( r'.starts: \*/\nvoid (.*)_InitializeIO().*', self.file_content, re.S)[0][0] def get_all_outputs(self): # return all inputs on this file f_read = open(self.input_file, 'r') input_events_string = re.findall( r'.GetInputSignals\(.*events != NULL(.*)input_fv != NULL.*', f_read.read(), re.S) inputs = re.findall(r'events->(.*) \*\/', input_events_string[0]) f_read.close() return inputs if __name__ == "__main__": app = NSApplication.sharedApplication() # Initiate the contrller with a XIB viewController = MainController.alloc().initWithWindowNibName_("Main") # Show the window viewController.showWindow_(viewController) # Bring app to top NSApp.activateIgnoringOtherApps_(True) from PyObjCTools import AppHelper AppHelper.runEventLoop()
class Capture(NSObject): def __new__(cls, device): return cls.alloc().initWithDevice_(device) def initWithDevice_(self, device): self = self.init() self.state = CaptureState.DETACHED self.device = device self._delegate = None self.session = None self.script = None self.modules = Modules() self.recvTotal = 0 self.calls = Calls(self) return self def delegate(self): return self._delegate def setDelegate_(self, delegate): self._delegate = delegate def attachToProcess_triggerPort_(self, process, triggerPort): assert self.state == CaptureState.DETACHED self._updateState_(CaptureState.ATTACHING) NSThread.detachNewThreadSelector_toTarget_withObject_( '_doAttachWithParams:', self, (process.pid, triggerPort)) def detach(self): assert self.state == CaptureState.ATTACHED session = self.session script = self.script self.session = None self.script = None self._updateState_(CaptureState.DETACHED) NSThread.detachNewThreadSelector_toTarget_withObject_( '_doDetachWithParams:', self, (session, script)) def _post(self, message): NSThread.detachNewThreadSelector_toTarget_withObject_( '_doPostWithParams:', self, (self.script, message)) def _updateState_(self, newState): self.state = newState self._delegate.captureStateDidChange() def _doAttachWithParams_(self, params): pid, triggerPort = params pool = NSAutoreleasePool.alloc().init() session = None script = None error = None try: session = self.device.attach(pid) session.on('detached', self._onSessionDetached) script = session.session.create_script( SCRIPT_TEMPLATE % {'trigger_port': triggerPort}) script.on('message', self._onScriptMessage) script.load() except Exception, e: if session is not None: try: session.detach() except: pass session = None script = None error = e AppHelper.callAfter(self._attachDidCompleteWithSession_script_error_, session, script, error) del pool