def save_to_file(self, file_name): if SUPPORTED_FORMATS.match(path.rsplit('.', 1)[-1]): options = ns({'SCNSceneExportDestinationURL': nsurl(path)}) file = nsurl(file_name) return self._objc.writeToURL_options_(url, options) else: raise TypeError('Not a supported export type')
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 main(): global wk UIScreen = objc_util.ObjCClass('UIScreen') if len(UIScreen.screens()) > 1: second_screen = UIScreen.screens()[1] second_screen.overscanCompensation = 0 bounds = second_screen.bounds() UIWindow = objc_util.ObjCClass('UIWindow') second_window = UIWindow.alloc().initWithFrame_(bounds) second_window.setScreen(second_screen) second_window.makeKeyAndVisible() wk = objc_util.ObjCClass('WKWebView').alloc().initWithFrame_(objc_util.CGRect((0, 0), (second_screen.bounds().size.width, second_screen.bounds().size.height - 1))).autorelease() second_window.addSubview(wk) request = objc_util.ObjCClass('NSURLRequest').alloc().init() nsurl = objc_util.nsurl('http://localhost:8080') x = request.initWithURL_(nsurl) wk.loadRequest_(x) else: print('No secondary screen detected. Connect your Looking Glass.') v.close() s.stop_server() quit()
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 main(): NSMutableDictionary = objc_util.ObjCClass('NSMutableDictionary') settings = NSMutableDictionary.dictionary() kAudioFormatMPEG4AAC = 1633772320 settings.setObject_forKey_(kAudioFormatMPEG4AAC, 'AVFormatIDKey') settings.setObject_forKey_(44100.0, 'AVSampleRateKey') settings.setObject_forKey_(2, 'AVNumberOfChannelsKey') AVAudioRecorder = objc_util.ObjCClass('AVAudioRecorder') recorder = AVAudioRecorder.alloc() output_path = os.path.abspath('Recording.m4a') out_url = objc_util.nsurl(output_path) recorder = recorder.initWithURL_settings_error_(out_url, settings, None) started_recording = recorder.record() if started_recording: print( 'Recording started, press the "stop script" button to end recording...' ) try: while True: pass except KeyboardInterrupt: print('Stopping...') recorder.stop() recorder.release() print('Stopped recording.') import console console.quicklook(os.path.abspath('Recording.m4a'))
def loadInstrument(self, instrument): if self._soundBank is None: return error = ctypes.c_void_p(0) self._sampler.loadSoundBankInstrumentAtURL_program_bankMSB_bankLSB_error_( nsurl(self._soundBank), instrument, 0x79, 0, ctypes.pointer(error)) if error: raise Exception(f'Error loading sound bank {self._soundBank}')
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 load_model() -> VNCoreMLModel: global vn_model # Compile the model: c_model_url = MLModel.compileModelAtURL_error_(nsurl(MODEL_PATH), None) # Load model from the compiled model file: ml_model = MLModel.modelWithContentsOfURL_error_(c_model_url, None) # Create a VNCoreMLModel from the MLModel for use with the Vision framework: vn_model = VNCoreMLModel.modelForMLModel_error_(ml_model, None) return vn_model
def __init__(self, url): if type(url) == str: url = nsurl(url) if type(url) == ObjCInstance: self.errorhandler = ObjcErrorHandler() self._objc = file_handler.initForReading_error_(url, None) fformat = self._objc.fileFormat() self.sampleRate = fformat.sampleRate() self.channels = fformat.channelCount() self.format = urlparse(str(url)).path.split('.')[-1]
def __init__(self, url=None, fileName=None, named=None, ID=None): if named is not None: fileName=named if url is not None: self.ID = SCNAudioSource.alloc().initWithURL_(nsurl(self.convertURL(url))) elif fileName is not None: self.ID = SCNAudioSource.audioSourceNamed_(fileName) elif ID is not None: self.ID = ID else: self.ID = SCNAudioSource.alloc()
def load_model(self): '''Helper method for downloading/caching the mlmodel file''' ml_model_url = objc_util.nsurl('pydnet.mlmodel') # Compile the model: c_model_url = self.MLModel.compileModelAtURL_error_(ml_model_url, None) # Load model from the compiled model file: ml_model = self.MLModel.modelWithContentsOfURL_error_(c_model_url, None) # Create a VNCoreMLModel from the MLModel for use with the Vision framework: vn_model = self.VNCoreMLModel.modelForMLModel_error_(ml_model, None) return vn_model
def setFilePath(self, fpath: str): if not os.path.exists(fpath): ex_fpath = os.path.expanduser(fpath) if os.path.exists(ex_fpath): fpath = ex_fpath else: raise FileNotFoundError(fpath) self.player = objc_util.ObjCClass('AVAudioPlayer').alloc() self.player.initWithContentsOfURL_error_(objc_util.nsurl(fpath), None) self.fpath = fpath self.isPlayed = False
def makeSelf(self): self.name = "WebTab" self.right_button_items = [ ButtonItem(self, image=image, action=action) for image, action in (("Action", "wtShare"), ("Forward", "wtGoForward"), ("Back", "wtGoBack")) ] self.newVC.navigationItem().titleView = SearchBar(self) wv = WebView(self) wv.loadRequest_(NSURLRequest.requestWithURL_(nsurl("https://google.com"))) self.newVC.view = wv
def textureSelect(sender): global wk, rgbData if textureSelector.selected_index == 0: rgbData = chosen_pic_photo_image_buffer.getvalue() elif textureSelector.selected_index == 1: rgbData = chosen_pic_colormap_image_buffer.getvalue() request = objc_util.ObjCClass('NSURLRequest').alloc().init() nsurl = objc_util.nsurl('http://localhost:8080') x = request.initWithURL_(nsurl) wk.loadRequest_(x)
def makeSelf(self): self.name = "WebTab" self.right_button_items = [ ButtonItem(self, image=image, action=action) for image, action in (("Action", "wtShare"), ("Forward", "wtGoForward"), ("Back", "wtGoBack")) ] self.newVC.navigationItem().titleView = SearchBar(self) wv = WebView(self) wv.loadRequest_( NSURLRequest.requestWithURL_(nsurl("https://google.com"))) self.newVC.view = wv
def urlHandle(url): if type(url) != ObjCInstance: if type(url) != str: raise TypeError('{} is not a string'.format(str(url))) url = nsurl(url) try: url.isKindOfClass_(NSURL) except AttributeError: raise TypeError('{} is not an NSURL'.format(str(url))) if url.isKindOfClass_(NSURL): return url else: raise TypeError('{} is not an NSURL'.format(str(url)))
def get(self, url=None, auth=None, headers=None, params=None): # Make url if params: params_encoded = urlencode(params) else: params_encoded = "" url = objc_util.nsurl("{}?{}".format(url, params_encoded)) #request = objc_util.ObjCClass("NSURLRequest").request(URL=url) request = objc_util.ObjCClass( 'NSMutableURLRequest').alloc().initWithURL_(url) # Make headers if headers: for key in headers: request.setValue_forHTTPHeaderField_(headers[key], key) if auth: userName, password = auth authStr = "%s:%s" % (userName, password) authencode = base64.b64encode(bytes(authStr)) request.addValue_forHTTPHeaderField_("Basic %s" % authencode, "Authorization") configuration = objc_util.ObjCClass( "NSURLSessionConfiguration").defaultSessionConfiguration() session = objc_util.ObjCClass( "NSURLSession").sessionWithConfiguration_(configuration) completionHandler = objc_util.ObjCBlock( self.responseHandlerBlock, restype=None, argtypes=[c_void_p, c_void_p, c_void_p, c_void_p]) objc_util.retain_global(completionHandler) #dataTask = session.dataTask(Request=request, completionHandler=completionHandler) dataTask = session.dataTaskForRequest_completion_( request, completionHandler) dataTask.resume() # Wait for completions wait = True while wait: if self.data != None: wait = False return json.loads(self.data) elif self.error != None: wait = False raise RequestsException(["Error in request", self.error])
def searchBarSearchButtonClicked_(_self, _cmd, _sb): searchbar = ObjCInstance(_sb) term = str(searchbar.text()) searchbar.resignFirstResponder() if term: det = NSDataDetector.dataDetectorWithTypes_error_(1<<5, None) res = det.firstMatchInString_options_range_(term, 0, (0, len(term))) view = ObjCInstance(_self).view() if res: view.loadRequest_(NSURLRequest.requestWithURL_(res.URL())) searchbar.text = res.URL().absoluteString() else: view.loadRequest_(NSURLRequest.requestWithURL_(nsurl('https://google.com/search?q=' + urllib.quote(term))))
def searchBarSearchButtonClicked_(_self, _cmd, _sb): searchbar = ObjCInstance(_sb) term = str(searchbar.text()) searchbar.resignFirstResponder() if term: det = NSDataDetector.dataDetectorWithTypes_error_(1 << 5, None) res = det.firstMatchInString_options_range_(term, 0, (0, len(term))) view = ObjCInstance(_self).view() if res: view.loadRequest_(NSURLRequest.requestWithURL_(res.URL())) searchbar.text = res.URL().absoluteString() else: view.loadRequest_( NSURLRequest.requestWithURL_( nsurl('https://google.com/search?q=' + urllib.quote(term))))
def load_model(): '''Helper method for downloading/caching the mlmodel file''' if not os.path.exists(MODEL_PATH): print(f'Downloading model: {MODEL_FILENAME}...') r = requests.get(MODEL_URL, stream=True) file_size = int(r.headers['content-length']) with open(MODEL_PATH, 'wb') as f: bytes_written = 0 for chunk in r.iter_content(1024 * 100): f.write(chunk) print(f'{bytes_written/file_size*100:.2f}% downloaded') bytes_written += len(chunk) print('Download finished') ml_model_url = nsurl(MODEL_PATH) c_model_url = MLModel.compileModelAtURL_error_(ml_model_url, None) ml_model = MLModel.modelWithContentsOfURL_error_(c_model_url, None) vn_model = VNCoreMLModel.modelForMLModel_error_(ml_model, None) return vn_model
def search_action(sender): #get swichs state global legbr, legpt, tor, title #, legendasdivxUrl, legendasdivxUrlLang, title, torrentUrl legpt = view['switchPt'].value legbr = view['switchBr'].value tor = view['switchTor'].value torSearchZ2 = view['switchTorZ2'].value torSearchPBay = view['switchTorzPBay'].value torSearchZooqle = view['switchTorZooqle'].value torSearchRarBg = view['switchTorRarBg'].value imdbSearch = view['switchImdb'].value dueSearch = view['switchDue'].value aftercredits = view['switchAfterCredits'].value if legbr and legpt: url = geturl(title, Lingua.ALL, Site.Legendas) elif legbr or legpt: if legbr: url = geturl(title, Lingua.BR, Site.Legendas) else: url = geturl(title, Lingua.PT, Site.Legendas) if tor: url = geturl(title, None, Site.Torrent) elif torSearchPBay: url = geturl(title, None, Site.TorSearchPBay) elif torSearchZ2: url = geturl(title, None, Site.TorSearchZ2) elif torSearchZooqle: url = geturl(title, None, Site.TorSearchZooqle) elif torSearchRarBg: url = geturl(title, None, Site.TorSearchRarBg) elif imdbSearch: url = geturl(title, None, Site.ImdbSearch) elif dueSearch: url = geturl(title, None, Site.DueRemember) elif aftercredits: url = geturl(title, None, Site.AfterCredits) log('url: '.format(url)) app = UIApplication.sharedApplication() app.openURL_(nsurl(url))
def validate(url, params, responseHandler): if params: params_encoded = urllib.parse.urlencode(params) else: params_encoded = "" url = objc_util.nsurl("{}?{}".format(url, params_encoded)) request = NSURLRequest.request(URL=url) configuration = NSURLSessionConfiguration.defaultSessionConfiguration() session = NSURLSession.session(Configuration=configuration) completionHandler = objc_util.ObjCBlock( responseHandler, restype=None, argtypes=[c_void_p, c_void_p, c_void_p, c_void_p]) objc_util.retain_global(completionHandler) dataTask = session.dataTask(Request=request, completionHandler=completionHandler) dataTask.resume()
def modeSelect(sender): global wk, mode, control_startcamera, control_sphere, cameracontrol if modeSelector.selected_index == 0: mode = mesh control_startcamera = '0, 0, 220' control_sphere = '14.667, 8, 8' elif modeSelector.selected_index == 1: mode = wireframe control_startcamera = '0, 0, 15' control_sphere = '1, 8, 8' elif modeSelector.selected_index == 2: mode = pointcloud control_startcamera = '0, 0, 450' control_sphere = '30, 8, 8' request = objc_util.ObjCClass('NSURLRequest').alloc().init() nsurl = objc_util.nsurl('http://localhost:8080') x = request.initWithURL_(nsurl) wk.loadRequest_(x) cameracontrol.load_url('http://localhost:8080/cameracontrol.html')
def __init__(self, url=None, params=None): self.data = None if params: params_encoded = urlencode(params) else: params_encoded = "" url = objc_util.nsurl("{}?{}".format(url, params_encoded)) request = objc_util.ObjCClass("NSURLRequest").request(URL=url) configuration = objc_util.ObjCClass( "NSURLSessionConfiguration").defaultSessionConfiguration() session = objc_util.ObjCClass("NSURLSession").session( Configuration=configuration) completionHandler = objc_util.ObjCBlock( self.responseHandlerBlock, restype=None, argtypes=[c_void_p, c_void_p, c_void_p, c_void_p]) objc_util.retain_global(completionHandler) dataTask = session.dataTask(Request=request, completionHandler=completionHandler) dataTask.resume()
def _urlHandle(url): if not isinstance(url, ObjCInstance): return nsurl(url) return url if url.isKindOfClass_(ObjCClass('NSURL')) else None
def open_in(self, app): ''' Display self's location in the app with the given moniker ''' from objc_util import UIApplication, nsurl app_ = UIApplication.sharedApplication() xurl = nsurl(self.as_xurl(app)) app_.openURL_(xurl)
def openURL(url): """Open a url in a way that works through appex. This is useful for using URL schemes to open other apps with data gained from appex.""" shared.app._openURL_(nsurl(url))
def run(): import ctypes import datetime import errno import io import objc_util import os import shutil import sys import console try: unicode except NameError: unicode = str print(u"Enabling fault handler and Objective-C exception handler...") LOGDIR = os.path.expanduser(u"~/Documents/faultlog") LOGNAME_TEMPLATE = u"faultlog-{:%Y-%m-%d-%H-%M-%S}.txt" LOGNAME_DEFAULT = u"faultlog-temp.txt" EXCEPTIONLOGNAME_DEFAULT = u"exceptionlog-temp.txt" # Create the faultlog directory if necessary try: os.mkdir(LOGDIR) except (IOError, OSError) as err: if err.errno != errno.EEXIST: raise # Check whether an Objective-C exception log exists and append it to the fault log try: fin = io.open(os.path.join(LOGDIR, EXCEPTIONLOGNAME_DEFAULT), "rb") except (IOError, OSError) as err: if err.errno != errno.ENOENT: raise else: with fin: data = fin.read() if data: with io.open(os.path.join(LOGDIR, LOGNAME_DEFAULT), "ab") as fout: # If the faultlog is not empty, add a separator if fout.tell() != 0: fout.write(b"\n" + b"-"*72 + b"\n\n") fout.write(data) os.remove(os.path.join(LOGDIR, EXCEPTIONLOGNAME_DEFAULT)) # Check whether a faultlog was written did_fault = False try: f = io.open(os.path.join(LOGDIR, LOGNAME_DEFAULT), "rb") except (IOError, OSError) as err: if err.errno != errno.ENOENT: raise else: with f: if f.read(1): did_fault = True # Notify the user that a crash has happened if did_fault: print(u"Pythonista quit abnormally last time.", file=sys.stderr) stamped_name = LOGNAME_TEMPLATE.format(datetime.datetime.fromtimestamp(os.stat(os.path.join(LOGDIR, LOGNAME_DEFAULT)).st_mtime)) shutil.move(os.path.join(LOGDIR, LOGNAME_DEFAULT), os.path.join(LOGDIR, stamped_name)) console.write_link(u"For details, see the log file '{}'.".format(stamped_name), str(objc_util.nsurl(os.path.join(LOGDIR, stamped_name)))) if sys.version_info < (3,): print(u"Setting exception handler.") # Set the Objective-C exception handler only under Python 2. # Otherwise under Pythonista 3 it would be set twice - once by Python 2 and once by Python 3. # This way the exception handler is set exactly once and works under Pythonista 2 and 3. # typedef void (*objc_uncaught_exception_handler)(id exception); objc_uncaught_exception_handler = ctypes.CFUNCTYPE(None, ctypes.c_void_p) # objc_uncaught_exception_handler objc_setUncaughtExceptionHandler(objc_uncaught_exception_handler fn); objc_util.c.objc_setUncaughtExceptionHandler.argtypes = [objc_uncaught_exception_handler] objc_util.c.objc_setUncaughtExceptionHandler.restype = objc_uncaught_exception_handler # Set Objective-C uncaught exception handler @objc_uncaught_exception_handler def handler(exc_pointer): exc = objc_util.ObjCInstance(exc_pointer) name = exc.name() reason = exc.reason() user_info = exc.userInfo() call_stack_symbols = exc.callStackSymbols() with io.open(os.path.join(LOGDIR, EXCEPTIONLOGNAME_DEFAULT), "wb") as f: try: f.write(b"Objective-C exception details:\n\n") if reason is None: f.write(str(name).encode("utf-8") + b"\n") else: f.write(str(name).encode("utf-8") + b": " + str(reason).encode("utf-8") + b"\n") if user_info is not None: f.write(str(user_info).encode("utf-8") + b"\n") f.write(b"\nStack trace:\n\n") for sym in call_stack_symbols: f.write(str(sym).encode("utf-8") + b"\n") f.write(b"\nEnd of exception details.\n") except Exception as err: import traceback f.write(b"I messed up! Python exception:\n") f.write(traceback.format_exc().encode("utf-8")) raise # The exception handler must be kept in some kind of permanent location, otherwise it will be collected by the garbage collector, because there are no more references to it from Python. objc_util._dgelessus_pythonista_startup_exception_handler = handler objc_util.c.objc_setUncaughtExceptionHandler(handler) else: # The faulthandler module is only available under Python 3. print("Setting fault handler.") import faulthandler logfile = io.open(os.path.join(LOGDIR, LOGNAME_DEFAULT), "wb") faulthandler.enable(logfile) print(u"Done enabling fault handler and Objective-C exception handler.")
# coding: utf-8 # https://forum.omz-software.com/topic/2915/delete-photos-from-camera-roll from objc_util import nsurl, UIApplication app = UIApplication.sharedApplication() app.openURL_(nsurl('workflow://...'))
# coding: utf-8 # @omz twitter import urllib import appex from objc_util import UIApplication, nsurl import time page_url = appex.get_url() if page_url: overcast_url = 'overcast://x-callback-url/add?url=%s' % (urllib.quote( page_url, ''), ) app = UIApplication.sharedApplication() app.openURL_(nsurl(overcast_url)) time.sleep(0.5) appex.finish()
def create_url(image_url): ''' Accepts an image_url [string]. Returns search by image URL. ''' search_url = 'https://www.google.co.uk/searchbyimage?&image_url=' try: search_url += image_url except: print('Could not create URL from clipboard.') return search_url def main(): image_url = clipboard.get() if is_url(image_url): search_url = create_url(image_url) webbrowser.open('safari-' + search_url) print('Done.') if __name__ == '__main__': main() # -------------------- from objc_util import nsurl,UIApplication app = UIApplication.sharedApplication() URL = 'https://www.google.co.uk/searchbyimage?&image_url=' app.openURL_(nsurl(URL)) # --------------------
import youtube_dl import sys import urllib from objc_util import nsurl, UIApplication ydl_opts = { 'format': 'best[ext=mp4]/best', 'simulate': True, 'quiet': True, } with youtube_dl.YoutubeDL(ydl_opts) as ydl: source_url = sys.argv[1] info = ydl.extract_info(source_url, download=False) base_url = 'https://watchable-video.github.io/player' query = urllib.parse.urlencode({ 'url': info.get('url'), 'title': info.get('title', ''), 'poster': info.get('thumbnail', '') }) url = base_url + '?' + query app = UIApplication.sharedApplication() app.openURL_(nsurl(url))
def open_url(url): from objc_util import UIApplication, nsurl app=UIApplication.sharedApplication() app._openURL_(nsurl(url))
import appex import requests import webbrowser import clipboard import console def main(): if not appex.is_running_extension(): url = "www.example.com" else: url = appex.get_url() if url: clipboard.set(url) # Editorial.app will use the clipboard and paste it at the end of a document webbrowser.open('editorial://x-callback-url/open/path-to-file.txt?root=dropbox&command=PasteLink&x-success=pythonista3://') else: print('No input URL found.') if __name__ == '__main__': main() # -------------------- from objc_util import UIApplication, nsurl app = UIApplication.sharedApplication() app.openURL_(nsurl('editorial://...')) # --------------------