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
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
def __get_albums(type, subtype): # Helper function: constructs dictionary with user / smart albums # Sort albums in ascending order, based on their localized title PHAssetCollection = ObjCClass("PHAssetCollection") NSSortDescriptor = ObjCClass("NSSortDescriptor") PHFetchOptions = ObjCClass("PHFetchOptions") fetchOptions = PHFetchOptions.alloc().init().autorelease() fetchOptions.sortDescriptors = [ NSSortDescriptor.sortDescriptorWithKey_ascending_( "localizedTitle", True) ] # Fetch the albums with the specified type and return a list of their unique identifiers result = PHAssetCollection.fetchAssetCollectionsWithType_subtype_options_( type, subtype, fetchOptions) albums = dict() for index in range(result.count()): # Get each PHAssetCollection object and save (key,value) = (title,identifier) collection = result.objectAtIndex_(index) if type == __SMART_ALBUM: albums[__localized_smart_album_title( collection.assetCollectionSubtype())] = str( collection.localIdentifier()) else: albums[str(collection.localizedTitle())] = str( collection.localIdentifier()) # Return the dictionary with titles and identifiers return albums
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]
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())
def superclass(self, alloc=False): if 'superclass' in self.initializers: if ObjCClass(self.name).superclass(): return ObjCClassInfo( ObjCInstance(ObjCClass(self.name).superclass()), alloc) else: return None else: return None
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()
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)
def __get_asset_count(album, media_type): PHAsset = ObjCClass("PHAsset") NSPredicate = ObjCClass("NSPredicate") PHFetchOptions = ObjCClass("PHFetchOptions") fetchOptions = PHFetchOptions.alloc().init().autorelease() fetchOptions.predicate = NSPredicate.predicateWithFormat_("mediaType==" + str(media_type)) assets = PHAsset.fetchAssetsInAssetCollection_options_(album, fetchOptions) return assets.count()
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}")
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
def _setupEngine(self): AVAudioEngine = ObjCClass('AVAudioEngine') AVAudioSession = ObjCClass('AVAudioSession') error = ctypes.c_void_p(0) session = AVAudioSession.sharedInstance() category = session.setCategory('AVAudioSessionCategoryPlayback', error=ctypes.pointer(error)) if error: raise Exception('error setting up category') session.setActive(True, error=ctypes.pointer(error)) if error: raise Exception('error setting up session active') engine = AVAudioEngine.new() return engine
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)
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)
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)
def get_font_list(): # from someone on the forum, i think @omz UIFont = ObjCClass('UIFont') lst = [str(font) for family in UIFont.familyNames() for font in UIFont.fontNamesForFamilyName_(family)] lst.sort() return lst
def main(): 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 True: pass finally: altimeter.stopRelativeAltitudeUpdates() print('Updates stopped.')
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 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 }
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 pickerView_viewForRow_forComponent_reusingView_(self, cmd, picker_view, row, component, view_ptr): idx = row % len(assets) if (idx, component) in view_of_row: # add V0.1 #print('reuse',component,row,idx) # test # add V0.1 view = view_of_row[(idx, component)] # reuse view # add V0.1 view.setHidden_(False) # not sure needed # add V0.1 return view.ptr # add V0.1 UIPickerView = ObjCInstance(picker_view) if view_ptr == None: #print(row, component) view = ObjCClass('UILabel').alloc().init() #view.text = str(row)+','+str(component) # test only # add V0.1 iv = ui.ImageView() iv.frame = (0, 0, UIPickerView.myRowWidth, UIPickerView.myRowHeight) iv.content_mode = ui.CONTENT_SCALE_ASPECT_FIT if type(assets) is str: iv.image = emoji_to_image(assets[idx], w=iv.width, h=iv.height) else: iv.image = assets[idx].get_ui_image(size=(iv.width, iv.height)) view.addSubview_(ObjCInstance(iv)) view_of_row[(idx, component)] = view # add V0.1 else: view = ObjCInstance(view_ptr) return view.ptr
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()
def __init__(self, ui_file_path): NSBundle.bundleWithPath_( '/System/Library/Frameworks/MediaPlayer.framework').load() self._player = ObjCClass('MPMusicPlayerController').systemMusicPlayer() self._nc = NotificationController(self) self._uic = UIController(self, ui_file_path) self._npc = NowPlayingController() self.thumb_size = 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
def run_script(sender): import os #sender.superview.close() app,arg = sender.name.split(('|')) dir = os.path.expanduser('~/Documents/'+app) I3=ObjCClass('PYK3Interpreter').sharedInterpreter() # run a script like in wrench menu (path, args, reset env yesy/no) I3.runScriptAtPath_argv_resetEnvironment_(dir, [arg], True)
def get_font_list(): # from someone on the forum, i think @omz UIFont = ObjCClass('UIFont') return list( itertools.chain(*[ UIFont.fontNamesForFamilyName_(str(x)) for x in UIFont.familyNames() ]))
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) device.setTorchMode_((mode + 1) % 2) device.unlockForConfiguration()
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 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
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 ''