def assemble_menu(parent_menu, menu_spec: dict, top_menu: bool = False): if not menu_spec: if not top_menu: parent_menu.addItem_(NSMenuItem.separatorItem()) else: raise AssertionError('Cannot put separator into top menu') elif 'children' in menu_spec: menu_item = NSMenuItem.alloc().init() if not top_menu: menu_item.setTitle_(menu_spec['title']) parent_menu.addItem_(menu_item) menu = NSMenu.alloc().init() if top_menu: menu.setTitle_(menu_spec['title']) for child in menu_spec['children']: assemble_menu(menu, child) menu_item.setSubmenu_(menu) else: menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( menu_spec['title'], None, menu_spec.get('key', '') if not top_menu else '') parent_menu.addItem_(menu_item) if top_menu: # workaround: # I cannot get Mac to play the action on a top menu if it is a menu item # Mac does not display top menu item without submenu... menu = NSMenu.alloc().init() menu.setTitle_(menu_spec['title']) assemble_menu(menu, menu_spec) menu_item.setSubmenu_(menu) if 'action' in menu_spec: set_action(menu_item, menu_spec['action'])
def setupStatusBar(self): statusbar = NSStatusBar.systemStatusBar() statusitem = statusbar.statusItemWithLength_(20).retain() icon = NSImage.imageNamed_('status') icon.setSize_((20, 20)) statusitem.setImage_(icon) iconHighlight = NSImage.imageNamed_('status-hi') iconHighlight.setSize_((20, 20)) statusitem.setAlternateImage_(iconHighlight) statusitem.setHighlightMode_(1) # TODO: Put this whole menu creation stuff into interface builder! menu = NSMenu.alloc().init() linkMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Post a Link', 'doLink:', '') linkMenu.setTarget_(self) # Make it possible to invoke the link menu via a keyboard shortcut. linkMenu.setKeyEquivalentModifierMask_(NSShiftKeyMask | NSCommandKeyMask) linkMenu.setKeyEquivalent_('l') menu.addItem_(linkMenu) menu.addItem_(NSMenuItem.separatorItem()) previewMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Update Preview', 'doPreview:', '') previewMenu.setTarget_(self) menu.addItem_(previewMenu) publishMenuItem = NSMenuItem.alloc( ).initWithTitle_action_keyEquivalent_('Publish', None, '') publishMenu = NSMenu.alloc().init() s3MenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'S3', 'doPublish:', '') s3MenuItem.setTarget_(self) publishMenu.addItem_(s3MenuItem) publishMenuItem.setSubmenu_(publishMenu) menu.addItem_(publishMenuItem) menu.addItem_(NSMenuItem.separatorItem()) quitMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') menu.addItem_(quitMenu) statusitem.setMenu_(menu) menu.release()
def executeVanillaTest(cls, nibPath=None, calls=None, **kwargs): """ Execute a Vanilla UI class in a mini application. """ app = _VanillaMiniApp.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) if hasCorefoundationasyncio: loop = CoreFoundationEventLoop() asyncio.set_event_loop(loop) try: loop.run_forever() finally: loop.close() else: AppHelper.runEventLoop()
def __init__(self, title, items, **kwds): #print "Menu: creating with items", items ### GMenu.__init__(self, title, items, **kwds) ns_menu = NSMenu.alloc().initWithTitle_(title) ns_menu.setAutoenablesItems_(False) ns_menu.setDelegate_(Globals.ns_application) self._ns_menu = ns_menu
def setupUI(self): self.statusbar = NSStatusBar.systemStatusBar() self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) #NSSquareStatusItemLength #NSVariableStatusItemLength # Set initial image icon icon_path = os.path.join(current_path, "../trayicon.ico") image = NSImage.alloc().initByReferencingFile_(icon_path) image.setScalesWhenResized_(True) image.setSize_((20, 20)) self.statusitem.setImage_(image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_("ZeroNet") # Build a very simple menu self.menu = NSMenu.alloc().init() self.menu.setAutoenablesItems_(False) #self.create_menu_item( 'ip_external', 'IP: %s' % INFO['ip_external'], 'info:') self.menu.addItem_( NSMenuItem.separatorItem() ) # Links self.create_menu_item( 'open_zeronet', 'Open ZeroNet', 'open:') self.create_menu_item( 'open_reddit', 'Zeronet Reddit Community', 'openreddit:') self.create_menu_item( 'open_gh', 'Report issues/feature requests', 'opengithub:') self.menu.addItem_( NSMenuItem.separatorItem() ) self.create_menu_item( 'quit_zeronet', 'Quit ZeroNet', 'windowWillClose:' ) # Bind it to the status item and hide dock icon self.statusitem.setMenu_(self.menu) NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
def applicationDidFinishLaunching_(self, notification): self.statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) # Set initial image raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines())) self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data)) self.image = NSImage.alloc().initWithData_(self.image_data) self.statusitem.setImage_(self.image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) # Set a tooltip self.statusitem.setToolTip_('GoAgent OSX') # Build a very simple menu self.menu = NSMenu.alloc().init() # Show Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '') self.menu.addItem_(menuitem) # Hide Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide:', '') self.menu.addItem_(menuitem) # Rest Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reset', 'reset:', '') self.menu.addItem_(menuitem) # Default event menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menu.addItem_(menuitem) # Bind it to the status item self.statusitem.setMenu_(self.menu)
def applicationDidFinishLaunching_(self, _n): self.statusbar = NSStatusBar.systemStatusBar() self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) self.image = NSImage.alloc().initByReferencingFile_("mydock.icns") for i in self.toggles: self.toggle_images[i] = NSImage.alloc().initByReferencingFile_(i+".png") #self.statusitem.setTitle_(u"Set up %s" % NAME) self.statusitem.setImage_(self.image) self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_("Docker tray tool") self.menu = NSMenu.alloc().init() # menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Kill', 'killornot:', '') # menuitem.setState_(NSOnState if not self.kill else NSOffState) # self.menu.addItem_(menuitem) # menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Docker instances', 'instances:', '') # self.menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menu.addItem_(menuitem) self.statusitem.setMenu_(self.menu) # Get config if there is any self.restore_config() #print("interval: %s" % self.interval) self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, self.interval, self, 'loop:', None, True) getattr(self, self.loop_func)("Bs?")
def applicationDidFinishLaunching_(self, notification): self.noDevice = None #Create menu self.menu = NSMenu.alloc().init() self.barItem = dict() # Load images self.noDeviceImage = NSImage.alloc().initByReferencingFile_('icons/no_device.png') self.barImage = dict(kb = NSImage.alloc().initByReferencingFile_('icons/kb.png'), magicMouse = NSImage.alloc().initByReferencingFile_('icons/magic_mouse.png'), mightyMouse = NSImage.alloc().initByReferencingFile_('icons/mighty_mouse.png'), magicTrackpad = NSImage.alloc().initByReferencingFile_('icons/TrackpadIcon.png')) #Define menu items self.statusbar = NSStatusBar.systemStatusBar() self.menuAbout = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('About BtBatStat', 'about:', '') self.separator_menu_item = NSMenuItem.separatorItem() self.menuQuit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') # Get the timer going self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 10.0, self, 'tick:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.timer.fire() #Add menu items self.menu.addItem_(self.menuAbout) self.menu.addItem_(self.separator_menu_item) self.menu.addItem_(self.menuQuit) #Check for updates checkForUpdates()
def _create_menu(self): self.menu = NSMenu.alloc().init() self.menu.setAutoenablesItems_(False) self.trayicon.setMenu_(self.menu) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Status: loading', '', '') menuitem.setEnabled_(False) self._menu_items['status'] = menuitem self.menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Sync now', 'sync:', '') menuitem.setEnabled_(False) self._menu_items['sync'] = menuitem self.menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Resolve conflicts', 'resolve:', '') menuitem.setEnabled_(False) self._menu_items['resolve'] = menuitem self.menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( app.get().status == interfaces.STATUS_DISABLED \ and 'Enable' or 'Disable', 'enabledisable:', '') self._menu_items['enable_disable'] = menuitem self.menu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self._menu_items['quit'] = menuitem self.menu.addItem_(menuitem)
def applicationDidFinishLaunching_(self, notification): #activate logging with ToggleProxy -logging 1 self.shouldLog = NSUserDefaults.standardUserDefaults().boolForKey_("logging") # load icon files self.active_image = NSImage.imageNamed_("StatusBarImage") self.inactive_image = NSImage.imageNamed_("StatusBarImage-inactive") self.no_network_image = NSImage.imageNamed_("StatusBarImage-noNetwork") self.active_image.setTemplate_(True) self.inactive_image.setTemplate_(True) self.no_network_image.setTemplate_(True) # make status bar item self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) self.statusitem.retain() self.statusitem.setHighlightMode_(False) self.statusitem.setEnabled_(True) # insert a menu into the status bar item self.menu = NSMenu.alloc().init() self.statusitem.setMenu_(self.menu) # open connection to the dynamic (configuration) store self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None) self.prefDict = SCNetworkProtocolGetConfiguration(SCNetworkServiceCopyProtocol(self.service, kSCNetworkProtocolTypeProxies)) self.constructMenu() self.watchForProxyOrIpChanges() self.updateUI() self.setEnvVariables()
def initializeStatusBar(self): _log(self) self.nsstatusitem = NSStatusBar.systemStatusBar( ).statusItemWithLength_(-1) # variable dimensions self.nsstatusitem.setHighlightMode_(True) self.mainmenu = NSMenu.alloc().init() self.nsstatusitem.setMenu_( self.mainmenu) # mainmenu of our status bar spot self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') _log(self.mainmenu) if self._app['_icon'] is not None: self.setStatusBarIcon() _log('creating icon') if self._app['_title'] is not None: self.setStatusBarTitle() else: self.setStatusBarTitle() if self._app['_menu'] is not None: for item in self._app['_menu'].itervalues(): self.mainmenu.addItem_( item() ) # calling works for separators and getting NSMenuItem from MenuItem objs self.mainmenu.addItem_(self.quit)
def setupAppleMenu(): appleMenuController = objc.lookUpClass('NSAppleMenuController').alloc().init() appleMenu = NSMenu.alloc().initWithTitle_('') appleMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('', None, '') appleMenuItem.setSubmenu_(appleMenu) NSApp().mainMenu().addItem_(appleMenuItem) appleMenuController.controlMenu_(appleMenu) NSApp().mainMenu().removeItem_(appleMenuItem)
def setupStatusBar(self): statusbar = NSStatusBar.systemStatusBar() statusitem = statusbar.statusItemWithLength_(20).retain() icon = NSImage.imageNamed_('status') icon.setSize_((20, 20)) statusitem.setImage_(icon) iconHighlight = NSImage.imageNamed_('status-hi') iconHighlight.setSize_((20, 20)) statusitem.setAlternateImage_(iconHighlight) statusitem.setHighlightMode_(1) # TODO: Put this whole menu creation stuff into interface builder! menu = NSMenu.alloc().init() linkMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Post a Link', 'doLink:', '') linkMenu.setTarget_(self); # Make it possible to invoke the link menu via a keyboard shortcut. linkMenu.setKeyEquivalentModifierMask_(NSShiftKeyMask | NSCommandKeyMask) linkMenu.setKeyEquivalent_('l') menu.addItem_(linkMenu) menu.addItem_(NSMenuItem.separatorItem()) previewMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Update Preview', 'doPreview:', '') previewMenu.setTarget_(self); menu.addItem_(previewMenu) publishMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Publish', None, '') publishMenu = NSMenu.alloc().init(); s3MenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('S3', 'doPublish:', '') s3MenuItem.setTarget_(self); publishMenu.addItem_(s3MenuItem) publishMenuItem.setSubmenu_(publishMenu) menu.addItem_(publishMenuItem) menu.addItem_(NSMenuItem.separatorItem()) quitMenu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') menu.addItem_(quitMenu) statusitem.setMenu_(menu) menu.release();
def applicationDidFinishLaunching_(self, notification): # load icon files self.active_image = NSImage.imageNamed_("active") self.inactive_image = NSImage.imageNamed_("inactive") # make status bar item self.statusitem = NSStatusBar.systemStatusBar().statusItemWithLength_( NSVariableStatusItemLength) self.statusitem.retain() self.statusitem.setHighlightMode_(False) self.statusitem.setEnabled_(True) # insert a menu into the status bar item self.menu = NSMenu.alloc().init() self.statusitem.setMenu_(self.menu) # open connection to the dynamic (configuration) store self.store = SCDynamicStoreCreate(None, "name.klep.toggleproxy", self.dynamicStoreCallback, None) proxyRef = SCNetworkServiceCopyProtocol(self.service, kSCNetworkProtocolTypeProxies) prefDict = SCNetworkProtocolGetConfiguration(proxyRef) hasProxies = False # For each of the proxies we are concerned with, check to see if any # are configured. If so (even if not enabled), create a menuitem for # that proxy type. for proxy in self.proxies.values(): enabled = CFDictionaryGetValue(prefDict, proxy['pref']) if enabled is not None: proxy[ 'menuitem'] = self.menu.addItemWithTitle_action_keyEquivalent_( proxy['title'], proxy['action'], proxy['keyEquivalent']) hasProxies = True else: proxy['menuitem'] = None if hasProxies: self.menu.addItem_(NSMenuItem.separatorItem()) self.enableallmi = self.menu.addItemWithTitle_action_keyEquivalent_( 'Enable All', 'enableall', '') self.disableallmi = self.menu.addItemWithTitle_action_keyEquivalent_( 'Disable All', 'disableall', '') self.menu.addItem_(NSMenuItem.separatorItem()) # Need a way to quit self.menu.addItemWithTitle_action_keyEquivalent_( "Quit", "quitApp:", "") # Start working # self.loadNetworkServices() self.watchForProxyChanges() self.updateProxyStatus()
def setupWindowMenu(): windowMenu = NSMenu.alloc().initWithTitle_('Window') menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Minimize', 'performMiniaturize:', 'm') windowMenu.addItem_(menuItem) del menuItem windowMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Window', None, '') windowMenuItem.setSubmenu_(windowMenu) NSApp().mainMenu().addItem_(windowMenuItem) NSApp().setWindowsMenu_(windowMenu)
def setupUI(self): self.statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = self.statusbar.statusItemWithLength_(NSVariableStatusItemLength) # Set initial image raw_data = base64.b64decode(''.join(GOAGENT_ICON_DATA.strip().splitlines())) self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data)) self.image = NSImage.alloc().initWithData_(self.image_data) self.statusitem.setImage_(self.image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) # Set a tooltip self.statusitem.setToolTip_(GOAGENT_TITLE) # Build a very simple menu self.menu = NSMenu.alloc().init() # Show Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Show', 'show:', '') self.menu.addItem_(menuitem) # Hide Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Hide', 'hide2:', '') self.menu.addItem_(menuitem) # Rest Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Reload', 'reset:', '') self.menu.addItem_(menuitem) # Default event menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'exit:', '') self.menu.addItem_(menuitem) # Bind it to the status item self.statusitem.setMenu_(self.menu) # Console window frame = NSMakeRect(0,0,550,350) self.console_window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(frame, NSClosableWindowMask|NSTitledWindowMask, NSBackingStoreBuffered, False) self.console_window.setTitle_(GOAGENT_TITLE) self.console_window.setDelegate_(self) # Console view inside a scrollview self.scroll_view = NSScrollView.alloc().initWithFrame_(frame) self.scroll_view.setBorderType_(NSNoBorder) self.scroll_view.setHasVerticalScroller_(True) self.scroll_view.setHasHorizontalScroller_(False) self.scroll_view.setAutoresizingMask_(NSViewWidthSizable|NSViewHeightSizable) self.console_view = NSTextView.alloc().initWithFrame_(frame) self.console_view.setVerticallyResizable_(True) self.console_view.setHorizontallyResizable_(True) self.console_view.setAutoresizingMask_(NSViewWidthSizable) self.scroll_view.setDocumentView_(self.console_view) contentView = self.console_window.contentView() contentView.addSubview_(self.scroll_view) # Hide dock icon NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
def setItems(self, items): """ Set the items to appear in the pop up list. """ self._callbackWrappers = [] self._nsObject.removeAllItems() menu = NSMenu.alloc().init() menu.addItem_(self.getFirstItem()) VanillaMenuBuilder(self, items, menu) self._nsObject.setMenu_(menu)
def initialize_menu(self): self.menubarMenu = NSMenu.alloc().init() self.menubarMenu.addItem_(NSMenuItem.separatorItem()) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.menubarMenu.addItem_(self.quit) self.statusitem.setMenu_(self.menubarMenu) self.statusitem.setToolTip_('Project Cron')
def __setitem__(self, key, value): if key in self: return if not isinstance(value, MenuItem): raise TypeError('values must be instances of MenuItem class; given {}'.format(type(value))) if self._submenu is None: self._submenu = NSMenu.alloc().init() self._menuitem.setSubmenu_(self._submenu) self._submenu.addItem_(value._menuitem) super(MenuItem, self).__setitem__(key, value)
def _makeMenuForGlyphRecord(self, index): glyphRecord = self._glyphRecords[index] glyph = glyphRecord.glyph font = glyph.getParent() if font is None: return None menu = NSMenu.alloc().init() for alternateName in glyphRecord.alternates: alternate = font[alternateName] item = self._getGlyphMenuItem(alternate) menu.addItem_(item) return menu
def finishLaunching(self): # Make statusbar item statusbar = NSStatusBar.systemStatusBar() self.statusitem = statusbar.statusItemWithLength_( NSVariableStatusItemLength) # Thanks Matthias Kretschmann # at http://kremalicious.com/coffee-cup-icon/ icon_path = NSBundle.mainBundle()\ .pathForResource_ofType_( ICON_BASE, ICON_EXT) if not icon_path: icon_path = ICON_FILE self.icon = NSImage.alloc()\ .initByReferencingFile_(icon_path) self.icon.setScalesWhenResized_(True) self.icon.setSize_((20, 20)) self.statusitem.setImage_(self.icon) # Make the menu self.menubarMenu = NSMenu.alloc().init() self.menuItem = NSMenuItem.alloc()\ .initWithTitle_action_keyEquivalent_( 'Connect', 'connectAndCloseCNA:', '') self.menubarMenu.addItem_(self.menuItem) self.quit = NSMenuItem.alloc()\ .initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.menubarMenu.addItem_(self.quit) # Add menu to statusitem self.statusitem.setMenu_(self.menubarMenu) self.statusitem.setToolTip_('Cartel') self.statusitem.setHighlightMode_(True) # Get the default notification center. self.workspace = NSWorkspace.sharedWorkspace() self.default_center = NSNotificationCenter.defaultCenter() # Create the handler self.rhandler = ReachabilityHandler.new() self.rhandler.app = self self.default_center.addObserver_selector_name_object_( self.rhandler, "handleChange:", kReachabilityChangedNotification, None) # Create the reachability object and start notifactions. self.reachability = Reachability() self.reachability.startNotifier()
def __setitem__(self, key, value): if key in self: return if not isinstance(value, MenuItem): raise TypeError( 'values must be instances of MenuItem class; given {}'.format( type(value))) if self._submenu is None: self._submenu = NSMenu.alloc().init() self._menuitem.setSubmenu_(self._submenu) self._submenu.addItem_(value._menuitem) super(MenuItem, self).__setitem__(key, value)
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 createMainMenu(self): mainMenu = NSMenu.alloc().init() # menu bar mainMenuItem = NSMenuItem.alloc().init() mainMenu.addItem_(mainMenuItem) # NOTE: The title of the first menu will automatically refer to CFBundleName. appMenu = NSMenu.alloc().init() appMenu.addItemWithTitle_action_keyEquivalent_( "About", "orderFrontStandardAboutPanel:", "", ) appMenu.addItem_(NSMenuItem.separatorItem()) appMenu.addItemWithTitle_action_keyEquivalent_( "Quit", "terminate:", "q", ) mainMenuItem.setSubmenu_(appMenu) return mainMenu
def build_menu(labels): menu = NSMenu.alloc().init() menu.setAutoenablesItems_(True) for label in labels: item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( localize._X(label), label.lower().replace(" ", "").split(" ")[0]+":", "") iconpath = os.path.join(settings.menuiconfolder, label.lower() + ".icns") if os.path.exists(iconpath): img = NSImage.alloc().initByReferencingFile_(iconpath) img.setSize_(NSSize(16, 16)) item.setImage_(img) menu.addItem_(item) return menu
def finishLaunching(self): # Get current track info curr_track = get_current_track() self.lyrics = get_lyrics(curr_track['curr_artist'], curr_track['curr_song']).split('<br>') # Remove empty lines self.lyrics = [x for x in self.lyrics if x] # Cache current track to avoid unnecessary requests self.curr_track_hash = abs(hash(curr_track['curr_track_full'])) % (10** 8) # Create the status & menu bar statusBar = NSStatusBar.systemStatusBar() self.statusItem = statusBar.statusItemWithLength_(-1) self.statusItem.setTitle_(curr_track['curr_track_full']) self.menuBar = NSMenu.alloc().init() # Lyrics block for i, row in enumerate(self.lyrics): row = re.sub('<[^<]+?>', '', row).strip() setattr( self, 'row_{}'.format(i), NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( row, 'doNothing:', '')) self.menuBar.addItem_(getattr(self, 'row_{}'.format(i))) self.SEPERATOR = NSMenuItem.separatorItem() self.menuBar.addItem_(self.SEPERATOR) # Quit option self.QUIT = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.SEPERATOR = NSMenuItem.separatorItem() self.menuBar.addItem_(self.SEPERATOR) self.menuBar.addItem_(self.QUIT) # Add menu to status bar self.statusItem.setMenu_(self.menuBar) # Create our timer for song title updates self.timer = NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 1, self, 'update:', '', True) # Add our timer to the runloop NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSEventTrackingRunLoopMode)
def menuForEvent_(self, event): _point = self.convertPoint_fromView_(event.locationInWindow(), None) _index = self.rowAtPoint_(_point) if -1 == _index: return None if not self.isRowSelected_(_index): self.selectRow_byExtendingSelection_(_index, False) _item = self.itemAtRow_(_index) _layer = Globals.unwrap(_item) if not isinstance(_layer, PythonCAD.Generic.layer.Layer): raise TypeError, "Invalid Layer: " + `_layer` _menu = NSMenu.alloc().initWithTitle_("Context") _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Rename", "EditLayerName:", "") _menu.addItem_(_menuItem) if _layer.isVisible(): _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Hide", "HideLayer:", "") else: _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Show", "ShowLayer:", "") _menuItem.setRepresentedObject_(_item) _menu.addItem_(_menuItem) _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Add Child Layer", "AddChildLayer:", "") _menuItem.setRepresentedObject_(_item) _menu.addItem_(_menuItem) _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Clear", "ClearLayer:", "") _menuItem.setRepresentedObject_(_item) _menu.addItem_(_menuItem) if _layer.hasChildren(): _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Hide Children", "HideChildLayers:", "") _menuItem.setRepresentedObject_(_item) _menu.insertItem_atIndex_(_menuItem, 3) _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Show Children", "ShowChildLayers:", "") _menuItem.setRepresentedObject_(_item) _menu.insertItem_atIndex_(_menuItem, 4) elif _layer.getParentLayer() is not None: _menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Delete", "DeleteLayer:", "") _menuItem.setRepresentedObject_(_item) _menu.addItem_(_menuItem) return _menu
def start_taskbar(): t = NSStatusBar.systemStatusBar() icon = t.statusItemWithLength_(NSVariableStatusItemLength) icon.setHighlightMode_(1) menuitems = [] labels = ["Open", "Logout", "Quit"] if patch.current.current == "DEV" or patch.config.branch == "master": labels = ["Open", "Logout", "Restart", "Test", "Quit"] for label in labels: item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( localize._X(label), label.lower().replace(" ", "").split(" ")[0] + ":", "") iconpath = os.path.join(settings.menuiconfolder, label.lower() + ".icns") if os.path.exists(iconpath): img = NSImage.alloc().initByReferencingFile_(iconpath) img.setSize_(NSSize(16, 16)) item.setImage_(img) menuitems.append(item) menu = NSMenu.alloc().init() menu.setAutoenablesItems_(True) icon.setMenu_(menu) for m in menuitems: menu.addItem_(m) def set_image(path): taskbarimg = NSImage.alloc().initByReferencingFile_(path) taskbarimg.setSize_(NSSize(18, 18)) icon.setImage_(taskbarimg) # taskbar icon switching @event.register("api:connected") def set_active(*_): set_image(settings.taskbaricon) @event.register("api:disconnected") @event.register("api:connection_error") def set_inactive(*_): set_image(settings.taskbaricon_inactive) set_image(settings.taskbaricon_inactive) icon.setEnabled_(True) @login.config.register('username') def _(): item = menu.itemAtIndex_(0) item.setTitle_(login.config.username or "Open")
def _initialize_menu(self): self.menubarMenu = NSMenu.alloc().init() for schedule in self._schedules: menu_item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(schedule.name, 'execute:', '') self._menu_items.append(menu_item) self.menubarMenu.addItem_(menu_item) menu_item = NSMenuItem.separatorItem() self.menubarMenu.addItem_(menu_item) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menubarMenu.addItem_(self.quit) self.statusitem.setMenu_(self.menubarMenu) self.statusitem.setToolTip_('Crow')
def build_menu(labels): menu = NSMenu.alloc().init() menu.setAutoenablesItems_(True) for label in labels: item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( localize._X(label), label.lower().replace(" ", "").split(" ")[0] + ":", "") iconpath = os.path.join(settings.menuiconfolder, label.lower() + ".icns") if os.path.exists(iconpath): img = NSImage.alloc().initByReferencingFile_(iconpath) img.setSize_(NSSize(16, 16)) item.setImage_(img) menu.addItem_(item) return menu
def start_taskbar(): t = NSStatusBar.systemStatusBar() icon = t.statusItemWithLength_(NSVariableStatusItemLength) icon.setHighlightMode_(1) menuitems = [] labels = ["Open", "Logout", "Quit"] if patch.current.current == "DEV" or patch.config.branch == "master": labels = ["Open", "Logout", "Restart", "Test", "Quit"] for label in labels: item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( localize._X(label), label.lower().replace(" ", "").split(" ")[0]+":", "") iconpath = os.path.join(settings.menuiconfolder, label.lower() + ".icns") if os.path.exists(iconpath): img = NSImage.alloc().initByReferencingFile_(iconpath) img.setSize_(NSSize(16, 16)) item.setImage_(img) menuitems.append(item) menu = NSMenu.alloc().init() menu.setAutoenablesItems_(True) icon.setMenu_(menu) for m in menuitems: menu.addItem_(m) def set_image(path): taskbarimg = NSImage.alloc().initByReferencingFile_(path) taskbarimg.setSize_(NSSize(18, 18)) icon.setImage_(taskbarimg) # taskbar icon switching @event.register("api:connected") def set_active(*_): set_image(settings.taskbaricon) @event.register("api:disconnected") @event.register("api:connection_error") def set_inactive(*_): set_image(settings.taskbaricon_inactive) set_image(settings.taskbaricon_inactive) icon.setEnabled_(True) @login.config.register('username') def _(): item = menu.itemAtIndex_(0) item.setTitle_(login.config.username or "Open")
def _setup_menu_bar(self): """Setup the menu bar of the app.""" self.main_menu = NSStatusBar.systemStatusBar().statusItemWithLength_(-1) self.menuBar = NSMenu.alloc().init() # [f for f in dir(NSButton) if 'Title' in f] self.button = self.main_menu.button self.update_(None) # Menu items quit_menu = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Quit", "terminate:", "") # Add items to the menuBar self.menuBar.addItem_(quit_menu) # Add menu to status bar self.main_menu.setMenu_(self.menuBar)
def _init_menu(self): menu = NSMenu.alloc().init() # App name menu appname_menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( # noqa u'{} {}'.format(unicode(sc.name), sc.version), None, '' ) menu.addItem_(appname_menuitem) # Quit menu # action `xxx:` will bind to `xxx_` method of delegate quit_menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( # noqa unicode('Quit'), 'quit:', 'q' ) quit_menuitem.setTarget_(sc) menu.addItem_(quit_menuitem) self.nsstatusitem.setMenu_(menu)
def applicationDidFinishLaunching_(self, notification): global start_time statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = statusbar.statusItemWithLength_(70.0) # Set initial image self.statusitem.setTitle_(self.updateGeektime()) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.menu = NSMenu.alloc().init() menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menu.addItem_(menuitem) self.statusitem.setMenu_(self.menu) self.timer = NSTimer.alloc().initWithFireDate_interval_target_selector_userInfo_repeats_(start_time, 0.65, self, 'tick:', None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) self.timer.fire()
def update_(self, timer): curr_track = get_current_track() self.statusItem.setTitle_(curr_track['curr_track_full']) self.next_track_hash = abs(hash(curr_track['curr_track_full'])) % (10** 8) if self.curr_track_hash != self.next_track_hash: self.lyrics = get_lyrics(curr_track['curr_artist'], curr_track['curr_song']).split('<br>') # Remove empty lines self.lyrics = [x for x in self.lyrics if x] self.curr_track_hash = abs(hash( curr_track['curr_track_full'])) % (10**8) # Create the status & menu bar statusBar = NSStatusBar.systemStatusBar() self.statusItem = statusBar.statusItemWithLength_(-1) self.statusItem.setTitle_(curr_track['curr_track_full']) self.menuBar = NSMenu.alloc().init() # Lyrics block for i, row in enumerate(self.lyrics): row = re.sub('<[^<]+?>', '', row).strip() setattr( self, 'row_{}'.format(i), NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( row, 'doNothing:', '')) self.menuBar.addItem_(getattr(self, 'row_{}'.format(i))) self.SEPERATOR = NSMenuItem.separatorItem() self.menuBar.addItem_(self.SEPERATOR) # Quit option self.QUIT = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.SEPERATOR = NSMenuItem.separatorItem() self.menuBar.addItem_(self.SEPERATOR) self.menuBar.addItem_(self.QUIT) # Add menu to status bar self.statusItem.setMenu_(self.menuBar)
def create_ui(self): icon = NSImage.alloc().initByReferencingFile_('main.icns') icon.setScalesWhenResized_(True) icon.setSize_((20, 20)) self.menu = NSMenu.alloc().init() configureMenuItem = NSMenuItem.alloc( ).initWithTitle_action_keyEquivalent_('Configure', 'clickedConfigure:', '') self.menu.addItem_(configureMenuItem) quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.menu.addItem_(quit) self.nsstatusitem = NSStatusBar.systemStatusBar( ).statusItemWithLength_(NSVariableStatusItemLength) self.nsstatusitem.setImage_(icon) self.nsstatusitem.setHighlightMode_(True) self.nsstatusitem.setMenu_(self.menu)
def finishLaunching(self): # Make statusbar item statusbar = NSStatusBar.systemStatusBar() self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength) self.icon = NSImage.alloc().initByReferencingFile_('icon.png') self.icon.setScalesWhenResized_(True) self.icon.setSize_((20, 20)) self.statusitem.setImage_(self.icon) #make the menu self.menubarMenu = NSMenu.alloc().init() self.menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Click Me', 'clicked:', '') self.menubarMenu.addItem_(self.menuItem) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') self.menubarMenu.addItem_(self.quit) #add menu to statusitem self.statusitem.setMenu_(self.menubarMenu) self.statusitem.setToolTip_('My App')
def finishLaunching(self): # Make statusbar item statusbar = NSStatusBar.systemStatusBar() self.statusitem = statusbar.statusItemWithLength_(NSVariableStatusItemLength) self.icon = NSImage.alloc().initByReferencingFile_("icon.png") self.icon.setScalesWhenResized_(True) self.icon.setSize_((20, 20)) self.statusitem.setImage_(self.icon) # make the menu self.menubarMenu = NSMenu.alloc().init() self.menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Test Notification", "clicked:", "") self.menubarMenu.addItem_(self.menuItem) self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Quit", "terminate:", "") self.menubarMenu.addItem_(self.quit) # add menu to statusitem self.statusitem.setMenu_(self.menubarMenu) self.statusitem.setToolTip_("My App") self._notify_obj = Notification.alloc().init()
def applicationDidFinishLaunching_(self, notification): self.native.activateIgnoringOtherApps(True) self.statusItem = NSStatusBar.systemStatusBar().statusItemWithLength_(NSVariableStatusItemLength) self.statusItem.setHighlightMode_(True) self.statusItem.setEnabled_(True) self.icon = NSImage.alloc().initByReferencingFile_("resources/app.icns") self.icon.setSize_((20,20)) self.statusItem.setImage_(self.icon) self.menu = NSMenu.alloc().init() item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Check For Updates", "update:", "") self.menu.addItem_(item) item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Open Website", "website:", "") self.menu.addItem_(item) item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("About", "about:", "") self.menu.addItem_(item) item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_("Quit", "quit:", "") self.menu.addItem_(item) self.statusItem.setMenu_(self.menu)
def initializeStatusBar(self): _log(self) self.nsstatusitem = NSStatusBar.systemStatusBar().statusItemWithLength_(-1) # variable dimensions self.nsstatusitem.setHighlightMode_(True) self.mainmenu = NSMenu.alloc().init() self.nsstatusitem.setMenu_(self.mainmenu) # mainmenu of our status bar spot self.quit = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') _log(self.mainmenu) if self._app['_icon'] is not None: self.setStatusBarIcon() _log('creating icon') if self._app['_title'] is not None: self.setStatusBarTitle() else: self.setStatusBarTitle() if self._app['_menu'] is not None: for item in self._app['_menu'].itervalues(): self.mainmenu.addItem_(item()) # calling works for separators and getting NSMenuItem from MenuItem objs self.mainmenu.addItem_(self.quit)
def setupUI(self): self.statusbar = NSStatusBar.systemStatusBar() self.statusitem = self.statusbar.statusItemWithLength_( NSVariableStatusItemLength ) #NSSquareStatusItemLength #NSVariableStatusItemLength # Set initial image icon icon_path = os.path.join(current_path, "../trayicon.ico") image = NSImage.alloc().initByReferencingFile_(icon_path) image.setScalesWhenResized_(True) image.setSize_((20, 20)) self.statusitem.setImage_(image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) self.statusitem.setToolTip_("ZeroNet") # Build a very simple menu self.menu = NSMenu.alloc().init() self.menu.setAutoenablesItems_(False) #self.create_menu_item( 'ip_external', 'IP: %s' % INFO['ip_external'], 'info:') self.menu.addItem_(NSMenuItem.separatorItem()) # Links self.create_menu_item('open_zeronet', 'Open ZeroNet', 'open:') self.create_menu_item('open_reddit', 'Zeronet Reddit Community', 'openreddit:') self.create_menu_item('open_gh', 'Report issues/feature requests', 'opengithub:') self.menu.addItem_(NSMenuItem.separatorItem()) self.create_menu_item('quit_zeronet', 'Quit ZeroNet', 'windowWillClose:') # Bind it to the status item and hide dock icon self.statusitem.setMenu_(self.menu) NSApp.setActivationPolicy_(NSApplicationActivationPolicyProhibited)
def _update_menubar(self): ns_app = self._ns_app ns_menubar = NSMenu.alloc().initWithTitle_("") menu_list = self._effective_menus() for menu in menu_list: ns_item = NSMenuItem.alloc() ns_item.initWithTitle_action_keyEquivalent_(menu.title, '', "") ns_menubar.addItem_(ns_item) ns_menu = menu._ns_menu # An NSMenu can only be a submenu of one menu at a time, so # remove it from the old menubar if necessary. old_supermenu = ns_menu.supermenu() if old_supermenu: i = old_supermenu.indexOfItemWithSubmenu_(ns_menu) old_supermenu.removeItemAtIndex_(i) ns_menubar.setSubmenu_forItem_(ns_menu, ns_item) # The menu you pass to setAppleMenu_ must *also* be a member of the # main menu. ns_app.setMainMenu_(ns_menubar) if menu_list: ns_app_menu = menu_list[0]._ns_menu ns_app.setAppleMenu_(ns_app_menu)
def _buildMenu(self, items, menu): for item in items: if isinstance(item, NSMenuItem): menu.addItem_(item) elif item == "----": item = NSMenuItem.separatorItem() menu.addItem_(item) else: title = item["title"] callback = item.get("callback") subItems = item.get("items") menuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(title, "", "") if callback: wrapper = VanillaCallbackWrapper(callback) self._callbackWrappers.append(wrapper) menuItem.setTarget_(wrapper) menuItem.setAction_("action:") if subItems: subMenu = NSMenu.alloc().init() self._buildMenu(subItems, subMenu) menuItem.setSubmenu_(subMenu) menu.addItem_(menuItem)
def applicationDidFinishLaunching_(self, notification): self.statusbar = NSStatusBar.systemStatusBar() # Create the statusbar item self.statusitem = self.statusbar.statusItemWithLength_( NSVariableStatusItemLength) # Set initial image raw_data = base64.b64decode(''.join( GOAGENT_ICON_DATA.strip().splitlines())) self.image_data = NSData.dataWithBytes_length_(raw_data, len(raw_data)) self.image = NSImage.alloc().initWithData_(self.image_data) self.statusitem.setImage_(self.image) # Let it highlight upon clicking self.statusitem.setHighlightMode_(1) # Set a tooltip self.statusitem.setToolTip_('GoAgent OSX') # Build a very simple menu self.menu = NSMenu.alloc().init() # Show Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Show', 'show:', '') self.menu.addItem_(menuitem) # Hide Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Hide', 'hide:', '') self.menu.addItem_(menuitem) # Rest Menu Item menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Reset', 'reset:', '') self.menu.addItem_(menuitem) # Default event menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.menu.addItem_(menuitem) # Bind it to the status item self.statusitem.setMenu_(self.menu)
def __init__(self): self._separators = 1 if not hasattr(self, '_menu'): self._menu = NSMenu.alloc().init() super(Menu, self).__init__()
def _make_main_menu(self): self.main_menu = NSMenu.alloc().init() self.main_menu_delegate = DropboxDefaultMenuDelegate.alloc().init() self.main_menu.setDelegate_(self.main_menu_delegate) NSApplication.sharedApplication().setMainMenu_(self.main_menu)
def __init__(self): self._counts = {} if not hasattr(self, '_menu'): self._menu = NSMenu.alloc().init() super(Menu, self).__init__()
def instances_(self, _n): self.loop_func = sys._getframe(0).f_code.co_name try: x = subprocess.check_output(["/usr/local/bin/docker", "ps", "--format", "{{.Names}}"]) except subprocess.CalledProcessError as e: #print(e) self.statusitem.setImage_(self.image) # Keep looping, but don't do anything NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) return containers = x.splitlines() self.statusitem.setTitle_(str(len(containers))) new_menu = NSMenu.alloc().init() shellmenu = NSMenu.alloc().init() logmenu = NSMenu.alloc().init() i = NSMenuItem.alloc().init() i.setTitle_("Shell") i.setSubmenu_(shellmenu) new_menu.addItem_(i) i = NSMenuItem.alloc().init() i.setTitle_("Logs") i.setSubmenu_(logmenu) new_menu.addItem_(i) new_menu.addItem_(NSMenuItem.separatorItem()) for container in containers: shellmenuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(container, 'shellinto:', '') shellmenu.addItem_(shellmenuitem) logmenuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(container, 'loginto:', '') logmenu.addItem_(logmenuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(container, 'killinstance:', '') menuitem.setImage_(self.toggle_images['kill' if self.kill else 'refresh']) # pprint(dir(menuitem)) new_menu.addItem_(menuitem) new_menu.addItem_(NSMenuItem.separatorItem()) i = NSMenuItem.alloc().init() configmenu = NSMenu.alloc().init() i.setTitle_("Settings") i.setSubmenu_(configmenu) new_menu.addItem_(i) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Kill', 'killornot:', '') menuitem.setState_(NSOnState if self.kill else NSOffState) configmenu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Restart', 'killornot:', '') menuitem.setState_(NSOnState if not self.kill else NSOffState) configmenu.addItem_(menuitem) configmenu.addItem_(NSMenuItem.separatorItem()) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('iTerm', 'itermtoggle:', '') menuitem.setState_(NSOnState if self.which_terminal == 'iTerm' else NSOffState) configmenu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Terminal', 'itermtoggle:', '') menuitem.setState_(NSOnState if not self.which_terminal == 'iTerm' else NSOffState) configmenu.addItem_(menuitem) menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_('Quit', 'terminate:', '') new_menu.addItem_(menuitem) self.menu = new_menu self.statusitem.setMenu_(self.menu) if self.state == 'setup': self.state = 'running' if self.state == 'running': NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode)
def __setitem__(self, key, value): if self._menu is None: self._menu = NSMenu.alloc().init() self._menuitem.setSubmenu_(self._menu) super(MenuItem, self).__setitem__(key, value)
def finishLaunching(self): # Note: variable names here are camelCased to stay consistent with # pyobjc (except menubar items). # Create the status & menu bar statusBar = NSStatusBar.systemStatusBar() self.statusItem = statusBar.statusItemWithLength_(-1) self.statusItem.setTitle_('Simon') self.menuBar = NSMenu.alloc().init() # System self.SYSTEM = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'System', 'doNothing:', '') self.CPU_USAGE = self._create_empty_menu_item() self.RAM_USAGE = self._create_empty_menu_item() self.RAM_AVAILABLE = self._create_empty_menu_item() self.menuBar.addItem_(self.SYSTEM) self.menuBar.addItem_(self.CPU_USAGE) self.menuBar.addItem_(self.RAM_USAGE) self.menuBar.addItem_(self.RAM_AVAILABLE) # Disk I/O self.DISKIO = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Disk I/O', 'doNothing:', '') self.DATA_READ = self._create_empty_menu_item() self.DATA_WRITTEN = self._create_empty_menu_item() self.menuBar.addItem_(self.DISKIO) self.menuBar.addItem_(self.DATA_READ) self.menuBar.addItem_(self.DATA_WRITTEN) # Network self.NETWORK = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Network', 'doNothing:', '') self.NETWORK_RECV = self._create_empty_menu_item() self.NETWORK_SENT = self._create_empty_menu_item() self.menuBar.addItem_(self.NETWORK) self.menuBar.addItem_(self.NETWORK_RECV) self.menuBar.addItem_(self.NETWORK_SENT) # Quit self.QUIT = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( 'Quit', 'terminate:', '') self.SEPERATOR = NSMenuItem.separatorItem() self.menuBar.addItem_(self.SEPERATOR) self.menuBar.addItem_(self.QUIT) # Add menu to status bar self.statusItem.setMenu_(self.menuBar) # Create our timer self.timer = \ NSTimer \ .scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 1, self, 'update:', '', True ) # Add our timer to the runloop NSRunLoop.currentRunLoop().addTimer_forMode_( self.timer, NSEventTrackingRunLoopMode) print('Simon is now running.') print('CTRL+C does not work here.') print('You can quit through the menubar.')