def get_bundle_identifier_for_path(path): """ Get bundle identifier for the given path. """ bundle_url = 'file://' + os.path.abspath(path) return NSBundle.bundleWithURL_( NSURL.URLWithString_(bundle_url)).bundleIdentifier()
def openUrl(self, url, background=False): ws = NSWorkspace.sharedWorkspace() option = NSWorkspaceLaunchDefault if background: option = NSWorkspaceLaunchWithoutActivation ws.openURL_options_configuration_error_(NSURL.URLWithString_(url), option, dict(), None)
def goto(self, url, show=True): if self._webkit is None: raise RuntimeError("needs to be a web window") url = NSURL.URLWithString_(url).retain() request = NSURLRequest.requestWithURL_(url) self._webkit.mainFrame().loadRequest_(request) self.show()
def pageCount(pdfPath): # The first way of counting pages, using PDFDocument. pdfPath = pdfPath.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(pdfPath) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: return pdfDoc.pageCount()
def run(self): self.panel = NSOpenPanel.alloc().init() if self.messageText: self.panel.setMessage_(self.messageText) if self.title: self.panel.setTitle_(self.title) if self.fileName: self.panel.setNameFieldLabel_(self.fileName) if self.directory: self.panel.setDirectoryURL_(NSURL.fileURLWithPath_(self.directory)) if self.fileTypes: self.panel.setAllowedFileTypes_(self.fileTypes) self.panel.setCanChooseDirectories_(self.canChooseDirectories) self.panel.setCanChooseFiles_(self.canChooseFiles) self.panel.setAllowsMultipleSelection_(self.allowsMultipleSelection) self.panel.setResolvesAliases_(self.resolvesAliases) self.panel.setAccessoryView_(self.accessoryView) if self._parentWindow is not None: self.panel.beginSheetModalForWindow_completionHandler_( self._parentWindow, self.completionHandler_) else: isOK = self.panel.runModalForDirectory_file_types_( self.directory, self.fileName, self.fileTypes) if isOK == NSOKButton: self._result = self.panel.filenames()
def sethtml(self, html, url, show=True): if self._webkit is None: raise RuntimeError("needs to be the web window") url = NSURL.URLWithString_(url).retain() if isinstance(html, str): html = html.decode("utf-8") self._webkit.mainFrame().loadHTMLString_baseURL_(html, url) self.show()
def load(self, url, headers = {}): url = NSURL.alloc().initWithString_(url) request = NSMutableURLRequest.alloc().initWithURL_(url) for header, value in headers.iteritems(): request.setValue_forHTTPHeaderField_(value, header) self._nsObject.loadRequest_(request)
def upload(self, app): if app == 'local': pass else: url = CREATE_URL[app] + urlencode(self.CONTENTS, quote_via=quote) ws = NSWorkspace.sharedWorkspace() ws.openURL_options_configuration_error_( NSURL.URLWithString_(url), NSWorkspaceLaunchWithoutActivation, None, None)
def speak(text, voice, output_file): if not voice in VALID_VOICES: raise ValueError("Invalid voice, should be one of {0}".format(VOICES)) ve = NSSpeechSynthesizer.alloc().init() ve.setVoice_('com.apple.speech.synthesis.voice.' + voice) ve.startSpeakingString_toURL_(text, NSURL.fileURLWithPath_(output_file)) while ve.isSpeaking(): pass return find_aiff_length_ms(output_file)
def refreshView(self): """ Refresh the actual data view for the selected resource. """ if self.selectedResource: self.progress.startAnimation_(self) if self.dataview == self.DATAVIEW_PROPERTIES: self.selectedDetails = self.selectedResource.getAllDetails() self.table.reloadData() self.table.deselectAll_(self) self.text.setString_("") elif self.dataview == self.DATAVIEW_DATA: self.selectedData = self.selectedResource.getDataAsHTML() url = NSURL.alloc().initWithString_(self.serverText.stringValue()) self.webView.mainFrame().loadHTMLString_baseURL_(self.selectedData, url) self.progress.stopAnimation_(self)
def launchAppByBundlePath(bundlePath, arguments=[]): ''' launchAppByBundlePath - Launch app with a given bundle path Return True if succeed ''' bundleUrl = NSURL.fileURLWithPath_(bundlePath) workspace = AppKit.NSWorkspace.sharedWorkspace() arguments_strings = map(lambda a: NSString.stringWithString_(str(a)), arguments) arguments = NSDictionary.dictionaryWithDictionary_({ AppKit.NSWorkspaceLaunchConfigurationArguments: NSArray.arrayWithArray_(arguments_strings) }) return workspace.launchApplicationAtURL_options_configuration_error_( bundleUrl, AppKit.NSWorkspaceLaunchAllowingClassicStartup, arguments, None)
def speak(message=None): data = json.loads(message) text = data['text'] siteId = data['siteId'] sessionId = data['sessionId'] theId = data['id'] filename = settings.VOICE_DIR + "/{}.aiff".format(siteId) newFilename = settings.VOICE_DIR + "/{}.wav".format(siteId) try: from AppKit import NSSpeechSynthesizer from AppKit import NSURL nssp = NSSpeechSynthesizer ve = nssp.alloc().init() #using the system default voice.. else can set it here #from_voice = "com.apple.speech.synthesis.voice.samantha.premium" #ve.setVoice_(from_voice) result_url = NSURL.fileURLWithPath_(filename) ve.startSpeakingString_toURL_(text, result_url) time.sleep(0.5) except: log.info("TTS Failed.. most likely not OSX system") else: tfm = sox.Transformer() tfm.convert(samplerate=16000, n_channels=1, bitdepth=16) tfm.build(filename, newFilename) fp = open(newFilename,'rb') f = fp.read() #send the ID in reverse to use it later when say finished in the mqtt_api topic = 'hermes/audioServer/{}/playBytes/{}'.format(siteId, theId[::-1]) api_lib['mqtt'].publish_item(topic, bytearray(f)) fp.close() #hermes/tts/say #{"text":"where to","lang":"en","id":"fb9687f7-991f-4638-9a9c-033ef008834a","siteId":"zero","sessionId":"22db028e-6f52-4455-b7eb-3b1798848cf0"} #hermes/tts/sayFinished #{"id":"7f82d563-5b25-410b-8fa9-5681c25c34b6","sessionId":null}
def __init__(self, font): self._font = font if font.path: document = DoodleDocument.alloc().init() document.setFileURL_(NSURL.fileURLWithPath_(font.path)) dc = NSDocumentController.sharedDocumentController() dc.addDocument_(document) self._canUpdateChangeCount = True self.w = Window((250, 500), "SimpleFontWindow", minSize=(200, 300)) glyphs = sorted(font.keys()) self.w.glyphs = List((0, 0, -0, -0), glyphs, doubleClickCallback=self.openGlyph) toolbarItems = [ dict(itemIdentifier="spaceCenter", label="Space Center", imageNamed="toolbarSpaceCenterAlternate", callback=self.openSpaceCenter ), dict(itemIdentifier="fontInfo", label="Font Info", imageNamed="toolbarFontInfo", callback=self.openFontInfo ) ] self.w.addToolbar(toolbarIdentifier="SimpleToolbar", toolbarItems=toolbarItems) windowController = self.w.getNSWindowController() windowController.setShouldCloseDocument_(True) self._font.UIdocument().addWindowController_(windowController) self._font.addObserver(self, "fontChanged", "Font.Changed") self.setUpBaseWindowBehavior() self.w.open() self.openFirstGlyph()
def refreshView(self): """ Refresh the actual data view for the selected resource. """ if self.selectedResource: self.progress.startAnimation_(self) if self.dataview == self.DATAVIEW_PROPERTIES: self.selectedDetails = self.selectedResource.getAllDetails() self.table.reloadData() self.table.deselectAll_(self) self.text.setString_("") elif self.dataview == self.DATAVIEW_DATA: self.selectedData = self.selectedResource.getDataAsHTML() url = NSURL.alloc().initWithString_( self.serverText.stringValue()) self.webView.mainFrame().loadHTMLString_baseURL_( self.selectedData, url) self.progress.stopAnimation_(self)
def delete_file(fpath): """On OS X: Trashes a path using the Finder, via OS X's Scripting Bridge. On other platforms: unlinks file. """ try: from AppKit import NSURL from ScriptingBridge import SBApplication except ImportError: log().debug("Deleting %r" % fpath) os.unlink(fpath) else: log().debug("Trashing %r" % fpath) targetfile = NSURL.fileURLWithPath_(fpath) finder = SBApplication.applicationWithBundleIdentifier_("com.apple.Finder") items = finder.items().objectAtLocation_(targetfile) items.delete()
def __init__(self, font): self._font = font if font.path: document = DoodleDocument.alloc().init() document.setFileURL_(NSURL.fileURLWithPath_(font.path)) dc = NSDocumentController.sharedDocumentController() dc.addDocument_(document) self._canUpdateChangeCount = True self.w = Window((250, 500), "SimpleFontWindow", minSize=(200, 300)) glyphs = font.keys() glyphs.sort() self.w.glyphs = List((0, 0, -0, -0), glyphs, doubleClickCallback=self.openGlyph) toolbarItems = [ dict(itemIdentifier="spaceCenter", label="Space Center", imageNamed="toolbarSpaceCenterAlternate", callback=self.openSpaceCenter ), dict(itemIdentifier="fontInfo", label="Font Info", imageNamed="toolbarFontInfo", callback=self.openFontInfo ) ] self.w.addToolbar(toolbarIdentifier="SimpleToolbar", toolbarItems=toolbarItems) windowController = self.w.getNSWindowController() windowController.setShouldCloseDocument_(True) self._font.UIdocument().addWindowController_(windowController) self._font.addObserver(self, "fontChanged", "Font.Changed") self.setUpBaseWindowBehavior() self.w.open()
def run(self): self.panel = NSSavePanel.alloc().init() if self.messageText: self.panel.setMessage_(self.messageText) if self.title: self.panel.setTitle_(self.title) if self.fileName: self.panel.setNameFieldStringValue_(self.fileName) if self.directory: self.panel.setDirectoryURL_(NSURL.fileURLWithPath_(self.directory)) if self.fileTypes: self.panel.setAllowedFileTypes_(self.fileTypes) self.panel.setCanCreateDirectories_(self.canCreateDirectories) self.panel.setCanSelectHiddenExtension_(True) self.panel.setAccessoryView_(self.accessoryView) if self._parentWindow is not None: self.panel.beginSheetModalForWindow_completionHandler_(self._parentWindow, self.completionHandler_) else: isOK = self.panel.runModalForDirectory_file_(self.directory, self.fileName) if isOK == NSOKButton: self._result = self.panel.filename()
def ensure_permissions() -> None: from ApplicationServices import AXIsProcessTrusted from AppKit import NSAlert, NSAlertFirstButtonReturn, NSWorkspace, NSURL accessibility_permissions = AXIsProcessTrusted() if not accessibility_permissions: title = "Missing accessibility permissions" info = "To let ActivityWatch capture window titles grant it accessibility permissions. \n If you've already given ActivityWatch accessibility permissions and are still seeing this dialog, try removing and re-adding them." alert = NSAlert.new() alert.setMessageText_(title) alert.setInformativeText_(info) ok_button = alert.addButtonWithTitle_("Open accessibility settings") alert.addButtonWithTitle_("Close") choice = alert.runModal() print(choice) if choice == NSAlertFirstButtonReturn: NSWorkspace.sharedWorkspace().openURL_( NSURL.URLWithString_( "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility" ))
def speak(message=None): data = json.loads(message) text = data['text'] siteId = data['siteId'] sessionId = data['sessionId'] theId = data['id'] filename = settings.VOICE_DIR + "/{}.aiff".format(siteId) newFilename = settings.VOICE_DIR + "/{}.wav".format(siteId) try: from AppKit import NSSpeechSynthesizer from AppKit import NSURL nssp = NSSpeechSynthesizer ve = nssp.alloc().init() #using the system default voice.. else can set it here #from_voice = "com.apple.speech.synthesis.voice.samantha.premium" #ve.setVoice_(from_voice) result_url = NSURL.fileURLWithPath_(filename) ve.startSpeakingString_toURL_(text, result_url) time.sleep(0.5) except: log.info("TTS Failed.. most likely not OSX system") else: tfm = sox.Transformer() tfm.convert(samplerate=16000, n_channels=1, bitdepth=16) tfm.build(filename, newFilename) fp = open(newFilename, 'rb') f = fp.read() #send the ID in reverse to use it later when say finished in the mqtt_api topic = 'hermes/audioServer/{}/playBytes/{}'.format( siteId, theId[::-1]) api_lib['mqtt_api'].publish_item(topic, bytearray(f)) fp.close()
def findFontLabCandidatesOSX(self): """ This tries to catch all applications that can open a .vfb file. That should include a good number of FontLab applications. In order to find out, we need LaunchServices. Should LaunchServices itself not be available, return the 2 most common FontLab.app names and hope for the best. """ from AppKit import NSURL self.log("findFontLabCandidatesOSX start") try: from LaunchServices import LSCopyApplicationURLsForURL, kLSRolesEditor canLaunch = True self.log("LaunchServices available.") except ImportError: canLaunch = False self.log("LaunchServices unavailable.") if not canLaunch: return ["FontLab Studio 5 OSX.app", "FontLab Studio.app"] # make a bogus VFB dummyPath = tempfile.mkstemp(suffix=".vfb")[1] # find VFB editors url = NSURL.fileURLWithPath_(dummyPath) fontLabs = [] for url in LSCopyApplicationURLsForURL(url, kLSRolesEditor): path = url.path() name = os.path.basename(path) if name not in fontLabs: self.log("Candidate: %s at %s"%(name, path)) fontLabs.append(name) # remove the bogus VFB os.remove(dummyPath) self.log("findFontLabCandidatesOSX end") self.appCandidates = fontLabs return fontLabs
def findFontLabCandidatesOSX(self): """ This tries to catch all applications that can open a .vfb file. That should include a good number of FontLab applications. In order to find out, we need LaunchServices. Should LaunchServices itself not be available, return the 2 most common FontLab.app names and hope for the best. """ from AppKit import NSURL self.log("findFontLabCandidatesOSX start") try: from LaunchServices import LSCopyApplicationURLsForURL, kLSRolesEditor canLaunch = True self.log("LaunchServices available.") except ImportError: canLaunch = False self.log("LaunchServices unavailable.") if not canLaunch: return ["FontLab Studio 5 OSX.app", "FontLab Studio.app"] # make a bogus VFB dummyPath = tempfile.mkstemp(suffix=".vfb")[1] # find VFB editors url = NSURL.fileURLWithPath_(dummyPath) fontLabs = [] for url in LSCopyApplicationURLsForURL(url, kLSRolesEditor): path = url.path() name = os.path.basename(path) if name not in fontLabs: self.log("Candidate: %s at %s" % (name, path)) fontLabs.append(name) # remove the bogus VFB os.remove(dummyPath) self.log("findFontLabCandidatesOSX end") self.appCandidates = fontLabs return fontLabs
def selectfiles(show): workspace.activateFileViewerSelectingURLs_(list(NSURL.fileURLWithPath_(i.decode("utf-8")) for i in show)) return 0
def open_URL(url): """Open the url with launchservices.""" URL = NSURL.URLWithString_(url) LSOpenCFURLRef(URL, None)
def open_file(file_path): '''Opens file/folder at specified path''' file_url = NSURL.fileURLWithPath_(file_path) NSWorkspace.sharedWorkspace().openURL_(file_url) NSLog('User opened {0}'.format(file_path))
def donateButtonPressed_(self, sender): NSWorkspace.sharedWorkspace().openURL_( NSURL.URLWithString_( "https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=4UF2KB2BTW6AC" ))
def helpButtonPressed_(self, sender): # open help url NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("Attribution"))
def donateButtonPressed_(self, sender): NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("https://paypal.com"))
def set(self, url): if url is not None: url = NSURL.URLWithString_(url) self._nsObject.setURL_(url)
'Kxps': 0x4B787073, # include skipped slides 'Kxpb': 0x4B787062, # add borders around slides 'Kxpn': 0x4B78706E, # include slide numbers 'Kxpd': 0x4B787064, # include date 'Kxkf': 0x4B786B66, # export in raw KPF 'KxPW': 0x4B785057, # password 'KxPH': 0x4B785048, # password hint } if len(sys.argv) < 2: print "usage: %s <keynote-file>" % sys.argv[0] sys.exit(-1) # Export options keynote_file = sys.argv[1] to_file = NSURL.fileURLWithPath_(keynote_file.split('.key')[0] + '.pdf') as_format = EXPORT_FORMAT['Kpdf'] with_properties = NSMutableDictionary.dictionaryWithDictionary_({ }) if DEBUG: print(" KEYNOTE_FILE: %s" % keynote_file) print(" TO_FILE: %s" % to_file) print(" AS_FORMAT: %s" % as_format) print("WITH_PROPERTIES: %s" % with_properties) # Open Keynote file keynote = SBApplication.applicationWithBundleIdentifier_(BUNDLE) doc = keynote.open_(keynote_file) # Export to format
def howToUseMyOwnDomain_(self, sender): NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_("http://myownsipdomain.sip2sip.info"))
def pageCount(pdfPath): # pdfPath = pdfPath.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(pdfPath) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: return pdfDoc.pageCount()
if schema_fname.rfind('.') != -1: export_info_fname = os.path.join(schema_dir, '.' + schema_fname[0:schema_fname.rindex('.')] + '.omnigraffle_export') if os.path.exists(export_info_fname): # if it exists it should contain one line that gives a relative path to a # directory where to export with open(export_info_fname) as f: target_dir = f.read().strip() target_dir = os.path.join(schema_dir, target_dir) target_dir = os.path.normpath(target_dir) target_path = os.path.join(target_dir, canvas_name + '.' + format) else: # otherwise ask for a path savePanel = NSSavePanel.savePanel() savePanel.setTitle_("Save %s as" % canvas_name) savePanel.setDirectoryURL_(NSURL.fileURLWithPath_(schema_dir)) savePanel.setCanCreateDirectories_(True) savePanel.setExtensionHidden_(False) savePanel.setNameFieldStringValue_(canvas_name+'.pdf') NSApplication.sharedApplication().activateIgnoringOtherApps_(True); if savePanel.runModal() == NSFileHandlingPanelOKButton: target_path = savePanel.URL().path() format = target_path[target_path.rindex('.')+1:] if not target_path: sys.exit(0) try: schema.export(canvas_name, target_path, format=format) log("Exported %s to: %s as: %s" % (canvas_name, target_path, format))
def helpButtonPressed_(self, sender): # open help url NSWorkspace.sharedWorkspace().openURL_( NSURL.URLWithString_( "http://code.google.com/p/quotefixformac/wiki/CustomAttribution" ))