def open_url(url): if url.startswith("file:"): raise Exception("Opening file urls is not supported: " + url) try: NSURL = autoclass('NSURL') UIApplication = autoclass("UIApplication") nsurl = NSURL.URLWithString_(objc_str(url)) UIApplication.sharedApplication().openURL_(nsurl) except: import traceback traceback.print_exc() raise
class PyobjusGame(Widget): ball = ObjectProperty(None) screen = ObjectProperty(autoclass('UIScreen').mainScreen()) bridge = ObjectProperty(autoclass('bridge').alloc().init()) sensitivity = ObjectProperty(50) br_slider = ObjectProperty(None) def __init__(self, *args, **kwargs): super(PyobjusGame, self).__init__() self.bridge.startAccelerometer() def __dealloc__(self, *args, **kwargs): self.bridge.stopAccelerometer() super(PyobjusGame, self).__dealloc__() def reset_ball_pos(self): self.ball.pos = self.width / 2, self.height / 2 def on_bright_slider_change(self): self.screen.brightness = self.br_slider.value def update(self, dt): self.ball.move() self.ball.velocity_x = self.bridge.ac_x * self.sensitivity self.ball.velocity_y = self.bridge.ac_y * self.sensitivity if (self.ball.y < 0) or (self.ball.top >= self.height): self.reset_ball_pos() self.ball.h = random() if (self.ball.x < 0) or (self.ball.right >= self.width): self.reset_ball_pos() self.ball.h = random()
def setUp(self): global NSURL, NSURLConnection, NSURLRequest load_framework(INCLUDE.AppKit) load_framework(INCLUDE.Foundation) NSURL = autoclass('NSURL') NSURLConnection = autoclass('NSURLConnection') NSURLRequest = autoclass('NSURLRequest')
def __init__(self, **kwargs): super(JumpyKittenPage, self).__init__(**kwargs) self.g_grav = -0.5 #pizel * frame_rate^2 self.obstacles = [] self.coins = [] self.mcnay = Mcnay() self.add_widget(self.mcnay) self.bind(size=self.size_callback) # for bkg sizing if platform == 'ios': print('requesting banner') from pyobjus import autoclass self.banner_ad = autoclass('adSwitchBanner').alloc().init() self.banner_ad.show_ads() self.interstitial_ad = autoclass( 'adSwitchInterstitial').alloc().init() if platform == 'android': # self.ads = KivMob(TestIds.APP) # self.ads.new_banner(TestIds.BANNER) # self.ads.new_interstitial(TestIds.INTERSTITIAL) self.ads = KivMob('ca-app-pub-8564280870740386~8534172049') self.ads.new_banner('ca-app-pub-8564280870740386/2464625123') self.ads.new_interstitial('ca-app-pub-8564280870740386/8985921895') if platform == 'ios': self.user_data_dir = App.get_running_app().user_data_dir else: self.user_data_dir = 'data' filename_scale = join(self.user_data_dir, 'fontScaling.pickle') self.font_scale = pickle.load(open(filename_scale, 'rb'))[0] self.reset()
def create(self): self.callback = None self.peripherals = {} load_framework(INCLUDE.IOBluetooth) CBCentralManager = autoclass('CBCentralManager') self.central = CBCentralManager.alloc().initWithDelegate_queue_( self, None)
def test_objc_arr_behaviour(input_array): NSArray = lambda: autoclass('NSArray') a1 = NSArray().arrayWithObjects_(*input_array + [None]) a2 = objc_arr(*input_array) arr1 = [a1.objectAtIndex_(i).intValue() for i in range(a1.count())] arr2 = [a2.objectAtIndex_(i).intValue() for i in range(a2.count())] assert arr1 == arr2
def account_for_iphone_notch(self): # Account for the notch in newer iPhones from pyobjus import autoclass notch_detector = autoclass("NotchDetector").alloc().init() notch_exists = notch_detector.hasTopNotch() if notch_exists: self.notch_height = dp(30)
def text_capitalizedStringWithLocale(self): NSLocale = autoclass("NSLocale") locale = NSLocale.currentLocale() text = N("some text") self.assertEqual( text.capitalizedStringWithLocale_(locale).UTF8String(), "Some Text")
def detect_user_locale(): import locale if renpy.windows: import ctypes windll = ctypes.windll.kernel32 locale_name = locale.windows_locale.get(windll.GetUserDefaultUILanguage()) elif renpy.android: from jnius import autoclass Locale = autoclass('java.util.Locale') locale_name = str(Locale.getDefault().getLanguage()) elif renpy.ios: import pyobjus NSLocale = pyobjus.autoclass("NSLocale") languages = NSLocale.preferredLanguages() locale_name = languages.objectAtIndex_(0).UTF8String().decode("utf-8") locale_name.replace("-", "_") else: locale_name = locale.getdefaultlocale() if locale_name is not None: locale_name = locale_name[0] if locale_name is None: return None, None normalize = locale.normalize(locale_name) if normalize == locale_name: language = region = locale_name else: locale_name = normalize if '.' in locale_name: locale_name, _ = locale_name.split('.', 1) language, region = locale_name.lower().split("_") return language, region
def create_webview(self, *args): from pyobjus import autoclass, objc_str ObjcClass = autoclass('ObjcClassINSD') self.o_instance = ObjcClass.alloc().init() self.o_instance.aParam1 = objc_str(self._url) self.o_instance.openWebView() self._localserve.dispatch('on_webview')
def centralManager_didConnectPeripheral_(self, central, peripheral): if not peripheral.name.UTF8String(): return peripheral.delegate = self CBUUID = autoclass('CBUUID') service = CBUUID.UUIDWithString_('1901') peripheral.discoverServices_([service])
def detect_user_locale(): import locale if renpy.windows: import ctypes windll = ctypes.windll.kernel32 locale_name = locale.windows_locale.get( windll.GetUserDefaultUILanguage()) elif renpy.android: from jnius import autoclass Locale = autoclass('java.util.Locale') locale_name = str(Locale.getDefault().getLanguage()) elif renpy.ios: import pyobjus NSLocale = pyobjus.autoclass("NSLocale") languages = NSLocale.preferredLanguages() locale_name = languages.objectAtIndex_(0).UTF8String().decode("utf-8") locale_name.replace("-", "_") else: locale_name = locale.getdefaultlocale() if locale_name is not None: locale_name = locale_name[0] if locale_name is None: return None, None normalize = locale.normalize(locale_name) if normalize == locale_name: language = region = locale_name else: locale_name = normalize if '.' in locale_name: locale_name, _ = locale_name.split('.', 1) language, region = locale_name.lower().split("_") return language, region
def __init__(self): super(IosGyroscope, self).__init__() self.bridge = autoclass('bridge').alloc().init() if int(device.systemVersion.UTF8String().split('.')[0]) <= 4: self.bridge.motionManager.setGyroscopeUpdateInterval_(0.1) else: self.bridge.motionManager.setGyroUpdateInterval_(0.1)
def load_framework(framework): ''' Function for loading frameworks Args: framework: Framework to load Raises: ObjcException if it can't load framework ''' NSBundle = autoclass('NSBundle') ns_framework = autoclass('NSString').stringWithUTF8String_(framework) bundle = NSBundle.bundleWithPath_(ns_framework) try: if bundle.load(): dprint("Framework {0} succesufully loaded!".format(framework)) except: raise ObjcException('Error while loading {0} framework'.format(framework))
def download_file(self, url): """ Download the specified file in place it in the destination. """ NSURL = autoclass('NSURL') oc_url = NSURL.URLWithString_(objc_str(url)) # Tasks are intialised in a paused state self.task = self.session.downloadTaskWithURL_(oc_url) self.task.resume()
def run(): Bridge = autoclass('bridge') br = Bridge.alloc().init() br.motionManager.setAccelerometerUpdateInterval_(0.1) br.startAccelerometer() for i in range(10000): print 'x: {0} y: {1} z: {2}'.format(br.ac_x, br.ac_y, br.ac_z)
def _get_picker(self): """ Return an instantiated and configured UIImagePickerController. """ picker = autoclass("UIImagePickerController") po = picker.alloc().init() po.sourceType = 0 po.delegate = self return po
def __init__(self): super(BackgroundTransfer, self).__init__() load_framework(INCLUDE.Foundation) # Load the configuration required for background sessions ns_config = autoclass('NSURLSessionConfiguration') self.config = ns_config.backgroundSessionConfigurationWithIdentifier_( self.identifier) # Load the session using the config and this class as the delegate session = autoclass('NSURLSession') self.session = session.sessionWithConfiguration_delegate_delegateQueue_( self.config, self, None) self.task = None # Note the policy restriction on HTTP as mentioned in the doc string # Use HTTPS to make you life easier :-) self.download_file('http://kivy.org/logos/kivy-logo-black-256.png')
def load_framework(framework): ''' Function for loading frameworks Args: framework: Framework to load Raises: ObjcException if it can't load framework ''' NSBundle = autoclass('NSBundle') ns_framework = autoclass('NSString').stringWithUTF8String_(framework) bundle = NSBundle.bundleWithPath_(ns_framework) try: if bundle.load(): dprint("Framework {0} succesufully loaded!".format(framework)) except: raise ObjcException( 'Error while loading {0} framework'.format(framework))
def setUp(self): # LOADING USER DEFINED CLASS (dylib) FROM /objc_usr_classes/ DIR # root_pyobjus = os.path.abspath("../") usrlib_dir = root_pyobjus + '/objc_usr_classes/usrlib.dylib' ctypes.CDLL(usrlib_dir) # -------------------------------------------------------------- # global Car, car Car = autoclass('Car') car = Car.alloc().init()
def _open(self): """ Launch the native iOS file browser. Upon selection, the `imagePickerController_didFinishPickingMediaWithInfo_` delegate is called where we close the file browser and handle the result. """ picker = self._get_picker() UIApplication = autoclass('UIApplication') vc = UIApplication.sharedApplication().keyWindow.rootViewController() vc.presentViewController_animated_completion_(picker, True, None)
def __init__(self, **kwargs): super(IOSKeyboard, self).__init__() self.kheight = 0 NSNotificationCenter = autoclass("NSNotificationCenter") center = NSNotificationCenter.defaultCenter() center.addObserver_selector_name_object_( self, selector("keyboardWillShow"), "UIKeyboardWillShowNotification", None) center.addObserver_selector_name_object_( self, selector("keyboardDidHide"), "UIKeyboardDidHideNotification", None)
def test_basic_properties(self): car.propInt = 12345 self.assertEqual(car.propInt, 12345) car.propDouble = 3456.2345 self.assertEqual(car.propDouble, 3456.2345) # car.prop_double_ptr = 333.444 # self.assertEqual(dereference(car.prop_double_ptr), 333.444) car.propNSString = autoclass('NSString').stringWithUTF8String_('string for test') self.assertEqual(car.propNSString.UTF8String(), 'string for test')
def test_carray_class(self): NSNumber = autoclass("NSNumber") nsnumber_class = NSNumber.oclass() nsnumber_class_array = [nsnumber_class for i in xrange(0, 10)] _instance.setClassValues_(nsnumber_class_array) returned_classes = dereference(_instance.getClassValues(), of_type=CArray, return_count=10) returned_classes_WithCount = dereference(_instance.getClassValuesWithCount_(CArrayCount), of_type=CArray) flag = True for i in xrange(len(returned_classes_WithCount)): if NSNumber.isKindOfClass_(returned_classes_WithCount[i]) == False: flag = False self.assertEquals(flag, True)
def create_webview(self, *args): from jnius import autoclass #VLayoutParams = autoclass('android.view.ViewGroup$LayoutParams') LLayoutParams = autoclass('android.widget.LinearLayout$LayoutParams') #RLayoutParams = autoclass('android.widget.RelativeLayout$LayoutParams') WebView = autoclass('android.webkit.WebView') WebViewClient = autoclass('android.webkit.WebViewClient') activity = autoclass('org.renpy.android.PythonActivity').mActivity webview = WebView(activity) webview.getSettings().setJavaScriptEnabled(True) wvc = WebViewClient() webview.setWebViewClient(wvc) linear = LLayoutParams(-2, -2) linear.setMargins(100, 100, 100, 100) #relative = RLayoutParams(-2, -2) #relative.addRule(14, 1) #relative.addRule(15, 1) activity.addContentView(webview, linear) webview.loadUrl(self._url) self._webview = webview Logger.info('reschedule send on_webview') Clock.schedule_once(self.sendWebViewEvent, 1)
def test_basic_properties(self): car.propInt = 12345 self.assertEqual(car.propInt, 12345) car.propDouble = 3456.2345 self.assertEqual(car.propDouble, 3456.2345) # car.prop_double_ptr = 333.444 # self.assertEqual(dereference(car.prop_double_ptr), 333.444) car.propNSString = autoclass('NSString').stringWithUTF8String_( 'string for test') self.assertEqual(car.propNSString.UTF8String(), 'string for test')
def create_webview(self, *args): from jnius import autoclass #VLayoutParams = autoclass('android.view.ViewGroup$LayoutParams') LLayoutParams = autoclass( 'android.widget.LinearLayout$LayoutParams') #RLayoutParams = autoclass('android.widget.RelativeLayout$LayoutParams') WebView = autoclass('android.webkit.WebView') WebViewClient = autoclass('android.webkit.WebViewClient') activity = autoclass('org.renpy.android.PythonActivity').mActivity webview = WebView(activity) webview.getSettings().setJavaScriptEnabled(True) wvc = WebViewClient() webview.setWebViewClient(wvc) linear = LLayoutParams(-2, -2) linear.setMargins(100, 100, 100, 100) #relative = RLayoutParams(-2, -2) #relative.addRule(14, 1) #relative.addRule(15, 1) activity.addContentView(webview, linear) webview.loadUrl(self._url) self._webview = webview Logger.info('reschedule send on_webview') Clock.schedule_once(self.sendWebViewEvent, 1)
def build(self): # Specific to iOS Bridge = autoclass('bridge') self.br = Bridge.alloc().init() self.br.startGyroscope() # ip found using socket.gethostbyname(socket.gethostname()) on the server (your computer) g = GridLayout(cols=1) b = Button(on_release=self.go) self.l = Label() self.host = TextInput(text='192.168.0.6') g.add_widget(b) g.add_widget(self.host) g.add_widget(self.l) return g
def test_carray_class(self): NSNumber = autoclass("NSNumber") nsnumber_class = NSNumber.oclass() nsnumber_class_array = [nsnumber_class for i in xrange(0, 10)] _instance.setClassValues_(nsnumber_class_array) returned_classes = dereference(_instance.getClassValues(), of_type=CArray, return_count=10) returned_classes_WithCount = dereference( _instance.getClassValuesWithCount_(CArrayCount), of_type=CArray) flag = True for i in xrange(len(returned_classes_WithCount)): if NSNumber.isKindOfClass_(returned_classes_WithCount[i]) == False: flag = False self.assertEquals(flag, True)
def imagePickerController_didFinishPickingMediaWithInfo_( self, image_picker, frozen_dict): """ Delegate which handles the result of the image selection process. """ image_picker.dismissViewControllerAnimated_completion_(True, None) # Note: We need to call this Objective C class as there is currently # no way to call a non-class function via pyobjus. And here, # we have to use the `UIImagePNGRepresentation` to get the png # representation. For this, please ensure you are using an # appropriate version of kivy-ios. native_image_picker = autoclass("NativeImagePicker").alloc().init() path = native_image_picker.writeToPNG_(frozen_dict) self._on_selection([path.UTF8String()])
def enumerate_monitors() -> T.Iterable[Monitor]: load_framework(INCLUDE.AppKit) screens = autoclass("NSScreen").screens() for i in range(screens.count()): f = screens.objectAtIndex_(i).frame if callable(f): f = f() yield Monitor( x=int(f.origin.x), y=int(f.origin.y), width=int(f.size.width), height=int(f.size.height), )
def get_monitors(): from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) screens = autoclass('NSScreen').screens() monitors = [] for i in range(screens.count()): f = screens.objectAtIndex_(i).frame if callable(f): f = f() monitors.append(Monitor(f.origin.x, f.origin.y, f.size.width, f.size.height)) return monitors
def on_start(self): self.custom_dialogs = CustomDialogs() self.custom_pickers = CustomPickers() self.custom_tap_target_views = CustomTapTargetViews(app=self) # Set up the menus for the menu screen menu_items = [{"icon": "git", "text": f"Item {i}"} for i in range(5)] self.menu_1 = MDDropdownMenu( caller=self.root.ids.MD_menu_screen.ids.button_1, items=menu_items, width_mult=4, position='center') self.menu_2 = MDDropdownMenu(caller=self.root.ids.MD_menu_screen.ids. custom_toolbar.ids.button_2, items=menu_items, width_mult=4) # Set up the swipe cards for card screen for i in range(10): self.root.ids.MD_card_swipe_screen.ids.MD_card_swipe_demo.add_widget( SwipeToDeleteItem(text=f'Item {i}')) self.root.ids.MD_expansion_panel_screen.ids.box.add_widget( MDExpansionPanel(icon=r'kivymd/images/kivymd_logo.png', content=ExpansionPanelContent(), panel_cls=MDExpansionPanelThreeLine( text="Text", secondary_text="Secondary text", tertiary_text="Tertiary text", ))) # Set up the tabs for tab screen tabs = ['Home', 'Search', 'Friends', 'History', 'Account', 'Settings'] for tab in tabs: self.root.ids.MD_tabs_screen.ids.tabs_holder.add_widget( CustomTab(text=tab)) # Update the current toolbar current_screen = self.root.ids.screen_manager.current toolbar = self.root.ids[current_screen].ids.toolbar toolbar.left_action_items = [[ 'menu', lambda x: self.root.ids.nav_drawer.set_state('toggle') ]] # If on ios, do this to display the ad banner if platform == 'ios': from pyobjus import autoclass self.banner_ad = autoclass('adSwitch').alloc().init()
def _enumerate_osx(): from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) screens = autoclass('NSScreen').screens() monitors = [] for i in range(screens.count()): f = screens.objectAtIndex_(i).frame if callable(f): f = f() monitors.append( Monitor(f.origin.x, f.origin.y, f.size.width, f.size.height)) return monitors
def _thread_handle_request(self, *largs): try: self.httpd.handle_request() self.webviewwidget.remove() self.query_params = self.httpd.query_params self.httpd.server_close() print 'request recieved' except: pass self.dispatch('on_request_served') if platform == "android": from jnius import autoclass try: Thread = autoclass('java.lang.Thread') Thread.currentThread().join() except: pass
def test_carray_object(self): NSNumber = autoclass("NSNumber") ns_number_array = list() for i in xrange(0, 10): ns_number_array.append(NSNumber.alloc().initWithInt_(i)) py_ints = [i for i in xrange(0,10)] _instance.setNSNumberValues_(ns_number_array) nsnumber_ptr_array = _instance.getNSNumberValues() returned_nsnumbers = dereference(nsnumber_ptr_array, of_type=CArray, return_count=10) returned_ints = list() for i in xrange(len(returned_nsnumbers)): returned_ints.append(returned_nsnumbers[i].intValue()) returned_nsnumbers_WithCount = dereference(_instance.getNSNumberValuesWithCount_(CArrayCount), of_type=CArray) returned_ints_WithCount = list() for i in xrange(len(returned_nsnumbers_WithCount)): returned_ints_WithCount.append(returned_nsnumbers_WithCount[i].intValue()) self.assertEquals(returned_ints, py_ints) self.assertEquals(returned_ints_WithCount, py_ints)
def enumerate_osx(): """Create a list of Monitor instances on the macOS platform.""" from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) screens = autoclass('NSScreen').screens() monitors = [] for i in range(screens.count()): f = screens.objectAtIndex_(i).frame if callable(f): f = f() monitors.append( Monitor(f.origin.x, f.origin.y, f.size.width, f.size.height)) return monitors
def test_carray_object(self): NSNumber = autoclass("NSNumber") ns_number_array = list() for i in xrange(0, 10): ns_number_array.append(NSNumber.alloc().initWithInt_(i)) py_ints = [i for i in xrange(0, 10)] _instance.setNSNumberValues_(ns_number_array) nsnumber_ptr_array = _instance.getNSNumberValues() returned_nsnumbers = dereference(nsnumber_ptr_array, of_type=CArray, return_count=10) returned_ints = list() for i in xrange(len(returned_nsnumbers)): returned_ints.append(returned_nsnumbers[i].intValue()) returned_nsnumbers_WithCount = dereference( _instance.getNSNumberValuesWithCount_(CArrayCount), of_type=CArray) returned_ints_WithCount = list() for i in xrange(len(returned_nsnumbers_WithCount)): returned_ints_WithCount.append( returned_nsnumbers_WithCount[i].intValue()) self.assertEquals(returned_ints, py_ints) self.assertEquals(returned_ints_WithCount, py_ints)
def get_resolution(): ''' Get visible frame for Windows, Mac. Should call this function after pre_run_app function called. ''' width, height = 200, 200 if PLATFORM == 'win': import ctypes user32 = ctypes.windll.user32 width = int(user32.GetSystemMetrics(0)) height = int(user32.GetSystemMetrics(1)) elif PLATFORM == 'macosx': from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.Cocoa) NSScreen = autoclass('NSScreen') mainScreen = NSScreen.mainScreen() width = int(mainScreen.visibleFrame.size.width) height = int(mainScreen.visibleFrame.size.height) return width, height
''' Mac OS X file chooser --------------------- ''' from plyer.facades import FileChooser from pyobjus import autoclass, objc_arr, objc_str from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) NSURL = autoclass('NSURL') NSOpenPanel = autoclass('NSOpenPanel') NSSavePanel = autoclass('NSSavePanel') NSOKButton = 1 class MacFileChooser(object): '''A native implementation of file chooser dialogs using Apple's API through pyobjus. Not implemented features: * filters (partial, wildcards are converted to extensions if possible. Pass the Mac-specific "use_extensions" if you can provide Mac OS X-compatible to avoid automatic conversion) * multiple (only for save dialog. Available in open dialog) * icon * preview ''' mode = "open" path = None
def path_to_saves(gamedir, save_directory=None): import renpy # @UnresolvedImport if save_directory is None: save_directory = renpy.config.save_directory save_directory = renpy.exports.fsencode(save_directory) # Makes sure the permissions are right on the save directory. def test_writable(d): try: fn = os.path.join(d, "test.txt") open(fn, "w").close() open(fn, "r").close() os.unlink(fn) return True except: return False # Android. if renpy.android: paths = [ os.path.join(os.environ["ANDROID_OLD_PUBLIC"], "game/saves"), os.path.join(os.environ["ANDROID_PRIVATE"], "saves"), os.path.join(os.environ["ANDROID_PUBLIC"], "saves"), ] for rv in paths: if os.path.isdir(rv) and test_writable(rv): break print("Saving to", rv) # We return the last path as the default. return rv if renpy.ios: from pyobjus import autoclass from pyobjus.objc_py_types import enum NSSearchPathDirectory = enum("NSSearchPathDirectory", NSDocumentDirectory=9) NSSearchPathDomainMask = enum("NSSearchPathDomainMask", NSUserDomainMask=1) NSFileManager = autoclass('NSFileManager') manager = NSFileManager.defaultManager() url = manager.URLsForDirectory_inDomains_( NSSearchPathDirectory.NSDocumentDirectory, NSSearchPathDomainMask.NSUserDomainMask, ).lastObject() # url.path seems to change type based on iOS version, for some reason. try: rv = url.path().UTF8String().decode("utf-8") except: rv = url.path.UTF8String().decode("utf-8") print("Saving to", rv) return rv # No save directory given. if not save_directory: return gamedir + "/saves" # Search the path above Ren'Py for a directory named "Ren'Py Data". # If it exists, then use that for our save directory. path = renpy.config.renpy_base while True: if os.path.isdir(path + "/Ren'Py Data"): return path + "/Ren'Py Data/" + save_directory newpath = os.path.dirname(path) if path == newpath: break path = newpath # Otherwise, put the saves in a platform-specific location. if renpy.macintosh: rv = "~/Library/RenPy/" + save_directory return os.path.expanduser(rv) elif renpy.windows: if 'APPDATA' in os.environ: return os.environ['APPDATA'] + "/RenPy/" + save_directory else: rv = "~/RenPy/" + renpy.config.save_directory return os.path.expanduser(rv) else: rv = "~/.renpy/" + save_directory return os.path.expanduser(rv)
# Note that we arent specify type of structs, so they types will be missing in method signatures # typedef struct { # float a; # int b; # NSRect rect; # } unknown_str_new; # typedef struct { # int a; # int b; # NSRect rect; # unknown_str_new u_str; # } unknown_str; Car = autoclass('Car') car = Car.alloc().init() # Let's play know. Suppose that we have defined following objective c method: # - (unknown_str) makeUnknownStr { # unknown_str str; # str.a = 10; # str.rect = NSMakeRect(20, 30, 40, 50); # str.u_str.a = 2.0; # str.u_str.b = 4; # return str; # } # Purpose of this method is to make unknown type struct, and assing some values to it's members # If you see debug logs of pyobjus, you will see that method returns following type: # {?=ii{CGRect={CGPoint=dd}{CGSize=dd}}{?=fi{CGRect={CGPoint=dd}{CGSize=dd}}}}
__all__ = ('ClipboardNSPaste', ) from kivy.core.clipboard import ClipboardBase from kivy.utils import platform if platform != 'macosx': raise SystemError('Unsupported platform for appkit clipboard.') try: from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) except ImportError: raise SystemError('Pyobjus not installed. Please run the following' ' command to install it. `pip install --user pyobjus`') NSPasteboard = autoclass('NSPasteboard') NSString = autoclass('NSString') class ClipboardNSPaste(ClipboardBase): def __init__(self): super(ClipboardNSPaste, self).__init__() self._clipboard = NSPasteboard.generalPasteboard() def get(self, mimetype='text/plain'): pb = self._clipboard data = pb.stringForType_('public.utf8-plain-text') if not data: return "" return data.UTF8String()
""" This example simplifies the code from the URL Loading System Programming Guide (http://goo.gl/JJ2Q8T). It uses NSURLConnection to request an invalid connection and get the connection:didFailWithError: delegate method triggered. """ from kivy.app import App from kivy.uix.widget import Widget from pyobjus import autoclass, protocol, objc_str from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) load_framework(INCLUDE.Foundation) NSURL = autoclass("NSURL") NSURLConnection = autoclass("NSURLConnection") NSURLRequest = autoclass("NSURLRequest") class DelegateApp(App): def build(self): self.request_connection() return Widget() def request_connection(self): # This method request connection to an invalid URL so the # connection_didFailWithError_ protocol method will be triggered. url = NSURL.URLWithString_(objc_str("abc")) request = NSURLRequest.requestWithURL_(url) # Converts the Python delegate object to Objective C delegate instance # simply by calling the objc_delegate() function. connection = NSURLConnection.connectionWithRequest_delegate_(request, self)
from plyer.facades import Wifi from pyobjus.dylib_manager import load_framework, INCLUDE from pyobjus import autoclass load_framework(INCLUDE.Foundation) load_framework(INCLUDE.CoreWLAN) CWInterface = autoclass("CWInterface") CWNetwork = autoclass("CWNetwork") CWWiFiClient = autoclass("CWWiFiClient") NSArray = autoclass("NSArray") NSDictionary = autoclass("NSDictionary") NSString = autoclass("NSString") class OSXWifi(Wifi): names = {} def _is_enabled(self): """ Returns `True` if the Wifi is enabled else returns `False`. """ return CWWiFiClient.sharedWiFiClient().interface().powerOn() def _get_network_info(self, name): """ Returns all the network information. """ def ns(x):
from pyobjus import autoclass, objc_str from pyobjus.dylib_manager import load_framework from plyer.facades import TTS load_framework('/System/Library/Frameworks/AVFoundation.framework') AVSpeechUtterance = autoclass('AVSpeechUtterance') AVSpeechSynthesizer = autoclass('AVSpeechSynthesizer') AVSpeechSynthesisVoice = autoclass('AVSpeechSynthesisVoice') class iOSTextToSpeech(TTS): def __init__(self): super(iOSTextToSpeech, self).__init__() self.synth = AVSpeechSynthesizer.alloc().init() self.voice = None def _set_locale(self, locale="en-US"): self.voice = AVSpeechSynthesisVoice.voiceWithLanguage_(objc_str(locale)) def _speak(self, **kwargs): message = kwargs.get('message') if(not self.voice): self._set_locale() utterance = \ AVSpeechUtterance.speechUtteranceWithString_(objc_str(message)) utterance.voice = self.voice self.synth.speakUtterance_(utterance)
from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE load_framework(INCLUDE.AppKit) # get both nsalert and nsstring class NSAlert = autoclass('NSAlert') NSString = autoclass('NSString') ns = lambda x: NSString.alloc().initWithUTF8String_(x) alert = NSAlert.alloc().init() alert.setMessageText_(ns('Hello world from python!')) alert.addButtonWithTitle_(NSString.stringWithUTF8String_("OK")) alert.addButtonWithTitle_(NSString.stringWithUTF8String_("Cancel")) alert.runModal()
def setUp(self): global Car, car load_dylib('testlib.dylib', usr_path=False) Car = autoclass('Car') car = Car.alloc().init()
try: from urllib.parse import quote except ImportError: from urllib import quote from plyer.facades import Email from plyer.utils import whereis_exe from pyobjus import autoclass, objc_str from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') NSURL = autoclass('NSURL') NSString = autoclass('NSString') UIApplication = autoclass('UIApplication') class iOSXEmail(Email): def _send(self, **kwargs): recipient = kwargs.get('recipient') subject = kwargs.get('subject') text = kwargs.get('text') uri = "mailto:" if recipient: uri += str(recipient) if subject: uri += "?" if not "?" in uri else "&" uri += "subject=" uri += quote(str(subject)) if text:
def setUp(self): global NSValue NSValue = autoclass("NSValue")
import ctypes from pyobjus import autoclass, selector NSObject = autoclass("NSObject") NSArray = autoclass("NSArray") NSString = autoclass('NSString') text = NSString.alloc().initWithUTF8String_("some text") text_n = NSString.alloc().initWithUTF8String_("other text") array = NSArray.arrayWithObject_(text) # equivalent to [NSString class]; objc_class = NSString.oclass() print NSString.isKindOfClass_(NSObject.oclass()) print NSString.isKindOfClass_(NSArray.oclass()) print text.isKindOfClass_(NSObject.oclass()) print text.isKindOfClass_(array.oclass()) print text.isKindOfClass_(text_n.oclass()) # equivalent to @selector(UTF8String) sel_one = selector("UTF8String") sel_two = selector("objectAtIndex:") # examples with NSString print NSString.instancesRespondToSelector_(sel_one) print text.respondsToSelector_(sel_one) print text.respondsToSelector_(sel_two) print text.respondsToSelector_(selector("init")) # examples with NSArray print array.respondsToSelector_(sel_one)
import ctypes from pyobjus import autoclass NSString = autoclass('NSString') NSArray = autoclass("NSArray") NSDictionary = autoclass("NSDictionary") string_object = NSString.stringWithUTF8String_("some text for NSDictionary") string_key = NSString.stringWithUTF8String_("someKey") array_object = NSArray.arrayWithObject_(string_object) array_key = NSArray.arrayWithObject_(string_key) # we are passing array with objects and keys dictionary = NSDictionary.dictionaryWithObjects_forKeys_(array_object, array_key) returned_nsstring = dictionary.objectForKey_(array_key.objectAtIndex_(0)) str_value = returned_nsstring.UTF8String() print str_value
''' iOS Storage Path -------------------- ''' from plyer.facades import StoragePath from pyobjus import autoclass import os NSFileManager = autoclass('NSFileManager') # Directory constants (NSSearchPathDirectory enumeration) NSApplicationDirectory = 1 NSDocumentDirectory = 9 NSDownloadsDirectory = 15 NSMoviesDirectory = 17 NSMusicDirectory = 18 NSPicturesDirectory = 19 class iOSStoragePath(StoragePath): def __init__(self): self.defaultManager = NSFileManager.defaultManager() def _get_home_dir(self): return os.path.expanduser('~/') def _get_external_storage_dir(self): return 'This feature is not implemented for this platform.'