def create_button(label, func):
			button_width = 25
			black = ObjCClass('UIColor').alloc().initWithWhite_alpha_(0.0, 1.0)
			action_button = ui.Button()
			action_button.action = func
			accessory_button = ObjCClass('UIBarButtonItem').alloc().initWithTitle_style_target_action_(label, 0, action_button, sel('invokeAction:'))
			accessory_button.width = button_width
			accessory_button.tintColor = black
			return (action_button, accessory_button)
Example #2
0
 def __init__(self, cla=''):
     self.class_name = cla
     self.obs = []
     try:
         c = ObjCClass(self.class_name)
     except ValueError:
         dialogs.alert(self.class_name + ' is not a known class')
     try:
         self.obs.append(['Class',dir(c.alloc())])
     except:
         pass
	def create_accessory_toolbar(self):
		from objc_util import ObjCClass, ObjCInstance, sel
		
		def create_button(label, func):
			button_width = 25
			black = ObjCClass('UIColor').alloc().initWithWhite_alpha_(0.0, 1.0)
			action_button = ui.Button()
			action_button.action = func
			accessory_button = ObjCClass('UIBarButtonItem').alloc().initWithTitle_style_target_action_(label, 0, action_button, sel('invokeAction:'))
			accessory_button.width = button_width
			accessory_button.tintColor = black
			return (action_button, accessory_button)
		
		vobj = ObjCInstance(self.markup)

		keyboardToolbar = ObjCClass('UIToolbar').alloc().init()
		
		keyboardToolbar.sizeToFit()
		
		button_width = 25
		black = ObjCClass('UIColor').alloc().initWithWhite_alpha_(0.0, 1.0)
		
		# Create the buttons
		# Need to retain references to the buttons used
		# to handle clicks
		(self.indentButton, indentBarButton) = create_button(u'\u21E5', self.indent)
		
		(self.outdentButton, outdentBarButton) = create_button(u'\u21E4', self.outdent)
		
		(self.quoteButton, quoteBarButton) = create_button('>', self.block_quote)
		
		(self.linkButton, linkBarButton) = create_button('[]', self.link)
		
		#(self.anchorButton, anchorBarButton) = create_button('<>', self.anchor)
		
		(self.hashButton, hashBarButton) = create_button('#', self.heading)
		
		(self.numberedButton, numberedBarButton) = create_button('1.', self.numbered_list)
		
		(self.listButton, listBarButton) = create_button('•', self.unordered_list)
		
		(self.underscoreButton, underscoreBarButton) = create_button('_', self.insert_underscore)
		
		(self.backtickButton, backtickBarButton) = create_button('`', self.insert_backtick)
		
		# Flex between buttons
		f = ObjCClass('UIBarButtonItem').alloc().initWithBarButtonSystemItem_target_action_(5, None, None)
		
		doneBarButton = ObjCClass('UIBarButtonItem').alloc().initWithBarButtonSystemItem_target_action_(0, vobj, sel('endEditing:')) 
		
		keyboardToolbar.items = [indentBarButton, f, outdentBarButton, f, quoteBarButton, f, linkBarButton, f, hashBarButton, f, numberedBarButton, f, listBarButton, f, underscoreBarButton, f, backtickBarButton, f, doneBarButton]
		vobj.inputAccessoryView = keyboardToolbar
Example #4
0
def live_player_is_installed():
	try:
		from objc_util import ObjCClass, nsurl
	except ImportError:
		# don't blow up if objc_util doesn't exist
		return True
	LSApplicationWorkspace = ObjCClass('LSApplicationWorkspace')
	workspace = LSApplicationWorkspace.defaultWorkspace()
	if workspace.applicationForOpeningResource_(
		nsurl('fb493207460770675:')) or workspace.applicationForOpeningResource_(
		nsurl('fb1574042342908027:')):
		return True
	return True
 def __init__(self, **kwargs):
     super().__init__(**kwargs)
     
     UIPickerView = ObjCClass('UIPickerView')
     self._picker_view = UIPickerView.alloc().initWithFrame_(ObjCInstance(self).bounds()).autorelease()
     ObjCInstance(self).addSubview_(self._picker_view)
     self.delegate_and_datasource = UIPickerViewDataSourceAndDelegate.alloc().init().autorelease()
     self._picker_view.delegate = self.delegate_and_datasource
     self._picker_view.dataSource = self.delegate_and_datasource
     
     self._picker_view.assets = photos.get_assets()
     self._picker_view.myRowWidth = self.width
     self._picker_view.myRowHeight = int(self.height/5)
Example #6
0
def get_lan_ip():
    try:
        from objc_util import ObjCClass
        NSHost = ObjCClass('NSHost')
        addresses = []
        for address in NSHost.currentHost().addresses():
            address = str(address)
            if 48 <= ord(address[0]) <= 57 and address != '127.0.0.1':
                addresses.append(address)
        return '   '.join(addresses)

    except ImportError:
        return ''
Example #7
0
def get_lan_ip():
    try:
        from objc_util import ObjCClass
        NSHost = ObjCClass('NSHost')
        addresses = []
        for address in NSHost.currentHost().addresses():
            address = str(address)
            if 48 <= ord(address[0]) <= 57 and address != '127.0.0.1':
                addresses.append(address)
        return '   '.join(addresses)

    except ImportError:
        return ''
def pickerView_viewForRow_forComponent_reusingView_(self, cmd, picker_view, row, component,view_ptr):
    UIPickerView = ObjCInstance(picker_view)
    if view_ptr == None:
      view = ObjCClass('UILabel').alloc().init()
      #view.setText_('test')
      iv = ui.ImageView()
      iv.frame = (0,0, UIPickerView.myRowWidth, UIPickerView.myRowHeight)
      iv.content_mode = ui.CONTENT_SCALE_ASPECT_FIT
      iv.image = UIPickerView.assets[row].get_ui_image(size=(iv.width,iv.height))
      view.addSubview_(ObjCInstance(iv))
    else:
      view = ObjCInstance(view_ptr)
    return view.ptr
Example #9
0
    def get_ip(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            #offline
            if pythonista:
                try:
                    from objc_util import ObjCClass
                    NSHost = ObjCClass('NSHost')
                    addresses = []
                    for address in NSHost.currentHost().addresses():
                        address = str(address)
                        if 48 <= ord(
                                address[0]) <= 57 and address != '127.0.0.1':
                            addresses.append(address)
                    #return '   '.join(addresses)
                    return addresses[-1]

                except ImportError:
                    return ''
            else:
                #PC
                import subprocess
                try:
                    result = subprocess.check_output(
                        'ifconfig en0 |grep -w inet', shell=True)
                except:
                    try:
                        result = subprocess.check_output(
                            'ifconfig eth0 |grep -w inet', shell=True)
                    except:
                        return False
                ip = ''
                if result:
                    strs = result.split('\n')
                    for line in strs:
                        # remove \t, space...
                        line = line.strip()
                        if line.startswith('inet '):
                            a = line.find(' ')
                            ipStart = a + 1
                            ipEnd = line.find(' ', ipStart)
                            if a != -1 and ipEnd != -1:
                                ip = line[ipStart:ipEnd]
                                break

                    return ip
Example #10
0
	def sendEvent2_(_self, _cmd, _event):
		from objc_util import ObjCInstance, CGRect, ObjCClass
		
		UIView = ObjCClass('UIView')
		
		try:
			self = ObjCInstance(_self)
			e = ObjCInstance(_event)
			self.sendEvent2_(e)
			global __tvs
			global __show_touches
			if not __show_touches:
				if __tvs:
					if len(__tvs) > 0:
						for k, v in enumerate(__tvs):
							v[1].removeFromSuperview()
							__tvs.pop(k)
				return
			for tid in __tvs.keys():
				ids = [id(t) for t in e.allTouches().allObjects()]
				if not tid in ids:
					__tvs[tid][1].removeFromSuperview()
					__tvs.pop(tid)
			for t in e.allTouches().allObjects():
				if t.phase() == 3 or t.phase() == 4:
					__tvs[id(t)][1].removeFromSuperview()
					__tvs.pop(id(t), None)
				elif t.phase() == 0:
					vc = t.window().rootViewController()
					while vc.presentedViewController():
						vc = vc.presentedViewController()
					v = UIView.new()
					v.size = (30, 30)
					v.center = t.locationInView_(vc.view())
					v.backgroundColor = UIColor.blackColor()
					v.alpha = 0.4
					v.layer().cornerRadius = 15
					v.userInteractionEnabled = False
					vc.view().addSubview_(v)
					__tvs[id(t)] = [t, v]
				elif t.phase() == 1:
					__tvs[id(t)][0] = t
					vc = t.window().rootViewController()
					while vc.presentedViewController():
						vc = vc.presentedViewController()
					v = __tvs[id(t)][1]
					v.center = t.locationInView_(vc.view())
		except:
			pass
Example #11
0
def flash_signals(kana, span):
    AVCaptureDevice = ObjCClass('AVCaptureDevice')
    device = AVCaptureDevice.defaultDeviceWithMediaType_('vide')
    if not device.hasTorch():
        raise RuntimeError('Device has no flashlight')
    mode = device.torchMode()
    counts = _to_counts(kana)
    device.lockForConfiguration_(None)
    for s in counts:
        if int(s) != 0:
            device.setTorchMode_(1)
            time.sleep(int(s) * span)
        device.setTorchMode_(0)
        time.sleep(span)
    device.unlockForConfiguration()
Example #12
0
def class_objects(cla='', alloc=True):
    functions = []
    initializers = []
    py_methods = []
    try:
        c = ObjCClass(cla)
    except ValueError:
        dialogs.alert(cla + ' is not a known class')
    try:
        initializers = dir(c)
    except:
        return None
    if alloc:
        num_methods = c_uint(0)
        method_list_ptr = class_copyMethodList(c.ptr, byref(num_methods))
        for i in range(num_methods.value):
            selector = method_getName(method_list_ptr[i])
            sel_name = sel_getName(selector)
            if not isinstance(sel_name, str):
                sel_name = sel_name.decode('ascii')
            py_method_name = sel_name.replace(':', "_")
            if '.' not in py_method_name:
                py_methods.append(py_method_name)
        free(method_list_ptr)
    if not alloc:
        py_methods = []
        functions = []
    functions = [x for x in py_methods if x not in initializers]
    return {
        'Initializers': initializers,
        'Methods': functions,
        'PyMethods': py_methods
    }
Example #13
0
def swizzle(cls_name, selector_name, fn):
    cls = ObjCClass(cls_name).ptr

    new_selector_name = SWIZZLED_SELECTOR_PREFIX + selector_name
    new_selector = sel(new_selector_name)

    if c.class_getInstanceMethod(cls, new_selector):
        error('Skipping swizzling, already responds to {} selector'.format(
            new_selector_name))
        return

    selector = sel(selector_name)
    method = c.class_getInstanceMethod(cls, selector)
    if not method:
        error('Failed to get {} instance method'.format(selector_name))
        return

    type_encoding = c.method_getTypeEncoding(method)
    parsed_types = parse_types(type_encoding)
    restype = parsed_types[0]
    argtypes = parsed_types[1]

    IMPTYPE = CFUNCTYPE(restype, *argtypes)
    imp = IMPTYPE(fn)
    retain_global(imp)

    did_add = c.class_addMethod(cls, new_selector, imp, type_encoding)

    if not did_add:
        error('Failed to add {} method'.format(new_selector_name))
        return

    new_method = c.class_getInstanceMethod(cls, new_selector)
    method_exchangeImplementations(method, new_method)
Example #14
0
def add_method(cls_name, selector_name, fn, type_encoding):
    cls = ObjCClass(cls_name).ptr

    selector = sel(selector_name)

    if c.class_getInstanceMethod(cls, selector):
        error(
            'Failed to add method, class {} already provides method {}'.format(
                cls_name, selector_name))
        return

    parsed_types = parse_types(type_encoding)
    restype = parsed_types[0]
    argtypes = parsed_types[1]

    IMPTYPE = CFUNCTYPE(restype, *argtypes)
    imp = IMPTYPE(fn)
    retain_global(imp)

    did_add = c.class_addMethod(cls, selector, imp,
                                c_char_p(type_encoding.encode('utf-8')))
    if not did_add:
        error('Failed to add class method')

    return did_add
def _make_webview_transparent(webview):
    #
    # Any UI manipulation in ObjC must be done on the main thread, thus there's
    # @on_main_thread decorator to ensure that this function is always called
    # on the main thread.
    #
    # Pythonista usually wraps ObjC views / controls / ... in own
    # view. ui.WebView is not real UIWebView, it's kind of wrapper.
    # So we have to get ObjC instance of the wrapper view, traverse
    # subviews and check classes to find real UIWebView (ObjC).
    #
    # Actually ui.WebView (Python) consists of:
    #
    # SUIWebView_PY3 (ObjC)
    #    | UIWebView (ObjC)
    #    |     | _UIWebViewScrollView (ObjC)
    #    |     |     | UIWebBrowserView (ObjC)
    # ...
    #
    pythonista_wrapper_objc = ObjCInstance(webview)
    real_webview_objc = _find_real_webview(pythonista_wrapper_objc)
    if real_webview_objc:
        # UIWebView found

        # Make it transparent
        # https://developer.apple.com/documentation/uikit/uiview/1622622-opaque?language=objc
        real_webview_objc.setOpaque_(False)

        # Set background color to clear color
        # https://developer.apple.com/documentation/uikit/uicolor/1621945-clearcolor?language=objc
        clear_color = ObjCClass('UIColor').clearColor()
        real_webview_objc.setBackgroundColor_(clear_color)
Example #16
0
 def __init__(self, cla=''):
     self.obs = class_objects(cla)
     try:
         self.supercls = ObjCInstance(ObjCClass(cla).superclass())
     except AttributeError:
         self.supercls = None
     self.obs = [['Superclass', [str(self.supercls)]]] + self.obs
     pass
Example #17
0
def get_pressure():
    def handler(_cmd, _data, _error):
        global pressure
        pressure = ObjCInstance(_data).pressure()

    handler_block = ObjCBlock(handler,
                              restype=None,
                              argtypes=[c_void_p, c_void_p, c_void_p])

    CMAltimeter = ObjCClass('CMAltimeter')
    NSOperationQueue = ObjCClass('NSOperationQueue')
    if not CMAltimeter.isRelativeAltitudeAvailable():
        print('This device has no barometer.')
        return
    altimeter = CMAltimeter.new()
    main_q = NSOperationQueue.mainQueue()
    altimeter.startRelativeAltitudeUpdatesToQueue_withHandler_(
        main_q, handler_block)
    #print('Started altitude updates.')
    try:
        while pressure is None:
            pass
    finally:
        altimeter.stopRelativeAltitudeUpdates()
        #print('Updates stopped.')
        return pressure
Example #18
0
def get_pressure():
    ''' Obter a pressão atmosférica do barómetro do próprio dispositivo, se
    existir '''
    def handler(_cmd, _data, _error):
        global pressure
        pressure = ObjCInstance(_data).pressure()

    handler_block = ObjCBlock(handler,
                              restype=None,
                              argtypes=[c_void_p, c_void_p, c_void_p])

    CMAltimeter = ObjCClass('CMAltimeter')
    NSOperationQueue = ObjCClass('NSOperationQueue')
    if not CMAltimeter.isRelativeAltitudeAvailable():
        # print('This device has no barometer.')
        return None
    altimeter = CMAltimeter.new()
    main_q = NSOperationQueue.mainQueue()
    altimeter.startRelativeAltitudeUpdatesToQueue_withHandler_(
        main_q, handler_block)

    try:
        while pressure is None:
            pass
    finally:
        altimeter.stopRelativeAltitudeUpdates()
        return pressure.floatValue() * 7.5006375541921
Example #19
0
class NotificationController:
    def __init__(self, l_mpc):
        self._mpc = l_mpc
        self._ndc = ObjCClass('NSNotificationCenter').defaultCenter()

        def willResignActive(_self, _cmd):
            pass

        def didBecomeActive(_self, _cmd):
            pass

        def playbackStateDidChange(_self, _cmd):
            self._mpc.updatePlaybackState()

        def nowPlayingItemDidChange(_self, _cmd):
            self._mpc.setNowPlayingSongArtwork()

        self._method_table = {
            'UIApplicationWillResignActiveNotification':
            willResignActive,
            'UIApplicationDidBecomeActiveNotification':
            didBecomeActive,
            'MPMusicPlayerControllerPlaybackStateDidChangeNotification':
            playbackStateDidChange,
            'MPMusicPlayerControllerNowPlayingItemDidChangeNotification':
            nowPlayingItemDidChange,
        }
        self._mp4p_nc = create_objc_class(
            'NSMP4PNotificationController',
            methods=self._method_table.values()).new()

    def __del__(self):
        del self._mp4p_nc
        del self._method_table
        del self._ndc

    def registerAllObservers(self):
        for k, v in self._method_table.items():
            self._ndc.addObserver_selector_name_object_(
                self._mp4p_nc, sel(v.__name__), k, None)

    def removeAllObservers(self):
        for k in self._method_table.keys():
            self._ndc.removeObserver_name_object_(self._mp4p_nc, k, None)
Example #20
0
def get_device_info():
    device = ObjCClass('UIDevice').currentDevice()
    main_screen = ObjCClass('UIScreen').mainScreen()
    native_size = main_screen.nativeBounds().size

    return 'iOS {}, model {}, resolution (portrait) {} x {} @ {}'.format(
        device.systemVersion(), platform.machine(), native_size.width,
        native_size.height, main_screen.nativeScale())
Example #21
0
def __get_album_dates(album):
    PHAsset = ObjCClass("PHAsset")
    NSSortDescriptor = ObjCClass("NSSortDescriptor")
    PHFetchOptions = ObjCClass("PHFetchOptions")
    fetchOptions = PHFetchOptions.alloc().init().autorelease()
    fetchOptions.sortDescriptors = [
        NSSortDescriptor.sortDescriptorWithKey_ascending_(
            "creationDate", True)
    ]
    result = PHAsset.fetchAssetsInAssetCollection_options_(album, fetchOptions)
    if result.count() != 0:
        start_date = result.firstObject().creationDate()
        end_date = result.lastObject().creationDate()
        return (start_date, end_date)
    else:
        return (None, None)
Example #22
0
	def create_accessory_toolbar(self):
		from objc_util import ObjCClass, ObjCInstance, sel
		
		def create_button(label, func):
			button_width = 25
			black = ObjCClass('UIColor').alloc().initWithWhite_alpha_(0.0, 1.0)
			action_button = ui.Button()
			action_button.action = func
			accessory_button = ObjCClass('UIBarButtonItem').alloc().initWithTitle_style_target_action_(label, 0, action_button, sel('invokeAction:'))
			accessory_button.width = button_width
			accessory_button.tintColor = black
			return (action_button, accessory_button)
		
		vobj = ObjCInstance(self.markup)

		keyboardToolbar = ObjCClass('UIToolbar').alloc().init()
		
		keyboardToolbar.sizeToFit()
		
		button_width = 25
		black = ObjCClass('UIColor').alloc().initWithWhite_alpha_(0.0, 1.0)
		
		# Create the buttons
		# Need to retain references to the buttons used
		# to handle clicks
		(self.indentButton, indentBarButton) = create_button('\u21E5', self.indent)
		
		(self.outdentButton, outdentBarButton) = create_button('\u21E4', self.outdent)
		
		(self.quoteButton, quoteBarButton) = create_button('>', self.block_quote)
		
		(self.linkButton, linkBarButton) = create_button('[]', self.link)
		
		#(self.anchorButton, anchorBarButton) = create_button('<>', self.anchor)
		
		(self.hashButton, hashBarButton) = create_button('#', self.heading)
		
		(self.numberedButton, numberedBarButton) = create_button('1.', self.numbered_list)
		
		(self.listButton, listBarButton) = create_button('•', self.unordered_list)
		
		(self.underscoreButton, underscoreBarButton) = create_button('_', self.insert_underscore)
		
		(self.backtickButton, backtickBarButton) = create_button('`', self.insert_backtick)
		
		# Flex between buttons
		f = ObjCClass('UIBarButtonItem').alloc().initWithBarButtonSystemItem_target_action_(5, None, None)
		
		doneBarButton = ObjCClass('UIBarButtonItem').alloc().initWithBarButtonSystemItem_target_action_(0, vobj, sel('endEditing:')) 
		
		keyboardToolbar.items = [indentBarButton, f, outdentBarButton, f, quoteBarButton, f, linkBarButton, f, hashBarButton, f, numberedBarButton, f, listBarButton, f, underscoreBarButton, f, backtickBarButton, f, doneBarButton]
		vobj.inputAccessoryView = keyboardToolbar
Example #23
0
def main():
    num_samples = 1000000
    arrayA = []
    arrayM = []
    #arrayG = []
    arrayP = []
    arrayJ = []
    arrayGPS = []  #GPS
    dataArray = []

    CMAltimeter = ObjCClass('CMAltimeter')
    NSOperationQueue = ObjCClass('NSOperationQueue')
    if not CMAltimeter.isRelativeAltitudeAvailable():
        print('This device has no barometer.')
        return
    altimeter = CMAltimeter.new()
    main_q = NSOperationQueue.mainQueue()
    altimeter.startRelativeAltitudeUpdatesToQueue_withHandler_(
        main_q, handler_block)
    motion.start_updates()
    location.start_updates()  # GPS
    print("Logging start...")
    sleep(1.0)
    for i in range(num_samples):
        sleep(0.05)
        a = motion.get_user_acceleration()
        m = motion.get_magnetic_field()
        j = motion.get_attitude()
        gps = location.get_location()  # GPS
        if a[1] > 0.8:
            break
        dataArray.append([relativeAltitude, a[2], m[0], m[1]])
        arrayA.append(a)
        arrayM.append(m)
        arrayJ.append(j)
        arrayP.append(relativeAltitude)
        arrayGPS.append(gps)  #GPS

    motion.stop_updates()
    location.stop_updates()  # GPS
    altimeter.stopRelativeAltitudeUpdates()
    print("Logging stop and Saving start...")
    import pickle
    f = open('yokohama.serialize', 'wb')
    #pickle.dump([arrayA, arrayM, arrayP],f)
    pickle.dump([arrayA, arrayM, arrayJ, arrayP, arrayGPS], f)  #GPS
    f.close
    print("Saving is finished.")
    x_values = [x * 0.05 for x in range(len(dataArray))]
    for i, color, label in zip(range(3), 'rgb', 'XYZ'):
        plt.plot(x_values, [g[i] for g in arrayM], color, label=label, lw=2)
    plt.grid(True)
    plt.xlabel('t')
    plt.ylabel('G')
    plt.gca().set_ylim([-100, 100])
    plt.legend()
    plt.show()
Example #24
0
def _load_data_imp(_cmd, _block_ptr):
    global _dragged_item_path
    handler = runtime.ObjCBlockPointer(
        _block_ptr, argtypes=[ctypes.c_void_p, ctypes.c_bool, ctypes.c_void_p])

    if _dragged_item_path:
        NSURL = ObjCClass('NSURL')
        url = NSURL.fileURLWithPath_isDirectory_(
            ns(_dragged_item_path), os.path.isdir(_dragged_item_path))

        _dragged_item_path = None
    else:
        url = None

    if not url:
        error = NSError.errorWithDomain_code_userInfo_(
            'com.robertvojta.blackmamba', 1, None)
        handler(None, None, error)
    else:
        handler(url.ptr, False, None)
Example #25
0
def toggle_flashlight():
    AVCaptureDevice = ObjCClass('AVCaptureDevice')
    device = AVCaptureDevice.defaultDeviceWithMediaType_('vide')
    if not device.hasTorch():
        raise RuntimeError('Device has no flashlight')
    mode = device.torchMode()
    device.lockForConfiguration_(None)
    if device.torchMode() > 0:
        device.setTorchMode_((mode + 1) % 2)
    else:
        a = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4, 0.3, 0.2, 0.1]

        for each in a:

            device.setTorchModeOnWithLevel_error_(each, None)
            print('level ' + str(each))
            time.sleep(.6)

        #device.setTorchModeOnWithLevel_error_(0.88, None)

    device.unlockForConfiguration()
Example #26
0
def bundleForClass(cls):
    if type(cls) == str:
        try:
            cls = ObjCClass(cls)
        except:
            return None

    try:
        b = NSBundle.bundleForClass_(cls)
        return Bundle(b)
    except ValueError:
        return None
Example #27
0
def main():

    if not is_running_extension():
        print('This script is intended to be run from the sharing extension.')
        return

    files = get_file_paths()

    if not files:
        alert('No files were specified')
        return

    for file in files:
        filename = path.basename(file)

        if not filename.endswith('.pdf'):
            showAlert('Only PDF are allowed', filename)
            continue

        pdf = ObjCClass('PDFDocument').alloc().initWithURL(nsurl(file))

        if pdf.isEncrypted():
            pwd = input_alert('Password', filename)
            if pdf.unlockWithPassword_(pwd):
                pdf.writeToFile_(file)
            else:
                showAlert("Wrong Password", filename)
        else:
            showAlert("This PDF is not encrypted", filename)
    finish()
Example #28
0
    def get_ip(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(("8.8.8.8", 80))
            ip = s.getsockname()[0]
            s.close()
            return ip
        except:
            #offline
            try:
                from objc_util import ObjCClass
                NSHost = ObjCClass('NSHost')
                addresses = []
                for address in NSHost.currentHost().addresses():
                    address = str(address)
                    if 48 <= ord(address[0]) <= 57 and address != '127.0.0.1':
                        addresses.append(address)
                #return '   '.join(addresses)
                return addresses[-1]

            except ImportError:
                return ''
Example #29
0
def create_icons():
    Catalog = ObjCClass('CUICatalog').alloc()
    NSBundle = ObjCClass('NSBundle')
    path = nsurl(str(NSBundle.mainBundle().bundlePath()) + '/Assets.car')
    assets = Catalog.initWithURL_error_(path, None)
    all_names = assets.allImageNames()
    named = ui.Image.named
    return [named(str(i)) for i in all_names]
Example #30
0
def album(identifier, title=""):
    # Fetch the album for the specified identifier and check if it's found
    PHAssetCollection = ObjCClass("PHAssetCollection")
    result = PHAssetCollection.fetchAssetCollectionsWithLocalIdentifiers_options_(
        [identifier], None)
    album_details = dict()
    if result.count() != 0:
        if title == "":
            album_details["title"] = str(
                result.objectAtIndex_(0).localizedTitle())
        else:
            album_details["title"] = title
        album_details["type"] = __localized_type_description(
            result.objectAtIndex_(0).assetCollectionSubtype())
        album_details["number_of_photos"] = int(
            __get_asset_count(result.objectAtIndex_(0), MEDIA_TYPE_IMAGE))
        album_details["number_of_videos"] = int(
            __get_asset_count(result.objectAtIndex_(0), MEDIA_TYPE_VIDEO))
        start_date, end_date = __get_album_dates(result.objectAtIndex_(0))
        album_details["start_date"] = start_date
        album_details["end_date"] = end_date
        return album_details
    else:
        return None
Example #31
0
    def did_load(self):
        self._tableview = self['tableview']
        self._textfield = self['textfield']
        self._help_label = self['helplabel']
        self._title_label = self['titlelabel']

        self._tableview.allows_selection = True
        self._tableview.allows_multiple_selection = False
        self._textfield.delegate = self

        UITextField = ObjCClass('UITextField')
        tf = ObjCInstance(self._textfield._objc_ptr)
        for sv in tf.subviews():
            if sv.isKindOfClass_(UITextField):
                sv.becomeFirstResponder()
Example #32
0
    def __init__(self, *args, **kwargs):
        # todo: おまじないになっとる
        super().__init__(self, *args, **kwargs)
        self.bg_color = 'red'
        self.selfIns = ObjCInstance(self)

        initFrame = CGRect(CGPoint(0, 0), CGSize(self.width, self.height))
        # fullViewSize
        flex_w, flex_h = (1 << 1), (1 << 4)

        uiTextView = ObjCClass('UITextView').alloc()
        self.uiTV = uiTextView
        self.uiTV.initWithFrame_(initFrame)
        self.uiTV.setAutoresizingMask_(flex_w | flex_h)
        self.uiTV.returnKeyType = 10
        self.selfIns.addSubview_(self.uiTV)
Example #33
0
    def setup_begin(self):
        '''game on, prep cancel and pause buttons'''
        self.pause_button.enabled = True
        self.pause_button.hidden = False

        self.cancel_button.enabled = True
        self.cancel_button.hidden = False

        self.begin_button.enabled = False
        self.begin_button.hidden = True

        self.pb.width = 0
        self.cancel_pressed = False

        # Disable screen sleeping.
        ObjCClass('UIApplication').sharedApplication().idleTimerDisabled = True
Example #34
0
def get_synthesizer_and_voice(
        language: str = "ja-JP") -> Tuple[ObjCInstance, ObjCInstance]:
    assert isinstance(language, str), (type(language), language)
    AVSpeechSynthesizer = ObjCClass("AVSpeechSynthesizer")
    AVSpeechSynthesisVoice = ObjCClass("AVSpeechSynthesisVoice")
    synthesizer = AVSpeechSynthesizer.new()
    for voice in AVSpeechSynthesisVoice.speechVoices():
        # print(voice, voice.description())
        if language in str(voice.description()):
            return synthesizer, voice
    raise ValueError(f"No voice found for {language}")
Example #35
0
 def get_frameworks():
     flist = []
     frameworks = {}
     frameworks['No Framework'] = {'bundle': None, 'items': []}
     for i in ObjCClass.get_names():
         if bundles.bundleForClass(i):
             try:
                 if frameworks[bundles.bundleForClass(i).bundleID]:
                     frameworks[bundles.bundleForClass(i).bundleID]['items'] += [i]
                 else:
                     frameworks[bundles.bundleForClass(i).bundleID] = {'bundle': bundles.bundleForClass(i), 'items': [i]}
             except KeyError:
                 frameworks[bundles.bundleForClass(i).bundleID] = {'bundle': bundles.bundleForClass(i), 'items': [i]}
         else:
             frameworks['No Framework']['items'] += [i]
     flist = sorted(frameworks.keys())
     return {'flist': flist, 'frameworks': frameworks}
Example #36
0
    def reset(self):
        '''cleanup ui, prep for action'''
        self.pause_button.enabled = False
        self.pause_button.hidden = True

        self.cancel_button.enabled = False
        self.cancel_button.hidden = True

        self.begin_button.enabled = True
        self.begin_button.hidden = False

        self.pose_name.text = 'current pose'
        self.update_progress_bar(1.0, '', DONE_COLOR)

        # Enable screen sleeping.
        ObjCClass(
            'UIApplication').sharedApplication().idleTimerDisabled = False
Example #37
0
 def get_classes():
     classes = {}
     classes['No Class'] = []
     for i in ObjCClass.get_names():
         if bundles.bundleForClass(i):
             try:
                 if classes[bundles.bundleForClass(i).bundleID]:
                     classes[bundles.bundleForClass(i).bundleID] += [i]
                 else:
                     classes[bundles.bundleForClass(i).bundleID] = [i]
             except KeyError:
                 classes[bundles.bundleForClass(i).bundleID] = [i]
         else:
             classes['No Class'] += [i]
     
             
     clist = []
     for k, v in classes.items():
         clist += [[k, v]]
     return clist
Example #38
0
        if type(value) == str:
            self._objc.setLightingModelName_(value)
        else:
            print('not a valid type')
        
def load_scene(file):
    url = ns(file)
    s = SCNScene.sceneWithURL_options_(url, ns({}))
    return Scene(s)
                
if __name__ == '__main__':
    for i in UIApplication.sharedApplication().keyWindow().rootViewController().view().gestureRecognizers():
            if b'UIPanGestureRecognizer' == i._get_objc_classname():
                slide = i
    slide.setEnabled_(False)
    SCNLookAtConstraint = ObjCClass('SCNLookAtConstraint')
    
    v = SceneTab()
    v.allowsCameraControl=True
    SCNBox = ObjCClass('SCNBox')
    SCNFloor = ObjCClass('SCNFloor')
    SCNSphere = ObjCClass('SCNSphere')
    v.debugOptions = DebugOptions.showLightInfluences| DebugOptions.showLightExtents
    v.showsStatistics=True
    v.scene = Scene()
    floor = SCNFloor.floor()
    cnode = Node()
    c = Camera()
    cnode.camera = c
    v.scene.node.addChild(cnode)
    n=Node()
Example #39
0
from objc_util import ObjCClass

NSFileManager = ObjCClass('NSFileManager')
manager = NSFileManager.defaultManager()
Example #40
0
from objc_util import ObjCClass, NSBundle

#__all__ = ['battery','backlight_level','set_backlight_level']
UIDevice = ObjCClass('UIDevice')
device = UIDevice.currentDevice()
battery_states = {1: 'unplugged', 2: 'charging', 3: 'full'}

class battery(object):

    def __init__(self):
        device.setBatteryMonitoringEnabled(True)
        
    def __enter__(self):
        device.setBatteryMonitoringEnabled(True)
        return self
    
    def charge_status(self):
        return battery_states[device.batteryState()]
    
    def level(self):
        return device.batteryLevel()

    def __exit__(self, exc_type, exc_value, traceback):
        device.setBatteryMonitoringEnabled(False)

def backlight_level():
    return device._backlightLevel()

def set_backlight_level(value):
    if type(value) == float:
        if 0<= value <= 1:
Example #41
0
from objc_util import ObjCClass
UIDevice = ObjCClass('UIDevice')
NSProcessInfo = ObjCClass('NSProcessInfo')
device = UIDevice.currentDevice()
process = NSProcessInfo.processInfo()
_fsizes = {'B': 1.0, 'KB': 1024.0, 'MB':  float(pow(1024,2)), 'GB': float(pow(1024,3))}


class Process (object):
    def __init__(self):
        self._objc = NSProcessInfo.processInfo()
        self._fsizes = {'B': 1.0, 'KB': 1024.0, 'MB':  float(pow(1024,2)), 'GB': float(pow(1024,3))}
    @property
    def lowPowerModeStatus(self):
        return self._objc.isLowPowerModeEnabled()
        
    @property
    def hostName(self):
        return str(self._objc.hostName())
        
    @property
    def osVersion(self):
        major = self._objc.operatingSystemVersion().a
        minor = self._objc.operatingSystemVersion().b
        patch = self._objc.operatingSystemVersion().c
        return (major, minor, patch)
    
    @property
    def osVersionString(self):
        return str(self._objc.operatingSystemVersionString())
    
Example #42
0
from objc_util import ObjCClass, nsurl, ObjCInstance, uiimage_to_png, UIImage
from datetime import datetime
from io import BytesIO
from PIL import Image
from objc_tools.objc_json import objc_to_py
from objc_tools.backports.enum_backport import IntEnum
import warnings

warnings.warn("This API was broken in iOS 10 and greater", FutureWarning)

LSApplicationWorkspace = ObjCClass('LSApplicationWorkspace')
workspace = LSApplicationWorkspace.defaultWorkspace()
LSApplicationProxy = ObjCClass('LSApplicationProxy')

_timediff = 978307200

class AppType (IntEnum):
    '''Used to bridge with the numerical version'''
    system = 1
    user = 0
    
class App (object):
    def __init__(self, app):
        try:
            app.applicationIdentifier()
        except AttributeError:
            raise AttributeError('{0} is not an app ObjC Class'.format(app))
        bg = []
        self.objc = app
        if len(self.objc.appTags()):
            for i in app.appTags():