Example #1
0
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()
Example #2
0
    def initialize(cls):
        # instantiate updater
        updater = Updater()

        # register ourselves
        objc.runtime.MVMailBundle.registerBundle()

        # extract plugin version from Info.plist
        bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
        version = bundle.infoDictionary().get('CFBundleVersion', '??')

        # initialize app
        app = App(version, updater)

        # initialize our posing classes with app instance
        DocumentEditor.registerQuoteFixApplication(app)
        ComposeViewController.registerQuoteFixApplication(app)
        MessageHeaders.registerQuoteFixApplication(app)
        MailApp.registerQuoteFixApplication(app)
        QuoteFixPreferencesController.registerQuoteFixApplication(app)
        CustomizedAttribution.registerQuoteFixApplication(app)

        # announce that we have loaded
        NSLog("QuoteFix Plugin (version %s) registered with Mail.app" %
              version)
Example #3
0
    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)
Example #4
0
def keyboard_tap_callback(proxy, type_, event, refcon):
    from AppKit import NSKeyUp, NSEvent, NSBundle
    NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
        dict(NSAllowsArbitraryLoads=True)
    if type_ < 0 or type_ > 0x7fffffff:
        logger.error('Unkown mac event')
        run_event_loop()
        logger.error('restart mac key board event loop')
        return event
    try:
        key_event = NSEvent.eventWithCGEvent_(event)
    except:
        logger.info("mac event cast error")
        return event
    if key_event.subtype() == 8:
        key_code = (key_event.data1() & 0xFFFF0000) >> 16
        key_state = (key_event.data1() & 0xFF00) >> 8
        if key_code in (16, 19, 20):
            # 16 for play-pause, 19 for next, 20 for previous
            if key_state == NSKeyUp:
                if key_code is 19:
                    logger.info('mac hotkey: play next')
                    send_cmd('next')
                elif key_code is 20:
                    logger.info('mac hotkey: play last')
                    send_cmd('previous')
                elif key_code is 16:
                    os.system('echo "play_pause" | nc -4u -w0 localhost 8000')
                    send_cmd('toggle')
            return None
    return event
Example #5
0
def get_bundle_identifier_for_path(path):
    """
    Get bundle identifier for the given path.
    """
    bundle_url = 'file://' + os.path.abspath(path)
    return NSBundle.bundleWithURL_(
        NSURL.URLWithString_(bundle_url)).bundleIdentifier()
Example #6
0
def extract_tb(tb, script=None, src=None):
    """Return a list of pre-processed entries from traceback."""
    list = []
    n = 0
    while tb is not None:
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if filename == script:
            line = src.split('\n')[lineno - 1]
        else:
            linecache.checkcache(filename)
            line = linecache.getline(filename, lineno, f.f_globals)
        if line: line = line.strip()
        else: line = None
        list.append((filename, lineno, name, line))
        tb = tb.tb_next

    # omit the internal plotdevice stack frames in `dist` builds
    from AppKit import NSBundle
    debug = 'flux' in NSBundle.mainBundle().infoDictionary().get(
        'CFBundleVersion', '')
    if not debug:
        moduledir = abspath(dirname(dirname(__file__)))
        return [frame for frame in list if moduledir not in frame[0]]
    return list
Example #7
0
 def __init__(self, path):
     bundle = NSBundle.mainBundle()
     info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
     # Did you know you can override parts of infoDictionary (Info.plist, after loading) even though Apple says it's read-only?
     info['LSUIElement'] = '1'
     # Initialize our shared application instance
     NSApplication.sharedApplication()
     # Two possibilities here
     # Either the path is a directory and we really want the file inside it
     # or the path is just a real .nib file
     if os.path.isdir(path):
         # Ok, so they just saved it from Xcode, not their fault
         # let's fix the path
         path = os.path.join(path, 'keyedobjects.nib')
     with open(path, 'rb') as f:
         # get nib bytes
         d = buffer(f.read())
     n_obj = NSNib.alloc().initWithNibData_bundle_(d, None)
     placeholder_obj = NSObject.alloc().init()
     result, n = n_obj.instantiateWithOwner_topLevelObjects_(
         placeholder_obj, None)
     self.hidden = True
     self.nib_contents = n
     self.win = [
         x for x in self.nib_contents if x.className() == 'NSWindow'
     ][0]
     self.views = views_dict(self.nib_contents)
     self._attached = []
Example #8
0
def resource_path(resource, resource_type):
        path = NSBundle.mainBundle().pathForResource_ofType_(
            resource, resource_type)
        if NSFileManager.defaultManager().fileExistsAtPath_(path):
            return path
        else:
            return None
Example #9
0
def keyboard_tap_callback(proxy, type_, event, refcon):
    NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
        dict(NSAllowsArbitraryLoads=True)
    if type_ < 0 or type_ > 0x7fffffff:
        logger.error('Unkown mac event')
        run_event_loop()
        logger.error('restart mac key board event loop')
        return event
    try:
        # 这段代码如果运行在非主线程,它会有如下输出,根据目前探索,
        # 这并不影响它的运行,我们暂时可以忽略它。
        # Python pid(11)/euid(11) is calling TIS/TSM in non-main thread environment.
        # ERROR : This is NOT allowed.
        key_event = NSEvent.eventWithCGEvent_(event)
    except:
        logger.info("mac event cast error")
        return event
    if key_event.subtype() == 8:
        key_code = (key_event.data1() & 0xFFFF0000) >> 16
        key_state = (key_event.data1() & 0xFF00) >> 8
        if key_code in (16, 19, 20):
            # 16 for play-pause, 19 for next, 20 for previous
            if key_state == NSKeyUp:
                if key_code == 19:
                    logger.info('mac hotkey: play next')
                    send_cmd('next')
                elif key_code == 20:
                    logger.info('mac hotkey: play last')
                    send_cmd('previous')
                elif key_code == 16:
                    logger.info('mac hotkey: toggle')
                    send_cmd('toggle')
            return None
    return event
Example #10
0
def migrateSupport(oldAppName, newAppName):
    print('Checking Miro preferences and support migration...')

    global migrated
    migrated = False

    from AppKit import NSBundle

    prefsPath = os.path.expanduser('~/Library/Preferences').decode('utf-8')
    newDomain = NSBundle.mainBundle().bundleIdentifier()
    newPrefs = '%s.plist' % os.path.join(prefsPath, newDomain)
    oldDomain = newDomain.replace(newAppName, oldAppName)
    oldPrefs = '%s.plist' % os.path.join(prefsPath, oldDomain)
    
    if os.path.exists(oldPrefs):
        if os.path.exists(newPrefs):
            print("Both %s and %s preference files exist." % (oldAppName, newAppName))
        else:
            os.rename(oldPrefs, newPrefs)
            print("Migrated preferences to %s" % newPrefs)

    supportFolderRoot = os.path.expanduser('~/Library/Application Support')
    oldSupportFolder = os.path.join(supportFolderRoot, oldAppName)
    newSupportFolder = os.path.join(supportFolderRoot, newAppName)
    if os.path.exists(oldSupportFolder):
        if os.path.exists(newSupportFolder):
            print("Both %s and %s support folders exist." % (oldAppName, newAppName))
        else:
            os.rename(oldSupportFolder, newSupportFolder)
            print("Migrated support folder to %s" % newSupportFolder)
            migrated = True
Example #11
0
def extract_tb(tb, script=None, src=None):
    """Return a list of pre-processed entries from traceback."""
    list = []
    n = 0
    while tb is not None:
        f = tb.tb_frame
        lineno = tb.tb_lineno
        co = f.f_code
        filename = co.co_filename
        name = co.co_name
        if filename==script:
            line = src.split('\n')[lineno-1]
        else:
            linecache.checkcache(filename)
            line = linecache.getline(filename, lineno, f.f_globals)
        if line: line = line.strip()
        else: line = None
        list.append((filename, lineno, name, line))
        tb = tb.tb_next

    # omit the internal plotdevice stack frames in `dist` builds
    from AppKit import NSBundle
    debug = 'flux' in NSBundle.mainBundle().infoDictionary().get('CFBundleVersion','')
    if not debug:
        moduledir = abspath(dirname(dirname(__file__)))
        return [frame for frame in list if moduledir not in frame[0]]
    return list
Example #12
0
    def _init_popover(self):
        print 'init popover'
        #import pdb; pdb.set_trace()
        rect = NSMakeRect(0, 0, 40, 40)
        self.button = NSButton.alloc().initWithFrame_(rect)
        self.button.setImage_(self._app['_icon_nsimage'])
        self.button.setAction_('mycallback:')
        #self.button.setTransparent_(True)
        self.button.setBordered_(False)
        self.button.setTitle_('W')
        self.button.setButtonType_(AppKit.NSMomentaryChangeButton)

        print 'BUTTON ', self.nsstatusitem.action
        #rect2 = NSMakeRect(0, 0, 100, 100)
        self.popover = NSPopover.alloc().init()
        #myBundle = NSBundle bundleWithPath:@"/Library/MyBundle.bundle"]
        myBundle = NSBundle.alloc().initWithPath_("/Users/pfitzsimmons/repos/webchiver/app/webchiver.bundle")
        #view_controller = NSViewController.alloc().initWithNibName_bundle_('SnippetPopoverViewController.nib', myBundle)
        view_controller = PopViewController.alloc().init()
        #self.popover.setContentViewController_(view_controller)
        #self.nsstatusitem.setAction_('mycallback:')
        self.nsstatusitem.setView_(self.button)
        #import pdb; pdb.set_trace()

        rect3 = NSMakeRect(500, 500, 600, 600)
        self.window = MyWindow.alloc().initWithContentRect_styleMask_backing_defer_(
            rect3,
            AppKit.NSBorderlessWindowMask,
            #AppKit.NSTexturedBackgroundWindowMask,
            NSBackingStoreBuffered,
            True
            )
        self.window.setOpaque_(False)
Example #13
0
def migrateSupport(oldAppName, newAppName):
    print('Checking Miro preferences and support migration...')

    global migrated
    migrated = False

    from AppKit import NSBundle

    prefsPath = os.path.expanduser('~/Library/Preferences').decode('utf-8')
    newDomain = NSBundle.mainBundle().bundleIdentifier()
    newPrefs = '%s.plist' % os.path.join(prefsPath, newDomain)
    oldDomain = newDomain.replace(newAppName, oldAppName)
    oldPrefs = '%s.plist' % os.path.join(prefsPath, oldDomain)

    if os.path.exists(oldPrefs):
        if os.path.exists(newPrefs):
            print("Both %s and %s preference files exist." %
                  (oldAppName, newAppName))
        else:
            os.rename(oldPrefs, newPrefs)
            print("Migrated preferences to %s" % newPrefs)

    supportFolderRoot = os.path.expanduser('~/Library/Application Support')
    oldSupportFolder = os.path.join(supportFolderRoot, oldAppName)
    newSupportFolder = os.path.join(supportFolderRoot, newAppName)
    if os.path.exists(oldSupportFolder):
        if os.path.exists(newSupportFolder):
            print("Both %s and %s support folders exist." %
                  (oldAppName, newAppName))
        else:
            os.rename(oldSupportFolder, newSupportFolder)
            print("Migrated support folder to %s" % newSupportFolder)
            migrated = True
Example #14
0
    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
        editmenu.addItemWithTitle_action_keyEquivalent_(
            'Fill Text', 'fillText', '\\').setKeyEquivalentModifierMask_(mask)

        mask = NSCommandKeyMask | NSAlternateKeyMask
        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', True)
        EditingMessageWebView._bulletLists = defaults.get('BulletLists', True)
        EditingMessageWebView._indentWidth = int(defaults.get(
            'IndentWidth', 2))
        EditingMessageWebView._wrapWidth = int(defaults.get('WrapWidth', 76))

        # Report the plugin name and version to the com.apple.mail log.

        version = bundle.objectForInfoDictionaryKey_('CFBundleVersion')
        NSLog('Loaded MailWrap %s' % version)
Example #15
0
def keyboard_tap_callback(proxy, type_, event, refcon):
        from AppKit import NSKeyUp, NSEvent, NSBundle
        NSBundle.mainBundle().infoDictionary()['NSAppTransportSecurity'] =\
            dict(NSAllowsArbitraryLoads=True)
        if type_ < 0 or type_ > 0x7fffffff:
            LOG.error('Unkown mac event')
            run_event_loop()
            LOG.error('restart mac key board event loop')
            return event
        try:
            key_event = NSEvent.eventWithCGEvent_(event)
        except:
            LOG.info("mac event cast error")
            return event
        if key_event.subtype() == 8:
            key_code = (key_event.data1() & 0xFFFF0000) >> 16
            key_state = (key_event.data1() & 0xFF00) >> 8
            if key_code in (16, 19, 20):
                # 16 for play-pause, 19 for next, 20 for previous
                if key_state == NSKeyUp:
                    if key_code is 19:
                        ControllerApi.player.play_next()
                    elif key_code is 20:
                        ControllerApi.player.play_last()
                    elif key_code is 16:
                        ControllerApi.player.play_or_pause()
                return None
        return event
Example #16
0
def Environment():
    """\
	Return the environment, from which this script is being called.
	Currently supported: FontLab, GlyphsApp, NodeBox, Python
	"""

    environment = 'Python'

    try:
        import FL
        environment = 'FontLab'
    except:
        pass

    try:
        from AppKit import NSBundle
        MainBundle = NSBundle.mainBundle()
        if 'Glyphs' in MainBundle.bundlePath():
            environment = 'GlyphsApp'
    except:
        pass

    try:
        import mojo
        environment = 'RoboFont'
    except:
        pass

    try:
        import nodebox
        environment = 'NodeBox'
    except:
        pass

    return environment
Example #17
0
 def initWithApp_(self, app):
     self = super(Menu, self).init()
     if self is None:
         return None
     self.app        = app
     self.mainwindow = NSApplication.sharedApplication().mainWindow()
     self.bundle     = NSBundle.bundleWithIdentifier_('pt.barraca.MailTrack')
     return self
Example #18
0
 def initWithApp_(self, app):
     self = super(Menu, self).init()
     if self is None:
         return None
     self.app = app
     self.mainwindow = NSApplication.sharedApplication().mainWindow()
     self.bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
     return self
Example #19
0
 def initWithApp_(self, app):
     self = super(Menu, self).init()
     if self is None:
         return None
     self.app        = app
     self.mainwindow = NSApplication.sharedApplication().mainWindow()
     self.bundle     = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
     return self
Example #20
0
 def start(self):
     newMenuItem = NSMenuItem(self.name, self.showWindow_)
     Glyphs.menu[WINDOW_MENU].append(newMenuItem)
     try:
         bundle = NSBundle.bundleWithIdentifier_(
             "com.dyb.floatingImageFrame")
         self.icon = bundle.imageForResource_("icon.png")
         self.icon.setTemplate_(True)
     except:
         pass
Example #21
0
 def init(self):
     bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
     nib = bundle.loadNibNamed_owner_topLevelObjects_('QuoteFixPreferencesModule', self, None)
     if not nib or nib[0] < 1:
         raise AssertionError('unable to load nib')
     nib[1].retain()
     self.view = filter(lambda _: isinstance(_, NSBox), nib[1])[0]
     self.setMinSize_(self.view.boundsSize())
     self.setPreferencesView_(self.view)
     return self
Example #22
0
def get_path(filename):
    name = os.path.splitext(filename)[0]
    ext = os.path.splitext(filename)[1]
    if platform.system() == "Darwin":
        from AppKit import NSBundle

        file = NSBundle.mainBundle().pathForResource_ofType_(name, ext)
        return file or os.path.realpath(filename)
    else:
        return os.path.realpath(filename)
Example #23
0
 def directory(cls):
     if cls._cached_directory is None:
         application_name = str(
             NSBundle.mainBundle().infoDictionary().objectForKey_(
                 "CFBundleExecutable"))
         path = unicodedata.normalize(
             'NFC',
             NSSearchPathForDirectoriesInDomains(
                 NSApplicationSupportDirectory, NSUserDomainMask, True)[0])
         cls._cached_directory = os.path.join(path, application_name)
     return cls._cached_directory
Example #24
0
 def _helpBookCallback(self, sender):
     from Carbon import AH
     bundle = NSBundle.mainBundle()
     if bundle is None:
         return
     info = bundle.infoDictionary()
     helpBookName = info.get("CFBundleHelpBookName")
     if self._page is not None:
         AH.AHGoToPage(helpBookName, self._page, self._anchor)
     elif self._anchor is not None:
         AH.AHLookupAnchor(helpBookName, self._anchor)
Example #25
0
 def _helpBookCallback(self, sender):
     from Carbon import AH
     bundle = NSBundle.mainBundle()
     if bundle is None:
         return
     info = bundle.infoDictionary()
     helpBookName = info.get("CFBundleHelpBookName")
     if self._page is not None:
         AH.AHGoToPage(helpBookName, self._page, self._anchor)
     elif self._anchor is not None:
         AH.AHLookupAnchor(helpBookName, self._anchor)
Example #26
0
 def init(self):
     bundle = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
     nib = bundle.loadNibNamed_owner_topLevelObjects_(
         'QuoteFixPreferencesModule', self, None)
     if not nib or nib[0] < 1:
         raise AssertionError('unable to load nib')
     nib[1].retain()
     self.view = filter(lambda _: isinstance(_, NSBox), nib[1])[0]
     self.setMinSize_(self.view.boundsSize())
     self.setPreferencesView_(self.view)
     return self
Example #27
0
 def applicationDidFinishLaunching_(self, notification):
     u"""
     Setting up globals.
     """
     print '* Meta Application finished launching, initializing...'
     self.model = Model()
     self.path = os.path.join(os.path.dirname(__file__))
     self.resourcePath = NSBundle.mainBundle().resourcePath()
     self.documentFilesPath = self.resourcePath + '/en.lproj/'
     path = '/Users/michiel/Projects/Meta/imftc/imftc.meta'
     document = self.model.openDocument(path)
     self.openStartWindow()
Example #28
0
    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()
Example #29
0
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()
Example #30
0
 def __init__(self) -> None:
     self.text_input_context = NSTextInputContext.alloc().initWithClient_(NSTextView.new())
     self.last_ime = ImSwitcher.english_ime
     manager = multiprocessing.Manager()
     self.cur_ime = manager.Value(ctypes.c_wchar_p, ImSwitcher.english_ime)
     multiprocessing.Process(target=Observer.watch,
                             args=(self.cur_ime,)).start()
     try:
         # 隐藏macos dock栏小火箭
         info = NSBundle.mainBundle().infoDictionary()
         info["LSBackgroundOnly"] = "1"
     except ImportError:
         print("隐藏macos dock栏小火箭,需要pip3 install -U PyObjC")
Example #31
0
	def offsetPath(self, Layer, h, v):
		try:
			GLYPHSAPPVERSION = NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString")
			offsetCurveFilter = NSClassFromString("GlyphsFilterOffsetCurve")
			if GLYPHSAPPVERSION.startswith("1."):
				offsetCurveFilter.offsetLayer_offsetX_offsetY_makeStroke_position_error_shadow_(Layer, h, v, False, 0.5, None, None)
			elif GLYPHSAPPVERSION.startswith("2."):
				offsetCurveFilter.offsetLayer_offsetX_offsetY_makeStroke_autoStroke_position_error_shadow_(Layer, h, v, False, False, 0.5, None, None)
			else:
				offsetCurveFilter.offsetLayer_offsetX_offsetY_makeStroke_autoStroke_position_metrics_error_shadow_capStyleStart_capStyleEnd_keepCompatibleOutlines_(Layer, h, v, False, False, 0.5, None, None, None, 0, 0, False)
		except Exception as e:
			Glyphs.showMacroWindow()
			print("Make Bubble Layers Error (offsetPath): %s" % e)
Example #32
0
def get_path(filename):
    """Return the full path for the passed filename. This works cross-platform
    and uses AppKit to refer to the path when used on macOS.
    This uses code suggested on this pyinstaller issues page:
    https://github.com/pyinstaller/pyinstaller/issues/5109#issuecomment-683313824"""
    name = os.path.splitext(filename)[0]
    ext = os.path.splitext(filename)[1]
    if platform.system() == "Darwin":
        from AppKit import NSBundle
        file = NSBundle.mainBundle().pathForResource_ofType_(name, ext)
        return file or os.path.realpath(filename)
    else:
        return os.path.realpath(filename)
Example #33
0
    def check_version(self):
        infodict = NSBundle.mainBundle().infoDictionary()
        mailversion = infodict['CFBundleVersion']
        lastknown = self.prefs.string["MailTrackLastKnownBundleVersion"]
        if lastknown and lastknown != mailversion:
            NSRunAlertPanel(
                'MailTrack plug-in', '''
The MailTrack plug-in detected a different Mail.app version (perhaps you updated?).

If you run into any problems with regards to replying or forwarding mail, consider removing this plug-in (from ~/Library/Mail/Bundles/).

(This alert is only displayed once for each new version of Mail.app)''', None,
                None, None)
            self.prefs.string["MailTrackLastKnownBundleVersion"] = mailversion
Example #34
0
    def run_with_icon(self, launch, shutdown):

        from . import Icon
        import pystray
        from functools import partial
        import os

        def on_openBox(icon, item, self):
            os.system(f"open /Applications/Safari.app {self.url}")

        menu = pystray.Menu(
            pystray.MenuItem('Show TheOnionBox...',
                             partial(on_openBox, self=self)))

        icon = Icon('The Onion Box', menu=menu)
        from PIL import Image, ImageDraw

        def create_image():
            # Generate an image and draw a pattern
            width = 41
            height = 41
            color1 = 0x000000
            color2 = 0xffffff

            image = Image.new('RGB', (width, height), color1)
            dc = ImageDraw.Draw(image)
            dc.rectangle((width // 2, 0, width, height // 2), fill=color2)
            dc.rectangle((0, height // 2, width // 2, height), fill=color2)

            return image

        icon.icon = create_image()

        # Prevent app from showing up in the dock
        # https://stackoverflow.com/questions/4345102/how-to-hide-application-icon-from-mac-os-x-dock
        from AppKit import NSBundle
        bundle = NSBundle.mainBundle()
        info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        info['LSUIElement'] = '1'

        def run_call(icon):
            if icon is not None:
                icon.visible = True
            launch()

        icon.run(run_call, shutdown)
Example #35
0
	def start(self):
		try: 
			# new API in Glyphs 2.3.1-910
			newMenuItem = NSMenuItem(self.name, self.showWindow_)
			Glyphs.menu[WINDOW_MENU].append(newMenuItem)
		except:
			mainMenu = Glyphs.mainMenu()
			s = objc.selector(self.showWindow_,signature='v@:@')
			newMenuItem = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(self.name, s, "")
			newMenuItem.setTarget_(self)
			mainMenu.itemWithTag_(5).submenu().addItem_(newMenuItem)
		try:
			bundle = NSBundle.bundleWithIdentifier_("com.dyb.floatingImageFrame")
			self.icon = bundle.imageForResource_("icon.png")
			self.icon.setTemplate_(True)
		except:
			pass
Example #36
0
    def check_version(self):
        infodict    = NSBundle.mainBundle().infoDictionary()
        mailversion = infodict['CFBundleVersion']
        lastknown   = self.prefs.string["QuoteFixLastKnownBundleVersion"]
        if lastknown and lastknown != mailversion:
            NSRunAlertPanel(
                'QuoteFix plug-in',
                '''
The QuoteFix plug-in detected a different Mail.app version (perhaps you updated?).

If you run into any problems with regards to replying or forwarding mail, consider removing this plug-in (from ~/Library/Mail/Bundles/).

(This alert is only displayed once for each new version of Mail.app)''',
                    None,
                    None,
                    None
            )
            self.prefs.string["QuoteFixLastKnownBundleVersion"] = mailversion
Example #37
0
    def awakeFromNib(self):
        self.currentVersionUpdater.setStringValue_(self.app.version)
        self.updateInterval.setSelectedSegment_(self.app.check_update_interval)
        self.setLastUpdateCheck()

        # set donate image
        bundle  = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
        path    = bundle.pathForResource_ofType_("donate", "gif")
        image   = NSImage.alloc().initByReferencingFile_(path)
        self.donateButton.setImage_(image)

        # check custom signature matcher
        self.check_signature_matcher(self.customSignatureMatcher)
        self.customSignatureMatcherDefault.setStringValue_(self.app.default_signature_matcher)

        # set attribution previews
        self.set_preview(self.customReplyAttribution)
        self.set_preview(self.customForwardingAttribution)
        self.set_preview(self.customSendAgainAttribution)
Example #38
0
    def awakeFromNib(self):
        self.currentVersionUpdater.setStringValue_(self.app.version)
        self.updateInterval.setSelectedSegment_(self.app.check_update_interval)
        self.setLastUpdateCheck()

        # set donate image
        bundle  = NSBundle.bundleWithIdentifier_('name.klep.mail.MailTrack')
        path    = bundle.pathForResource_ofType_("donate", "gif")
        image   = NSImage.alloc().initByReferencingFile_(path)
        self.donateButton.setImage_(image)

        # check custom signature matcher
        self.check_signature_matcher(self.customSignatureMatcher)
        self.customSignatureMatcherDefault.setStringValue_(self.app.default_signature_matcher)

        # set attribution previews
        self.set_preview(self.customReplyAttribution)
        self.set_preview(self.customForwardingAttribution)
        self.set_preview(self.customSendAgainAttribution)
Example #39
0
def _get_localized_name(abs_path):
    '''get the localized name of given app'''
    bundle = NSBundle.new()
    bundle.initWithPath_(abs_path)
    localizations = bundle.localizations()
    chinese = ('zh_CN', 'zh_Hans', 'zh-Hans', 'zh-CN')

    b = any(map(lambda x: x in localizations, chinese))
    if not b: return 

    for ch in chinese:
        path = bundle.pathForResource_ofType_inDirectory_forLanguage_('InfoPlist', 'strings', None, ch)
        if not path: continue
        # the path must surround with "", there may be space characters
        json_str = subprocess.check_output(u'plutil -convert json -o - "%s"' % path, shell=True)
        # print json_str
        json_res = json.loads(json_str, encoding='utf8')
        name = json_res.get('CFBundleName')
        if name: return name
Example #40
0
    def initialize(cls):
        # instantiate updater
        updater = Updater()

        # register ourselves
        objc.runtime.MVMailBundle.registerBundle()

        # extract plugin version from Info.plist
        bundle  = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
        version = bundle.infoDictionary().get('CFBundleVersion', '??')

        # initialize app
        app = App(version, updater)

        # initialize our posing classes with app instance
        DocumentEditor.registerQuoteFixApplication(app)
        MessageHeaders.registerQuoteFixApplication(app)
        MailApp.registerQuoteFixApplication(app)
        QuoteFixPreferencesController.registerQuoteFixApplication(app)
        CustomizedAttribution.registerQuoteFixApplication(app)

        # announce that we have loaded
        NSLog("QuoteFix Plugin (version %s) registered with Mail.app" % version)
Example #41
0
 def hide_dock_icon(self):
     bundle = NSBundle.mainBundle()
     info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
     info['LSUIElement'] = '1'
     app = NSApplication.sharedApplication()
Example #42
0
	def _findrubyrenderer():
		from AppKit import NSBundle
		return NSBundle.mainBundle().pathForResource_ofType_('rubyrenderer', 'rb')
import xml.etree.cElementTree as etree

# This script logs actions to both STDOUT and system.log
# You can set your own 'tag' for the log entries here
syslog.openlog("jamfsw-it-logs")


def log(msg):
    """Logging function to write to system.log and STDOUT"""
    print(msg)
    syslog.syslog(syslog.LOG_ALERT, "AssetTag: " + str(msg))

log("Starting Submit Mac Asset Tag")

# Prevent the Python app icon from appearing in the Dock
info = NSBundle.mainBundle().infoDictionary()
info['LSUIElement'] = True


def get_uuid():
    """This will obtain the UUID of the current Mac using system_profiler"""
    mac_uuid = subprocess.check_output(["/usr/sbin/system_profiler", "SPHardwareDataType"])
    return mac_uuid[mac_uuid.find("Hardware UUID:"):].split()[-1]

# The UUID is used for API calls to the JSS
macUUID = get_uuid()
log("Mac UUID: {0}".format(macUUID))

# The JSS URL and API credentials are assigned here (credentials passed as parameters)
jssURL = "https://yourjss.jamfcloud.com/JSSResource/computers/udid/{}".format(macUUID)
jssAuth = base64.b64encode(sys.argv[4] + ':' + sys.argv[5])
Example #44
0
    "cmd": cmdKey,
    "command": cmdKey,
    "control": controlKey,
    "ctrl": controlKey,
    "shift": shiftKey
}
key_map = {
    "left": 123,
    "right": 124,
    "down": 125,
    "up": 126,
    "help": 114, "mute": 74, "comma": 43, "volumedown": 73, "1": 18, "0": 29, "4": 21, "8": 28, "return": 36, "enter": 36, "slash": 44, "downarrow": 125, "d": 2, "h": 4, "l": 37, "p": 35, "t": 17, "x": 7, "forwarddelete": 117, "rightbracket": 30, "right": 124, "escape": 53, "home": 115, "5": 23, "space": 49, "3": 20, "f20": 90, "pagedown": 121, "7": 26, "keypadequals": 81, "keypadplus": 69, "c": 8, "f11": 103, "keypadclear": 71, "g": 5, "k": 40, "equal": 24, "o": 31, "minus": 27, "s": 1, "w": 13, "f15": 113, "rightshift": 60, "period": 47, "down": 125, "capslock": 57, "f6": 97, "2": 19, "keypadmultiply": 67, "6": 22, "function": 63, "option": 58, "leftbracket": 33, "f19": 80, "b": 11, "f": 3, "j": 38, "pageup": 116, "up": 126, "n": 45, "f18": 79, "r": 15, "rightoption": 61, "v": 9, "f12": 111, "f13": 105, "f10": 109, "z": 6, "f16": 106, "f17": 64, "f14": 107, "delete": 51, "f1": 122, "f2": 120, "f3": 99, "f4": 118, "f5": 96, "semicolon": 41, "f7": 98, "f8": 100, "f9": 101, "backslash": 42, "keypaddivide": 75, "tab": 48, "rightarrow": 124, "end": 119, "leftarrow": 123, "keypad7": 89, "keypad6": 88, "keypad5": 87, "keypad4": 86, "keypad3": 85, "keypad2": 84, "keypad1": 83, "keypad0": 82, "9": 25, "u": 32, "keypad9": 92, "keypad8": 91, "quote": 39, "volumeup": 72, "grave": 50, "<": 50, ">": 62, "keypaddecimal": 65, "e": 14, "i": 34, "keypadminus": 78, "m": 46, "uparrow": 126, "q": 12, "y": 16, "keypadenter": 76, "left": 123
}


base_path = os.path.join(NSBundle.mainBundle().bundlePath(), "Contents", "Frameworks")
bundle_path = os.path.abspath(os.path.join(base_path, "PTHotkey.framework"))
objc.loadBundle("PTHotKey", globals(), bundle_path=objc.pathForFramework(bundle_path))

PTHotKey = NSClassFromString("PTHotKey")
PTKeyCombo = NSClassFromString("PTKeyCombo")
PTHotKeyCenter = NSClassFromString("PTHotKeyCenter")

def register_key_from_string(key_str, target, signal):
    elems = key_str.split("+")
    modifiers = 0
    keycode = -1
    for e in elems:
        if e in mod_map:
            modifiers |= mod_map[e]
        elif e in key_map:
Example #45
0
 def init(self):
     context     = { NSNibTopLevelObjects : [] }
     nib         = NSNib.alloc().initWithNibNamed_bundle_("MailTrackPreferencesModule.nib", NSBundle.bundleWithIdentifier_('name.klep.mail.MailTrack'))
     inited      = nib.instantiateNibWithExternalNameTable_(context)
     self.view   = filter(lambda _: isinstance(_, NSBox), context[NSNibTopLevelObjects])[0]
     self.setMinSize_(self.view.boundsSize())
     self.setPreferencesView_(self.view)
     return self
Example #46
0
 def directory(cls):
     if cls._cached_directory is None:
         cls._cached_directory = unicodedata.normalize('NFC', NSBundle.mainBundle().resourcePath())
     return cls._cached_directory
Example #47
0
# statement from all source files in the program, then also delete it here.

from AppKit import NSUserDefaults, NSBundle
from PyObjCTools import Conversion

import os
import objc

from miro import prefs
from miro.plat import bundle
from miro.plat import keychain
from miro.plat import resources
from miro.plat.filenames import os_filename_to_filename_type, filename_type_to_os_filename

sysconfPath = objc.pathForFramework('/System/Library/Frameworks/SystemConfiguration.framework')
sysconfBundle = NSBundle.bundleWithPath_(sysconfPath)
objc.loadBundleFunctions(sysconfBundle, globals(), ((u'SCDynamicStoreCopyProxies', '@@'), ))


MOVIES_DIRECTORY_PARENT = os.path.expanduser('~/Movies')
SUPPORT_DIRECTORY_PARENT = os.path.expanduser('~/Library/Application Support')

def load():
    domain = bundle.getBundleIdentifier()
    plist =  NSUserDefaults.standardUserDefaults().persistentDomainForName_(domain)
    try:
        pydict = Conversion.pythonCollectionFromPropertyList(plist)
    except:
        print "WARNING!! Error while converting the preference property list to python dictionary:"
        print plist
Example #48
0
from    AppKit          import NSBundle, NSObject
from    Foundation      import NSLog
from    datetime        import datetime
from    logger          import logger
import  objc, os, os.path

# load Sparkle framework
BUNDLE          = NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix')
frameworkspath  = BUNDLE.privateFrameworksPath()
sparklepath     = os.path.join(frameworkspath, 'Sparkle.framework')
sparkle         = dict() # use 'private' storage to keep Sparkle classes in
objc.loadBundle('Sparkle', sparkle, bundle_path = sparklepath)

class Updater:

    def __init__(self):
        # instantiate Sparkle updater
        try:
            self.updater = sparkle['SUUpdater'].updaterForBundle_(BUNDLE)
        except:
            NSLog("QuoteFix: updater error - cannot initialize the updater for QuoteFix. This usually happens because of compatibility issues between Mail plugins. Updates are disabled, but QuoteFix should function normally.")
            self.enabled = False
            return

        # set delegate
        self.updater.setDelegate_(UpdaterDelegate.alloc().init().retain())

        # reset update cycle
        self.updater.resetUpdateCycle()

        # updates are enabled
Example #49
0
 def pathToRelaunchForUpdater_(self, updater):
     return NSBundle.mainBundle().bundlePath()
Example #50
0
    # FontLab
    # alternative syntax to cheat on the FL import filtering in RF
    __import__("FL")
    application = "fontlab"
    #applicationVersion = fl.version
except ImportError:
    pass

if application is None:
    try:
        # RoboFont
        import mojo
        application = 'robofont'
        try:
            from AppKit import NSBundle
            b = NSBundle.mainBundle()
            applicationVersion = b.infoDictionary()["CFBundleVersion"]
        except ImportError:
            pass
    except ImportError:
        pass
    
if application is None:
    try:
        # Glyphs
        import GlyphsApp
        application = "glyphs"
    except ImportError:
        pass

if application is None:
Example #51
0
 def init(self):
     context     = { NSNibTopLevelObjects : [] }
     nib         = NSNib.alloc().initWithNibNamed_bundle_("QuoteFixPreferencesModule.nib", NSBundle.bundleWithIdentifier_('name.klep.mail.QuoteFix'))
     inited      = nib.instantiateNibWithExternalNameTable_(context)
     self.view   = filter(lambda _: isinstance(_, NSBox), context[NSNibTopLevelObjects])[0]
     self.setMinSize_(self.view.boundsSize())
     self.setPreferencesView_(self.view)
     return self
Example #52
0
from AppKit import NSBundle, NSObject
from Foundation import NSLog
from datetime import datetime
from logger import logger
import objc, os, os.path

# load Sparkle framework
BUNDLE = NSBundle.bundleWithIdentifier_('pt.barraca.MailTrack')
frameworkspath = BUNDLE.privateFrameworksPath()
sparklepath = os.path.join(frameworkspath, 'Sparkle.framework')
sparkle = dict()  # use 'private' storage to keep Sparkle classes in
objc.loadBundle('Sparkle', sparkle, bundle_path=sparklepath)


class Updater:
    def __init__(self):
        # instantiate Sparkle updater
        try:
            self.updater = sparkle['SUUpdater'].updaterForBundle_(BUNDLE)
        except:
            NSLog(
                "MailTrack: updater error - cannot initialize the updater for MailTrack. This usually happens because of compatibility issues between Mail plugins. Updates are disabled, but MailTrack should function normally."
            )
            self.enabled = False
            return

        # set delegate
        self.updater.setDelegate_(UpdaterDelegate.alloc().init().retain())

        # reset update cycle
        self.updater.resetUpdateCycle()
Example #53
0
 def directory(cls):
     if cls._cached_directory is None:
         application_name = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable"))
         path = unicodedata.normalize('NFC', NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0])
         cls._cached_directory = os.path.join(path, application_name)
     return cls._cached_directory
Example #54
0
 def pathToRelaunchForUpdater_(self, updater):
     return NSBundle.mainBundle().bundlePath()
Example #55
0
    "control": NSControlKeyMask,
    "ctrl": NSControlKeyMask,
    "shift": NSShiftKeyMask
}
key_map = {
    "left": 123,
    "right": 124,
    "down": 125,
    "up": 126,
    'help': 114, 'mute': 74, 'comma': 43, 'volumedown': 73, '1': 18, '0': 29, '4': 21, '8': 28, 'return': 36, 'enter': 36, 'slash': 44, 'downarrow': 125, 'd': 2, 'h': 4, 'l': 37, 'p': 35, 't': 17, 'x': 7, 'forwarddelete': 117, 'rightbracket': 30, 'right': 124, 'escape': 53, 'home': 115, '5': 23, 'space': 49, '3': 20, 'f20': 90, 'pagedown': 121, '7': 26, 'keypadequals': 81, 'keypadplus': 69, 'c': 8, 'f11': 103, 'keypadclear': 71, 'g': 5, 'k': 40, 'equal': 24, 'o': 31, 'minus': 27, 's': 1, 'w': 13, 'f15': 113, 'rightshift': 60, 'period': 47, 'down': 125, 'capslock': 57, 'f6': 97, '2': 19, 'keypadmultiply': 67, '6': 22, 'function': 63, 'option': 58, 'leftbracket': 33, 'f19': 80, 'b': 11, 'f': 3, 'j': 38, 'pageup': 116, 'up': 126, 'n': 45, 'f18': 79, 'r': 15, 'rightoption': 61, 'v': 9, 'f12': 111, 'f13': 105, 'f10': 109, 'z': 6, 'f16': 106, 'f17': 64, 'f14': 107, 'delete': 51, 'f1': 122, 'f2': 120, 'f3': 99, 'f4': 118, 'f5': 96, 'semicolon': 41, 'f7': 98, 'f8': 100, 'f9': 101, 'backslash': 42, 'keypaddivide': 75, 'tab': 48, 'rightarrow': 124, 'end': 119, 'leftarrow': 123, 'keypad7': 89, 'keypad6': 88, 'keypad5': 87, 'keypad4': 86, 'keypad3': 85, 'keypad2': 84, 'keypad1': 83, 'keypad0': 82, '9': 25, 'u': 32, 'keypad9': 92, 'keypad8': 91, 'quote': 39, 'volumeup': 72, 'grave': 50, '<': 50, '>':62, 'keypaddecimal': 65, 'e': 14, 'i': 34, 'keypadminus': 78, 'm': 46, 'uparrow': 126, 'q': 12, 'y': 16, 'keypadenter': 76, 'left': 123
}


# this module contains a wrapper around the SGHotKeysLib to make it usable from Python/PyObjC
base_path = os.path.join(
    NSBundle.mainBundle().bundlePath(), "Contents", "Frameworks")
bundle_path = os.path.abspath(os.path.join(base_path, 'SGHotKey.framework'))
objc.loadBundle(
    'SGHotKey', globals(), bundle_path=objc.pathForFramework(bundle_path))

SGHotKey = NSClassFromString("SGHotKey")
SGKeyCombo = NSClassFromString("SGKeyCombo")
SGHotKeyCenter = NSClassFromString("SGHotKeyCenter")

cmdKeyBit = 8
shiftKeyBit = 9
optionKeyBit = 11
controlKeyBit = 12

cmdKey = 1 << cmdKeyBit
shiftKey = 1 << shiftKeyBit
Example #56
0
    def __init__(self):
        self.mac = None
        self.pc = None
        self.platform = sys.platform
        self.applicationName = None  # name of the application we're running in
        self.name = os.name
        self.version = version  # the robofab version
        self.numberVersion = numberVersion
        self.run = True

        # get some platform information
        if self.name == "mac" or self.name == "posix":
            if self.platform == "darwin":
                self.mac = "X"
            else:
                self.mac = "pre-X"
        elif self.name == "nt":
            # if you know more about PC & win stuff, add it here!
            self.pc = True
        else:
            raise RoboFabError, "We're running on an unknown platform."

            # collect versions
        self.pyVersion = sys.version[:3]
        self.inPython = False
        self.inFontLab = False
        self.flVersion = None
        self.inGlyphs = False
        self.glyphsVersion = None
        self.inRoboFont = False
        self.roboFontVersion = None

        # are we in FontLab?
        try:
            from FL import fl

            self.applicationName = fl.filename
            self.inFontLab = True
            self.flVersion = fl.version
        except ImportError:
            pass
        # are we in Glyphs?
        try:
            import objectsGS
            from AppKit import NSBundle

            bundle = NSBundle.mainBundle()
            self.applicationName = bundle.infoDictionary()["CFBundleName"]
            self.inGlyphs = True
            self.glyphsVersion = bundle.infoDictionary()["CFBundleVersion"]
        except ImportError:
            pass
        # are we in RoboFont
        try:
            import mojo
            from AppKit import NSBundle

            bundle = NSBundle.mainBundle()
            self.applicationName = bundle.infoDictionary()["CFBundleName"]
            self.inRoboFont = True
            self.roboFontVersion = bundle.infoDictionary()["CFBundleVersion"]
        except ImportError:
            pass
        # we are in NoneLab
        if not self.inFontLab:
            self.inPython = True

            # see if we have DialogKit
        self.supportsDialogKit = False
Example #57
0
import xml.etree.cElementTree as etree

# This script logs actions to both STDOUT and system.log
# You can set your own 'tag' for the log entries here
syslog.openlog("jamfsw-it-logs")


def log(msg):
    """Logging function to write to system.log and STDOUT"""
    print(msg)
    syslog.syslog(syslog.LOG_ALERT, "AssetTag: " + str(msg))

log("Starting Submit Mac Asset Tag")

# Prevent the Python app icon from appearing in the Dock
info = NSBundle.mainBundle().infoDictionary()
info['LSUIElement'] = True


def get_uuid():
    """This will obtain the UUID of the current Mac using system_profiler"""
    mac_uuid = subprocess.check_output(["/usr/sbin/system_profiler", "SPHardwareDataType"])
    return mac_uuid[mac_uuid.find("Hardware UUID:"):].split()[-1]

# The UUID is used for API calls to the JSS
macUUID = get_uuid()
log("Mac UUID: {0}".format(macUUID))

# The JSS URL and API credentials are assigned here (credentials passed as parameters)
jssURL = "https://yourjss.jamfcloud.com/JSSResource/computers/udid/{}".format(macUUID)
jssAuth = base64.b64encode(sys.argv[4] + ':' + sys.argv[5])
Example #58
0
		</div>
	</div>
		
	<!-- Disclaimer -->
	<p id="helptext" onmouseleave="vanish(this);">
		Ctrl-R: Reset Charset. Ctrl-L: Latin1. Ctrl-J: LTR/RTL. Ctrl-C: Center. Ctrl-X: X-Ray. Not working? Please try in a newer macOS or use the <a href="https://www.google.com/chrome/">latest Chrome</a>. Pull mouse across this note to make it disappear.
	</p>
	</body>
</html>
""" % (samsaPlaceholder)

# clears macro window log:
Glyphs.clearLog()

# Query app version:
GLYPHSAPPVERSION = NSBundle.bundleForClass_(NSClassFromString(
    "GSMenu")).infoDictionary().objectForKey_("CFBundleShortVersionString")
appVersionHighEnough = not GLYPHSAPPVERSION.startswith("1.")

optionKeyFlag = 524288
optionKeyPressed = NSEvent.modifierFlags() & optionKeyFlag == optionKeyFlag
shouldCreateSamsa = False
if optionKeyPressed:
    shouldCreateSamsa = True

if appVersionHighEnough:
    firstDoc = Glyphs.orderedDocuments()[0]
    thisFont = Glyphs.font  # frontmost font
    exportPath = currentOTVarExportPath()
    # familyName = otVarFamilyName(thisFont)
    fullName = otVarFullName(thisFont)
    fileName = otVarFileName(thisFont)
Example #59
0
#   http://twistedmatrix.com/documents/13.0.0/api/twisted.internet._threadedselect.html
#
#
import os
from PyObjCTools import AppHelper
from AppKit import NSApplication, NSApp, NSBundle, NSLog  # @UnresolvedImport
import objc

objc.setVerbose(True)  # @UndefinedVariable

# Specialized reactor for integrating with arbitrary foreign event loop, such as those you find in GUI toolkits.
from twisted.internet._threadedselect import install

reactor = install()

# import modules containing classes required to start application and load MainMenu.nib
import XierpaAppDelegate

app = NSApplication.sharedApplication()
nibPath = os.path.join(
    os.path.dirname(__file__), "dist", "Xierpa3.app", "Contents", "Resources", "en.lproj", "MainMenu.nib"
)
NSBundle.loadNibFile_externalNameTable_withZone_(nibPath, {}, None)  # @UndefinedVariable
delegate = XierpaAppDelegate.XierpaAppDelegate.alloc().init()  # @UndefinedVariable
app.setDelegate_(delegate)

# Bring app to top
NSApp.activateIgnoringOtherApps_(True)

AppHelper.runEventLoop()