def startupOKAction_(self, btn): """ User clicked OK in the server setup sheet. """ # Create the actual session. server = self.serverText.stringValue() path = self.pathText.stringValue() user = self.userText.stringValue() pswd = self.passwordText.stringValue() self.session = Session(server, path, user, pswd, logging=False) self.window.setTitle_(self.serverText.stringValue()) self.pathLabel.setStringValue_(self.session.path) NSUserDefaults.standardUserDefaults().setObject_forKey_(server, "LastServer") NSUserDefaults.standardUserDefaults().setObject_forKey_(path, "LastPath") NSUserDefaults.standardUserDefaults().setObject_forKey_(user, "LastUser") # List the root resource. self.progress.startAnimation_(self) resources = self.session.getRoot().listChildren() self.progress.stopAnimation_(self) self.columns = [resources] # Done with the sheet. self.startupSheet.close() NSApplication.sharedApplication().endSheet_(self.startupSheet) # Force reload of browser pane views. self.browser.loadColumnZero() self.list.reloadItem_(None)
def resize_image(source_img, dimensions, method = ResizeMethod.FIT): assert source_img NSApplication.sharedApplication() initial_width = float(dimensions[0]) initial_height = float(dimensions[1]) width = source_img.bestRepresentationForDevice_(None).pixelsWide() height = source_img.bestRepresentationForDevice_(None).pixelsHigh() pixel_size = NSMakeSize(width, height) orig_size = source_img.size() width_ratio = initial_width / pixel_size[0] height_ratio = initial_height / pixel_size[1] if method == ResizeMethod.FIT: width_ratio = min(width_ratio, height_ratio) height_ratio = min(width_ratio, height_ratio) if method == ResizeMethod.CROP: width_ratio = max(width_ratio, height_ratio) height_ratio = max(width_ratio, height_ratio) resized_width = width * width_ratio resized_height = height * height_ratio crop_width = orig_size.width crop_height = orig_size.height if method is ResizeMethod.CROP: crop_width = initial_width / resized_width * orig_size.width crop_height = initial_height / resized_height * orig_size.height final_width = min(resized_width, initial_width) final_height = min(resized_height, initial_height) target_img = NSImage.alloc().initWithSize_(NSMakeSize(final_width, final_height)) target_img.lockFocus() TRACE('Resized image sizes W=%r, H=%r', final_width, final_height) source_img.drawInRect_fromRect_operation_fraction_(NSMakeRect(0, 0, final_width, final_height), NSMakeRect((orig_size.width - crop_width) / 2, (orig_size.height - crop_height) / 2, crop_width, crop_height), NSCompositeSourceOver, 1.0) target_img.unlockFocus() return target_img
def interruptwait(): """ If waituntil() has been called, this will interrupt the waiting process so it can check whether it should stop waiting. """ evt = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(NSApplicationDefined, NSPoint(), NSApplicationDefined, 0, 1, None, LIGHTBLUE_NOTIFY_ID, 0, 0) NSApplication.sharedApplication().postEvent_atStart_(evt, True)
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() 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 resetServer_(self, sender): """ Display the sheet asking for server details. """ NSApplication.sharedApplication().beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_( self.startupSheet, self.window, None, None, 0 )
def __init__(self): # Force NSApp initialisation. NSApplication.sharedApplication().activateIgnoringOtherApps_(0) self.namespace = {} self.canvas = graphics.Canvas() self.context = graphics.Context(self.canvas, self.namespace) self.__doc__ = {} self._pageNumber = 1 self.frame = 1
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() def handler(signal, frame): AppHelper.stopEventLoop() signal.signal(signal.SIGINT, handler) AppHelper.runEventLoop()
def log_std(msg): from AppKit import NSAlert, NSInformationalAlertStyle, NSRunningApplication, NSApplicationActivateIgnoringOtherApps # initialize # tip from: http://graphicsnotes.blogspot.fr/2010/01/programmatically-creating-window-in-mac.html NSApplication.sharedApplication() NSRunningApplication.currentApplication().activateWithOptions_(NSApplicationActivateIgnoringOtherApps); alert = NSAlert.alloc().init() alert.autorelease() alert.setAlertStyle_(NSInformationalAlertStyle) alert.setMessageText_(msg) alert.runModal()
def start(self): # Load today's count data back from data file super(KeyCounter, self).start() NSApplication.sharedApplication() self.delegate = self._create_app_delegate().alloc().init() NSApp().setDelegate_(self.delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) signal.signal(signal.SIGINT, self.stop) signal.signal(signal.SIGTERM, self.stop) self._check_for_access() self.delegate.initializeStatusBar() AppHelper.runEventLoop()
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 inject(self): try: # necessary because of the menu callbacks self.retain() # get application menu instance appmenu = NSApplication.sharedApplication().mainMenu().itemAtIndex_(0).submenu() # make a new menu item self.item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "QuoteFix", "toggleState:", "") self.item.setToolTip_(self.get_string("QUOTEFIX_TOOLTIP", "")) self.set_state_and_title(self.item) self.item.setTarget_(self) # add separator and new item appmenu.insertItem_atIndex_(NSMenuItem.separatorItem(), 1) appmenu.insertItem_atIndex_(self.item, 2) # observe changes for active state NSUserDefaultsController.sharedUserDefaultsController().addObserver_forKeyPath_options_context_( self, "values.QuoteFixDisabled", NSKeyValueObservingOptionNew, None ) except Exception, e: raise e
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()
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, **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 selectGlyphsWithErrors(self): """ Selects all glyphs with errors in the active layer """ font = NSApplication.sharedApplication().font if font is None: return None options, run_tests = self.selectGlyphsOptions() if run_tests is None: return if options is None: return font.disableUpdateInterface() mid = font.selectedFontMaster.id self.options["grid_length"] = font.gridLength glyphlist = font.glyphs.keys() outline_test_pen = OutlineTestPen(font, options, run_tests) for glyph_name in glyphlist: glyph = font.glyphs[glyph_name] layer = glyph.layers[mid] outline_test_pen.errors = [] if layer is not None: try: layer.drawPoints(outline_test_pen) if len(outline_test_pen.errors) > 0: glyph.selected = True else: glyph.selected = False except Exception as e: self.logToConsole( "selectGlyphsWithErrors: Layer '%s': %s" % (glyph_name, str(e)) ) font.enableUpdateInterface()
def generateStylesheets(url): delegate = AppDelegate.alloc().init() delegate.url = url app = NSApplication.sharedApplication() app.setDelegate_(delegate) app.run()
def _setup_ui_dialogs(self): # This needs to be here otherwise we can't install the dialog if 'STOQ_TEST_MODE' in os.environ: return log.debug('providing graphical notification dialogs') from stoqlib.gui.base.dialogs import DialogSystemNotifier from stoqlib.lib.interfaces import ISystemNotifier from kiwi.component import provide_utility provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True) import gtk from kiwi.environ import environ from kiwi.ui.pixbufutils import pixbuf_from_string data = environ.get_resource_string( 'stoq', 'pixmaps', 'stoq-stock-app-24x24.png') gtk.window_set_default_icon(pixbuf_from_string(data)) if platform.system() == 'Darwin': from AppKit import NSApplication, NSData, NSImage bytes = environ.get_resource_string( 'stoq', 'pixmaps', 'stoq-stock-app-48x48.png') data = NSData.alloc().initWithBytes_length_(bytes, len(bytes)) icon = NSImage.alloc().initWithData_(data) app = NSApplication.sharedApplication() app.setApplicationIconImage_(icon)
def _nestedRunLoopReaderUntilEOLchars_(self, eolchars): """ This makes the baby jesus cry. I want co-routines. """ app = NSApplication.sharedApplication() window = self.textView.window() self.setCharacterIndexForInput_(self.lengthOfTextView()) # change the color.. eh self.textView.setTypingAttributes_( {NSFontAttributeName: self.font(), NSForegroundColorAttributeName: self.codeColor()} ) while True: event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSUIntegerMax, NSDate.distantFuture(), NSDefaultRunLoopMode, True ) if (event.type() == NSKeyDown) and (event.window() == window): eol = event.characters() if eol in eolchars: break app.sendEvent_(event) cl = self.currentLine() if eol == "\r": self.writeCode_("\n") return cl + eol
def initialize(cls): # Register ourselves as a Mail.app plugin and add an entry for our # 'Fill Text' and Wrap Text' actions to the Edit menu. application = NSApplication.sharedApplication() bundle = NSBundle.bundleWithIdentifier_('uk.me.cdw.MailWrap') cls.registerBundle() editmenu = application.mainMenu().itemAtIndex_(2).submenu() editmenu.addItem_(NSMenuItem.separatorItem()) mask = NSCommandKeyMask | NSAlternateKeyMask editmenu.addItemWithTitle_action_keyEquivalent_('Fill Text', 'fillText', '\\').setKeyEquivalentModifierMask_(mask) mask = NSCommandKeyMask editmenu.addItemWithTitle_action_keyEquivalent_('Wrap Text', 'wrapText', "\\").setKeyEquivalentModifierMask_(mask) # Read our configuration settings if present. Otherwise, set the # correct default values. defaults = NSUserDefaults.standardUserDefaults() defaults = defaults.dictionaryForKey_('MailWrap') or {} ComposeViewController._fixAttribution = defaults.get('FixAttribution', False) EditingMessageWebView._bulletLists = defaults.get('BulletLists', True) EditingMessageWebView._indentWidth = int(defaults.get('IndentWidth', 2)) EditingMessageWebView._wrapWidth = int(defaults.get('WrapWidth', 72)) # Report the plugin name and version to the com.apple.mail log. version = bundle.objectForInfoDictionaryKey_('CFBundleVersion') NSLog('Loaded MailWrap %s' % version)
def initWithApp_(self, app): self = super(Menu, self).init() if self is None: return None self.app = app self.mainwindow = NSApplication.sharedApplication().mainWindow() self.bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix') return self
def test(): import sys sys.path.insert(0, '../..') from nodebox.graphics import Canvas, Context from math import sin NSApplication.sharedApplication().activateIgnoringOtherApps_(0) w, h = 500, 300 m = Movie("xx3.mov") for i in range(200): print "Frame", i ctx = Context() ctx.size(w, h) ctx.rect(100.0+sin(i/10.0)*100.0,i/2.0,100,100) ctx.text(i, 0, 200) m.add(ctx) m.save()
def withoutUpdateDialog_(self, notification): app = NSApplication.sharedApplication() message = "There is no updated version of MyCube Vault yet. Try again next time." alertPanel = NSGetAlertPanel("MyCube Vault", message, "Close", None, None) alertPanel.setFloatingPanel_(True) self.displayed = True app.runModalForWindow_(alertPanel) NSReleaseAlertPanel(alertPanel)
def main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def notify(title, message, bring_up=False): print title, message try: notification.notify(title, message) if system == 'Darwin': from AppKit import NSApp, NSApplication NSApplication.sharedApplication() app = NSApp() app.requestUserAttention_(0) # this should bounce the icon # the 0 should be replaced by the NSRequestUserAttentionType.NSCriticalRequest # imported from NSApplication? TODO # https://developer.apple.com/library/mac/documentation/Cocoa/Reference/ApplicationKit/Classes/NSApplication_Class/Reference/Reference.html#//apple_ref/doc/c_ref/NSRequestUserAttentionType if bring_up: app.activateIgnoringOtherApps_(True) # this should bring the app to the foreground except Exception as e: print e Logger.exception('Notification error:\n%s' % e)
def setup_event_listener(self): log("setup_event_listener()") if NSObject is object: log.warn("NSObject is missing, not setting up OSX event listener") return self.shared_app = None self.delegate = None from AppKit import NSApplication, NSWorkspace, NSWorkspaceWillSleepNotification, NSWorkspaceDidWakeNotification #@UnresolvedImport import objc #@UnresolvedImport self.shared_app = NSApplication.sharedApplication() class Delegate(NSObject): def applicationDidFinishLaunching_(self, notification): log("applicationDidFinishLaunching_(%s)", notification) if SLEEP_HANDLER: self.register_sleep_handlers() def register_sleep_handlers(self): log("register_sleep_handlers()") workspace = NSWorkspace.sharedWorkspace() notificationCenter = workspace.notificationCenter() notificationCenter.addObserver_selector_name_object_(self, self.receiveSleepNotification_, NSWorkspaceWillSleepNotification, None) notificationCenter.addObserver_selector_name_object_(self, self.receiveWakeNotification_, NSWorkspaceDidWakeNotification, None) @objc.signature('B@:#B') def applicationShouldHandleReopen_hasVisibleWindows_(self, ns_app, flag): log("applicationShouldHandleReopen_hasVisibleWindows%s", (ns_app, flag)) self.cb("deiconify_callback") return True def receiveSleepNotification_(self, aNotification): log("receiveSleepNotification_(%s) sleep_callback=%s", aNotification, self.sleep_callback) self.cb("sleep_callback") def receiveWakeNotification_(self, aNotification): log("receiveWakeNotification_(%s)", aNotification) self.cb("wake_callback") def cb(self, name): #find the named callback and call it callback = getattr(self, name, None) log("cb(%s)=%s", name, callback) if callback: try: callback() except: log.error("Error in %s callback %s", name, callback, exc_info=True) self.delegate = Delegate.alloc().init() self.delegate.retain() if self.client: self.delegate.sleep_callback = self.client.suspend self.delegate.wake_callback = self.client.resume self.delegate.deiconify_callback = self.client.deiconify_windows self.shared_app.setDelegate_(self.delegate) log("setup_event_listener() the application delegate has been registered")
def register(self, root, keycode, modifiers): self.root = root self.keycode = keycode self.modifiers = modifiers self.activated = False if keycode: if not self.observer: self.root.after_idle(self._observe) self.root.after(HotkeyMgr.POLL, self._poll) # Monkey-patch tk (tkMacOSXKeyEvent.c) if not self.tkProcessKeyEvent_old: sel = 'tkProcessKeyEvent:' cls = NSApplication.sharedApplication().class__() self.tkProcessKeyEvent_old = NSApplication.sharedApplication().methodForSelector_(sel) newmethod = objc.selector(self.tkProcessKeyEvent, selector = self.tkProcessKeyEvent_old.selector, signature = self.tkProcessKeyEvent_old.signature) objc.classAddMethod(cls, sel, newmethod)
def looponce(): app = NSApplication.sharedApplication() # to push the run loops I seem to have to do this twice # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode? for i in range(2): event = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02), NSDefaultRunLoopMode, False)
def main(): print("Launching keylogger…") global __client args = parser.parse_args() __client = SimpleClient(args.host, args.port) app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
def drawTextSheetCancel_(self, sender): _win = sender.window() _app = NSApplication.sharedApplication() _app.endSheet_(_win) _win.orderOut_(_win) _textview = _win.initialFirstResponder() if not isinstance(_textview, NSTextView): return _textview.setString_("")
def _main_setup_osx(window): from AppKit import NSObject, NSApplication import objc try: import gi gi.require_version('GtkosxApplication', '1.0') from gi.repository import GtkosxApplication except (ValueError, ImportError): print_d("importing GtkosxApplication failed, no native menus") else: osx_app = GtkosxApplication.Application() window.set_as_osx_window(osx_app) osx_app.ready() shared_app = NSApplication.sharedApplication() gtk_delegate = shared_app.delegate() # Instead of quitting when the main window gets closed just hide it. # If the dock icon gets clicked we get # applicationShouldHandleReopen_hasVisibleWindows_ and show everything. class Delegate(NSObject): @objc.signature(b'B@:#B') def applicationShouldHandleReopen_hasVisibleWindows_( self, ns_app, flag): print_d("osx: handle reopen") app.present() return True def applicationShouldTerminate_(self, sender): print_d("osx: block termination") # FIXME: figure out why idle_add is needed here from gi.repository import GLib GLib.idle_add(app.quit) return False def applicationDockMenu_(self, sender): return gtk_delegate.applicationDockMenu_(sender) def application_openFile_(self, sender, filename): return app.window.open_file(filename.encode("utf-8")) delegate = Delegate.alloc().init() delegate.retain() shared_app.setDelegate_(delegate) # QL shouldn't exit on window close, EF should if window.get_is_persistent(): window.connect("delete-event", lambda window, event: window.hide() or True)
def addMenuItem(self): mainMenu = NSApplication.sharedApplication().mainMenu() s = objc.selector(self.selectGlyphsWithErrors, signature=b"v@:@") newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( Glyphs.localize({ "en": "Select Glyphs With Outline Errors", "de": "Glyphen mit Outlinefehlern auswählen", "ko": "윤곽선 오류가 있는 글리프 선택", }), s, "", ) newMenuItem.setTarget_(self) mainMenu.itemAtIndex_(2).submenu().insertItem_atIndex_(newMenuItem, 12)
def _newPlainTextPartWithAttributedString_partData_(self, old, *args): event = NSApplication.sharedApplication().currentEvent() result = old(self, *args) if event and event.modifierFlags() & NSAlternateKeyMask: return result charset = result.bodyParameterForKey_('charset') or 'utf-8' data = args[1].objectForKey_(result) lines = bytes(data).decode(charset).split('\n') lines = [line for text in lines for line in flow(text)] data.setData_(buffer(u'\n'.join(lines).encode(charset))) result.setBodyParameter_forKey_('yes', 'delsp') result.setBodyParameter_forKey_('flowed', 'format') return result
def __init__(self, videoWindowController): self.videoWindowController = videoWindowController self.log_debug('Init %s' % self) if self.finished: self._finish_close() return from VideoWindowController import TitleBarView NSBundle.loadNibNamed_owner_("VideoLocalWindow", self) self.window().center() title = NSLocalizedString( "Video with %s", "Window title") % self.videoWindowController.title NSApplication.sharedApplication().addWindowsItem_title_filename_( self.window(), title, False) self.window().setTitle_(title) self.window().setLevel_(NSFloatingWindowLevel) themeFrame = self.window().contentView().superview() self.titleBarView = LocalTitleBarView.alloc().init() topmenu_frame = self.titleBarView.view.frame() self.disconnectLabel.superview().hide() newFrame = NSMakeRect( 0, themeFrame.frame().size.height - topmenu_frame.size.height, themeFrame.frame().size.width, topmenu_frame.size.height) self.titleBarView.view.setFrame_(newFrame) themeFrame.addSubview_(self.titleBarView.view) self.titleBarView.textLabel.setHidden_(False) self.updateTrackingAreas() self.videoView.setProducer(SIPApplication.video_device.producer) self.notification_center = NotificationCenter() self.notification_center.add_observer( self, name="VideoDeviceDidChangeCamera")
def setup_event_listener(self): log("setup_event_listener()") self.delegate = None self.shared_app = NSApplication.sharedApplication() self.delegate = Delegate.alloc().init() self.delegate.retain() if self.client: self.delegate.sleep_callback = self.client.suspend self.delegate.wake_callback = self.client.resume self.delegate.deiconify_callback = self.client.deiconify_windows self.shared_app.setDelegate_(self.delegate) log("setup_event_listener() the application delegate has been registered") r = CGDisplayRegisterReconfigurationCallback(self.display_change, self) if r!=0: log.warn("Warning: failed to register display reconfiguration callback")
def run(self): self._syncer = Syncer() self._syncer.start() app = NSApplication.sharedApplication() app.setActivationPolicy_(2) # Hide from dock app.setApplicationIconImage_(create_icon('appicon.png')) self.traymenu = TrayMenu.alloc() self.traymenu.init() app.setDelegate_(self.traymenu) self._observer = setup_observer(self) self._cron = setup_syncing_cronjobs() AppHelper.runEventLoop()
def drawTextSheetOK_(self, sender): _win = sender.window() _app = NSApplication.sharedApplication() _app.endSheet_(_win) _win.orderOut_(_win) _textview = _win.initialFirstResponder() if not isinstance(_textview, NSTextView): return _text = _textview.string() if not len(_text) > 0: return _doc = self.getCurrentDocument() _tool = _doc.getTool() if not isinstance(_tool, tools.TextTool): return _tool.setText(_text) CocoaText.text_entered(_doc, _tool, _textview)
def setup_event_listener(self): log("setup_event_listener()") if NSObject is object: log.warn("NSObject is missing, not setting up OSX event listener") return self.shared_app = None self.delegate = None self.shared_app = NSApplication.sharedApplication() self.delegate = Delegate.alloc().init() self.delegate.retain() if self.client: self.delegate.sleep_callback = self.client.suspend self.delegate.wake_callback = self.client.resume self.delegate.deiconify_callback = self.client.deiconify_windows self.shared_app.setDelegate_(self.delegate) log("setup_event_listener() the application delegate has been registered")
def waituntil(conditionfunc, timeout=None): """ Waits until conditionfunc() returns true, or <timeout> seconds have passed. (If timeout=None, this waits indefinitely until conditionfunc() returns true.) Returns false if the process timed out, otherwise returns true. Note!! You must call interruptwait() when you know that conditionfunc() should be checked (e.g. if you are waiting for data and you know some data has arrived) so that this can check conditionfunc(); otherwise it will just continue to wait. (This allows the function to wait for an event that is sent by interruptwait() instead of polling conditionfunc().) This allows the caller to wait while the main event loop processes its events. This must be done for certain situations, e.g. to receive socket data or to accept client connections on a server socket, since IOBluetooth requires the presence of an event loop to run these operations. This function doesn't need to be called if there is something else that is already processing the main event loop, e.g. if called from within a Cocoa application. """ app = NSApplication.sharedApplication() starttime = time.time() if timeout is None: timeout = NSDate.distantFuture().timeIntervalSinceNow() if not isinstance(timeout, (int, float)): raise TypeError("timeout must be int or float, was %s" % \ type(timeout)) endtime = starttime + timeout while True: currtime = time.time() if currtime >= endtime: return False # use WAIT_MAX_TIMEOUT, don't wait forever in case of KeyboardInterrupt e = app.nextEventMatchingMask_untilDate_inMode_dequeue_( NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_( min(endtime - currtime, WAIT_MAX_TIMEOUT)), NSDefaultRunLoopMode, True) if e is not None: if (e.type() == NSApplicationDefined and e.subtype() == LIGHTBLUE_NOTIFY_ID): if conditionfunc(): return True else: app.postEvent_atStart_(e, True)
def determine_state_and_nudge(self): '''Determine the state of nudge and re-fresh window''' workspace = NSWorkspace.sharedWorkspace() currently_active = NSApplication.sharedApplication().isActive() frontmost_app = workspace.frontmostApplication().bundleIdentifier() if not currently_active and frontmost_app not in self.acceptable_apps: nudgelog('Nudge or acceptable applications not currently active') # If this is the under max dismissed count, just bring nudge back to the forefront # This is the old behavior if self.nudge_dismissed_count < self.dismissall_count_threshold: nudgelog('Nudge dismissed count under threshold') self.nudge_dismissed_count += 1 bring_nudge_to_forefront(self.nudge) else: # Get more aggressive - new behavior nudgelog('Nudge dismissed count over threshold') self.nudge_dismissed_count += 1 nudgelog('Enforcing acceptable applications') # Loop through all the running applications for app in NSWorkspace.sharedWorkspace().runningApplications(): app_name = str(app.bundleIdentifier()) app_bundle = str(app.bundleURL()) if app_bundle: # The app bundle contains file://, quoted path and trailing slashes app_bundle_path = unquote( urlparse(app_bundle).path).rstrip('/') # Add Software Update pane or macOS upgrade app to acceptable app list if app_bundle_path == self.nudge.path_to_app: self.acceptable_apps.append(app_name) else: # Some of the apps from NSWorkspace don't have bundles, # so force empty string app_bundle_path = '' # Hide any apps that are not in acceptable list or are not the macOS upgrade app if (app_name not in self.acceptable_apps) or ( app_bundle_path != self.nudge.path_to_app): app.hide() # Race condition with NSWorkspace. Python is faster :) time.sleep(0.001) # Another small sleep to ensure we can bring Nudge on top time.sleep(0.5) bring_nudge_to_forefront(self.nudge) # Pretend to open the button and open the update mechanism self.nudge.button_update(True) self.ux_when_timer_is_controlling()
def main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) def handler(signal, frame): print( "\nSending stopEventLoop in run function sub function handler") AppHelper.stopEventLoop() signal.signal(signal.SIGINT, handler) AppHelper.runEventLoop() except (SystemExit, KeyboardInterrupt): print("\nCtrl-C is entered") AppHelper.stopEventLoop()
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: try: notification_center = _default_user_notification_center() except RuntimeError: pass else: notification_center.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 alert(title=None, message='', ok=None, cancel=None): """ Repackaged from rumps, so we can try to make the window float above the others. Generate a simple alert window. .. versionchanged:: 0.2.0 Providing a `cancel` string will set the button text rather than only using text "Cancel". `title` is no longer a required parameter. :param title: the text positioned at the top of the window in larger font. If ``None``, a default localized title is used. If not ``None`` or a string, will use the string representation of the object. :param message: the text positioned below the `title` in smaller font. If not a string, will use the string representation of the object. :param ok: the text for the "ok" button. Must be either a string or ``None``. If ``None``, a default localized button title will be used. :param cancel: the text for the "cancel" button. If a string, the button will have that text. If `cancel` evaluates to ``True``, will create a button with text "Cancel". Otherwise, this button will not be created. :return: a number representing the button pressed. The "ok" button is ``1`` and "cancel" is ``0``. """ message = text_type(message) if title is not None: title = text_type(title) rumps.rumps._require_string_or_none(ok) if not isinstance(cancel, string_types): cancel = 'Cancel' if cancel else None alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_( title, ok, cancel, None, message) alert.setAlertStyle_(0) # informational style #panel = alert.window() #panel.setLevel_(NSStatusWindowLevel) # alert.window().setFloatingPanel_(True) # import ipdb; ipdb.set_trace(); rumps.rumps._log('alert opened with message: {0}, title: {1}'.format(repr(message), repr(title))) #app = NSRunningApplication.currentApplication() #app.activateWithOptions_(NSApplicationActivateIgnoringOtherApps) nsapplication = NSApplication.sharedApplication() nsapplication.activateIgnoringOtherApps_(True) result = alert.runModal() return result
def main_darwin(): """ Custom main for OSX. """ from PyObjCTools import AppHelper from AppKit import NSNotificationCenter, NSApplication from apaf.utils.osx_support import ApafAppWrapper, TorFinishedLoadNotification from twisted.internet import _threadedselect try: _threadedselect.install() except Exception as e: log.err(e) app = NSApplication.sharedApplication() delegate = ApafAppWrapper.alloc().init() delegate.setMainFunction_andReactor_(main, reactor) app.setDelegate_(delegate) AppHelper.runEventLoop()
def executeVanillaTest(cls, nibPath=None, calls=None, **kwargs): """ Execute a Vanilla UI class in a mini application. """ app = NSApplication.sharedApplication() delegate = _VanillaMiniAppDelegate.alloc().init() app.setDelegate_(delegate) if nibPath: NSBundle.loadNibFile_externalNameTable_withZone_(nibPath, {}, None) else: mainMenu = NSMenu.alloc().initWithTitle_("Vanilla Test") fileMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "File", None, "") fileMenu = NSMenu.alloc().initWithTitle_("File") fileMenuItem.setSubmenu_(fileMenu) mainMenu.addItem_(fileMenuItem) editMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Edit", None, "") editMenu = NSMenu.alloc().initWithTitle_("Edit") editMenuItem.setSubmenu_(editMenu) mainMenu.addItem_(editMenuItem) helpMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( "Help", None, "") helpMenu = NSMenu.alloc().initWithTitle_("Help") helpMenuItem.setSubmenu_(helpMenu) mainMenu.addItem_(helpMenuItem) app.setMainMenu_(mainMenu) if cls is not None: cls(**kwargs) if calls is not None: for call, kwargs in calls: call(**kwargs) app.activateIgnoringOtherApps_(True) AppHelper.runEventLoop()
def main(): # XXX: info.plist is generated by pyinstaller # bundle = NSBundle.mainBundle() # if bundle: # app_info = bundle.infoDictionary() # if app_info: # app_info['CFBundleName'] = "App" # app_info["NSAppTransportSecurity"] = { # "NSAllowsArbitraryLoads": True, # "NSAllowsArbitraryLoadsForMedia": True, # "NSAllowsArbitraryLoadsInWebContent": True, # } app = NSApplication.sharedApplication() # we must keep a reference to the delegate object ourselves, # NSApp.setDelegate_() doesn't retain it. A local variable is # enough here. delegate = AppDelegate.alloc().init() app.setDelegate_(delegate) AppHelper.runEventLoop()
def selectGlyphsWithErrors(self): """ Selects all glyphs with errors in the active layer """ font = NSApplication.sharedApplication().font if font is None: return None if can_display_ui: options, run_tests = self.selectGlyphsOptions() else: options = self.options run_tests = self.run_tests if run_tests is None: return if options is None: return font.disableUpdateInterface() mid = font.selectedFontMaster.id self.options["grid_length"] = font.gridLength glyphlist = font.glyphs.keys() outline_test_pen = OutlineTestPenGlyphs(font, options, run_tests) for glyph_name in glyphlist: glyph = font.glyphs[glyph_name] layer = glyph.layers[mid] outline_test_pen.errors = [] if layer is not None: try: layer.drawPoints(outline_test_pen) if len(outline_test_pen.errors) > 0: glyph.selected = True else: glyph.selected = False except Exception as e: self.logToConsole( "selectGlyphsWithErrors: Layer '%s': %s" % (glyph_name, str(e))) font.enableUpdateInterface()
def run(self): """ Perform various setup tasks then start application run loop. """ 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 self._nsapp.initializeStatusBar() nsapplication.setDelegate_(self._nsapp) 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 AppHelper.runEventLoop() sys.exit(0)
def init_dock_listener(client): global dock_listener if dock_listener: return try: import objc #@UnresolvedImport shared_app = NSApplication.sharedApplication() class Delegate(NSObject): @objc.signature('B@:#B') def applicationShouldHandleReopen_hasVisibleWindows_(self, ns_app, flag): log("applicationShouldHandleReopen_hasVisibleWindows%s", (ns_app, flag)) client.deiconify_windows() return True delegate = Delegate.alloc().init() delegate.retain() shared_app.setDelegate_(delegate) dock_listener = delegate except: log.error("Error setting up dock listener", exc_info=True) dock_listener = False
def present(self): """Present the Alert, giving up after configured time.. Returns: Int result code, based on PyObjC enums. See NSAlert Class reference, but result should be one of: User clicked the cancel button: NSAlertFirstButtonReturn = 1000 Alert timed out: NSRunAbortedResponse = -1001 """ if self.timer: NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSModalPanelRunLoopMode) # Start a Cocoa application by getting the shared app object. # Make the python app the active app so alert is noticed. app = NSApplication.sharedApplication() app.activateIgnoringOtherApps_(True) if self.alert_sound: sound = NSSound.soundNamed_(self.alert_sound).play() result = self.runModal() # pylint: disable=no-member print result return result
def try_maximize_window_osx(): try: from AppKit import NSApplication except ImportError: print( "try_maximize_window_osx(): install pyobjc to maximize the window on osx" ) return True app = NSApplication.sharedApplication() # wait until window is ready if app.mainWindow() is not None: menu = app.mainMenu() window_menu = menu.itemArray()[1].submenu() for i, menu_item in enumerate(window_menu.itemArray()): if menu_item.action() == "toggleFullScreen:": window_menu.performActionForItemAtIndex_(i) return True return False
def _setup_ui_dialogs(self): # This needs to be here otherwise we can't install the dialog if 'STOQ_TEST_MODE' in os.environ: return log.debug('providing graphical notification dialogs') from stoqlib.gui.base.dialogs import DialogSystemNotifier from stoqlib.lib.interfaces import ISystemNotifier from kiwi.component import provide_utility provide_utility(ISystemNotifier, DialogSystemNotifier(), replace=True) from gi.repository import Gtk from kiwi.environ import environ from stoqlib.gui.stockicons import STOQ_LAUNCHER Gtk.Window.set_default_icon_name(STOQ_LAUNCHER) if platform.system() == 'Darwin': from AppKit import NSApplication, NSData, NSImage # FIXME: This should be a 48x48 icon data = environ.get_resource_string( 'stoq', 'pixmaps', 'hicolor', '24x24', 'actions', 'stoq-launcher.png') data = NSData.alloc().initWithBytes_length_(data, len(data)) icon = NSImage.alloc().initWithData_(data) app = NSApplication.sharedApplication() app.setApplicationIconImage_(icon)
def quit_application(sender=None): """Quit the application. Some menu item should call this function so that the application can exit gracefully.""" nsapplication = NSApplication.sharedApplication() _log('closing application') nsapplication.terminate_(sender)
def get_input(): try: while True: line = sys.stdin.readline() if not line: break if line == '': continue print "info:Read %s" % line sys.stdout.flush() cfg = None try: cfg = json.loads(line) except: pass if cfg == None: print "info:Unable to parse line" sys.stdout.flush() continue if cfg.has_key("Action"): print "info:Running %s" % cfg["Action"] sys.stdout.flush() if cfg["Action"] == "setmenu": menu = cfg["Menu"] if lookup.has_key(menu["Key"]): lookup[menu["Key"]].title = menu["Text"] if menu.has_key("Enabled") and not menu["Enabled"]: lookup[menu["Key"]].set_callback(None) else: lookup[menu["Key"]].set_callback(item_clicked) app.menu.update([]) else: print "warn:Key not found %s" % cfg["Action"] sys.stdout.flush() elif cfg["Action"] == "setmenus": app.menu.clear() app.menu = parsemenus(cfg) print "info:Updated menus" sys.stdout.flush() elif cfg["Action"] == "seticon": try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) img = NSImage.alloc().initWithData_(data) img.setScalesWhenResized_(True) img.setSize_((18, 18)) img.setTemplate_(True) app.icon = img print "info:Image updated" sys.stdout.flush() except: print "warn:Failed to set image" sys.stdout.flush() elif cfg["Action"] == "setappicon": try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) img = NSImage.alloc().initWithData_(data) #img.setScalesWhenResized_(True) #img.setSize_((21, 21)) NSApplication.sharedApplication().setApplicationIconImage_(img) print "info:AppImage updated" sys.stdout.flush() except: print "warn:Failed to set image" sys.stdout.flush() elif cfg["Action"] == "shutdown": break elif cfg["Action"] == "foreground": transform_app_type(True) elif cfg["Action"] == "background": transform_app_type(False) elif cfg["Action"] == "notification": if rumps._NOTIFICATIONS: title = cfg["Title"] message = cfg["Message"] subtitle = '' playSound = True image = None if cfg.has_key("SubTitle"): subtitle = cfg["SubTitle"] if cfg.has_key("PlaySound"): playSound = cfg["PlaySound"] if cfg.has_key("Image"): try: raw = base64.b64decode(cfg["Image"]) data = NSData.dataWithBytes_length_(raw, len(raw)) image = NSImage.alloc().initWithData_(data) except: print "warn:Failed to decode image" sys.stdout.flush() rumps.notification(cfg["Title"], subtitle, cfg["Message"], sound=playSound, image=image) finally: try: traceback.print_exc() except: pass rumps.quit_application() print "info:Shutdown" sys.stdout.flush() print "info:Stdin close" sys.stdout.flush() sys.stdin.close()
def bring_to_front(self, timer=None): """ Bring the application to the front. """ nsapplication = NSApplication.sharedApplication() nsapplication.activateIgnoringOtherApps_(True)
def SetTopApp(w): NSApplication.sharedApplication() NSApp().activateIgnoringOtherApps_(True)
from PyObjCTools import AppHelper class AppDelegate(NSObject): def applicationDidFinishLaunching_(self, _): mask_down = NSKeyDownMask NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(mask_down, key_handler) def key_handler(event, timing_dict = {}): threshhold = args.threshhold # I know I know try: timing_dict[int(event.timestamp())] = timing_dict.get(int(event.timestamp()), 0) + 1 if timing_dict[int(event.timestamp())] > threshhold: print('HID ATTACK DETECTED') for ts in timing_dict.keys(): # This is some manual GC to keep the timing_dict small if not ts == int(event.timestamp()): timing_dict.pop(ts) except KeyboardInterrupt: AppHelper.stopEventLoop() except Exception as e: pass if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument("--threshhold", "-t", default=10, type=int, help="The number of keystrokes to trigger an alert. Default is 10") args = parser.parse_args() app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
def main(): app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.callLater(_BUCKET_SIZE_SECONDS, record) AppHelper.runEventLoop()
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def main(): app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()