def run(self): NSApplication.sharedApplication() delegate = self.createAppDelegate().alloc().init() NSApp().setDelegate_(delegate) NSApp().setActivationPolicy_(NSApplicationActivationPolicyProhibited) self.workspace = NSWorkspace.sharedWorkspace() AppHelper.runEventLoop()
def machInterrupt(signum): stopper = PyObjCAppHelperRunLoopStopper.currentRunLoopStopper() if stopper is not None: stopper.stop() elif NSApp() is not None: NSApp().terminate_(None) else: import os os._exit(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 stopEventLoop(): """ Stop the current event loop if possible returns True if it expects that it was successful, False otherwise """ stopper = PyObjCAppHelperRunLoopStopper.currentRunLoopStopper() if stopper is None: if NSApp() is not None: NSApp().terminate_(None) return True return False NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, stopper, "performStop:", None, False) return True
def run(self) -> None: NSApplication.sharedApplication() self.delegate = AppDelegate.alloc().init() self.delegate.handler = Handler() NSApp().setDelegate_(self.delegate) self.workspace = NSWorkspace.sharedWorkspace() nc = self.workspace.notificationCenter() nc.addObserver_selector_name_object_( self.delegate, 'applicationActivated:', 'NSWorkspaceDidActivateApplicationNotification', None, ) nc.addObserver_selector_name_object_( self.delegate, 'screenSleep:', 'NSWorkspaceScreensDidSleepNotification', None, ) NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( self.polling_time, self.delegate, 'writeActiveApp:', None, True) AppHelper.runConsoleEventLoop(maxTimeout=1)
def activateNow_(self, aNotification): NSApp().activateIgnoringOtherApps_(True) try: app_main() except: sys.excepthook(*sys.exc_info()) os._exit(0)
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 loadDisplaySettings(self): controller = NSApp().RoboHUD needsInactiveOpacity = self.fadeLayer.opacity( ) == self._inactiveOpacity self._inactiveOpacity = controller.getInactiveOpacity() if needsInactiveOpacity: self._setOpacity_(self._inactiveOpacity)
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 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 __init__(self): # debug windowname = 'Debug Glyph Metrics UI' windows = [w for w in NSApp().orderedWindows() if w.isVisible()] for window in windows: print(window.title()) if window.title() == windowname: window.close() if debug == True: self.debug = Window((333, 33), windowname) self.debug.bind('close', self.windowSideuiClose) self.debug.open() # setup self.showButtons = False self.sbui = None # add interface addObserver(self, 'addInterface', 'glyphWindowWillOpen') addObserver(self, 'updateSelfWindow', 'currentGlyphChanged') # toggle visibility of tool ui addObserver(self, 'showSideUIonDraw', 'draw') addObserver(self, 'hideSideUIonPreview', 'drawPreview') # remove UI and window manager when glyph window closes # addObserver(self, "observerGlyphWindowWillClose", "glyphWindowWillClose") # subscribe to glyph changes addObserver(self, "viewDidChangeGlyph", "viewDidChangeGlyph")
def __init__(self): windowname = 'comparing widths' self.i=10 self.checkWindow = Window((200, 140+(len(AllFonts())*self.i*1.2)), windowname) self.varDict = {} self.fontsToSend = [] for self.i in range(len(AllFonts())): self.varDict["string{0}".format(self.i)] = AllFonts()[self.i].info.styleName print(self.varDict) for font in self.varDict.values(): checkbox = CheckBox((5, 10+self.i, -10, 20), font, callback=self.checkBoxCallback, value=False) self.i+=20 setattr(self.checkWindow, font, checkbox) self.checkWindow.button = Button((10, (len(AllFonts())*25), -10, 20), "A Button", callback=self.buttonCallback) self.checkWindow.open() self.glyphlist = [] self.columnlist=[] self.f1 = "" self.f2 = "" self.listWindow = FloatingWindow((600, 400), windowname) self.listWindow.bind('close', self.windowClose) for window in [listWindow for listWindow in NSApp().windows() if listWindow.isVisible()]: if window.title() == windowname: window.close()
def applicationDidFinishLaunching_(self, aNotification): try: import aliens aliens.main() except: exception_handler() NSApp().terminate_(self)
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 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 main(): try: app = NSApplication.sharedApplication() delegate = AppDelegate.alloc().init() NSApp().setDelegate_(delegate) AppHelper.runEventLoop() except KeyboardInterrupt: AppHelper.stopEventLoop()
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 applicationDidFinishLaunching_(self, aNotification): try: import sys sys.path.append('../../src') import main main.main() except: exception_handler() NSApp().terminate_(self)
def open(self): """ Open the window. """ parentWindow = self.parentWindow NSApp( ).beginSheet_modalForWindow_modalDelegate_didEndSelector_contextInfo_( self._window, parentWindow, None, None, 0) # See Window.open(): self.retain()
def close(self): """ Close the window. Once a window has been closed it can not be re-opened. """ if self._window.isSheet(): NSApp().endSheet_(self._window) self._window.orderOut_(None) self._window.close()
def __init__(self): windowname = 'debug only test' if debug is True: self.w = Window((500, 50), windowname) self.w.bind('close', self.windowClose) for window in [ w for w in NSApp().orderedWindows() if w.isVisible() ]: if window.title() == windowname: window.close() self.w.open() self.doStuff()
def _cascade(self): allLeftTop = [] for other in NSApp().orderedWindows(): if other == self._window: continue (oL, oB), (oW, oH) = other.frame() allLeftTop.append((oL, oB + oH)) (sL, sB), (sW, sH) = self._window.frame() leftTop = sL, sB + sH while leftTop in allLeftTop: leftTop = self._window.cascadeTopLeftFromPoint_(leftTop) self._window.setFrameTopLeftPoint_(leftTop)
def __init__(self): windowname = 'comparing widths' if debug is True: self.glyphlist = [] self.columnlist = [] self.f1 = AllFonts()[0] self.f2 = AllFonts()[1] self.w = FloatingWindow((600, 400), windowname) self.w.bind('close', self.windowClose) for window in [w for w in NSApp().windows() if w.isVisible()]: if window.title() == windowname: window.close() self.w.open() self.listLaunch()
def resize(self, sender): SWM = getDefault("singleWindowMode") fw = CurrentFontWindow() fo = fw.fontOverview gc = fo.getGlyphCollection() v = gc.getGlyphCellView() # make cells small first starter = 10 v.setCellSize_([starter, starter]) # get the width of the whole window x, y, w, h = fw.window().getPosSize() # get the width of overall font overview fo_w = fo.getNSView().frameSize().width # get the width of the cell view vw, vh = v.frameSize().width, v.frameSize().height # get the width of the sets menu to the left of the font overview sets_w = fo_w - vw # get number of glyphs num_g = len(gc.getGlyphNames()) cells_across = 1 cw = int(vw / cells_across) while ((num_g) / cells_across) * cw > vh: cells_across += 1 cw = ch = int(vw / cells_across) vw = cw * cells_across fo_total_w = vw + sets_w # set frame size in single window mode if SWM == 1: fw.editor.splitView.setDimension('fontOverview', fo_total_w) fw.editor.splitView.setDimension('glyphView', w - fo_total_w) fw.centerGlyphInView() # set frame size in multi-window mode else: windows = NSApp().orderedWindows() (x, y), (w, h) = windows[0].frame() x_diff = w - fo_total_w windows[0].setFrame_display_animate_( ((x + x_diff, y), (fo_total_w, h)), True, False) # change the cell size once and for all, update the slider to reflect the change v.setCellSize_([cw, ch]) fo.views.sizeSlider.set(cw) # set this as the new default cell size (this happens when you use the native slide too) setDefault("fontCollectionViewGlyphSize", int(cw))
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 run(self, installSignalHandlers=1, withRunLoop=None): if self.running: raise ValueError, "Reactor already running" if installSignalHandlers: self.pollInterval = self.shortIntervalOfTime runLoop = self.getRunLoop(withRunLoop) self._startup() self.startRunning(installSignalHandlers=installSignalHandlers) self.running = True if NSApp() is None and self.nsRunLoop.currentMode() is None: # Most of the time the NSRunLoop will have already started, # but in this case it wasn't. runLoop.run() self.crashing = False self.didStartRunLoop = True
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 __init__(self): """ Add the "Change Suffixes" menu item to the Font menu. """ title = "Change Suffixes..." fontMenu = NSApp().mainMenu().itemWithTitle_("Font") if not fontMenu: print "Suffixer: Error, aborting" return fontMenu = fontMenu.submenu() if fontMenu.itemWithTitle_(title): return index = fontMenu.indexOfItemWithTitle_("Add Glyphs") self.target = CallbackWrapper(self.openWindow) newItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( title, "action:", "S") newItem.setKeyEquivalentModifierMask_(NSAlternateKeyMask | NSCommandKeyMask) newItem.setTarget_(self.target) fontMenu.insertItem_atIndex_(newItem, index + 1)
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 build(self): self.key = 'com.ryanbugden.FitGlyphCells.FitOnStartup' self.startupSetting = getExtensionDefault(self.key, fallback=1) # put in the menu item title = "Fit Glyph Cells on Open" font_menu = NSApp().mainMenu().itemWithTitle_("Font") if not font_menu: print("Fit Glyph Cells - Error") return font_menu = font_menu.submenu() if font_menu.itemWithTitle_(title): return index = font_menu.indexOfItemWithTitle_("Sort") self.target = CallbackWrapper(self.togglePref) new_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( title, "action:", "F") new_item.setKeyEquivalentModifierMask_(NSAlternateKeyMask | NSCommandKeyMask) new_item.setTarget_(self.target) new_item.setState_(self.startupSetting) font_menu.insertItem_atIndex_(new_item, index + 1)