def create(self): self.callback = None self.peripherals = {} load_framework(INCLUDE.IOBluetooth) CBCentralManager = autoclass('CBCentralManager') self.central = CBCentralManager.alloc().initWithDelegate_queue_( self, None)
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 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): try: load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclassios('UIDevice') self.UIDevice = UIDevice.alloc().init() NSSelectorFromString = autoclassios('NSSelectorFromString') self.NSString = NSSelectorFromString.alloc().init() except Exception as e: Logger.error("Orca is not supporting rotation on this IOS Version:"+str(e)) '''
def __init__(self): try: from pyobjus import autoclassios from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/UIKit.framework') UIDevice = autoclassios('UIDevice') self.UIDevice = UIDevice.alloc().init() NSSelectorFromString = autoclassios('NSSelectorFromString') self.NSString = NSSelectorFromString.alloc().init() except Exception as e: Logger.error("Orca is not supporting rotation on this IOS Version:"+str(e)) '''
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 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 _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 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 __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 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
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:
""" 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 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 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): NSString.alloc().initWithUTF8String_(x)
--------------------- ''' from uuid import UUID from os.path import dirname, join from plyer.facades import BlePeripheral from plyer.utils import iprop from pyobjus import (autoclass, protocol, CArray, objc_dict, objc_arr) from pyobjus.dylib_manager import load_framework from pyobjus.objc_py_types import enum from pyobjus.consts.corebluetooth import CBAdvertisementDataKeys load_framework('/System/Library/Frameworks/CoreBluetooth.framework') NSData = autoclass('NSData') CBPeripheralManager = autoclass('CBPeripheralManager') CBMutableService = autoclass('CBMutableService') CBMutableCharacteristic = autoclass('CBMutableCharacteristic') CBUUID = autoclass('CBUUID') CBPeripheralManagerState = enum('CBPeripheralManagerState', unknown=0, resetting=1, unsupported=2, unauthorized=3, powered_off=4, powered_on=5)
from os.path import join from pyobjus import autoclass from pyobjus.dylib_manager import INCLUDE, load_framework from plyer.facades import Audio from plyer.platforms.macosx.storagepath import OSXStoragePath load_framework(INCLUDE.Foundation) load_framework(INCLUDE.AVFoundation) AVAudioPlayer = autoclass("AVAudioPlayer") AVAudioRecorder = autoclass("AVAudioRecorder") AVAudioFormat = autoclass("AVAudioFormat") NSString = autoclass('NSString') NSURL = autoclass('NSURL') NSError = autoclass('NSError').alloc() class OSXAudio(Audio): def __init__(self, file_path=None): default_path = join(OSXStoragePath().get_music_dir(), 'audio.wav') super().__init__(file_path or default_path) self._recorder = None self._player = None self._current_file = None def _start(self): # Conversion of Python file path string to Objective-C NSString file_path_NSString = NSString.alloc()
''' iOS GPS ----------- ''' from pyobjus import autoclass, protocol from pyobjus.dylib_manager import load_framework from plyer.facades import GPS load_framework('/System/Library/Frameworks/CoreLocation.framework') CLLocationManager = autoclass('CLLocationManager') class IosGPS(GPS): def _configure(self): if not hasattr(self, '_location_manager'): self._location_manager = CLLocationManager.alloc().init() def _start(self, **kwargs): self._location_manager.delegate = self self._location_manager.requestWhenInUseAuthorization() # NSLocationWhenInUseUsageDescription key must exist in Info.plist # file. When the authorization prompt is displayed your app goes # into pause mode and if your app doesn't support background mode # it will crash. self._location_manager.startUpdatingLocation() def _stop(self): self._location_manager.stopUpdatingLocation()
''' AudioAvplayer: implementation of Sound using pyobjus / AVFoundation. Works on iOS / OSX. ''' __all__ = ('SoundAvplayer', ) from kivy.core.audio import Sound, SoundLoader from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE import sys load_framework(INCLUDE.AVFoundation) AVAudioPlayer = autoclass("AVAudioPlayer") NSURL = autoclass("NSURL") NSString = autoclass("NSString") class SoundAvplayer(Sound): @staticmethod def extensions(): # taken from https://goo.gl/015kvU return ("aac", "adts", "aif", "aiff", "aifc", "caf", "mp3", "mp4", "m4a", "snd", "au", "sd2", "wav") def __init__(self, **kwargs): self._avplayer = None super(SoundAvplayer, self).__init__(**kwargs) def load(self): self.unload()
''' IOS file chooser -------------------- This module houses the iOS implementation of the plyer FileChooser. .. versionadded:: 1.4.4 ''' from plyer.facades import FileChooser from pyobjus import autoclass, protocol from pyobjus.dylib_manager import load_framework load_framework('/System/Library/Frameworks/Photos.framework') class IOSFileChooser(FileChooser): ''' FileChooser implementation for IOS using the built-in file browser via UIImagePickerController. .. versionadded:: 1.4.0 ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._on_selection = None def _file_selection_dialog(self, *args, **kwargs): """
---------- ''' try: from urllib.parse import quote except ImportError: from urllib import quote from plyer.facades import Sms from pyobjus import autoclass, objc_str from pyobjus.dylib_manager import load_framework NSURL = autoclass('NSURL') NSString = autoclass('NSString') UIApplication = autoclass('UIApplication') load_framework('/System/Library/Frameworks/MessageUI.framework') class IOSSms(Sms): def _send(self, **kwargs): ''' This method provides sending messages to recipients. Expects 2 parameters in kwargs: - recipient: String type - message: String type Opens a mesage interface with recipient and message information. ''' recipient = kwargs.get('recipient') message = kwargs.get('message')
from plyer.facades import Notification try: import pyobjus # pylint: disable=unused-import except ImportError: raise Exception( "pyobjus missing, please install it. " "`python -m pip install git+http://github.com/kivy/pyobjus/`") from pyobjus import ( # pylint: disable=import-error autoclass, protocol, objc_str, ObjcBOOL) from pyobjus.dylib_manager import ( # pylint: disable=import-error load_framework, INCLUDE) load_framework(INCLUDE.AppKit) load_framework(INCLUDE.Foundation) NSUSERNOTIFICATION = autoclass('NSUserNotification') NSUSERNOTIFICATIONCENTER = autoclass('NSUserNotificationCenter') class OSXNotification(Notification): ''' Implementation of MacOS notification API. ''' def _notify(self, **kwargs): title = kwargs.get('title', '') message = kwargs.get('message', '') app_name = kwargs.get('app_name', '') # app_icon, timeout, ticker are not supported (yet)
---------- """ try: from urllib.parse import quote except ImportError: from urllib import quote from plyer.facades import Sms from pyobjus import autoclass, objc_str from pyobjus.dylib_manager import load_framework NSURL = autoclass("NSURL") NSString = autoclass("NSString") UIApplication = autoclass("UIApplication") load_framework("/System/Library/Frameworks/MessageUI.framework") class IOSSms(Sms): def _send(self, **kwargs): """ This method provides sending messages to recipients. Expects 2 parameters in kwargs: - recipient: String type - message: String type Opens a mesage interface with recipient and message information. """ recipient = kwargs.get("recipient") message = kwargs.get("message")
if environ['FREE'] == "0": paidApp = True except Exception, e: Logger.info('Unable to query ENV var FREE: ' + str(e)) if platform == 'android': ##Billing from jnius import autoclass import oiabilling ##Advertising PythonActivity = autoclass("org.renpy.android.PythonActivity") AdBuddiz = autoclass("com.purplebrain.adbuddiz.sdk.AdBuddiz") elif platform == 'ios' and paidApp is False: from pyobjus import autoclass from pyobjus.dylib_manager import load_framework, INCLUDE, make_dylib, load_dylib load_framework(INCLUDE.StoreKit) load_framework(INCLUDE.AVFoundation) load_framework(INCLUDE.SystemConfiguration) load_framework("./frameworks/AdSupport.framework") load_framework("./frameworks/AdBuddiz.framework") Ad = autoclass("AdBuddiz") Logger.info("\n\nview class methods:\n" + str(dir(Ad))) Logger.info("\n\nview instance methods:\n" + str(dir(Ad.alloc()))) class CustomLayout(FloatLayout): pass class ChicagoApp(App): billing = ObjectProperty(None)
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
''' 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
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):