Exemple #1
0
def load_plugins():
    dn = NSBundle.mainBundle().objectForInfoDictionaryKey_(
        'CFBundleExecutable')
    system_paths = NSSearchPathForDirectoriesInDomains(
        NSApplicationSupportDirectory, NSUserDomainMask | NSLocalDomainMask,
        YES)
    for search_path in system_paths:
        plugins = os.path.join(search_path, dn, 'PlugIns')
        if os.path.isdir(plugins):
            load_plugins_in_path(plugins)
    load_plugins_in_path(NSBundle.mainBundle().builtInPlugInsPath())
Exemple #2
0
def open_app_at_startup(enabled=True):
    """
    This function adds/removes the current app bundle from Login items in macOS
    """
    if sys.platform == 'darwin':
        from Foundation import NSDictionary

        from Cocoa import NSBundle, NSURL
        from CoreFoundation import kCFAllocatorDefault
        # CF = CDLL(find_library('CoreFoundation'))
        from LaunchServices import (LSSharedFileListCreate,
                                    kLSSharedFileListSessionLoginItems,
                                    LSSharedFileListInsertItemURL,
                                    kLSSharedFileListItemHidden,
                                    kLSSharedFileListItemLast,
                                    LSSharedFileListItemRemove)

        app_path = NSBundle.mainBundle().bundlePath()
        url = NSURL.alloc().initFileURLWithPath_(app_path)
        login_items = LSSharedFileListCreate(
            kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None)
        props = NSDictionary.dictionaryWithObject_forKey_(
            True, kLSSharedFileListItemHidden)

        new_item = LSSharedFileListInsertItemURL(login_items,
                                                 kLSSharedFileListItemLast,
                                                 None, None, url, props, None)
        if not enabled:
            LSSharedFileListItemRemove(login_items, new_item)
    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 = 'Type "help", "copyright", "credits" or "license" for more information.'
        if banner is None:
            write("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
 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 = 'Type "help", "copyright", "credits" or "license" for more information.'
     if banner is None:
         write("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
Exemple #5
0
def LoadDatabase():
    """Load the database from stored-data.txt.

    Returns:
    The loaded database.
    """

    
    textResourcesFilePaths = NSBundle.mainBundle().pathsForResourcesOfType_inDirectory_("txt", None)
    
    databaseFilePath = textResourcesFilePaths[0]
    
    NSLog ( "LoadDatabase: databaseFilePath is: %s " % (databaseFilePath, ) )

    #fn = "database.pickle.txt"

    try:
        f = open( databaseFilePath , "r" )

        #StoredData = cPickle.load(f)
        r = f.read()
        f.close()
        #print "read %d bytes from %s" % ( len(r), fn )
    except (IOError, ValueError):
        print "Could not read from file: %r." % (  databaseFilePath,  )
        StoredData = None
        f.close()
        return StoredData

    try:
        StoredData = eval(r)

    except (IOError, ValueError):
        StoredData = None
    return StoredData
Exemple #6
0
def get_system(attribute):
    """A helper function to get specific system attributes.
    Args:
        attribute:  The system attribute desired.
    Returns:
        stdout:  The system attribute value.
    """

    IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
    functions = [("IOServiceGetMatchingService", b"II@"), ("IOServiceMatching", b"@*"), ("IORegistryEntryCreateCFProperty", b"@I@@I"),]
    objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

    def io_key(keyname):
        return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))), keyname, None, 0)

    def get_hardware_uuid():
        return io_key("IOPlatformUUID".encode("utf-8"))

    def get_hardware_serial():
        return io_key("IOPlatformSerialNumber".encode("utf-8"))

    # def get_board_id():
    #     return str(io_key("board-id".encode("utf-8"))).rstrip('\x00')

    options = {'serial' : get_hardware_serial #,
        #    'uuid' : get_hardware_uuid,
        #    'boardID' : get_board_id
    }

    return options[attribute]()
Exemple #7
0
def report_webkit_version():
    path = ctypes.macholib.dyld.framework_find('JavaScriptCore')
    if not path:
        return
    bundle = NSBundle.bundleWithPath_(os.path.dirname(path))
    if bundle is None:
        return
    version = bundle.infoDictionary()['CFBundleVersion']
    report('webkit-version', version=version)
Exemple #8
0
def get_marketing_name():
    # get_marketing_name gets the marketing name for the model of the Mac
    # in the form of '13" MacBook Pro with Retina display (Early 2015)'
    ServerInformation = NSBundle.bundleWithPath_(
        '/System/Library/PrivateFrameworks/ServerInformation.framework')
    ServerCompatibility = NSBundle.bundleWithPath_(
        '/System/Library/PrivateFrameworks/ServerCompatibility.framework')

    ServerInformationComputerModelInfo = ServerInformation.classNamed_(
        'ServerInformationComputerModelInfo')
    SVCSystemInfo = ServerCompatibility.classNamed_('SVCSystemInfo')

    info = SVCSystemInfo.currentSystemInfo()
    extended_info = ServerInformationComputerModelInfo.attributesForModelIdentifier_(
        info.computerModelIdentifier())

    if extended_info:
        marketing_name = extended_info['marketingModel']
        return marketing_name
    else:
        return "-"
Exemple #9
0
def open_app_at_startup(enabled=True):
    """
    This function adds/removes the current app bundle from Login items in macOS or most Linux desktops
    """
    if sys.platform == 'darwin':
        from Foundation import NSDictionary

        from Cocoa import NSBundle, NSURL
        from CoreFoundation import kCFAllocatorDefault
        # CF = CDLL(find_library('CoreFoundation'))
        from LaunchServices import (LSSharedFileListCreate,
                                    kLSSharedFileListSessionLoginItems,
                                    LSSharedFileListInsertItemURL,
                                    kLSSharedFileListItemHidden,
                                    kLSSharedFileListItemLast,
                                    LSSharedFileListItemRemove)

        app_path = NSBundle.mainBundle().bundlePath()
        url = NSURL.alloc().initFileURLWithPath_(app_path)
        login_items = LSSharedFileListCreate(
            kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None)
        props = NSDictionary.dictionaryWithObject_forKey_(
            True, kLSSharedFileListItemHidden)

        new_item = LSSharedFileListInsertItemURL(login_items,
                                                 kLSSharedFileListItemLast,
                                                 None, None, url, props, None)
        if not enabled:
            LSSharedFileListItemRemove(login_items, new_item)

    elif sys.platform.startswith('linux'):
        autostart_path = Path.home() / '.config' / 'autostart'

        if not autostart_path.exists():
            autostart_path.mkdir()

        autostart_file_path = autostart_path / 'vorta.desktop'

        if enabled:
            if Path('/.flatpak-info').exists():
                # Vorta runs as flatpak
                autostart_file_path.write_text(
                    LINUX_STARTUP_FILE.format(
                        'flatpak run com.borgbase.vorta'))
            else:
                autostart_file_path.write_text(
                    LINUX_STARTUP_FILE.format('vorta'))

        else:
            if autostart_file_path.exists():
                autostart_file_path.unlink()
Exemple #10
0
    def awakeFromNib(self):
        # we're only using the AMWorkflowView for display
        self.workflowView.setEditable_(False)

        # set up the data for NSTableView.  We'll store a list of
        # NSDictonary records each containing some information about the
        # workflow.  We'll display the name of the workflow's file in the
        # window.

        # set up an array for storing the table information
        theWorkflows = NSMutableArray.alloc().initWithCapacity_(20)

        # retrieve a list of all of the workflows stored in the application's
        # resourced folder.
        workflowPaths = NSBundle.mainBundle(
        ).pathsForResourcesOfType_inDirectory_("workflow", "workflows")

        # iterate through the paths, adding them to our table information
        # as we go.
        for nthWorkflowPath in workflowPaths:
            wfError = None

            # convert the path into an URL
            nthWorkflowURL = NSURL.fileURLWithPath_isDirectory_(
                nthWorkflowPath, False)

            # allocate and initialize the workflow
            nthWorkflow, wfError = AMWorkflow.alloc(
            ).initWithContentsOfURL_error_(nthWorkflowURL, None)

            if nthWorkflow:
                # calculate the file name without path or extension
                nthFileName = nthWorkflowPath.componentsSeparatedByString_(
                    "/")[-1]
                nthDisplayName = nthFileName[:-9]

                # add the workflow to the list
                theWorkflows.append({
                    "name": nthDisplayName,
                    "path": nthWorkflowPath,
                    "workflow": nthWorkflow,
                })

        # set the workflows
        self._.workflows = theWorkflows

        # if there are any workflows in the list, then select and display the first one */
        if len(self._.workflows):
            self.workflowTable.selectRowIndexes_byExtendingSelection_(
                NSIndexSet.indexSetWithIndex_(0), False)
            self.displaySelectedWorkflow()
Exemple #11
0
    def awakeFromNib(self):
        # we're only using the AMWorkflowView for display
        self.workflowView.setEditable_(False)

        # set up the data for NSTableView.  We'll store a list of
        # NSDictonary records each containing some information about the
        # workflow.  We'll display the name of the workflow's file in the
        # window.

        # set up an array for storing the table information
        theWorkflows = NSMutableArray.alloc().initWithCapacity_(20)

        # retrieve a list of all of the workflows stored in the application's
        # resourced folder.
        workflowPaths = NSBundle.mainBundle().pathsForResourcesOfType_inDirectory_(
                "workflow", "workflows")

        # iterate through the paths, adding them to our table information
        # as we go.
        for nthWorkflowPath in workflowPaths:
            wfError = None

            # convert the path into an URL
            nthWorkflowURL = NSURL.fileURLWithPath_isDirectory_(nthWorkflowPath, False)

            # allocate and initialize the workflow
            nthWorkflow, wfError = AMWorkflow.alloc().initWithContentsOfURL_error_(nthWorkflowURL, None)

            if nthWorkflow:
                # calculate the file name without path or extension
                nthFileName = nthWorkflowPath.componentsSeparatedByString_("/")[-1]
                nthDisplayName = nthFileName[:-9]

                # add the workflow to the list
                theWorkflows.append(dict(
                        name=nthDisplayName,
                        path=nthWorkflowPath,
                        workflow=nthWorkflow,
                    ))

        # set the workflows
        self._.workflows = theWorkflows

        # if there are any workflows in the list, then select and display the first one */
        if len(self._.workflows):
            self.workflowTable.selectRowIndexes_byExtendingSelection_(
                NSIndexSet.indexSetWithIndex_(0), False)
            self.displaySelectedWorkflow()
Exemple #12
0
def fact():
    """Returns the marketing name"""
    result = "None"
    model = subprocess.check_output(["/usr/sbin/sysctl", "-n",
                                     "hw.model"]).strip()

    serverInfoBundle = NSBundle.bundleWithPath_(
        "/System/Library/PrivateFrameworks/ServerInformation.framework/")
    sysinfofile = serverInfoBundle.URLForResource_withExtension_subdirectory_(
        "SIMachineAttributes", "plist", "")

    d = plistlib.readPlist(sysinfofile.path())

    if d.get(model, False):
        result = d[model]["_LOCALIZABLE_"]["marketingModel"]

    return {factoid: result.strip()}
Exemple #13
0
def MachineName():
	if platform.system() == 'Linux':
		
		cpu = ''
		itemsUsed = []
		procinfo = Execute('cat /proc/cpuinfo')

		for line in procinfo.split('\n'):
			if ':' in line:
				k, v = line.split(':')[:2]
				if k.strip() == 'model name' and not k in itemsUsed:
					cpu += v.strip()
					itemsUsed.append(k)
		return '%s %s with %s' % (Execute('cat /sys/devices/virtual/dmi/id/sys_vendor'), Execute('cat /sys/devices/virtual/dmi/id/product_name'), cpu)

	elif platform.system() == 'Darwin':

		name = None


		# Approach 1
		import sys
		import plistlib
		import subprocess
		from Cocoa import NSBundle
		data = plistlib.readPlistFromString(Execute('system_profiler -xml SPHardwareDataType'))

		if (len(sys.argv) == 2):
			model = sys.argv[1]
		else:
			model = subprocess.check_output(["/usr/sbin/sysctl", "-n", "hw.model"]).strip()

		serverInfoBundle=NSBundle.bundleWithPath_("/System/Library/PrivateFrameworks/ServerInformation.framework/")
		sysinfofile=serverInfoBundle.URLForResource_withExtension_subdirectory_("SIMachineAttributes", "plist", "")

		plist = plistlib.readPlist(sysinfofile.path())

		if (model in plist):
			name = plist[model]["_LOCALIZABLE_"]["marketingModel"]

		# Approach 2
		if not name:
			name = data[0]['_items'][0]['machine_name']


		return 'Apple %s (%s) with %s %s, %s memory' % (name, data[0]['_items'][0]['machine_model'], data[0]['_items'][0]['cpu_type'], data[0]['_items'][0]['current_processor_speed'], data[0]['_items'][0]['physical_memory'])
Exemple #14
0
def fact():
    '''Returns the marketing name'''
    result = 'None'
    model = subprocess.check_output(
            ['/usr/sbin/sysctl', '-n', 'hw.model']
            ).strip()

    serverInfoBundle = NSBundle.bundleWithPath_(
            '/System/Library/PrivateFrameworks/ServerInformation.framework/'
            )
    sysinfofile = serverInfoBundle.URLForResource_withExtension_subdirectory_(
            'SIMachineAttributes', 'plist', ''
            )

    d = plistlib.readPlist(sysinfofile.path())

    if d.get(model, False):
        result = d[model]['_LOCALIZABLE_']['marketingModel']

    return {factoid: result.strip()}
Exemple #15
0
def open_app_at_startup(enabled=True):
    """
    This function adds/removes the current app bundle from Login items in macOS or most Linux desktops
    """
    if sys.platform == 'darwin':
        from Foundation import NSDictionary

        from Cocoa import NSBundle, NSURL
        from CoreFoundation import kCFAllocatorDefault
        # CF = CDLL(find_library('CoreFoundation'))
        from LaunchServices import (LSSharedFileListCreate,
                                    kLSSharedFileListSessionLoginItems,
                                    LSSharedFileListInsertItemURL,
                                    kLSSharedFileListItemHidden,
                                    kLSSharedFileListItemLast,
                                    LSSharedFileListItemRemove)

        app_path = NSBundle.mainBundle().bundlePath()
        url = NSURL.alloc().initFileURLWithPath_(app_path)
        login_items = LSSharedFileListCreate(
            kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None)
        props = NSDictionary.dictionaryWithObject_forKey_(
            True, kLSSharedFileListItemHidden)

        new_item = LSSharedFileListInsertItemURL(login_items,
                                                 kLSSharedFileListItemLast,
                                                 None, None, url, props, None)
        if not enabled:
            LSSharedFileListItemRemove(login_items, new_item)
    elif sys.platform.startswith('linux'):
        config_path = QtCore.QStandardPaths.writableLocation(
            QtCore.QStandardPaths.ConfigLocation)
        autostart_file_path = Path(config_path) / 'autostart' / 'vorta.desktop'
        if enabled:
            dir_entry_point = get_setuptools_script_dir()
            autostart_file_path.write_text(
                LINUX_STARTUP_FILE.format(dir_entry_point))
        else:
            if autostart_file_path.exists():
                autostart_file_path.unlink()
Exemple #16
0
def nsBundleRename(title, match='Python'):
    '''Change the bundle title if the current title matches.

       @param title: New bundle title (C{str}).
       @keyword match: Optional, previous title to match (C{str}).

       @return: The previous bundle title (C{str}) or None.

       @note: Used to mimick C{NSApplication.setTitle_(ns_title)},
              the application name shown in the menu bar.
    '''
    # <https://Developer.Apple.com/documentation/
    #        foundation/nsbundle/1495012-bundlewithpath>
    # ns = NSBundle.bundleWithPath_(os.path.abspath(match))
    p, ns = None, NSBundle.mainBundle()
    if ns:
        ns = ns.localizedInfoDictionary() or ns.infoDictionary()
        if ns:
            k = NSStr('CFBundleName')
            p = ns.objectForKey_(k) or None
            if title and match in (p, '', None):  # can't be empty
                ns.setObject_forKey_(NSStr(title), k)
    return p
Exemple #17
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, print_function

from Cocoa import NSBundle, NSTimer, NSRunLoop, NSDefaultRunLoopMode, NSApp
from objc import lookUpClass, YES, NO, signature

import os
import sys
import traceback
import cStringIO

# load the root classes
sys.path.append(NSBundle.mainBundle().resourcePath())
from plugin import load_plugins, Plugin, Formatter

# load any python plugins in the users directory
load_plugins()

sys.path.append(NSBundle.mainBundle().builtInPlugInsPath())
sys.path.append(
    '/Applications/Xcode.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources/Python'
)
import lldb

# == Enhancements ==
# 'process interrupt' to break in
# stdin support
# different core modules?
# menu items
# draw anywhere 'terminal' view
Exemple #18
0
def open_app_at_startup(enabled=True):
    """
    On macOS, this function adds/removes the current app bundle from Login items
    while on Linux it adds a .desktop file at ~/.config/autostart
    """
    if sys.platform == 'darwin':
        from Foundation import NSDictionary

        from Cocoa import NSBundle, NSURL
        from CoreFoundation import kCFAllocatorDefault
        # CF = CDLL(find_library('CoreFoundation'))
        from LaunchServices import (LSSharedFileListCreate,
                                    kLSSharedFileListSessionLoginItems,
                                    LSSharedFileListInsertItemURL,
                                    kLSSharedFileListItemHidden,
                                    kLSSharedFileListItemLast,
                                    LSSharedFileListItemRemove)

        app_path = NSBundle.mainBundle().bundlePath()
        url = NSURL.alloc().initFileURLWithPath_(app_path)
        login_items = LSSharedFileListCreate(
            kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None)
        props = NSDictionary.dictionaryWithObject_forKey_(
            True, kLSSharedFileListItemHidden)

        new_item = LSSharedFileListInsertItemURL(login_items,
                                                 kLSSharedFileListItemLast,
                                                 None, None, url, props, None)
        if not enabled:
            LSSharedFileListItemRemove(login_items, new_item)

    elif sys.platform.startswith('linux'):
        from appdirs import user_config_dir
        from pathlib import Path

        is_flatpak = Path('/.flatpak-info').exists()

        with open(
                Path(__file__).parent /
                "assets/metadata/com.borgbase.Vorta.desktop") as desktop_file:
            desktop_file_text = desktop_file.read()

        # Find XDG_CONFIG_HOME unless when running in flatpak
        if is_flatpak:
            autostart_path = Path.home() / '.config' / 'autostart'
        else:
            autostart_path = Path(user_config_dir("autostart"))

        if not autostart_path.exists():
            autostart_path.mkdir(parents=True, exist_ok=True)

        autostart_file_path = autostart_path / 'vorta.desktop'

        if enabled:
            # Replace command for flatpak if appropriate and start in background
            desktop_file_text = desktop_file_text.replace(
                "Exec=vorta", "Exec=flatpak run com.borgbase.Vorta --daemonize"
                if is_flatpak else "Exec=vorta --daemonize")
            # Add autostart delay
            desktop_file_text += (AUTOSTART_DELAY)

            autostart_file_path.write_text(desktop_file_text)
        elif autostart_file_path.exists():
            autostart_file_path.unlink()