コード例 #1
0
ファイル: BtBatStat.py プロジェクト: Ku2f/btbatstat
  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()
コード例 #2
0
ファイル: tray_osx.py プロジェクト: barrabinfc/ZeroNet
    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)
コード例 #3
0
ファイル: tray.py プロジェクト: jone/unison-tray
    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)
コード例 #4
0
ファイル: cocoa.py プロジェクト: BarnabasSzabolcs/pyquasargui
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'])
コード例 #5
0
ファイル: goagent-osx.py プロジェクト: SkyRaker/GoAgentX
    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)
コード例 #6
0
    def refreshDropboxMenu_(self, items):
        try:
            self.removeAllItems()
        except:
            for i in reversed(xrange(self.numberOfItems())):
                self.removeItemAtIndex_(i)

        for text, func in items:
            if text is None:
                menuitem = NSMenuItem.separatorItem()
            elif type(func) in (list, tuple):
                text = unicode(text)
                menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(text, None, '')
                submenu = DropboxNSMenu.menuWithDropboxMenuDescriptor_(func)
                menuitem.setSubmenu_(submenu)
            else:
                text = unicode(text)
                menuitem = DropboxNSMenuItem.alloc().initWithTitle_action_keyEquivalent_(text, None, '')
                if hasattr(func, '__call__'):
                    menuitem.dropboxFunc = func
                    menuitem.setTarget_(self)
                    menuitem.setAction_('menuAction:')
                else:
                    menuitem.setEnabled_(False)
            self.addItem_(menuitem)

        return self
コード例 #7
0
ファイル: menu.py プロジェクト: jpbarraca/MailTrack_OSX
    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_(
                "MailTrack",
                "toggleState:",
                "")
            self.item.setToolTip_(self.get_string("MAILTRACK_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.MailTrackDisabled",
                NSKeyValueObservingOptionNew,
                None
            )

        except Exception, e:
            raise e
コード例 #8
0
ファイル: menu.py プロジェクト: GLOP1978/quotefixformac
    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
コード例 #9
0
ファイル: macosx.py プロジェクト: deavid/soyamirror
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)
コード例 #10
0
ファイル: goagent-osx.py プロジェクト: 0ks3ii/GoAgentX
    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)
コード例 #11
0
ファイル: cartel.py プロジェクト: jmatt/cartel
    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()
コード例 #12
0
ファイル: testTools.py プロジェクト: roberto-arista/vanilla
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()
コード例 #13
0
    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)
コード例 #14
0
ファイル: main.py プロジェクト: smartstudy/project_cron
    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')
コード例 #15
0
ファイル: MailWrap.py プロジェクト: javigon/mailwrap
    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)
コード例 #16
0
ファイル: rumps.py プロジェクト: mjhea0/rumps
 def __init__(self, title, callback=None, key='', icon=None, dimensions=None):
     self._menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(str(title), None, '')
     if callable(callback):
         self.set_callback(callback, key)
     self._submenu = self._icon = None
     self.set_icon(icon, dimensions)
     super(MenuItem, self).__init__()
コード例 #17
0
def addToolbarItem(aController, anIdentifier, aLabel, aPaletteLabel, aToolTip,
                   aTarget, anAction, anItemContent, aMenu):
    """
    Add a toolbar button of some kind.
    """
    toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(anIdentifier)

    toolbarItem.setLabel_(aLabel)
    toolbarItem.setPaletteLabel_(aPaletteLabel)
    toolbarItem.setToolTip_(aToolTip)
    toolbarItem.setTarget_(aTarget)
    if anAction:
        toolbarItem.setAction_(anAction)

    if type(anItemContent) == NSImage:
        toolbarItem.setImage_(anItemContent)
    else:
        toolbarItem.setView_(anItemContent)
        bounds = anItemContent.bounds()
        minSize = (bounds[1][0], bounds[1][1])
        maxSize = (bounds[1][0], bounds[1][1])
        toolbarItem.setMinSize_(minSize)
        toolbarItem.setMaxSize_(maxSize)

    if aMenu:
        menuItem = NSMenuItem.alloc().init()
        menuItem.setSubmenu_(aMenu)
        menuItem.setTitle_(aMenu.title())
        toolbarItem.setMenuFormRepresentation_(menuItem)

    aController._toolbarItems[anIdentifier] = toolbarItem
コード例 #18
0
ファイル: rumps.py プロジェクト: mjhea0/rumps
    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)
コード例 #19
0
 def start(self):
     """Starts the plugin"""
     mainMenu = Glyphs.mainMenu()
     s = objc.selector(self.invokePlugin_, signature=b'v@:@')
     newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(self.name, s, '')
     newMenuItem.setTarget_(self)
     mainMenu.itemWithTag_(5).submenu().addItem_(newMenuItem)
コード例 #20
0
    def constructMenu(self):
        self.menu.removeAllItems()

        separator_required = False
        if self.is_ip_assigned:
            # For each of the proxyTypes 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.proxyTypes.values():
                enabled = CFDictionaryGetValue(self.prefDict, proxy['prefEnable'])
                if enabled is not None:
                    proxy['menuitem'] = self.menu.addItemWithTitle_action_keyEquivalent_(
                        proxy['title'],
                        proxy['action'],
                        proxy['keyEquivalent']
                    )
                    separator_required = True
                else:
                    proxy['menuitem'] = None
        else:
            self.menu.addItemWithTitle_action_keyEquivalent_("No connection - Please connect to any network before using this tool", None, "")

        if separator_required:
            self.menu.addItem_(NSMenuItem.separatorItem())

         # Need a way to quit
        self.menu.addItemWithTitle_action_keyEquivalent_("Quit", "quitApp:", "q")
コード例 #21
0
def addToolbarItem(aController, anIdentifier, aLabel, aPaletteLabel,
                   aToolTip, aTarget, anAction, anItemContent, aMenu):
    """
    Add a toolbar button of some kind.
    """
    toolbarItem = NSToolbarItem.alloc().initWithItemIdentifier_(anIdentifier)

    toolbarItem.setLabel_(aLabel)
    toolbarItem.setPaletteLabel_(aPaletteLabel)
    toolbarItem.setToolTip_(aToolTip)
    toolbarItem.setTarget_(aTarget)
    if anAction:
        toolbarItem.setAction_(anAction)

    if type(anItemContent) == NSImage:
        toolbarItem.setImage_(anItemContent)
    else:
        toolbarItem.setView_(anItemContent)
        bounds = anItemContent.bounds()
        minSize = (bounds[1][0], bounds[1][1])
        maxSize = (bounds[1][0], bounds[1][1])
        toolbarItem.setMinSize_(minSize)
        toolbarItem.setMaxSize_(maxSize)

    if aMenu:
        menuItem = NSMenuItem.alloc().init()
        menuItem.setSubmenu_(aMenu)
        menuItem.setTitle_(aMenu.title())
        toolbarItem.setMenuFormRepresentation_(menuItem)

    aController._toolbarItems[anIdentifier] = toolbarItem
コード例 #22
0
ファイル: WordOMat.py プロジェクト: mekkablue/word-o-mat
    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)
コード例 #23
0
ファイル: macosx.py プロジェクト: deavid/soyamirror
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)
コード例 #24
0
 def makeDisplaySettingsMenuItems(self):
     displaySettingsMenuItems = [
         NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
             self.displaySettingsRecord[key][0], None, '')
         for key in sorted(self.displaySettingsRecord.keys())
     ]
     displaySettingsMenuItems.insert(0, 'Settings')
     return displaySettingsMenuItems
コード例 #25
0
ファイル: macos_counter.py プロジェクト: mynicolas/KeyCounter
            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)
コード例 #26
0
            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)
コード例 #27
0
 def __init__(self, title, callback=None, key='', icon=None, dimensions=None):
     if isinstance(title, MenuItem):  # don't initialize already existing instances
         return
     self._menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(str(title), None, '')
     if callable(callback):
         self.set_callback(callback, key)
     self._menu = self._icon = None
     self.set_icon(icon, dimensions)
     super(MenuItem, self).__init__()
コード例 #28
0
ファイル: rumps.py プロジェクト: philippeowagner/rumps
 def __init__(self, title, callback=None, key='', icon=None, dimensions=None):
     if isinstance(title, MenuItem):  # don't initialize already existing instances
         return
     self._menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(str(title), None, '')
     if callable(callback):
         self.set_callback(callback, key)
     self._menu = self._icon = None
     self.set_icon(icon, dimensions)
     super(MenuItem, self).__init__()
コード例 #29
0
 def _getGlyphMenuItem(self, glyph):
     name = glyph.name
     menuItem = NSMenuItem.alloc().init()
     image = glyph.getRepresentation("defconAppKit.MenuImage")
     menuItem.setImage_(image)
     menuItem.setTitle_(name)
     menuItem.setTarget_(self)
     menuItem.setAction_("_dummyAction:")
     return menuItem
コード例 #30
0
ファイル: rumps.py プロジェクト: danallan/rumps
 def __init__(self, title, callback=None, key=None, icon=None, dimensions=None, state=False):
     if isinstance(title, MenuItem):  # don't initialize already existing instances
         return
     self._menuitem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(unicode(title), None, '')
     self._menuitem.setTarget_(NSApp)
     self._menu = self._icon = None
     self.set_callback(callback, key)
     self.set_icon(icon, dimensions)
     self.state = state
     super(MenuItem, self).__init__()
コード例 #31
0
    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)
コード例 #32
0
 def getFirstItem(self):
     actionImage = NSImage.imageNamed_(NSImageNameActionTemplate).copy()
     sizeStyle = _reverseSizeStyleMap[self._nsObject.cell().controlSize()]
     if sizeStyle == "small":
         actionImage.setSize_((10, 10))
     elif sizeStyle == "mini":
         actionImage.setSize_((10, 10))
     firstActionItem = NSMenuItem.alloc().init()
     firstActionItem.setImage_(actionImage)
     firstActionItem.setTitle_("")
     return firstActionItem
コード例 #33
0
    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)
コード例 #34
0
 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)
コード例 #35
0
ファイル: BubbleKern.py プロジェクト: Tosche/BubbleKern
 def refreshOptions(self):  # refresh option items
     try:
         favNameList = self.favNameList()
         self.w.tabs[0].options.setItems(tab0options + favNameList)
         menu = self.w.tabs[0].options._nsObject.menu()
         menu.itemAtIndex_(0).setEnabled_(False)
         divider0 = NSMenuItem.separatorItem()
         menu.insertItem_atIndex_(divider0, 6)
         menu.itemAtIndex_(7).setEnabled_(False)
     except Exception as e:
         Glyphs.showMacroWindow()
         print("BubbleKern Error (refreshOptions): %s" % e)
コード例 #36
0
ファイル: MailFlow.py プロジェクト: arachsys/mailflow
    def _finishLoadingEditor(self, old):
        result = old(self)
        if self.messageType() not in [1, 2, 3, 8]:
            return result

        view = self.composeWebView()
        document = view.mainFrame().DOMDocument()
        view.contentElement().removeStrayLinefeeds()
        blockquotes = document.getElementsByTagName_('BLOCKQUOTE')
        for index in xrange(blockquotes.length()):
            if blockquotes.item_(index):
                blockquotes.item_(index).removeStrayLinefeeds()

        if self.messageType() in [1, 2, 8]:
            view.moveToBeginningOfDocument_(None)
            view.moveToEndOfParagraphAndModifySelection_(None)
            view.moveForwardAndModifySelection_(None)
            item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
                'Decrease', 'changeQuoteLevel:', '')
            item.setTag_(-1)
            view.changeQuoteLevel_(item)

            attribution = view.selectedDOMRange().stringValue()
            attribution = attribution.rsplit(u',', 1)[-1].lstrip()
            if view.isAutomaticTextReplacementEnabled():
                view.setAutomaticTextReplacementEnabled_(False)
                view.insertText_(attribution)
                view.setAutomaticTextReplacementEnabled_(True)
            else:
                view.insertText_(attribution)

            signature = document.getElementById_('AppleMailSignature')
            if signature:
                range = document.createRange()
                range.selectNode_(signature)
                view.setSelectedDOMRange_affinity_(range, 0)
                view.moveUp_(None)
            else:
                view.moveToEndOfDocument_(None)
                view.insertParagraphSeparator_(None)

        if self.messageType() == 3:
            for index in xrange(blockquotes.length()):
                blockquote = blockquotes.item_(index)
                if blockquote.quoteLevel() == 1:
                    blockquote.parentNode().insertBefore__(
                        document.createElement_('BR'), blockquote)

        view.insertParagraphSeparator_(None)
        view.undoManager().removeAllActions()
        self.setHasUserMadeChanges_(False)
        self.backEnd().setHasChanges_(False)
        return result
コード例 #37
0
ファイル: ab.py プロジェクト: d910aa14/pyobjc
    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')
コード例 #38
0
ファイル: MailFlow.py プロジェクト: rashikkathuria/mailflow
    def _finishLoadingEditor(self, old):
        result = old(self)
        if self.messageType() not in [1, 2, 3, 8]:
            return result

        view = self.composeWebView()
        document = view.mainFrame().DOMDocument()
        view.contentElement().removeStrayLinefeeds()
        blockquotes = document.getElementsByTagName_('BLOCKQUOTE')
        for index in xrange(blockquotes.length()):
            if blockquotes.item_(index):
                blockquotes.item_(index).removeStrayLinefeeds()

        if self.messageType() in [1, 2, 8]:
            view.moveToBeginningOfDocument_(None)
            view.moveToEndOfParagraphAndModifySelection_(None)
            view.moveForwardAndModifySelection_(None)
            item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(
                'Decrease', 'changeQuoteLevel:', '')
            item.setTag_(-1)
            view.changeQuoteLevel_(item)

            attribution = view.selectedDOMRange().stringValue()
            attribution = attribution.split(u',', 2)[-1].lstrip()
            if view.isAutomaticTextReplacementEnabled():
                view.setAutomaticTextReplacementEnabled_(False)
                view.insertText_(attribution)
                view.setAutomaticTextReplacementEnabled_(True)
            else:
                view.insertText_(attribution)

            signature = document.getElementById_('AppleMailSignature')
            if signature:
                range = document.createRange()
                range.selectNode_(signature)
                view.setSelectedDOMRange_affinity_(range, 0)
                view.moveUp_(None)
            else:
                view.moveToEndOfDocument_(None)
                view.insertParagraphSeparator_(None)

        if self.messageType() == 3:
            for index in xrange(blockquotes.length()):
                blockquote = blockquotes.item_(index)
                if blockquote.quoteLevel() == 1:
                    blockquote.parentNode().insertBefore__(
                        document.createElement_('BR'), blockquote)

        view.insertParagraphSeparator_(None)
        view.undoManager().removeAllActions()
        self.setHasUserMadeChanges_(False)
        self.backEnd().setHasChanges_(False)
        return result
コード例 #39
0
    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
            
        
        


        
            
            
コード例 #40
0
ファイル: native.py プロジェクト: rvpradeep/Python-UI
    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()
コード例 #41
0
    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)
コード例 #42
0
ファイル: testTools.py プロジェクト: schriftgestalt/vanilla
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()
コード例 #43
0
ファイル: app.py プロジェクト: Werniman/client
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
コード例 #44
0
 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)
コード例 #45
0
ファイル: plugin.py プロジェクト: jenskutilek/RedArrow-Glyphs
	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)
コード例 #46
0
ファイル: plugins.py プロジェクト: schriftgestalt/GlyphsSDK
def setUpMenuHelper(Menu, Items, defaultTarget):
	if type(Items) == list:
		for entry in Items:

			if "index" in entry:
				index = int(entry["index"])
			else:
				index = -1

			# Use supplied NSMenuItem
			if "menu" in entry:
				newMenuItem = entry["menu"]

			# Create menu item
			else:


				if "view" in entry and "name" not in entry:
					entry["name"] = ""
				if "view" in entry and "action" not in entry:
					entry["action"] = None


				newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(entry["name"], entry["action"], "")

				if "view" in entry:
					try:
						view = entry["view"]
						if isinstance(view, NSView):
							newMenuItem.setView_(view)
					except:
						LogToConsole(traceback.format_exc(), "setUpMenuHelper")  # from GlyhsApp.py
				if "state" in entry:
					state = entry["state"]
					if state == ONSTATE or state == OFFSTATE or state == MIXEDSTATE:
						newMenuItem.setState_(entry["state"])
					else:
						LogToConsole("illegal state for menu item '%s'" % entry["name"], "setUpMenuHelper")


			if "target" in entry:
				newMenuItem.setTarget_(entry["target"])
			else:
				newMenuItem.setTarget_(defaultTarget)

			if index >= 0:
				Menu.insertItem_atIndex_(newMenuItem, index)
			else:
				Menu.addItem_(newMenuItem)
コード例 #47
0
ファイル: app.py プロジェクト: MoroGasper/client
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")
コード例 #48
0
ファイル: suffixer.py プロジェクト: ninastoessinger/Suffixer
 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)