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 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 run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
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 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 __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 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 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 ns_process_key_event(self, ns_event): # Perform menu setup before command-key events. # Send non-command key events to associated window if any, # otherwise pass them to the pygui application. This is necessary # because otherwise there is no way of receiving key events when # there are no windows. if ns_event.modifierFlags() & NSCommandKeyMask: NSApplication.sendEvent_(self._ns_app, ns_event) else: ns_window = ns_event.window() if ns_window: ns_window.sendEvent_(ns_event) else: event = Event(ns_event) self.handle(event.kind, event)
def generateStylesheets(url): delegate = AppDelegate.alloc().init() delegate.url = url app = NSApplication.sharedApplication() app.setDelegate_(delegate) app.run()
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 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 main(): try: import objc from PyObjCTools import AppHelper from AppKit import NSApplication, NSApp, NSObject, NSApplicationActivationPolicyRegular # from Foundation import * class AppDelegate(NSObject): def init(self): self = objc.super(AppDelegate, self).init() if self is None: return None return self def runjava_(self, arg): runAwtStuff() # we need to terminate explicitly, or it'll hang when # the wrapped code exits NSApp().terminate_(self) def applicationDidFinishLaunching_(self, aNotification): self.performSelectorInBackground_withObject_("runjava:", 0) app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) # this is necessary to have keyboard events sent to the UI; # basically this call makes the script act like an OS X application, # with Dock icon and everything NSApp.setActivationPolicy_(NSApplicationActivationPolicyRegular) AppHelper.runEventLoop() except ModuleNotFoundError: print("Skipping OSXAWTwrapper - module 'objc' is not installed")
def dp_it(cls): # Create a new application instance ... pu_app = NSApplication.sharedApplication() # ... and create its delgate. Note the use of the # Objective C constructors below, because Delegate # is a subcalss of an Objective C class, NSObject pu_delegate = WDelegate.alloc().init() # Tell the application which delegate object to use. pu_app.setDelegate_(pu_delegate) # Now we can can start to create the window ... pu_frame = ((0, 0), (250.0, 100.0)) # (Don't worry about these parameters for the moment. They just specify # the type of window, its size and position etc) pu_window = NSWindow.alloc( ).initWithContentRect_styleMask_backing_defer_(pu_frame, 15, 2, 0) # ... tell it which delegate object to use (here it happens # to be the same delegate as the application is using)... pu_window.setDelegate_(pu_delegate) # ... and set some properties. Unicode strings are preferred. pu_window.setTitle_(GC_TONO_NM) # All set. Now we can show the window ... pu_window.center() pu_window.orderFrontRegardless() # ... and start the application AppHelper.runEventLoop()
def run(self): NSApplication.sharedApplication() delegate = AppDelegate(self.handler) #delegate = AppDelegate.alloc().init() #self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) #print("NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited)", NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited)) self.workspace = NSWorkspace.sharedWorkspace() def handler(signal, frame): print( "\nSending stopEventLoop in run function sub function handler") AppHelper.stopEventLoop() signal.signal(signal.SIGINT, handler) AppHelper.runEventLoop()
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 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 _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 _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 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()
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 run(self): from AppKit import NSApplication, NSApp from Foundation import NSObject, NSLog from Cocoa import NSEvent, NSKeyDownMask from PyObjCTools import AppHelper def handler(event): try: character = event.keyCode() self.callback(character, "apple-keycode") except KeyboardInterrupt: AppHelper.stopEventLoop() class AppDelegate(NSObject): def applicationDidFinishLaunching_(self, notification): mask = NSKeyDownMask NSEvent.addGlobalMonitorForEventsMatchingMask_handler_( mask, handler) app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
def applicationDidFinishLaunching_(self, aNotification): logger.debug(f"applicationDidFinishLaunching: {aNotification}") certManager = CertManager() certManager.generate_certs() keychain = Keychain(b"my-example-app", b"PASSWORD") # TODO: generate password clientCredential = keychain.importP12(certManager.client_p12, certManager.client_p12pass) self.server = AioHTTPServer() ctx = certManager.create_ssl_context() self.server.start(ctx=ctx) app = NSApplication.sharedApplication() app.setMainMenu_(self.createMainMenu()) self.window = self.createWindow() # Get auto-saved frame frame = self.window.contentView().frame() webViewController = WebViewController.alloc().initWithFrame_(frame) webViewController.setServerCertificateFromPEM_(certManager.server_cert) webViewController.clientCredential = clientCredential webViewController.url = 'https://127.0.0.1:18760/' self.window.setContentViewController_(webViewController) self.window.setDelegate_(self) self.window.display() self.window.orderFrontRegardless()
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 _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 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 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 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) notifications._init_nsapp(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.installMachInterrupt() AppHelper.runEventLoop()
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 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 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 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 main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
def loadPlugin(self): mainMenu = NSApplication.sharedApplication().mainMenu() s = objc.selector(self.showWindow, signature='v@:') newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( self.title(), s, "") newMenuItem.setTarget_(self) mainMenu.itemAtIndex_(2).submenu().addItem_(newMenuItem)
def main(): app = NSApplication.sharedApplication() ### Zero out the log file when you start up to prevent wild disk utilization open('../data/keys.log', 'w').close() logging.basicConfig(filename='../data/keys.log', format='%(asctime)s %(message)s', level=logging.INFO) delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop()
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 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_('pt.barraca.MailTrack') return self
def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() def handler(signal, frame): log.debug("Got signal termination") release_lock() AppHelper.stopEventLoop() os._exit(1) signal.signal(signal.SIGINT, handler) signal.signal(signal.SIGTERM, handler) AppHelper.runEventLoop()
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 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 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 quit_application(sender=None): """Quit the application. Some menu item should call this function so that the application can exit gracefully.""" if _NOTIFICATIONS: Notifier.removeAllScheduledNotifications() Notifier.removeAllDeliveredNotifications() nsapplication = NSApplication.sharedApplication() _log('closing application') nsapplication.terminate_(sender)
def main(): """ Setup and start Cocoa GUI main loop """ app = NSApplication.sharedApplication() delegate = darwin.ApafAppWrapper.alloc().init() delegate.setMainFunction_andReactor_(start_apaf, reactor) app.setDelegate_(delegate) AppHelper.runEventLoop()
def addMenuItem(self): mainMenu = NSApplication.sharedApplication().mainMenu() s = objc.selector(self.selectGlyphsWithErrors, signature='v@:') newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( Glyphs.localize({ 'en': u"Select Glyphs With Outline Errors", 'de': u'Glyphen mit Outlinefehlern auswählen', 'ko': u"윤곽선 오류가 있는 글리프 선택" }), s, "") newMenuItem.setTarget_(self) mainMenu.itemAtIndex_(2).submenu().insertItem_atIndex_(newMenuItem, 11)
def main(): global __file__ __file__ = os.path.abspath(__file__) if os.path.islink(__file__): __file__ = getattr(os, 'readlink', lambda x: x)(__file__) os.chdir(os.path.dirname(os.path.abspath(__file__))) app = NSApplication.sharedApplication() delegate = GoAgentOSX.alloc().init() app.setDelegate_(delegate) AppHelper.runEventLoop()
def notify(title, message, bring_up=False): try: kwargs = {'title': title, 'message': message} if system == "Windows" or system == "Linux": kwargs['app_icon'] = os.path.abspath(get_icon_path()) kwargs['timeout'] = 4 notification.notify(**kwargs) 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 start(self): mainMenu = NSApplication.sharedApplication().mainMenu() s = objc.selector(self.editMasterGrid, signature=b'v@:@') newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( Glyphs.localize({ 'en': "Master Grid…", 'de': 'Master-Raster…' }), s, "") newMenuItem.setTarget_(self) submenu = mainMenu.itemAtIndex_(2).submenu() submenu.insertItem_atIndex_(newMenuItem, 12)
def make_circles(): #to install this, see options 2 and 4 at: #http://nodebox.net/code/index.php/Console . Mac Only! from AppKit import NSApplication NSApplication.sharedApplication().activateIgnoringOtherApps_(0) from nodebox.graphics import Context from nodebox.util import random, choice, grid, files hoods = simplejson.load(file("hoods.json")) max_n = float(max(v[0] for k, v in hoods.iteritems())) for hood, vals in hoods.iteritems(): ctx = Context() colors = ctx.ximport("colors") n = vals[0] a = vals[1] ctx.background(None) maxw = 100 pct = n / max_n d = pct * maxw margin = 2 w = h = d + (margin * 2) mid = w / 2 ctx.size(maxw + margin * 2, maxw + margin * 2) ctx.fill(colors.hex("#608902d")) ctx.oval(2, 2, d, d) ctx.fill(colors.hex("#E6FA87")) n = str(n) ctx.fontsize(int(24 * pct)) tw = ctx.textwidth(n) th = ctx.textheight(n) ctx.text(n, mid - (tw / 2), mid + (th / 4)) ctx.save("circles/%s.png" % clean_hood_name(hood)) print clean_hood_name(hood)
def dialog(): from AppKit import NSApplication, NSAutoreleasePool, NSOpenPanel app = NSApplication.sharedApplication() assert app pool = NSAutoreleasePool.alloc().init() assert pool panel = NSOpenPanel.openPanel() panel.setCanChooseFiles_(True) if panel.runModal(): return panel.URL().path() return None