Ejemplo n.º 1
0
        def __init__(self):
            self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.internal_plugin_dir = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable.decode(sys.getfilesystemencoding())), pardir, 'Library', 'plugins')) or join(dirname(__file__), 'plugins')

            self.default_journal_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], 'Frontier Developments', 'Elite Dangerous')

            self.default_interaction_dir = join(self.default_journal_dir, 'CommanderHistory')

            self.home = expanduser('~')

            self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable.decode(sys.getfilesystemencoding())), pardir, 'Resources')) or dirname(__file__)

            if not getattr(sys, 'frozen', False):
                # Don't use Python's settings if interactive
                self.identifier = 'uk.org.marginal.%s' % appname.lower()
                NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.identifier
            else:
                self.identifier = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            self.settings = dict(self.defaults.persistentDomainForName_(self.identifier) or {})	# make writeable

            # Check out_dir exists
            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
Ejemplo n.º 2
0
        def __init__(self):
            self.app_dir = join(NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname)
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            self.plugin_dir = join(self.app_dir, 'plugins')
            if not isdir(self.plugin_dir):
                mkdir(self.plugin_dir)

            self.home = expanduser('~')

            self.respath = getattr(sys, 'frozen', False) and normpath(join(dirname(sys.executable), pardir, 'Resources')) or dirname(__file__)

            if not getattr(sys, 'frozen', False):
                # Don't use Python's settings if interactive
                self.bundle = 'uk.org.marginal.%s' % appname.lower()
                NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = self.bundle
            self.bundle = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            settings = self.defaults.persistentDomainForName_(self.bundle) or {}
            self.settings = dict(settings)

            # Check out_dir exists
            if not self.get('outdir') or not isdir(self.get('outdir')):
                self.set('outdir', NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
Ejemplo n.º 3
0
def init(delegate):
    delegate.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable"))
    delegate.applicationNamePrint = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleName"))
    version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
    vdate = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate"))
    delegate.about_version = "%s version %s\n%s" % (delegate.applicationNamePrint, version, vdate)
    delegate.about_slogan = NSLocalizedString("A state of the art, easy to use SIP client", "Label")
Ejemplo n.º 4
0
    def init(self):
        self = objc.super(BlinkAppDelegate, self).init()
        if self:
            self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable"))
            self.applicationNamePrint = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleName"))
            build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion"))
            date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate"))

            branding_file = NSBundle.mainBundle().infoDictionary().objectForKey_("BrandingFile")

            try:
                branding = __import__(branding_file)
            except ImportError:
                try:
                    import branding
                except ImportError:
                    branding = Null

            branding.init(self)

            BlinkLogger().log_info("Starting %s %s" % (self.applicationNamePrint, build))

            self.registerURLHandler()
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None)
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)

            NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange")
            NotificationCenter().add_observer(self, name="SIPApplicationDidStart")
            NotificationCenter().add_observer(self, name="SIPApplicationWillEnd")
            NotificationCenter().add_observer(self, name="SIPApplicationDidEnd")
            NotificationCenter().add_observer(self, name="NetworkConditionsDidChange")
            NotificationCenter().add_observer(self, name="SIPEngineTransportDidDisconnect")
            NotificationCenter().add_observer(self, name="SIPEngineTransportDidConnect")
            NotificationCenter().add_observer(self, name="DNSNameserversDidChange")
            NotificationCenter().add_observer(self, name="SystemDidWakeUpFromSleep")

            # remove obsolete settings
            userdef = NSUserDefaults.standardUserDefaults()
            userdef.removeObjectForKey_('SIPTrace')
            userdef.removeObjectForKey_('MSRPTrace')
            userdef.removeObjectForKey_('XCAPTrace')
            userdef.removeObjectForKey_('EnablePJSIPTrace')
            userdef.removeObjectForKey_('EnableNotificationsTrace')

            try:
                from Updater import Updater
            except ImportError:
                pass
            else:
                self.updater = Updater()

            self.purge_temporary_files()

        return self
Ejemplo n.º 5
0
 def __init__(self):
     # It's only possible to send notifications if we have a bundle
     # identifier set. This happens by default if using Python
     # installed as a Framework (e.g. the system Python), but isn't
     # set in a virtualenv.
     NSBundle.mainBundle().infoDictionary().setdefault(
         "CFBundleIdentifier", "org.4pisky.tools")
     self.NSUserNotification = lookUpClass("NSUserNotification")
     NCenter = lookUpClass("NSUserNotificationCenter")
     self.center = NCenter.defaultUserNotificationCenter()
Ejemplo n.º 6
0
    def __init__(self, name, title=None, icon=None, menu=None, quit_button='Quit'):
        _require_string(name)
        self._name = name
        self._icon = self._icon_nsimage = self._title = None
        self.icon = icon
        self.title = title
        self.quit_button = quit_button
        self._menu = Menu()
        if menu is not None:
            self.menu = menu
        self._application_support = application_support(self._name)

        if not 'CFBundleIdentifier' in NSBundle.mainBundle().infoDictionary():
           NSBundle.mainBundle().infoDictionary()['CFBundleIdentifier'] = name
Ejemplo n.º 7
0
 def asyncinteract(self, write=None, banner=None):
     if self.lock:
         raise ValueError("Can't nest")
     self.lock = True
     if write is None:
         write = self.write
     cprt = u'Type "help", "copyright", "credits" or "license" for more information.'
     if banner is None:
         write(
             u"Python %s in %s\n%s\n"
             % (sys.version, NSBundle.mainBundle().objectForInfoDictionaryKey_("CFBundleName"), cprt)
         )
     else:
         write(banner + "\n")
     more = 0
     _buff = []
     try:
         while True:
             if more:
                 prompt = sys.ps2
             else:
                 prompt = sys.ps1
             write(prompt)
             # yield the kind of prompt we have
             yield more
             # next input function
             yield _buff.append
             more = self.push(_buff.pop())
     except:
         self.lock = False
         raise
     self.lock = False
Ejemplo n.º 8
0
 def __init__(self):
     self.smiley_directory = None
     self.icon = None
     self.smileys = {}
     self.smileys_html = {}
     self.smiley_keys = []
     self.load_theme(str(NSBundle.mainBundle().resourcePath())+"/smileys" , "default")
Ejemplo n.º 9
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 = []
Ejemplo n.º 10
0
def main():
    """Runs main Aqua user interface."""
    _check_extra_requires('gui_scripts', 'qiskit_aqua_ui')
    guiprovider = AquaGUIProvider()
    if sys.platform == 'darwin':
        # pylint: disable=no-name-in-module, import-error
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        if bundle:
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            info['CFBundleName'] = guiprovider.title

    root = tk.Tk()
    root.withdraw()
    root.update_idletasks()

    preferences = guiprovider.create_uipreferences()
    geometry = preferences.get_geometry()
    if geometry is None:
        w_s = root.winfo_screenwidth()
        h_s = root.winfo_screenheight()
        w_a = int(w_s / 1.3)
        h_a = int(h_s / 1.3)
        x = int(w_s / 2 - w_a / 2)
        y = int(h_s / 2 - h_a / 2)
        geometry = '{}x{}+{}+{}'.format(w_a, h_a, x, y)
        preferences.set_geometry(geometry)
        preferences.save()

    root.geometry(geometry)

    MainView(root, guiprovider)
    root.after(0, root.deiconify)
    root.after(0, set_preferences_logging)
    root.mainloop()
Ejemplo n.º 11
0
Archivo: misc.py Proyecto: ssalexa/meld
 def __init__(self):
     from Foundation import NSBundle
     from pathlib import Path, PurePath
     self.bashrc_file = str(PurePath(Path.home(), '.bashrc'))
     bundle = NSBundle.mainBundle()
     self.executable_path = bundle.executablePath(
     ).fileSystemRepresentation().decode("utf-8")
Ejemplo n.º 12
0
def _run():
    app_name = "MNELAB"
    if sys.platform.startswith("darwin"):
        try:  # set bundle name on macOS (app name shown in the menu bar)
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            if bundle:
                info = (bundle.localizedInfoDictionary()
                        or bundle.infoDictionary())
                if info:
                    info["CFBundleName"] = app_name
        except ImportError:
            pass
    matplotlib.use("Qt5Agg")
    app = QApplication(sys.argv)
    app.setApplicationName(app_name)
    app.setOrganizationName("cbrnr")
    if sys.platform.startswith("darwin"):
        app.setAttribute(Qt.AA_DontShowIconsInMenus, True)
    app.setAttribute(Qt.AA_UseHighDpiPixmaps)
    model = Model()
    model.view = MainWindow(model)
    if len(sys.argv) > 1:  # open files from command line arguments
        for f in sys.argv[1:]:
            model.load(f)
    model.view.show()
    sys.exit(app.exec_())
Ejemplo n.º 13
0
def main():
    if sys.platform == 'darwin':
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        if bundle:
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            info['CFBundleName'] = 'Qiskit Aqua'

    root = tk.Tk()
    root.withdraw()
    root.update_idletasks()

    preferences = UIPreferences()
    geometry = preferences.get_browser_geometry()
    if geometry is None:
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        w = int(ws / 1.2)
        h = int(hs / 1.3)
        x = int(ws / 2 - w / 2)
        y = int(hs / 2 - h / 2)
        geometry = '{}x{}+{}+{}'.format(w, h, x, y)
        preferences.set_browser_geometry(geometry)
        preferences.save()

    root.geometry(geometry)

    MainView(root)
    root.after(0, root.deiconify)
    root.after(0, set_preferences_logging)
    root.mainloop()
Ejemplo n.º 14
0
    def initWithAccount_target_name_(self, account, target, display_name):
        self = super(SMSViewController, self).init()
        if self:
            self.notification_center = NotificationCenter()
            self.account = account
            self.target_uri = target
            self.display_name = display_name
            self.queue = []
            self.messages = {}

            self.history=ChatHistory()

            self.local_uri = '%s@%s' % (account.id.username, account.id.domain)
            self.remote_uri = '%s@%s' % (self.target_uri.user, self.target_uri.host)

            NSBundle.loadNibNamed_owner_("SMSView", self)

            self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html"))
            self.chatViewController.setAccount_(self.account)
            self.chatViewController.resetRenderedMessages()

            self.chatViewController.inputText.unregisterDraggedTypes()
            self.chatViewController.inputText.setMaxLength_(MAX_MESSAGE_LENGTH)
            self.splitView.setText_("%i chars left" % MAX_MESSAGE_LENGTH)

        return self
Ejemplo n.º 15
0
    def __init__(self):
        if self:
            BlinkLogger().log_debug('Starting History Viewer')
            NSBundle.loadNibNamed_owner_("HistoryViewer", self)

            self.all_contacts = BlinkHistoryViewerContact('Any Address', name='All Contacts')
            self.bonjour_contact = BlinkHistoryViewerContact('bonjour.local', name='Bonjour Neighbours', icon=NSImage.imageNamed_("NSBonjour"))

            self.notification_center = NotificationCenter()
            self.notification_center.add_observer(self, name='ChatViewControllerDidDisplayMessage')
            self.notification_center.add_observer(self, name='AudioCallLoggedToHistory')
            self.notification_center.add_observer(self, name='BlinkContactsHaveChanged')
            self.notification_center.add_observer(self, name='BlinkTableViewSelectionChaged')
            self.notification_center.add_observer(self, name='BlinkConferenceContactPresenceHasChanged')
            self.notification_center.add_observer(self, name='BlinkShouldTerminate')

            self.searchText.cell().setSendsSearchStringImmediately_(True)
            self.searchText.cell().setPlaceholderString_(NSLocalizedString("Type text and press Enter", "Placeholder text"))

            self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html"))
            self.chatViewController.setHandleScrolling_(False)
            self.entriesView.setShouldCloseWithWindow_(False)

            for c in ('remote_uri', 'local_uri', 'date', 'type'):
                col = self.indexTable.tableColumnWithIdentifier_(c)
                descriptor = NSSortDescriptor.alloc().initWithKey_ascending_(c, True)
                col.setSortDescriptorPrototype_(descriptor)

            self.chat_history = ChatHistory()
            self.session_history = SessionHistory()
            self.setPeriod(1)

            self.selectedTableView = self.contactTable
def main():
    if sys.platform.startswith('darwin'):
        try:
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            if bundle:
                app_name = "OpenModem Configuration"
                app_info = bundle.localizedInfoDictionary(
                ) or bundle.infoDictionary()
                if app_info:
                    app_info['CFBundleName'] = app_name
                    app_info["CFBundleGetInfoString"] = "unsigned.io"
                    app_info["CFBundleLongVersionString"] = "unsigned.io"
                    app_info["NSHumanReadableCopyright"] = "unsigned.io"
                    app_info["CFBundleShortVersionString"] = "1.0.0"
                    app_info["CFBundleVersion"] = "1.0.0"
                    app_info[
                        "CFBundleIdentifier"] = "io.unsigned.openmodemconfig"
                    app_info["CFBundleExecutable"] = "Test"
                    print(app_info)
                    print(app_info["CFBundleExecutable"])
        except ImportError:
            pass

    include_path = os.path.dirname(os.path.realpath(sys.argv[0]))
    os.chdir(include_path)
    list_serial_ports()
    list_volumes()
    if (len(sys.argv) == 1):
        start_server()
Ejemplo n.º 17
0
def adjustEnv(logger, appinfo):
    #change macOS Bundle name
    if getattr(sys, "frozen", False) and appinfo["os"] == "Darwin":
        try:
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            if bundle:
                info = bundle.localizedInfoDictionary(
                ) or bundle.infoDictionary()
                if info and info['CFBundleName'] == 'Python':
                    info['CFBundleName'] = appinfo["appname"].lower()
        except:
            logger.debug("Error was happen on changeing MacOS ProcessName")
        else:
            logger.debug("MacOS ProcessName was succesfully changed.")
    sys.dont_write_bytecode = True  # __pycache__ deletion
    #path setting
    if not appinfo["share"] in sys.path:
        sys.path.append(appinfo["share"])  #share library path
    if not appinfo["share_os"] in os.environ["PATH"]:
        os.environ["PATH"] += ":" + appinfo["share_os"]
    if not appinfo["share_os"] in sys.path:
        sys.path.append(appinfo["share_os"])
    if platform.system() == "Windows":
        #Hi DPI Support
        import ctypes
        ctypes.windll.shcore.SetProcessDpiAwareness(True)
        logger.debug("HiDPI Support is enabled.")
        ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
            appinfo["appname"])
        logger.debug("Icon changing was fixed.")
Ejemplo n.º 18
0
    def __init__(self):
        if self:
            BlinkLogger().log_debug('Starting History Viewer')
            NSBundle.loadNibNamed_owner_("HistoryViewer", self)

            self.all_contacts = BlinkHistoryViewerContact('Any Address', name=u'All Contacts')
            self.bonjour_contact = BlinkHistoryViewerContact('bonjour', name=u'Bonjour Neighbours', icon=NSImage.imageNamed_("NSBonjour"))

            self.notification_center = NotificationCenter()
            self.notification_center.add_observer(self, name='ChatViewControllerDidDisplayMessage')
            self.notification_center.add_observer(self, name='AudioCallLoggedToHistory')
            self.notification_center.add_observer(self, name='BlinkContactsHaveChanged')
            self.notification_center.add_observer(self, name='BlinkTableViewSelectionChaged')
            self.notification_center.add_observer(self, name='BlinkConferenceContactPresenceHasChanged')
            self.notification_center.add_observer(self, name='BlinkShouldTerminate')

            self.searchText.cell().setSendsSearchStringImmediately_(True)
            self.searchText.cell().setPlaceholderString_(NSLocalizedString("Type text and press Enter", "Placeholder text"))

            self.chatViewController.setContentFile_(NSBundle.mainBundle().pathForResource_ofType_("ChatView", "html"))
            self.chatViewController.setHandleScrolling_(False)
            self.entriesView.setShouldCloseWithWindow_(False)

            for c in ('remote_uri', 'local_uri', 'date', 'type'):
                col = self.indexTable.tableColumnWithIdentifier_(c)
                descriptor = NSSortDescriptor.alloc().initWithKey_ascending_(c, True)
                col.setSortDescriptorPrototype_(descriptor)

            self.chat_history = ChatHistory()
            self.session_history = SessionHistory()
            self.setPeriod(1)

            self.selectedTableView = self.contactTable
Ejemplo n.º 19
0
 def __init__(self):
     self.smiley_directory = None
     self.icon = None
     self.smileys = {}
     self.smileys_html = {}
     self.smiley_keys = []
     self.load_theme(str(NSBundle.mainBundle().resourcePath())+"/smileys" , "default")
Ejemplo n.º 20
0
    def init(self):
        self = super(BlinkAppDelegate, self).init()
        if self:
            self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable"))
            self.applicationNamePrint = 'Blink' if self.applicationName == 'Blink Pro' else self.applicationName
            build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion"))
            date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate"))

            BlinkLogger().log_info(u"Starting %s build %s from %s" % (self.applicationNamePrint, build, date))

            self.registerURLHandler()
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None)
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)

            NotificationCenter().add_observer(self, name="SIPApplicationDidStart")
            NotificationCenter().add_observer(self, name="SIPApplicationWillEnd")
            NotificationCenter().add_observer(self, name="SIPApplicationDidEnd")
            NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange")

            # remove obsolete settings
            userdef = NSUserDefaults.standardUserDefaults()
            userdef.removeObjectForKey_('SIPTrace')
            userdef.removeObjectForKey_('MSRPTrace')
            userdef.removeObjectForKey_('XCAPTrace')
            userdef.removeObjectForKey_('EnablePJSIPTrace')
            userdef.removeObjectForKey_('EnableNotificationsTrace')

            def purge_screenshots():
                screenshots_folder = ApplicationData.get('.tmp_screenshots')
                if os.path.exists(screenshots_folder):
                    try:
                        shutil.rmtree(screenshots_folder)
                    except EnvironmentError:
                        pass

            try:
                from Updater import Updater
            except ImportError:
                pass
            else:
                self.updater = Updater()

            call_in_thread('file-io', purge_screenshots)

        return self
Ejemplo n.º 21
0
    def registerURLHandler(self):
        event_class = event_id = fourcharToInt("GURL")
        event_manager = NSAppleEventManager.sharedAppleEventManager()
        event_manager.setEventHandler_andSelector_forEventClass_andEventID_(self, "getURL:withReplyEvent:", event_class, event_id)

        bundleID = NSBundle.mainBundle().bundleIdentifier()
        LaunchServices.LSSetDefaultHandlerForURLScheme("sip", bundleID)
        LaunchServices.LSSetDefaultHandlerForURLScheme("tel", bundleID)
Ejemplo n.º 22
0
def appstore_edition():
    """Returns True if this is a Mac App Store Edition of Miro.
    It is differentiated by having a appStore file in the resources
    directory inside the application bundle.
    """
    appstore_file = os.path.join(NSBundle.mainBundle().resourcePath(),
                                 'appStore')
    return os.path.exists(appstore_file)
Ejemplo n.º 23
0
def appstore_edition():
    """Returns True if this is a Mac App Store Edition of Miro.
    It is differentiated by having a appStore file in the resources
    directory inside the application bundle.
    """
    appstore_file = os.path.join(NSBundle.mainBundle().resourcePath(),
                                 'appStore')
    return os.path.exists(appstore_file)
Ejemplo n.º 24
0
    def registerURLHandler(self):
        event_class = event_id = fourcharToInt("GURL")
        event_manager = NSAppleEventManager.sharedAppleEventManager()
        event_manager.setEventHandler_andSelector_forEventClass_andEventID_(self, "getURL:withReplyEvent:", event_class, event_id)

        bundleID = NSBundle.mainBundle().bundleIdentifier()
        LaunchServices.LSSetDefaultHandlerForURLScheme("sip", bundleID)
        LaunchServices.LSSetDefaultHandlerForURLScheme("tel", bundleID)
Ejemplo n.º 25
0
def osxtitle_def():
    if platform == 'darwin':
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        if bundle:
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            if info and info['CFBundleName'] == 'Python':
                info['CFBundleName'] = osxtitle_var
Ejemplo n.º 26
0
    def orderFrontAboutPanel_(self, sender):
        if not self.aboutPanel:
            NSBundle.loadNibNamed_owner_("About", self)
            version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
            build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion"))
            vdate = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate"))

            if self.applicationName == 'Blink Pro':
                self.aboutVersion.setStringValue_("Version Pro %s build %s\n%s" % (version, build, vdate))
            elif self.applicationName == 'Blink Lite':
                self.aboutVersion.setStringValue_("Version Lite %s build %s\n%s" % (version, build, vdate))
            else:
                self.aboutVersion.setStringValue_("Version %s\n%s" % (version, vdate))

        if self.applicationName == 'SIP2SIP':
            self.aboutSlogan.setStringValue_(NSLocalizedString("Special edition of Blink SIP Client for SIP2SIP", "About panel label"))

        self.aboutPanel.makeKeyAndOrderFront_(None)
Ejemplo n.º 27
0
    def init(self):
        self = super(BlinkAppDelegate, self).init()
        if self:
            self.applicationName = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleExecutable"))
            self.applicationNamePrint = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleName"))
            build = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleVersion"))
            date = str(NSBundle.mainBundle().infoDictionary().objectForKey_("BlinkVersionDate"))

            BlinkLogger().log_info(u"Starting %s build %s from %s" % (self.applicationNamePrint, build, date))

            self.registerURLHandler()
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerDidWake:", NSWorkspaceDidWakeNotification, None)
            NSWorkspace.sharedWorkspace().notificationCenter().addObserver_selector_name_object_(self, "computerWillSleep:", NSWorkspaceWillSleepNotification, None)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallTelephoneNumberWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)
            NSDistributedNotificationCenter.defaultCenter().addObserver_selector_name_object_suspensionBehavior_(self, "callFromAddressBook:", "CallSipAddressWithBlinkFromAddressBookNotification", "AddressBook", NSNotificationSuspensionBehaviorDeliverImmediately)

            NotificationCenter().add_observer(self, name="CFGSettingsObjectDidChange")
            NotificationCenter().add_observer(self, name="SIPApplicationDidStart")
            NotificationCenter().add_observer(self, name="SIPApplicationWillEnd")
            NotificationCenter().add_observer(self, name="SIPApplicationDidEnd")
            NotificationCenter().add_observer(self, name="SystemIPAddressDidChange")
            NotificationCenter().add_observer(self, name="NetworkConditionsDidChange")
            NotificationCenter().add_observer(self, name="SIPEngineTransportDidDisconnect")
            NotificationCenter().add_observer(self, name="SIPEngineTransportDidConnect")
            NotificationCenter().add_observer(self, name="DNSNameserversDidChange")

            # remove obsolete settings
            userdef = NSUserDefaults.standardUserDefaults()
            userdef.removeObjectForKey_('SIPTrace')
            userdef.removeObjectForKey_('MSRPTrace')
            userdef.removeObjectForKey_('XCAPTrace')
            userdef.removeObjectForKey_('EnablePJSIPTrace')
            userdef.removeObjectForKey_('EnableNotificationsTrace')

            try:
                from Updater import Updater
            except ImportError:
                pass
            else:
                self.updater = Updater()

            call_in_thread('file-io', self.purge_temporary_files)

        return self
Ejemplo n.º 28
0
def init_macOS():
    # MacOS: Set the bundle name so that the application menu shows 'Zim'
    # instead of 'Python' (this requires the pyobjc package)
    try:
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
        info['CFBundleName'] = 'Zim'
    except ImportError:
        pass
Ejemplo n.º 29
0
        def __init__(self):
            self.app_dir = join(
                NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, True)[0], appname
            )
            if not isdir(self.app_dir):
                mkdir(self.app_dir)

            if not getattr(sys, "frozen", False):
                # Don't use Python's settings if interactive
                self.bundle = "uk.org.marginal.%s" % appname.lower()
                NSBundle.mainBundle().infoDictionary()["CFBundleIdentifier"] = self.bundle
            self.bundle = NSBundle.mainBundle().bundleIdentifier()
            self.defaults = NSUserDefaults.standardUserDefaults()
            settings = self.defaults.persistentDomainForName_(self.bundle) or {}
            self.settings = dict(settings)

            # Check out_dir exists
            if not self.get("outdir") or not isdir(self.get("outdir")):
                self.set("outdir", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, True)[0])
Ejemplo n.º 30
0
 def register_protocol_handlers(self) -> None:
     """Register the URL scheme listener using PyObjC"""
     bundle_id = NSBundle.mainBundle().bundleIdentifier()
     if bundle_id == "org.python.python":
         log.debug("Skipping URL scheme registration as this program "
                   " was launched from the Python OSX app bundle")
         return
     LSSetDefaultHandlerForURLScheme(self.NXDRIVE_SCHEME, bundle_id)
     log.debug("Registered bundle %r for URL scheme %r", bundle_id,
               self.NXDRIVE_SCHEME)
Ejemplo n.º 31
0
def frozen():
    global DATADIR, LOCALEDIR, DATADIR_IS_UNINSTALLED

    bundle = NSBundle.mainBundle()
    resource_path = bundle.resourcePath().fileSystemRepresentation().decode(
        "utf-8")
    #bundle_path = bundle.bundlePath().fileSystemRepresentation().decode("utf-8")
    #frameworks_path = bundle.privateFrameworksPath().fileSystemRepresentation().decode("utf-8")
    #executable_path = bundle.executablePath().fileSystemRepresentation().decode("utf-8")
    etc_path = os.path.join(resource_path, "etc")
    lib_path = os.path.join(resource_path, "lib")
    share_path = os.path.join(resource_path, "share")

    # Glib and GI environment variables
    os.environ['GSETTINGS_SCHEMA_DIR'] = os.path.join(share_path, "glib-2.0")
    os.environ['GI_TYPELIB_PATH'] = os.path.join(lib_path, "girepository-1.0")

    # Avoid GTK warnings unless user specifies otherwise
    debug_gtk = os.environ.get('G_ENABLE_DIAGNOSTIC', "0")
    os.environ['G_ENABLE_DIAGNOSTIC'] = debug_gtk

    # GTK environment variables
    os.environ['GTK_DATA_PREFIX'] = resource_path
    os.environ['GTK_EXE_PREFIX'] = resource_path
    os.environ['GTK_PATH'] = resource_path

    # XDG environment variables
    os.environ['XDG_CONFIG_DIRS'] = os.path.join(etc_path, "xdg")
    os.environ['XDG_DATA_DIRS'] = ":".join(
        (share_path, os.path.join(share_path, "meld")))
    os.environ['XDG_CONFIG_HOME'] = etc_path

    # Pango environment variables
    os.environ['PANGO_RC_FILE'] = os.path.join(etc_path, "pango", "pangorc")
    os.environ['PANGO_SYSCONFDIR'] = etc_path
    os.environ['PANGO_LIBDIR'] = lib_path

    # Gdk environment variables
    os.environ['GDK_PIXBUF_MODULEDIR'] = os.path.join(lib_path,
                                                      "gdk-pixbuf-2.0",
                                                      "2.10.0", "loaders")
    #os.environ['GDK_RENDERING'] = "image"

    # Python environment variables
    os.environ['PYTHONHOME'] = resource_path
    original_python_path = os.environ.get('PYTHONPATH', "")
    python_path = ":".join(
        (lib_path, os.path.join(lib_path, "python", "lib-dynload"),
         os.path.join(lib_path, "python"), original_python_path))
    os.environ['PYTHONPATH'] = python_path

    # meld specific
    DATADIR = os.path.join(share_path, "meld")
    LOCALEDIR = os.path.join(share_path, "mo")
    DATADIR_IS_UNINSTALLED = True
Ejemplo n.º 32
0
 def preview(self, url=PREVIEW_URL):
     """
     Preview the link to see how it would look locally.
     """
     NSLog("Starting a preview.")
     # Rebuild the blog locally.
     self.build_blog()
     # Open a browser to see the local preview.
     bundle = NSBundle.mainBundle()
     script_path = bundle.pathForResource_ofType_('open-chrome-tab', 'scpt')
     self.run_command_async('osascript', script_path, url)
Ejemplo n.º 33
0
    def _NH_SIPApplicationWillStart(self, sender, data):
        settings = SIPSimpleSettings()
        _version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
        settings.user_agent = "%s %s (MacOSX)" % (NSApp.delegate().applicationName, _version)
        BlinkLogger().log_debug("SIP User Agent: %s" % settings.user_agent)
        settings.save()

        self.migratePasswordsToKeychain()
        self.cleanupIcons()

        # Set audio settings compatible with AEC and Noise Suppression
        settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled else 48000
        if NSApp.delegate().service_provider_help_url and settings.service_provider.help_url != NSApp.delegate().service_provider_help_url:
            settings.service_provider.help_url = NSApp.delegate().service_provider_help_url
            settings.save()

        if NSApp.delegate().service_provider_name and settings.service_provider.name != NSApp.delegate().service_provider_name:
            settings.service_provider.name = NSApp.delegate().service_provider_name
            settings.save()

        BlinkLogger().log_debug("Audio engine sampling rate %dKHz covering 0-%dKHz spectrum" % (settings.audio.sample_rate/1000, settings.audio.sample_rate/1000/2))
        BlinkLogger().log_debug("Acoustic Echo Canceller is %s" % ('enabled' if settings.audio.echo_canceller.enabled else 'disabled'))

        account_manager = AccountManager()
        for account in account_manager.iter_accounts():
            must_save = False
            if account is not BonjourAccount() and account.sip.primary_proxy is None and account.sip.outbound_proxy and not account.sip.selected_proxy:
                account.sip.primary_proxy = account.sip.outbound_proxy

            if account is not BonjourAccount() and settings.tls.verify_server != account.tls.verify_server:
                account.tls.verify_server = settings.tls.verify_server

            if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt':
                account.tls.certificate = DefaultValue

            if account.rtp.encryption_type == '':
                account.rtp.encryption.enabled = False
            elif account.rtp.encryption_type == 'opportunistic':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'opportunistic'
            elif account.rtp.encryption_type == 'sdes_optional':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'sdes_optional'
            elif account.rtp.encryption_type == 'sdes_mandatory':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'sdes_mandatory'
            elif account.rtp.encryption_type == 'zrtp':
                account.rtp.encryption.enabled = True
                account.rtp.encryption.key_negotiation = 'zrtp'
            account.save()

        logger = FileLogger()
        logger.start()
        self.ip_address_monitor.start()
Ejemplo n.º 34
0
    def testBasic(self):
        # This is mostly a regression tests, the function used to crash on
        # this...
        if objc.platform != "MACOSX":
            return

        pool = NSAutoreleasePool.alloc().init()
        s = NSLocalizedString(b"hello world".decode("ascii"),
                              b"".decode("ascii"))
        del pool
        self.assertEqual(s, b"hello world".decode("ascii"))
        # XXX : Since we get the same object back, it's still unicode
        # self.assertEqual (s.nsstring().description(), b"hello world".decode('ascii'))

        pool = NSAutoreleasePool.alloc().init()
        s = NSLocalizedStringFromTable(b"hello world".decode("ascii"),
                                       b"tab".decode("utf-8"),
                                       b"".decode("ascii"))
        del pool
        self.assertEqual(s, b"hello world".decode("ascii"))

        pool = NSAutoreleasePool.alloc().init()
        s = NSLocalizedStringFromTableInBundle(
            b"hello world".decode("ascii"),
            b"tab".decode("utf-8"),
            NSBundle.mainBundle(),
            b"".decode("ascii"),
        )
        del pool
        self.assertEqual(s, b"hello world".decode("ascii"))

        pool = NSAutoreleasePool.alloc().init()
        s = NSLocalizedStringWithDefaultValue(
            b"hello world".decode("ascii"),
            b"tab".decode("utf-8"),
            NSBundle.mainBundle(),
            b"default".decode("utf-8"),
            b"".decode("ascii"),
        )
        del pool
        self.assertEqual(s, b"default".decode("ascii"))
Ejemplo n.º 35
0
def bundle_path(subpath=None, rsrc=None, fmwk=None):
    """Find the path to the main NSBundle (or an optional subpath within it)"""
    from os.path import join
    from Foundation import NSBundle
    bundle = NSBundle.mainBundle().bundlePath()
    if rsrc:
      return join(bundle, "Contents", "Resources", rsrc)
    if fmwk:
      return join(bundle, "Contents", "Frameworks", '%s.framework' % fmwk)
    if subpath:
        return join(bundle, subpath)
    return bundle
Ejemplo n.º 36
0
def bundle_path(subpath=None, rsrc=None, fmwk=None):
    """Find the path to the main NSBundle (or an optional subpath within it)"""
    from os.path import join
    from Foundation import NSBundle
    bundle = NSBundle.mainBundle().bundlePath()
    if rsrc:
        return join(bundle, "Contents", "Resources", rsrc)
    if fmwk:
        return join(bundle, "Contents", "Frameworks", '%s.framework' % fmwk)
    if subpath:
        return join(bundle, subpath)
    return bundle
Ejemplo n.º 37
0
def _init_mne_qtapp(enable_icon=True, pg_app=False):
    """Get QApplication-instance for MNE-Python.

    Parameter
    ---------
    enable_icon: bool
        If to set an MNE-icon for the app.
    pg_app: bool
        If to create the QApplication with pyqtgraph. For an until know
        undiscovered reason the pyqtgraph-browser won't show without
        mkQApp from pyqtgraph.

    Returns
    -------
    app: ``PyQt5.QtWidgets.QApplication``
        Instance of QApplication.
    """
    from PyQt5.QtWidgets import QApplication
    from PyQt5.QtGui import QIcon

    app_name = 'MNE-Python'
    organization_name = 'MNE'

    # Fix from cbrnr/mnelab for app name in menu bar
    # This has to come *before* the creation of the QApplication to work.
    # It also only affects the title bar, not the application dock.
    # There seems to be no way to change the application dock from "python"
    # at runtime.
    if sys.platform.startswith("darwin"):
        try:
            # set bundle name on macOS (app name shown in the menu bar)
            from Foundation import NSBundle
            bundle = NSBundle.mainBundle()
            info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
            info["CFBundleName"] = app_name
        except ModuleNotFoundError:
            pass

    if pg_app:
        from pyqtgraph import mkQApp
        app = mkQApp(app_name)
    else:
        app = QApplication.instance() or QApplication(sys.argv or [app_name])
        app.setApplicationName(app_name)
    app.setOrganizationName(organization_name)

    if enable_icon:
        # Set icon
        _init_qt_resources()
        kind = 'bigsur-' if platform.mac_ver()[0] >= '10.16' else ''
        app.setWindowIcon(QIcon(f":/mne-{kind}icon.png"))

    return app
Ejemplo n.º 38
0
 def getItemView(self):
     array = NSMutableArray.array()
     context = NSMutableDictionary.dictionary()
     context.setObject_forKey_(self, NSNibOwner)
     context.setObject_forKey_(array, NSNibTopLevelObjects)
     path = NSBundle.mainBundle().pathForResource_ofType_("AlertPanelView", "nib")
     if not NSBundle.loadNibFile_externalNameTable_withZone_(path, context, self.zone()):
         raise RuntimeError("Internal Error. Could not find AlertPanelView.nib")
     for obj in array:
         if isinstance(obj, NSBox):
             return obj
     else:
         raise RuntimeError("Internal Error. Could not find NSBox in AlertPanelView.nib")
Ejemplo n.º 39
0
 def ns_init_application_name(self):
     #  Arrange for the application name to be used as the title
     #  of the application menu.
     ns_bundle = NSBundle.mainBundle()
     if ns_bundle:
         ns_info = ns_bundle.localizedInfoDictionary()
         if not ns_info:
             ns_info = ns_bundle.infoDictionary()
         if ns_info:
             if ns_info['CFBundleName'] == "Python":
                 #print "GUI.Application: NSBundle infoDictionary =", ns_info ###
                 ns_info['CFBundleName'] = Globals.application_name
             return
Ejemplo n.º 40
0
def _update_mac_app_info():
    if sys.platform.startswith('darwin'):
        try:
            from Foundation import NSBundle  # noqa
            bundle = NSBundle.mainBundle()
            if bundle:
                app_info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
                if app_info:
                    app_info['CFBundleName'] = extrap.__title__
            from AppKit import NSWindow
            NSWindow.setAllowsAutomaticWindowTabbing_(False)
        except ImportError:
            pass
Ejemplo n.º 41
0
    def register_protocol_handlers(self):
        """Register the URL scheme listener using PyObjC"""
        from Foundation import NSBundle
        from LaunchServices import LSSetDefaultHandlerForURLScheme

        bundle_id = NSBundle.mainBundle().bundleIdentifier()
        if bundle_id == 'org.python.python':
            log.debug("Skipping URL scheme registration as this program "
                      " was launched from the Python OSX app bundle")
            return
        LSSetDefaultHandlerForURLScheme(self.NXDRIVE_SCHEME, bundle_id)
        log.debug('Registered bundle %r for URL scheme %r', bundle_id,
                  self.NXDRIVE_SCHEME)
Ejemplo n.º 42
0
    def register_protocol_handlers(self):
        """Register the URL scheme listener using PyObjC"""
        from Foundation import NSBundle
        from LaunchServices import LSSetDefaultHandlerForURLScheme

        bundle_id = NSBundle.mainBundle().bundleIdentifier()
        if bundle_id == 'org.python.python':
            log.debug("Skipping URL scheme registration as this program "
                      " was launched from the Python OSX app bundle")
            return
        LSSetDefaultHandlerForURLScheme(self.NXDRIVE_SCHEME, bundle_id)
        log.debug('Registered bundle %r for URL scheme %r', bundle_id,
                  self.NXDRIVE_SCHEME)
Ejemplo n.º 43
0
 def ns_init_application_name(self):
     #  Arrange for the application name to be used as the title
     #  of the application menu.
     ns_bundle = NSBundle.mainBundle()
     if ns_bundle:
         ns_info = ns_bundle.localizedInfoDictionary()
         if not ns_info:
             ns_info = ns_bundle.infoDictionary()
         if ns_info:
             if ns_info['CFBundleName'] == "Python":
                 #print "GUI.Application: NSBundle infoDictionary =", ns_info ###
                 ns_info['CFBundleName'] = Globals.application_name
             return
Ejemplo n.º 44
0
def setAppName():
    if sys.platform == "darwin":
        try:
            from Foundation import NSBundle

            bundle = NSBundle.mainBundle()
            if bundle:
                app_info = bundle.localizedInfoDictionary(
                ) or bundle.infoDictionary()
                if app_info:
                    app_info["CFBundleName"] = "TruFont"
        except ImportError as e:
            print(f"Could not set title: {e}")
            pass
Ejemplo n.º 45
0
 def run(self):
     self.app = rumps.App("Quiet", title='Q')
     self.app.menu._menu.setDelegate_(self)
     # modules
     #modules.google_calendar.start(app)
     self.google_calendar = modules.google_calendar.Module()
     self.google_calendar.start(self.app)
     # Quiet menu items
     self.app.menu.add(None) # separator
     version = NSBundle.mainBundle().infoDictionary()['CFBundleShortVersionString']
     def _about(sender):
         webbrowser.open("https://github.com/hiroshi/quiet/wiki")
     self.app.menu.add(rumps.MenuItem("quiet %s" % version, callback=_about))
     self.app.run()
Ejemplo n.º 46
0
    def applicationDidFinishLaunching_(self, _):
        currentVersion = NSBundle.mainBundle().infoDictionary()["CFBundleVersion"]
        NSLog("Starting Yaybu version %s" % currentVersion)

        userDefaults = NSUserDefaults.standardUserDefaults()
        lastVersion = userDefaults.stringForKey_("version")

        if not lastVersion:
            NSLog("Detected that this is a first run!")
            self.applicationFirstRun()

        if not lastVersion or lastVersion != currentVersion:
            NSLog("Version changed from %s to %s" % (lastVersion, currentVersion))
            self.applicationVersionChanged(lastVersion, currentVersion)
            userDefaults.setObject_forKey_(currentVersion, "version")
Ejemplo n.º 47
0
    def prepare_bin(cls):
        """Find packaged borg binary. Prefer globally installed."""

        borg_in_path = shutil.which('borg')

        if borg_in_path:
            return borg_in_path
        elif sys.platform == 'darwin':
            # macOS: Look in pyinstaller bundle
            from Foundation import NSBundle
            mainBundle = NSBundle.mainBundle()

            bundled_borg = os.path.join(mainBundle.bundlePath(), 'Contents', 'Resources', 'borg-dir', 'borg.exe')
            if os.path.isfile(bundled_borg):
                return bundled_borg
        return None
Ejemplo n.º 48
0
 def showAboutPlugin_(self, sender):
     icon = None
     info = objc.currentBundle().infoDictionary()
     if 'CFBundleIconFile' in info:
         icon_file = info['CFBundleIconFile']
         icon_path = objc.currentBundle().pathForImageResource_(icon_file)
         if icon_path is not None:
             icon = NSImage.alloc().initWithContentsOfFile_(icon_path)
     if icon is None:
         icon = NSImage.imageNamed_('NSApplicationIcon')
     options = {'Credits': NSAttributedString.alloc().initWithString_('ÇFULLUSERNAMEÈ'),
                'ApplicationName': self.name(),
                'ApplicationIcon': icon,
                'ApplicationVersion': info['CFBundleShortVersionString'],
                'Version': 'Coda %s' % NSBundle.mainBundle().infoDictionary()['CFBundleShortVersionString']}
     NSApp.orderFrontStandardAboutPanelWithOptions_(options)
Ejemplo n.º 49
0
    def initWithAccount_target_name_(self, account, target, display_name):
        self = objc.super(SMSViewController, self).init()
        if self:
            self.session_id = str(uuid.uuid1())

            self.notification_center = NotificationCenter()
            self.account = account
            self.target_uri = target
            self.display_name = display_name
            self.messages = {}

            self.encryption = OTREncryption(self)

            self.message_queue = EventQueue(self._send_message)

            self.history = ChatHistory()

            self.local_uri = '%s@%s' % (account.id.username, account.id.domain)
            self.remote_uri = '%s@%s' % (self.target_uri.user.decode(),
                                         self.target_uri.host.decode())
            self.contact = NSApp.delegate(
            ).contactsWindowController.getFirstContactFromAllContactsGroupMatchingURI(
                self.remote_uri)

            NSBundle.loadNibNamed_owner_("SMSView", self)

            self.chatViewController.setContentFile_(
                NSBundle.mainBundle().pathForResource_ofType_(
                    "ChatView", "html"))
            self.chatViewController.setAccount_(self.account)
            self.chatViewController.resetRenderedMessages()

            self.chatViewController.inputText.unregisterDraggedTypes()
            self.chatViewController.inputText.setMaxLength_(MAX_MESSAGE_LENGTH)
            self.splitView.setText_(
                NSLocalizedString("%i chars left", "Label") %
                MAX_MESSAGE_LENGTH)

            self.enableIsComposing = True

            self.log_info('Using local account %s' % self.local_uri)

            self.notification_center.add_observer(
                self, name='ChatStreamOTREncryptionStateChanged')
            self.started = False

        return self
Ejemplo n.º 50
0
def register_protocol_handlers(controller):
    """Register the URL scheme listener using PyObjC"""
    try:
        from Foundation import NSBundle
        from LaunchServices import LSSetDefaultHandlerForURLScheme
    except ImportError:
        log.warning("Cannot register %r scheme: missing OSX Foundation module",
                    NXDRIVE_SCHEME)
        return

    bundle_id = NSBundle.mainBundle().bundleIdentifier()
    if bundle_id == 'org.python.python':
        log.debug("Skipping URL scheme registration as this program "
                  " was launched from the Python OSX app bundle")
        return
    LSSetDefaultHandlerForURLScheme(NXDRIVE_SCHEME, bundle_id)
    log.debug("Registered bundle '%s' for URL scheme '%s'", bundle_id,
              NXDRIVE_SCHEME)
Ejemplo n.º 51
0
def get_template(template_name, raw=False):
    '''return an html template. If raw is True, just return the string; otherwise
    return a string Template object'''
    customTemplatesPath = os.path.join(msclib.html_dir(), 'custom/templates')
    resourcesPath = NSBundle.mainBundle().resourcePath()
    defaultTemplatesPath = os.path.join(resourcesPath, 'templates')
    for directory in [customTemplatesPath, defaultTemplatesPath]:
        templatePath = os.path.join(directory, template_name)
        if os.path.exists(templatePath):
            try:
                file_ref = open(templatePath)
                template_html = file_ref.read()
                file_ref.close()
                if raw:
                    return template_html.decode('utf-8')
                else:
                    return Template(template_html.decode('utf-8'))
            except (IOError, OSError):
                return None
    return None
Ejemplo n.º 52
0
    def _NH_SIPApplicationWillStart(self, sender, data):
        settings = SIPSimpleSettings()
        _version = str(NSBundle.mainBundle().infoDictionary().objectForKey_("CFBundleShortVersionString"))
        settings.user_agent = "%s %s (MacOSX)" % (NSApp.delegate().applicationName, _version)
        BlinkLogger().log_info(u"SIP User Agent: %s" % settings.user_agent)

        self.migratePasswordsToKeychain()
        self.cleanupIcons()

        # Set audio settings compatible with AEC and Noise Supressor
        settings.audio.sample_rate = 32000 if settings.audio.echo_canceller.enabled else 48000
        if NSApp.delegate().applicationName == 'SIP2SIP':
            settings.service_provider.help_url  = 'http://wiki.sip2sip.info'
            settings.service_provider.name = 'SIP2SIP'
        settings.save()
        BlinkLogger().log_info(u"Audio engine sampling rate %dKHz covering 0-%dKHz spectrum" % (settings.audio.sample_rate/1000, settings.audio.sample_rate/1000/2))
        BlinkLogger().log_info(u"Acoustic Echo Canceller is %s" % ('enabled' if settings.audio.echo_canceller.enabled else 'disabled'))

        # Although this setting is set at enrollment time, people who have downloaded previous versions will not have it
        account_manager = AccountManager()
        for account in account_manager.iter_accounts():
            must_save = False
            if account is not BonjourAccount() and account.sip.primary_proxy is None and account.sip.outbound_proxy and not account.sip.selected_proxy:
                account.sip.primary_proxy = account.sip.outbound_proxy
                must_save = True

            if account is not BonjourAccount() and settings.tls.verify_server != account.tls.verify_server:
                account.tls.verify_server = settings.tls.verify_server
                must_save = True

            if account.tls.certificate and os.path.basename(account.tls.certificate.normalized) != 'default.crt':
                account.tls.certificate = DefaultValue
                must_save = True

            if must_save:
                account.save()

        logger = FileLogger()
        logger.start()
        self.ip_address_monitor.start()
Ejemplo n.º 53
0
 def init(self):
     self = super().init()
     if self is None:
         return None
     self._font = NSFont.userFixedPitchFontOfSize_(10)
     self._historyLength = 50
     self._history = ['']
     self._historyView = 0
     self._characterIndexForInput = 0
     self._stdin = PseudoUTF8Input(self._nestedRunLoopReaderUntilEOLchars_)
     self._stderr = PseudoUTF8Output(self.writeStderr_)
     self._stdout = PseudoUTF8Output(self.writeStdout_)
     self._isInteracting = False
     self._console = AsyncInteractiveConsole()
     self._interp = self._console.asyncinteract(
         write=self.writeCode_,
         banner="Python %s in %s\n%s\n" % (
             sys.version,
             NSBundle.mainBundle().objectForInfoDictionaryKey_('CFBundleName'),
             'Type "help", "copyright", "credits" or "license" for more information.'
         )
     ).__next__
     self._autoscroll = True
     return self
Ejemplo n.º 54
0
        os.path.join(objc.__path__[0], '_objc.so'))
    PyObjCMethodSignature_WithMetaData = (
        _objc_so.PyObjCMethodSignature_WithMetaData)
    PyObjCMethodSignature_WithMetaData.restype = ctypes.py_object

    def objc_method_signature(signature_str):
        '''Return a PyObjCMethodSignature given a call signature in string
        format'''
        return PyObjCMethodSignature_WithMetaData(
            ctypes.create_string_buffer(signature_str), None, False)

# pylint: enable=E0611

# disturbing hack warning!
# this works around an issue with App Transport Security on 10.11
bundle = NSBundle.mainBundle()
info = bundle.localizedInfoDictionary() or bundle.infoDictionary()
info['NSAppTransportSecurity'] = {'NSAllowsArbitraryLoads': True}


def NSLogWrapper(message):
    '''A wrapper function for NSLog to prevent format string errors'''
    NSLog('%@', message)


ssl_error_codes = {
    -9800: u'SSL protocol error',
    -9801: u'Cipher Suite negotiation failure',
    -9802: u'Fatal alert',
    -9803: u'I/O would block (not fatal)',
    -9804: u'Attempt to restore an unknown session',
Ejemplo n.º 55
0
	def customSendProc(event, modeFlags, timeout):
		# unpack required attributes
		try:
			eventcode, addressdesc = _unpackEventAttributes(event)
			appPath = ae.addressdesctopath(addressdesc)
			
			# reject events sent to self otherwise they'll block main event loop
			if appPath == NSBundle.mainBundle().bundlePath():
				raise MacOSError(-1708)
						
			# get app instance and associated data
			if not _appCache.has_key((addressdesc.type, addressdesc.data)):
				if addressdesc.type != kae.typeProcessSerialNumber:
					raise OSAError(10000, 
							"Can't identify application (addressdesc descriptor not typeProcessSerialNumber)")
				app = appscript.app(appPath)
				appData = app.AS_appdata
				
				_appCache[(addressdesc.type, addressdesc.data)] = (app, appData)
			app, appData = _appCache[(addressdesc.type, addressdesc.data)]
			
			# unpack parameters
			desc = event.coerce(kae.typeAERecord)
			params = {}
			for i in range(desc.count()):
				key, value = desc.getitem(i + 1, kae.typeWildCard)
				params[key] = appData.unpack(value)
			resultType = params.pop('rtyp', None)
			directParam = params.pop('----', kNoParam)
			try:
				subject = appData.unpack(event.getattr(kae.keySubjectAttr, kae.typeWildCard))
			except Exception:
				subject = None
			
			# apply special cases
			if subject is not None:
				targetRef = subject
			elif eventcode == 'coresetd':
				# Special case: for 'set' command, use direct parameter as target reference and use 'to' parameter for direct argument
				targetRef = directParam
				directParam = params.pop('data')
			elif isinstance(directParam, appscript.reference.Reference):
				# Special case: if direct parameter is a reference, use this as target reference
				targetRef = directParam
				directParam = kNoParam
			else:
				targetRef = app
			
			# render
			for key, renderer in [(kLangPython, pythonrenderer), (kLangRuby, rubyrenderer), (kLangObjC, objcrenderer)]:
				try:
					addResultFn(key, renderer.renderCommand(
							appPath, addressdesc, eventcode, 
							targetRef, directParam, params, 
							resultType, modeFlags, timeout, 
							appData))
				except Exception, e:
					traceback.print_exc()
					s = 'Untranslated event %r' % eventcode
					addResultFn(key, s)

		except Exception, e:
			traceback.print_exc()
			s = 'Untranslated event %r' % eventcode
			addResultFn(kLangAll, s)
Ejemplo n.º 56
0
def frozen():
    global DATADIR, LOCALEDIR

    try:
        from Foundation import NSBundle
        bundle = NSBundle.mainBundle()
        resource_path =  bundle.resourcePath().fileSystemRepresentation()
        bundle_path = bundle.bundlePath().fileSystemRepresentation()
        frameworks_path = bundle.privateFrameworksPath().fileSystemRepresentation()
        executable_path = bundle.executablePath().fileSystemRepresentation()
        etc_path = os.path.join(resource_path , "etc")
        lib_path = os.path.join(resource_path , "lib")
        share_path = os.path.join(resource_path , "share")

        # Default to Adwaita GTK Theme or override with user's environment var
        gtk_theme= os.environ.get('GTK_THEME', "Adwaita")
        os.environ['GTK_THEME'] = gtk_theme

        # Main libraries environment variables
        #dyld_library_path = os.environ.get('DYLD_LIBRARY_PATH', '').split(':')
        #dyld_library_path.insert(0, lib_path)
        #dyld_library_path.insert(1, frameworks_path)
        #os.environ['DYLD_LIBRARY_PATH'] = ':'.join(dyld_library_path)
        #print "DYLD_LIBRARY_PATH %s" % os.environ.get('DYLD_LIBRARY_PATH', '')

        # Glib and GI environment variables
        os.environ['GSETTINGS_SCHEMA_DIR'] = os.path.join(
                                    share_path, "glib-2.0")
        os.environ['GI_TYPELIB_PATH'] = os.path.join(
                                    lib_path, "girepository-1.0")

        # Avoid GTK warnings unless user specifies otherwise
        debug_gtk = os.environ.get('G_ENABLE_DIAGNOSTIC', "0")
        os.environ['G_ENABLE_DIAGNOSTIC'] = debug_gtk

        # GTK environment variables
        os.environ['GTK_DATA_PREFIX'] = resource_path
        os.environ['GTK_EXE_PREFIX'] = resource_path
        os.environ['GTK_PATH'] = resource_path

        # XDG environment variables
        os.environ['XDG_CONFIG_DIRS'] = os.path.join(etc_path, "xdg")
        os.environ['XDG_DATA_DIRS'] = ":".join((share_path,
                                            os.path.join(share_path, "meld")))

        # Pango environment variables
        os.environ['PANGO_RC_FILE'] = os.path.join(etc_path, "pango", "pangorc")
        os.environ['PANGO_SYSCONFDIR'] = etc_path
        os.environ['PANGO_LIBDIR'] = lib_path

        # Gdk environment variables
        os.environ['GDK_PIXBUF_MODULEDIR'] = os.path.join(
                                lib_path, "gdk-pixbuf-2.0", "2.10.0", "loaders")
        os.environ['GDK_RENDERING'] = "image"

        # Python environment variables
        os.environ['PYTHONHOME'] = resource_path
        original_python_path = os.environ.get('PYTHONPATH', "")
        python_path = ":".join((lib_path,
                        os.path.join(lib_path, "python", "lib-dynload"),
                        os.path.join(lib_path, "python"),
                        original_python_path))
        os.environ['PYTHONPATH'] = python_path

        # meld specific
        DATADIR = os.path.join(share_path, "meld")
        LOCALEDIR = os.path.join(share_path, "mo")

    except ImportError:
        print "frozen: ImportError"
        melddir = os.path.dirname(sys.executable)
        DATADIR = os.path.join(melddir, "share", "meld")
        LOCALEDIR = os.path.join(melddir, "share", "mo")

        # This first bit should be unnecessary, but some things (GTK icon theme
        # location, GSettings schema location) don't fall back correctly.
        data_dir = os.environ.get('XDG_DATA_DIRS', "/usr/local/share/:/usr/share/")
        data_dir = ":".join((melddir, data_dir))
        os.environ['XDG_DATA_DIRS'] = data_dir
Ejemplo n.º 57
0
 def __init__(self) -> None:
     info_dict = NSBundle.mainBundle().infoDictionary()
     if "CFBundleIdentifier" not in info_dict:
         info_dict["CFBundleIdentifier"] = BUNDLE_IDENTIFIER
Ejemplo n.º 58
0
                         "assuming '%s'\n" % (str(wk),
                                              str(win_version_num),
                                              os_version))
    del wh, wk

elif os_name == 'posix':
    os_version = os.uname()[0]

app_root = os.path.split(get_module_filename())[0]
doc_root = app_root
osx = False
if os.name == 'posix':
    if os.uname()[0] == "Darwin":
        doc_root = app_root = app_root.encode('utf8')
        if has_pyobjc:
            doc_root = NSBundle.mainBundle().resourcePath()
            osx = True

def calc_unix_dirs():
    appdir = '%s-%s' % (app_name, version)
    ip = os.path.join(efs2(u'share'), efs2(u'pixmaps'), appdir)
    dp = os.path.join(efs2(u'share'), efs2(u'doc'), appdir)
    lp = os.path.join(efs2(u'share'), efs2(u'locale'))
    return ip, dp, lp

def no_really_makedirs(path):
    # the deal here is, directories like "C:\" exist but can not be created
    # (access denied). We check for the exception anyway because of the race
    # condition.
    if not os.path.exists(path):
        try: