def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False): swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier', swizzled_bundleIdentifier) notification = NSUserNotification.alloc().init() notification.setInformativeText_(message) if title: notification.setTitle_(title) if subtitle: notification.setSubtitle_(subtitle) if appIcon: url = NSURL.alloc().initWithString_(appIcon) image = NSImage.alloc().initWithContentsOfURL_(url) notification.set_identityImage_(image) if contentImage: url = NSURL.alloc().initWithString_(contentImage) image = NSImage.alloc().initWithContentsOfURL_(url) notification.setContentImage_(image) if sound: notification.setSoundName_( "NSUserNotificationDefaultSoundName") notification.setDeliveryDate_( NSDate.dateWithTimeInterval_sinceDate_(delay, NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter().scheduleNotification_( notification)
def _pyobjc_notify(message, title=None, subtitle=None, appIcon=None, contentImage=None, open_URL=None, delay=0, sound=False): swizzle(objc.lookUpClass('NSBundle'), b'bundleIdentifier', swizzled_bundleIdentifier) notification = NSUserNotification.alloc().init() notification.setInformativeText_(message) if title: notification.setTitle_(title) if subtitle: notification.setSubtitle_(subtitle) if appIcon: url = NSURL.alloc().initWithString_(appIcon) image = NSImage.alloc().initWithContentsOfURL_(url) notification.set_identityImage_(image) if contentImage: url = NSURL.alloc().initWithString_(contentImage) image = NSImage.alloc().initWithContentsOfURL_(url) notification.setContentImage_(image) if sound: notification.setSoundName_( "NSUserNotificationDefaultSoundName") notification.setDeliveryDate_( NSDate.dateWithTimeInterval_sinceDate_( delay, NSDate.date())) NSUserNotificationCenter.defaultUserNotificationCenter( ).scheduleNotification_(notification)
def main(argv): (title, options, pathToFile) = argv[:] # Set the default location where the PDFs will go (you'll need to make sure this exists) destination = os.path.expanduser("~/Desktop/") # Set the filepath of the filter. # Check for custom user filter; otherwise use the Not-Very-Good System filter. filterpath = os.path.expanduser("~/Library/Filters/Better PDFX-3.qfilter") if not os.path.exists(filterpath): filterpath = "/System/Library/Filters/Create Generic PDFX-3 Document.qfilter" title += ".pdf" outputfile = save_dialog(destination, title) if outputfile != "": pdfURL = NSURL.fileURLWithPath_(pathToFile) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) filterURL = NSURL.fileURLWithPath_(filterpath) value = QuartzFilter.quartzFilterWithURL_(filterURL) options = {'QuartzFilter': value} pdfDoc.writeToFile_withOptions_(outputfile, options) # Delete original PDF from spool folder os.remove(pathToFile)
def copyOutlines(source, dest): pdfURL = NSURL.fileURLWithPath_(source) inPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if inPDF: outline = Quartz.PDFOutline.alloc().init() outline = inPDF.outlineRoot() pdfURL = NSURL.fileURLWithPath_(dest) outPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) outPDF.setOutlineRoot_(outline) outPDF.writeToFile_(dest)
def update_appcast(oldVersion, newVersion, appcastSignature, tarballName, fileSize, minimumSystemVersion, download_url): appcastDate = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) # creating this from a string is easier than manipulating NSXMLNodes... newItemString = """<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <item> <title>Version """ + newVersion + """</title> <description> <![CDATA[ <h3>Changes Since """ + str(oldVersion) + """</h3> <li></li> <li></li> ]]> </description> <pubDate>""" + appcastDate + """</pubDate> <sparkle:minimumSystemVersion>""" + minimumSystemVersion + """</sparkle:minimumSystemVersion> <enclosure url=\"""" + download_url + """\" sparkle:version=\"""" + newVersion + """\" length=\"""" + fileSize + """\" type="application/octet-stream" sparkle:dsaSignature=\"""" + appcastSignature + """\" /> </item> </channel> </rss>""" # read from the source directory appcastURL = NSURL.fileURLWithPath_(APPCAST_PATH) # xml doc from the current appcast (oldDoc, error) = NSXMLDocument.alloc().initWithContentsOfURL_options_error_(appcastURL, NSXMLNodePreserveCDATA, None) assert oldDoc is not None, error # xml doc from the new appcast string (newDoc, error) = NSXMLDocument.alloc().initWithXMLString_options_error_(newItemString, NSXMLNodePreserveCDATA, None) assert newDoc is not None, error # get an arry of the current item titles (oldTitles, error) = oldDoc.nodesForXPath_error_("//item/title", None) assert oldTitles.count > 0, "oldTitles had no elements" # now get the title we just created (newTitles, error) = newDoc.nodesForXPath_error_("//item/title", None) assert newTitles.count() is 1, "newTitles must have a single element" # easy test to avoid duplicating items if oldTitles.containsObject_(newTitles.lastObject()) is False: # get the parent node we'll be inserting to (parentChannel, error) = oldDoc.nodesForXPath_error_("//channel", None) assert parentChannel.count() is 1, "channel count must be one" parentChannel = parentChannel.lastObject() # now get the new node (newNodes, error) = newDoc.nodesForXPath_error_("//item", None) assert newNodes is not None, error # insert a copy of the new node parentChannel.addChild_(newNodes.lastObject().copy()) # write to NSData, since pretty printing didn't work with NSXMLDocument writing oldDoc.XMLDataWithOptions_(NSXMLNodePrettyPrint).writeToURL_atomically_(appcastURL, True)
def _playsoundOSX(sound, block=True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' from AppKit import NSSound from Foundation import NSURL from time import sleep if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound url = NSURL.URLWithString_(sound) nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if not nssound: raise IOError('Unable to load sound named: ' + sound) nssound.play() if block: sleep(nssound.duration())
def makeDockOtherEntry(self, thePath, arrangement=0, displayas=1, showas=0): """Returns a dictionary corresponding to a Dock folder or file item. arrangement values: 1: sort by name 2: sort by date added 3: sort by modification date 4: sort by creation date 5: sort by kind displayas values: 0: display as stack 1: display as folder showas values: 0: auto 1: fan 2: grid 3: list """ label_name = os.path.splitext(os.path.basename(thePath))[0] if arrangement == 0: if label_name == "Downloads": # set to sort by date added arrangement = 2 else: # set to sort by name arrangement = 1 ns_url = NSURL.fileURLWithPath_(thePath).absoluteString() if os.path.isdir(thePath): result = { "tile-data": { "arrangement": arrangement, "displayas": displayas, "file-data": { "_CFURLString": ns_url, "_CFURLStringType": 15 }, "file-label": label_name, "dock-extra": False, "showas": showas, }, "tile-type": "directory-tile", } else: result = { "tile-data": { "file-data": { "_CFURLString": ns_url, "_CFURLStringType": 15 }, "file-label": label_name, "dock-extra": False, }, "tile-type": "file-tile", } return result
def _play_sound(cls, file, playing_time=None): """ Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. """ from AppKit import NSSound from Foundation import NSURL if '://' not in file: if not file.startswith('/'): from os import getcwd file = f'{getcwd()}/{file}' file = f'file://{file}' nssound = NSSound.alloc().initWithContentsOfURL_byReference_(NSURL.URLWithString_(file), True) if not nssound: raise IOError(f'Unable to load sound named: {file}') nssound.play() if playing_time is None: time.sleep(nssound.duration()) else: time.sleep(playing_time)
def dropEvent(self, e): """ Drop files directly onto the widget File locations are stored in fname :param e: :return: """ newFolders = [] if e.mimeData().hasUrls: e.setDropAction(Qt.CopyAction) e.accept() # Workaround for OSx dragging and dropping for url in e.mimeData().urls(): if op_sys == 'Darwin': #check for dir here as well fname = str(NSURL.URLWithString_(str(url.toString())).filePathURL().path()) else: fname = str(url.toLocalFile()) if os.path.isdir(fname) == True: newFolders.append(fname) #print(fname) #self.fname = fname #print(self.fname) #self.load_image() self.addNewFolders(newFolders) self.inList = self.inList + newFolders else: e.ignore()
def LoadImageFromPath( path ): url = NSURL.fileURLWithPath_(path) NSLog( "LoadImageFromPath( %@ )", url ); # # Create image source from URL # # An image source abstracts the data-access task and eliminates the need for you to manage data through a raw memory buffer. # An image source can contain more than one image, thumbnail images, and properties for each image and the image file. # When you are working with image data and your application runs in Mac OS X v10.4 or later, image # sources are the preferred way to move image data into your application. # # CGImageSource objects, available in Mac OS X v10.4 or later, abstract the data-reading task. An image source can # read image data from a URL, a CFData object, or a data consumer. After creating a CGImageSource object for the # appropriate source, you can obtain images, thumbnails, image properties, and other image information using CGImageSource functions. # # CGImageSourceCreateWithURL ==> Creates an image source that reads from a location specified by a URL. # # CGImageSourceCreateImageAtIndex ==> Creates a CGImage object for the image data associated with the specified index in an image source. # Create an image from the first item in the image source. imagesrc = CGImageSourceCreateWithURL(url, None) # NSLog( "LoadImageFromPath: imagesrc is %r" % (imagesrc,) ) theImage = CGImageSourceCreateImageAtIndex(imagesrc, 0, None); # NSLog( "LoadImageFromPath: theImage is %r" % (theImage,) ) return theImage
def _build_NSRequest(request, timeout): """ Converts a Requests request into an NSMutableURLRequest. Does not touch the request body: that's handled elsewhere. Args: request: Request object timeout: Request timeout Returns: Instance of NSMutableURLRequest """ nsrequest = NSMutableURLRequest.requestWithURL_( NSURL.URLWithString_(request.url)) nsrequest.setHTTPMethod_(request.method) if timeout is not None: nsrequest.timeoutInterval = float(timeout) for k, v in request.headers.items(): k, v = k.lower(), v.lower() if k in _RESERVED_HEADERS: continue nsrequest.setValue_forHTTPHeaderField_(v, k) return nsrequest
def change_desktop_background(file, desk_id): """Function that applies the named file as wallaper for the specified monitor (desk_id)""" file_url = NSURL.fileURLWithPath_(file) screen = NSScreen.screens()[desk_id] ws = NSWorkspace.sharedWorkspace() ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def showPSTNAccessforAccount_(self, account): if account.server.settings_url is None: return self._account = account self.webView.setHidden_(True) self.loadingText.setHidden_(False) self.spinWheel.setHidden_(False) self.spinWheel.startAnimation_(None) self.errorText.setHidden_(True) self.window.setTitle_( NSLocalizedString("Server Tools For %s", "Window title") % self._account.id) query_string = "realm=%s&tab=payments&user_agent=blink" % self._account.id if account.server.settings_url.query: query_string = "%s&%s" % (account.server.settings_url.query, query_string) url = urllib.parse.urlunparse(account.server.settings_url[:4] + (query_string, ) + account.server.settings_url[5:]) url = NSURL.URLWithString_(url) request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 15) self.webView.mainFrame().loadRequest_(request) self.window.makeKeyAndOrderFront_(self)
def alertShowHelp_(self, alert): TRACE('Help button clicked on boot error dialog') help_link = alert.helpAnchor() if help_link is not None: url = NSURL.alloc().initWithString_(help_link) NSWorkspace.sharedWorkspace().openURL_(url) return YES
def exportAllInstances(): ''' This will export all instances of the font at 'path' as TrueType fonts. ''' path = os.path.expanduser("~/Desktop/test/file.glyphs") doc = Glyphs.openDocumentWithContentsOfFile_display_(path, False) print "Exporting:", doc.displayName() font = doc.font() for instance in font.instances(): print "Instance:", instance instance.generate_({ 'ExportFormat': "TTF", 'ExportContainer': "woff", 'Destination': NSURL.fileURLWithPath_(os.path.expanduser("~/Desktop/test/")) }) ''' possible keys: ExportContainer: "woff", "woff2", "eot" Destination: NSURL autoHint: bool (default = true) removeOverlap: bool (default = true) useSubroutines: bool (default = true) useProductionNames: bool (default = true) ''' doc.close() print "Ready!"
def start(self): '''Start the connection''' if not self.destination_path: self.log('No output file specified.') self.done = True return url = NSURL.URLWithString_(self.url) request = ( NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalCacheData, self.connection_timeout)) if self.additional_headers: for header, value in self.additional_headers.items(): request.setValue_forHTTPHeaderField_(value, header) # does the file already exist? See if we can resume a partial download if os.path.isfile(self.destination_path): stored_data = self.get_stored_headers() if (self.can_resume and 'expected-length' in stored_data and ('last-modified' in stored_data or 'etag' in stored_data)): # we have a partial file and we're allowed to resume self.resume = True local_filesize = os.path.getsize(self.destination_path) byte_range = 'bytes=%s-' % local_filesize request.setValue_forHTTPHeaderField_(byte_range, 'Range') if self.download_only_if_changed and not self.resume: stored_data = self.cache_data or self.get_stored_headers() if 'last-modified' in stored_data: request.setValue_forHTTPHeaderField_( stored_data['last-modified'], 'if-modified-since') if 'etag' in stored_data: request.setValue_forHTTPHeaderField_(stored_data['etag'], 'if-none-match') self.connection = NSURLConnection.alloc().initWithRequest_delegate_( request, self)
def eventFilter(self, obj, event): if event.type() == QtCore.QEvent.DragEnter: if event.mimeData().hasUrls(): event.accept() else: event.ignore() return True elif event.type() == QtCore.QEvent.Drop: if event.mimeData().hasUrls(): # event.accept() for url in event.mimeData().urls(): if sys.platform == "darwin": from Foundation import NSURL fname = str( NSURL.URLWithString_(str( url.toString())).filePathURL().path()) obj.topLevelWidget().lip_sync_frame.open(fname) else: fname = str(url.toLocalFile()) obj.topLevelWidget().lip_sync_frame.open(fname) return True else: event.ignore() return False else: return False
def getNextURL(self): self.current_url = self.urls[self.current_idx] logging.debug("Loading %s" % self.current_url) self.start_time = time.time() self.target_webview.mainFrame().loadRequest_( NSURLRequest.requestWithURL_(NSURL.URLWithString_( self.current_url))) if self.request_count >= self.options.max_requests: if not self.times: logging.critical("No pages loaded at all?") else: total_time = sum(self.times) print "Loaded %d pages in %0.2f seconds (avg=%0.2f)" % ( self.request_count, total_time, total_time / len(self.times)) AppKit.NSApplication.sharedApplication().terminate_(None) self.request_count += 1 if self.urls[0] == TEST_URL: self.urls.pop(0) self.request_count -= 1 if self.options.random: i = random.randint(0, len(self.urls) - 1) else: i = (self.current_idx + 1) % len(self.urls) self.current_idx = i
def __init__(self, source=None, path=None): """ source : str | None -- AppleScript source code path : str | None -- full path to .scpt/.applescript file Notes: - Either the path or the source argument must be provided. - If the script cannot be read/compiled, a ScriptError is raised. """ if path: url = NSURL.URLWithFilePath_(path) self._script, errorinfo = NSAppleScript.alloc( ).initWithContentsOfURL_error_(url, None) if errorinfo: raise ScriptError(errorinfo) elif source: self._script = NSAppleScript.alloc().initWithSource_(source) else: raise ValueError("Missing source or path argument.") if not self._script.isCompiled(): errorinfo = self._script.compileAndReturnError_(None)[1] if errorinfo: raise ScriptError(errorinfo)
def _set_urls(array): urls = [] if array is not None: for url in array: urls.append(NSURL.alloc().initWithString(url)) general_pasteboard().URLs = urls
def dropEvent(self, e): """ Drop files directly onto the widget File locations are stored in fname :param e: :return: """ if e.mimeData().hasUrls: e.setDropAction(QtCore.Qt.CopyAction) e.accept() # Workaround for OSx dragging and dropping for url in e.mimeData().urls(): if op_sys == 'Darwin': fname = str( NSURL.URLWithString_(str( url.toString())).filePathURL().path()) else: #if not os.path.isdir(str(url.toLocalFile())): # print("Please drag & drop a directory onto the main window") # return fname = str(url.toLocalFile()) if (self.customDropCallback is not None): self.customDropCallback(fname) else: self.imageFolder = fname self.folderWasSet() else: e.ignore()
def set_desktop_background(desktop_picture_path): file_url = NSURL.fileURLWithPath_(desktop_picture_path) ws = NSWorkspace.sharedWorkspace() screens = NSScreen.screens() for screen in screens: ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def main(): display_id = Quartz.CGMainDisplayID() session = AVF.AVCaptureSession.alloc().init() devices = AVF.AVCaptureDevice.defaultDeviceWithMediaType_( AVF.AVMediaTypeAudio) print(devices) screen_input = AVF.AVCaptureScreenInput.alloc().initWithDisplayID_( display_id) error = None audio, error = AVF.AVCaptureDeviceInput.deviceInputWithDevice_error_( devices, objc.nil) file_output = AVF.AVCaptureMovieFileOutput.alloc().init() session.addInput_(screen_input) session.addInput_(audio) session.addOutput_(file_output) session.startRunning() file_url = NSURL.fileURLWithPath_('fooste.mov') # Cheat and pass a dummy delegate object where normally we'd have a # AVCaptureFileOutputRecordingDelegate file_url = file_output.startRecordingToOutputFileURL_recordingDelegate_( file_url, NSObject.alloc().init()) time.sleep(30) session.stopRunning()
def set_background(image_file): from AppKit import NSWorkspace, NSScreen from Foundation import NSURL file_url = NSURL.fileURLWithPath_(image_file) ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)
def next_image(self, _): if not os.path.exists(self.media_dir): os.makedirs(self.media_dir) url = 'https://unsplash.it/' if self.gray_mood: url += 'g/' url += '{w}/{h}/?random' if self.blur: url += '&blur' url = url.format(w=self.screen_width, h=self.screen_height) file_name = self.media_dir + datetime.datetime.now().strftime("%H:%M:%S.%f") + '.jpg' try: self.icon = 'img/wait.png' urllib.urlretrieve(url, file_name) file_url = NSURL.fileURLWithPath_(file_name) # Get shared workspace ws = NSWorkspace.sharedWorkspace() # Iterate over all screens for screen in NSScreen.screens(): # Tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, {}, None) self.icon = 'img/icon.png' except IOError: print('Service unavailable, check your internet connection.') rumps.alert(title='Connection Error', message='Service unavailable\n' 'Please, check your internet connection')
def makeDockOtherEntry(self, thePath, arrangement=0, displayas=1, showas=0): '''returns a dictionary corresponding to a Dock folder or file item''' # arrangement values: # 1: sort by name # 2: sort by date added # 3: sort by modification date # 4: sort by creation date # 5: sort by kind # # displayas values: # 0: display as stack # 1: display as folder # # showas values: # 0: auto # 1: fan # 2: grid # 3: list label_name = os.path.splitext(os.path.basename(thePath))[0] if arrangement == 0: if label_name == 'Downloads': # set to sort by date added arrangement = 2 else: # set to sort by name arrangement = 1 ns_url = NSURL.fileURLWithPath_(thePath).absoluteString() if os.path.isdir(thePath): return { 'tile-data': { 'arrangement': arrangement, 'displayas': displayas, 'file-data': { '_CFURLString': ns_url, '_CFURLStringType': 15 }, 'file-label': label_name, 'dock-extra': False, 'showas': showas }, 'tile-type': 'directory-tile' } else: return { 'tile-data': { 'file-data': { '_CFURLString': ns_url, '_CFURLStringType': 15 }, 'file-label': label_name, 'dock-extra': False }, 'tile-type': 'file-tile' }
def export(self, canvasname, file, format='pdf', force=False, is_checksum=False): """ Exports one canvas named {@code canvasname} """ format = format.lower() chksum = None if os.path.isfile(file) and not force: existing_chksum = checksum(file) if format != 'pdf' \ else checksum_pdf(file) new_chksum = self.compute_canvas_checksum(canvasname) if existing_chksum == new_chksum and existing_chksum != None: logging.debug('No exporting - canvas %s not changed' % canvasname) return False else: chksum = new_chksum elif format == 'pdf': chksum = self.compute_canvas_checksum(canvasname) win = self.og.windows.first() canvas = [c for c in self.doc.canvases() if c.name() == canvasname] if len(canvas) == 1: canvas = canvas[0] else: logging.warn('Canvas %s does not exist in %s' % (canvasname, self.schemafile)) return False self.og.set(win.canvas, to=canvas) export_format = OmniGraffleSchema.EXPORT_FORMATS[format] if (export_format == None): self.doc.save(in_=file) else: self.doc.save(as_=export_format, in_=file) if not is_checksum and self.options.verbose: print "%s" % file logging.debug("Exported `%s' into `%s' as %s" % (canvasname, file, format)) if format == 'pdf': # save the checksum url = NSURL.fileURLWithPath_(file) pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url) attrs = NSMutableDictionary.alloc().initWithDictionary_(pdfdoc.documentAttributes()) attrs[PDFKit.PDFDocumentSubjectAttribute] = \ '%s%s' % (OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE, chksum) pdfdoc.setDocumentAttributes_(attrs) pdfdoc.writeToFile_(file) return True
def add_fav(path_to_item): current_paths = list_favs() if path_to_item not in current_paths: list_ref, current_items = _get_favs() added_item = NSURL.fileURLWithPath_(path_to_item) result = LSSharedFileListInsertItemURL(list_ref, kLSSharedFileListItemLast, None, None, added_item, {}, [])
def process_url(self, url): if isinstance(url, NSURL): url = str(url) if self._quote_url_path: url = self.quote_url_path(url) if self._force_https: url = self.http2https_url(url) return NSURL.URLWithString_(url)
def dropEvent(self, e): if op_sys == 'Darwin': fnames = [str(NSURL.URLWithString_(str(url.toString())).filePathURL().path()) for url in e.mimeData().urls()] else: fnames = e.mimeData().urls() e.accept() self.openfiles(fnames)
def update_appcast(oldVersion, newVersion, appcastSignature, tarballName, fileSize, minimumSystemVersion, download_url): appcastDate = strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()) # creating this from a string is easier than manipulating NSXMLNodes... newItemString = """<?xml version="1.0" encoding="utf-8"?> <rss version="2.0" xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle" xmlns:dc="http://purl.org/dc/elements/1.1/"> <channel> <item> <title>Version """ + newVersion + """</title> <description> <h3>Changes Since """ + str(oldVersion) + """</h3> <li></li> <li></li> </description> <pubDate>""" + appcastDate + """</pubDate> <sparkle:minimumSystemVersion>""" + minimumSystemVersion + """</sparkle:minimumSystemVersion> <enclosure url=\"""" + download_url + """\" sparkle:version=\"""" + newVersion + """\" length=\"""" + fileSize + """\" type="application/octet-stream" sparkle:dsaSignature=\"""" + appcastSignature + """\" /> </item> </channel> </rss>""" # read from the source directory appcastURL = NSURL.fileURLWithPath_(APPCAST_PATH) # xml doc from the current appcast (oldDoc, error) = NSXMLDocument.alloc().initWithContentsOfURL_options_error_(appcastURL, 0, None) assert oldDoc is not None, error # xml doc from the new appcast string (newDoc, error) = NSXMLDocument.alloc().initWithXMLString_options_error_(newItemString, 0, None) assert newDoc is not None, error # get an arry of the current item titles (oldTitles, error) = oldDoc.nodesForXPath_error_("//item/title", None) assert oldTitles.count > 0, "oldTitles had no elements" # now get the title we just created (newTitles, error) = newDoc.nodesForXPath_error_("//item/title", None) assert newTitles.count() is 1, "newTitles must have a single element" # easy test to avoid duplicating items if oldTitles.containsObject_(newTitles.lastObject()) is False: # get the parent node we'll be inserting to (parentChannel, error) = oldDoc.nodesForXPath_error_("//channel", None) assert parentChannel.count() is 1, "channel count must be one" parentChannel = parentChannel.lastObject() # now get the new node (newNodes, error) = newDoc.nodesForXPath_error_("//item", None) assert newNodes is not None, error # insert a copy of the new node parentChannel.addChild_(newNodes.lastObject().copy()) # write to NSData, since pretty printing didn't work with NSXMLDocument writing oldDoc.XMLDataWithOptions_(NSXMLNodePrettyPrint).writeToURL_atomically_(appcastURL, True)
def removePage(filename): pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pageNum = pdfDoc.pageCount() if pageNum > 1: pdfDoc.removePageAtIndex_(0) pdfDoc.writeToFile_(filename) return
def start(self): '''Start the connection''' if not self.destination_path: self.log('No output file specified.') self.done = True return url = NSURL.URLWithString_(self.url) request = ( NSMutableURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalCacheData, self.connection_timeout)) if self.additional_headers: for header, value in self.additional_headers.items(): request.setValue_forHTTPHeaderField_(value, header) # does the file already exist? See if we can resume a partial download if os.path.isfile(self.destination_path): stored_data = self.getStoredHeaders() if (self.can_resume and 'expected-length' in stored_data and ('last-modified' in stored_data or 'etag' in stored_data)): # we have a partial file and we're allowed to resume self.resume = True local_filesize = os.path.getsize(self.destination_path) byte_range = 'bytes=%s-' % local_filesize request.setValue_forHTTPHeaderField_(byte_range, 'Range') if self.download_only_if_changed and not self.resume: stored_data = self.cache_data or self.getStoredHeaders() if 'last-modified' in stored_data: request.setValue_forHTTPHeaderField_( stored_data['last-modified'], 'if-modified-since') if 'etag' in stored_data: request.setValue_forHTTPHeaderField_(stored_data['etag'], 'if-none-match') if NSURLSESSION_AVAILABLE: configuration = ( NSURLSessionConfiguration.defaultSessionConfiguration()) # optional: ignore system http/https proxies (10.9+ only) if self.ignore_system_proxy is True: configuration.setConnectionProxyDictionary_({ kCFNetworkProxiesHTTPEnable: False, kCFNetworkProxiesHTTPSEnable: False }) # set minumum supported TLS protocol (defaults to TLS1) configuration.setTLSMinimumSupportedProtocol_( self.minimum_tls_protocol) self.session = ( NSURLSession.sessionWithConfiguration_delegate_delegateQueue_( configuration, self, None)) self.task = self.session.dataTaskWithRequest_(request) self.task.resume() else: self.connection = NSURLConnection.alloc( ).initWithRequest_delegate_(request, self)
def start(self): if self.started: return self.init_session() self.started = True self.captureSession.startRunning() movieURL = NSURL.fileURLWithPath_(self.recording_path) self.movieOutput.startRecordingToOutputFileURL_recordingDelegate_( movieURL, self)
def renderTemplate(webView: WebView, name: str, **values): html = render_template(name, **values) frame = webView.mainFrame() resource_path = os.environ.get('RESOURCEPATH', os.path.dirname(__file__)) logger.debug('resource_path = %r', resource_path) baseUrl = NSURL.fileURLWithPath_( os.path.join(resource_path, 'static', '') ) frame.loadHTMLString_baseURL_(html, baseUrl)
def viewDidLoad(self): super().viewDidLoad() request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( NSURL.URLWithString_(self.url), NSURLRequestReloadIgnoringLocalCacheData, 3, ) self.webView.loadRequest_(request)
def convertIconToPNG(icon_path, destination_path, desired_pixel_height=350, desired_dpi=72): '''Converts an icns file to a png file, choosing the representation closest to (but >= if possible) the desired_pixel_height. Returns True if successful, False otherwise''' icns_url = NSURL.fileURLWithPath_(icon_path) png_url = NSURL.fileURLWithPath_(destination_path) image_source = CGImageSourceCreateWithURL(icns_url, None) if not image_source: return False number_of_images = CGImageSourceGetCount(image_source) if number_of_images == 0: return False selected_index = 0 candidate = {} # iterate through the individual icon sizes to find the "best" one for index in range(number_of_images): try: properties = CGImageSourceCopyPropertiesAtIndex( image_source, index, None) # perform not empty check for properties to prevent crash as CGImageSourceCopyPropertiesAtIndex sometimes fails in 10.15.4 and above if not properties: return False dpi = int(properties.get(kCGImagePropertyDPIHeight, 0)) height = int(properties.get(kCGImagePropertyPixelHeight, 0)) if (not candidate or (height < desired_pixel_height and height > candidate['height']) or (height >= desired_pixel_height and height < candidate['height']) or (height == candidate['height'] and dpi == desired_dpi)): candidate = {'index': index, 'dpi': dpi, 'height': height} selected_index = index except ValueError: pass image = CGImageSourceCreateImageAtIndex(image_source, selected_index, None) image_dest = CGImageDestinationCreateWithURL(png_url, 'public.png', 1, None) CGImageDestinationAddImage(image_dest, image, None) return CGImageDestinationFinalize(image_dest)
def removePage(filename): filename = filename.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pageNum = pdfDoc.pageCount() if pageNum > 1: pdfDoc.removePageAtIndex_(0) pdfDoc.writeToFile_(filename) return
def getOutlines(infile): pdfURL = NSURL.fileURLWithPath_(infile) myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myPDF: outline = Quartz.PDFOutline.alloc().init() outline = myPDF.outlineRoot() for n in range(outline.numberOfChildren()): print n print outline.childAtIndex_(n).label() print outline.childAtIndex_(n).destination()
def set_url(url: str): """ Copy the given URL to the pasteboard. :param url: The string to copy as an URL. """ check(url, "url", [str, None]) general_pasteboard().URL = NSURL.alloc().initWithString(url)
def setBackgroundOSX(fullPath): # generate a fileURL for the desktop picture file_path = NSURL.fileURLWithPath_(fullPath) # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_path, screen, {}, None)
def set_wallpaper_image(imgs, mode='stretched'): """Set the given file as wallpaper.""" if not len(imgs): return default_image = imgs[0] file_url = NSURL.fileURLWithPath_(default_image) options = {} ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, options, None)
def startLoading(self): self.loading = True self.setTitle() delimiter = '&' if '?' in self.screensharing_url else '?' url = '%s%sfit=1' % ( self.screensharing_url, delimiter ) if self.screensharing_fit_window else self.screensharing_url url = NSURL.URLWithString_(url) request = NSURLRequest.requestWithURL_cachePolicy_timeoutInterval_( url, NSURLRequestReloadIgnoringLocalAndRemoteCacheData, 15) self.webView.mainFrame().loadRequest_(request)
def checksum_pdf(filepath): assert os.path.isfile(filepath), '%s is not a file' % filepath url = NSURL.fileURLWithPath_(filepath) pdfdoc = PDFKit.PDFDocument.alloc().initWithURL_(url) assert pdfdoc != None chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute] if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE): return None else: return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]
def save_dialog(directory, filename): panel = NSSavePanel.savePanel() panel.setTitle_("Save PDF booklet") myUrl = NSURL.fileURLWithPath_isDirectory_(directory, True) panel.setDirectoryURL_(myUrl) panel.setNameFieldStringValue_(filename) NSApp.activateIgnoringOtherApps_(True) ret_value = panel.runModal() if ret_value: return panel.filename() else: return ''
def getDocInfo(file): file = file.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(file) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: metadata = pdfDoc.documentAttributes() if "Keywords" in metadata: keys = metadata["Keywords"] mutableMetadata = metadata.mutableCopy() mutableMetadata["Keywords"] = tuple(keys) return mutableMetadata else: return metadata
def checkLock(infile): pdfURL = NSURL.fileURLWithPath_(infile) myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myPDF: if myPDF.isLocked: print "Locked" password = getTextFromDialog() if myPDF.unlockWithPassword_(password): print infile, "Unlocked!" else: print "Unable to unlock", infile else: print "No PDF data retrieved from", infile
def addPage(filename): filename = filename.decode('utf-8') pdfURL = NSURL.fileURLWithPath_(filename) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pageNum = pdfDoc.pageCount() page = pdfDoc.pageAtIndex_(0) pageSize = page.boundsForBox_(mediabox) blankPage = PDFPage.alloc().init() blankPage.setBounds_forBox_(pageSize, mediabox) pdfDoc.insertPage_atIndex_(blankPage, pageNum) pdfDoc.writeToFile_(filename) return
def convertIconToPNG(icon_path, destination_path, desired_pixel_height=350, desired_dpi=72): '''Converts an icns file to a png file, choosing the representation closest to (but >= if possible) the desired_pixel_height. Returns True if successful, False otherwise''' icns_url = NSURL.fileURLWithPath_(icon_path) png_url = NSURL.fileURLWithPath_(destination_path) image_source = CGImageSourceCreateWithURL(icns_url, None) if not image_source: return False number_of_images = CGImageSourceGetCount(image_source) if number_of_images == 0: return False selected_index = 0 candidate = {} # iterate through the individual icon sizes to find the "best" one for index in range(number_of_images): try: properties = CGImageSourceCopyPropertiesAtIndex( image_source, index, None) dpi = int(properties.get(kCGImagePropertyDPIHeight, 0)) height = int(properties.get(kCGImagePropertyPixelHeight, 0)) if (not candidate or (height < desired_pixel_height and height > candidate['height']) or (height >= desired_pixel_height and height < candidate['height']) or (height == candidate['height'] and dpi == desired_dpi)): candidate = {'index': index, 'dpi': dpi, 'height': height} selected_index = index except ValueError: pass image = CGImageSourceCreateImageAtIndex(image_source, selected_index, None) image_dest = CGImageDestinationCreateWithURL(png_url, 'public.png', 1, None) CGImageDestinationAddImage(image_dest, image, None) return CGImageDestinationFinalize(image_dest)
def writeInstanceAsUFO(): ''' This will write the second instance of the active font as an .ufo to the desktop ''' font = currentDocument.font() intance = font.instances()[2] InterpolatedFont = font.generateInstance_error_(intance, None) print InterpolatedFont doc = Glyphs.objectWithClassName_("GSDocument") doc.setFont_(InterpolatedFont) url = NSURL.fileURLWithPath_(os.path.expanduser("~/Desktop/%s-%s.ufo" % (font.familyName(), intance.name()))) typeName = "org.unifiedfontobject.ufo" doc.writeToURL_ofType_forSaveOperation_originalContentsURL_error_(url, typeName, 0, url, None)
def setFile(): # generate a fileURL for the desktop picture file_path = NSURL.fileURLWithPath_(base_dir + image_file.decode("utf-8")) # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_path, screen, ws.desktopImageOptionsForScreen_(screen), None) if error: print error
def get_superfolders_list(basepath): """return list of superfolders from volume down to container of basepath. could be empty. """ superfolders_list = [] url = NSURL.fileURLWithPath_(basepath) # d1 = GetURLValues(url, enumeratorURLKeys) while True: # not d1[NSURLIsVolumeKey]: # base path could be a volume, then superfolder list is empty d1 = GetURLValues(url, enumeratorURLKeys) superfolders_list.insert(0,d1) if d1[NSURLIsVolumeKey]: break url = url.URLByDeletingLastPathComponent() # go "upwards" to volume GPR.print_superfolders_list("volume, superfolder(s)", superfolders_list, 4) return superfolders_list
def apply_cifilter_with_name(filter_name, orientation, in_path, out_path, dry_run=False): print "-- in: ", in_path print "-- out:", out_path assert in_path assert out_path assert filter_name in ["CIPhotoEffectTonal", "CIPhotoEffectMono", "CIPhotoEffectInstant", "CIPhotoEffectTransfer", "CIPhotoEffectProcess", "CIPhotoEffectChrome", "CIPhotoEffectNoir", "CIPhotoEffectFade", "CIPhotoEffect3DDramatic", "CIPhotoEffect3DVivid", "CIPhotoEffect3DDramaticCool", "CIPhotoEffect3DNoir"] url = NSURL.alloc().initFileURLWithPath_(in_path) ci_image = CIImage.imageWithContentsOfURL_(url) assert ci_image in_creation_timestamp = os.path.getmtime(in_path) print time.ctime(in_creation_timestamp) if orientation != None and orientation != 1: print "-- orientation:", orientation ci_image = ci_image.imageByApplyingOrientation_(orientation) ci_filter = CIFilter.filterWithName_(filter_name) assert ci_filter ci_filter.setValue_forKey_(ci_image, "inputImage") ci_filter.setDefaults() ci_image_result = ci_filter.outputImage() assert ci_image_result bitmap_rep = NSBitmapImageRep.alloc().initWithCIImage_(ci_image_result) assert bitmap_rep properties = { "NSImageCompressionFactor" : 0.9 } data = bitmap_rep.representationUsingType_properties_(3, properties) # 3 for JPEG if dry_run: print "-- dryrun, don't write", out_path return assert data.writeToFile_atomically_(out_path, True) os.utime(out_path, (time.time(), in_creation_timestamp))
def main(): width = 550 height = 550 print("Updating...") j = urllib2.urlopen("http://himawari8-dl.nict.go.jp/himawari8/img/D531106/latest.json") latest = strptime(json.load(j)["date"], "%Y-%m-%d %H:%M:%S") print("Latest version: {} GMT\n".format(strftime("%Y/%m/%d/%H:%M:%S", latest))) url_format = "http://himawari8.nict.go.jp/img/D531106/{}d/{}/{}_{}_{}.png" png = Image.new('RGB', (width*level, height*level)) print("Downloading tiles: 0/{} completed".format(level*level)) for x in range(level): for y in range(level): tile_w = urllib2.urlopen(url_format.format(level, width, strftime("%Y/%m/%d/%H%M%S", latest), x, y)) tiledata = tile_w.read() tile = Image.open(BytesIO(tiledata)) png.paste(tile, (width*x, height*y, width*(x+1), height*(y+1))) print("Downloading tiles: {}/{} completed".format(x*level + y + 1, level*level)) print("\nDownloaded\n") output_file = tempfile.NamedTemporaryFile().name + ".png" png.save(output_file, "PNG") file_url = NSURL.fileURLWithPath_(output_file) options = {'NSImageScaleProportionallyUpOrDown': True} # get shared workspace ws = NSWorkspace.sharedWorkspace() # iterate over all screens for screen in NSScreen.screens(): # tell the workspace to set the desktop picture (result, error) = ws.setDesktopImageURL_forScreen_options_error_( file_url, screen, options, None) if error: print error exit(-1) print("Done!\n")
def set_wallpaper(screen_index, path): ''' Set desktop wallpaper for screen at index CLI Example: .. code-block:: bash salt '*' desktop.set_wallpaper 0 '/Library/Desktop Pictures/Solid Colors/Solid Aqua Graphite.png' ''' workspace = NSWorkspace.sharedWorkspace() screens = NSScreen.screens() screen = screens[screen_index] file_url = NSURL.fileURLWithPath_isDirectory_(path, False) options = {} (status, error) = workspace.setDesktopImageURL_forScreen_options_error_(file_url, screen, options, None) return status
def _check_for_access(self): '''Check for accessibility permission''' # Because unsigned bundle will fail to call # AXIsProcessTrustedWithOptions with a segment falt, we're # not currently stepping into this function. return self.log('Begin checking for accessibility') core_services = objc.loadBundle( 'CoreServices', globals(), bundle_identifier='com.apple.ApplicationServices' ) objc.loadBundleFunctions( core_services, globals(), [('AXIsProcessTrustedWithOptions', b'Z@')] ) objc.loadBundleFunctions( core_services, globals(), [('kAXTrustedCheckOptionPrompt', b'@')] ) self.log('Bundle com.apple.ApplicationServices loaded') try: if not AXIsProcessTrustedWithOptions( # noqa {kAXTrustedCheckOptionPrompt: False} # noqa ): self.log('Requesting access, Opening syspref window') NSWorkspace.sharedWorkspace().openURL_( NSURL.alloc().initWithString_( 'x-apple.systempreferences:' 'com.apple.preference.security' '?Privacy_Accessibility' ) ) except: # Unsigned bundle will fail to call AXIsProcessTrustedWithOptions self.log(( 'Error detecting accessibility permission status, ' 'KeyCounter might not work' )) self.log('Access already granted')
def main(): if len(sys.argv) != 4: print("Usage: {} in.pdf out.pdf \"creator string\"".format(__file__)) sys.exit(1) in_PDF = os.path.expanduser(sys.argv[1]) out_PDF = os.path.expanduser(sys.argv[2]) creator_str = sys.argv[3] fn = os.path.expanduser(in_PDF) url = NSURL.fileURLWithPath_(fn) pdfdoc = PDFDocument.alloc().initWithURL_(url) attrs = (NSMutableDictionary.alloc() .initWithDictionary_(pdfdoc.documentAttributes())) attrs[PDFDocumentCreatorAttribute] = creator_str pdfdoc.setDocumentAttributes_(attrs) pdfdoc.writeToFile_(out_PDF)
def setSecurityScopedBookmark(self, path): #======================================================================= # Security Scoped Bookmark #======================================================================= try: dirURL = NSURL.alloc().initFileURLWithPath_(path) myData = dirURL.bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_(NSURLBookmarkCreationWithSecurityScope, None, None, None) theBytes = myData[0].bytes().tobytes() self.bookmarks.append(theBytes) except Exception, e: print "Unable to create security-scoped-bookmarks" print str(e) print "------------------------------------------"
def main(argv): (title, options, pathToFile) = argv[:] # Set the default location where the PDFs will go (you'll need to make sure this exists) destination = os.path.expanduser("~/Desktop/") stripTitle = (os.path.splitext(title)[0]) stripTitle += ".pdf" outputfile = save_dialog(destination, stripTitle) # Copy file to selected location. if outputfile != "": pdfURL = NSURL.fileURLWithPath_(pathToFile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: pdfDoc.writeToFile_(outputfile) # Delete original PDF from spool folder os.remove(pathToFile)