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 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 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 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 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 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 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 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 __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.fileURLWithPath_(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 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 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 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 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): 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 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 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 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 send2trash(paths): paths = preprocess_paths(paths) paths = [ path.decode("utf-8") if not isinstance(path, text_type) else path for path in paths ] for path in paths: file_url = NSURL.fileURLWithPath_(path) fm = NSFileManager.defaultManager() op_result = fm.trashItemAtURL_resultingItemURL_error_(file_url, None, None) check_op_result(op_result)
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 main(argv): inputfile = "" outputfile = "" filter = "" try: opts, args = getopt.getopt(sys.argv[1:], "ifo", ["input", "filter", "output"]) except getopt.GetoptError as err: print(err) usage() sys.exit(2) if len(args) != 3: print("Not enough arguments") sys.exit(2) inputfile = args[0].decode('utf-8') if not inputfile: print('Unable to open input file') sys.exit(2) filter = args[1].decode('utf-8') filter = checkFilter(filter) if not filter: print('Unable to find Quartz Filter') sys.exit(2) outputfile = args[2].decode('utf-8') if not outputfile: print('No valid output file specified') sys.exit(2) # You could just take the inputfile as the outputfile if not explicitly given. # outputfile = inputfile pdfURL = NSURL.fileURLWithPath_(inputfile) pdfDoc = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) filterURL = NSURL.fileURLWithPath_(filter) value = Quartz.QuartzFilter.quartzFilterWithURL_(filterURL) dict = {'QuartzFilter': value} pdfDoc.writeToFile_withOptions_(outputfile, dict)
def getNotes(infile): pdfURL = NSURL.fileURLWithPath_(infile) myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myPDF: pages = myPDF.pageCount() for p in range(0, pages): page = myPDF.pageAtIndex_(p) if page.annotations(): for eachNote in page.annotations(): print(eachNote) print(eachNote.contents()) print("-------")
def getOutlines(infile): pdfURL = NSURL.fileURLWithPath_(infile) myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myPDF: outline = Quartz.PDFOutline.alloc().init() outline = myPDF.outlineRoot() if outline: if outline.numberOfChildren() != 0: for n in range(outline.numberOfChildren()): recurseOutlines(outline.childAtIndex_(n)) else: print("No Outlines in this PDF.")
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 getDocInfo(file): 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 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 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 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 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 main(): """ Find and apply the most appropriate desktop pic for this machine """ final_path = find_picture(str(sys.argv[4])) if not final_path: sys.exit(1) print('Picture Path - ', final_path) file_url = NSURL.fileURLWithPath_(final_path) options = {} ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, options, None)
def makeDockAppEntry(self, thePath, label_name=None): """Returns a dictionary corresponding to a Dock application item.""" if not label_name: label_name = os.path.splitext(os.path.basename(thePath))[0] ns_url = NSURL.fileURLWithPath_(thePath).absoluteString() result = { "tile-data": { "file-data": {"_CFURLString": ns_url, "_CFURLStringType": 15}, "file-label": label_name, "file-type": 41, }, "tile-type": "file-tile", } return result
def makeDockAppEntry(self, thePath): '''returns a dictionary corresponding to a Dock application item''' label_name = os.path.splitext(os.path.basename(thePath))[0] ns_url = NSURL.fileURLWithPath_(thePath).absoluteString() return { 'tile-data': { 'file-data': { '_CFURLString': ns_url, '_CFURLStringType': 15 }, 'file-label': label_name, 'file-type': 41 }, 'tile-type': 'file-tile' }
def getOutlines(infile): pdfURL = NSURL.fileURLWithPath_(infile) myPDF = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myPDF: outline = Quartz.PDFOutline.alloc().init() outline = myPDF.outlineRoot() if outline: print(f'Root Outline: {outline.label()}') print(f'Number of Children: {outline.numberOfChildren()}') print(outline.index()) for n in range(outline.numberOfChildren()): print(f'Child: {n}') print(outline.childAtIndex_(n).label()) print(outline.childAtIndex_(n).destination()) print(outline.childAtIndex_(n).parent().label())
def pdfSearch(filepath, searchString): pdfURL = NSURL.fileURLWithPath_(filepath) pdfDoc = PDFDocument.alloc().initWithURL_(pdfURL) if pdfDoc: searchResults = (pdfDoc.findString_withOptions_(searchString, 0)) if searchResults: for result in searchResults: eachPage = result.pages() print("\'" + searchString + "\' was found on page: " + str(pdfDoc.indexForPage_(eachPage[0]) + 1)) else: print("Nothing found.") else: print("Not a valid PDF.") return
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 addChildObserver(self, name, callback): childPath = os.path.join(self.path, name) assert os.path.exists(childPath) url = NSURL.fileURLWithPath_(childPath) bookmarkData, error = url.bookmarkDataWithOptions_includingResourceValuesForKeys_relativeToURL_error_( 0, None, None, None) assert error is None, error st = os.stat(childPath) inode = st.st_ino modTime = st.st_mtime if inode in self.children: assert self.children[inode].name == name assert self.children[inode].modTime == modTime self.children[inode].bookmarkData = bookmarkData else: self.children[inode] = DirectoryEntry(name, modTime, bookmarkData) self.children[inode].callbacks.append(callback)
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 reverse_pdf(pdf_path): # build output PDF filename base_path, ext = os.path.splitext(pdf_path) resersed_pdf_path = base_path + '_reversed' + ext pdf_nsurl = NSURL.fileURLWithPath_(pdf_path) pdf = PDFDocument.alloc().initWithURL_(pdf_nsurl) reversed_pdf = PDFDocument.alloc().init() page_count = pdf.pageCount() pdf_page = PDFPage # n is sequential page increase, r is the reversed page number for n, r in enumerate(reversed(range(0, page_count))): pdf_page = pdf.pageAtIndex_(r) reversed_pdf.insertPage_atIndex_(pdf_page, n) reversed_pdf.writeToFile_(resersed_pdf_path) return resersed_pdf_path
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 canonicalize_tail_existing(path): """Fixes the case of the last component of a file to the name on disk. Works only if the path exists. """ if is_osx(): url = NSURL.fileURLWithPath_( path) # will be None if path doesn't exist if not url: return path return url.fileReferenceURL().path() if is_windows(): return canonicalize_tail_win32(path) # todo: make an explicit version of this line noise r = glob.glob(re.sub(r'([^:/\\])(?=[/\\]|$)', r'[\1]', path)) return r[0] if r else path
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 chsum = None attrs = pdfdoc.documentAttributes() if PDFKit.PDFDocumentSubjectAttribute in attrs: chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute] else: return None if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE): return None else: return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):]
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 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)
def runAutopsy(fonts, glyphNames): if fonts and glyphNames: starttime = time.time() global pagewidth, pageheight #global myDialog if Glyphs.intDefaults["com_yanone_Autopsy_PageOrientation"] == Portrait: if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]: pagewidth = letter[0] pageheight = letter[1] else: pagewidth = A4[0] pageheight = A4[1] else: if not Glyphs.boolDefaults["com_yanone_Autopsy_PageSize_a4"]: pagewidth = letter[1] pageheight = letter[0] else: pagewidth = A4[1] pageheight = A4[0] ############# # # Collect information about the glyphs # # Dimensions reports = Ddict(dict) glyphwidth = Ddict(dict) maxwidthperglyph = Ddict(dict) maxwidth = 0 maxsinglewidth = 0 glyphheight = Ddict(dict) maxheightperglyph = Ddict(dict) maxheight = 0 maxsingleheight = 0 for glyphName in glyphNames: glyphwidth[glyphName] = 0 glyphheight[glyphName] = 0 maxwidthperglyph[glyphName] = 0 maxheightperglyph[glyphName] = 0 reports[glyphName]['width'] = Report() reports[glyphName]['height'] = Report() reports[glyphName]['bboxwidth'] = Report() reports[glyphName]['bboxheight'] = Report() reports[glyphName]['highestpoint'] = Report() reports[glyphName]['lowestpoint'] = Report() reports[glyphName]['leftsidebearing'] = Report() reports[glyphName]['rightsidebearing'] = Report() for font in fonts: FontMaster = font.masters[0] if font.glyphs.has_key(glyphName): g = font.glyphs[glyphName].layers[FontMaster.id] #print "__g", g glyphwidth[glyphName] = g.width height = ascender(font) - descender(font) widthforgraph = glyphwidth[glyphName] if widthforgraph == 0: widthforgraph = g.bounds.size.width heightforgraph = height # width of kegel reports[glyphName]['width'].addvalue((glyphwidth[glyphName], widthforgraph, heightforgraph)) # sum of widths per glyph if reports[glyphName]['width'].sum > maxwidth: maxwidth = reports[glyphName]['width'].sum if reports[glyphName]['width'].max > maxsinglewidth: maxsinglewidth = reports[glyphName]['width'].max # height of kegel glyphheight[glyphName] = height reports[glyphName]['height'].addvalue((glyphheight[glyphName], widthforgraph, heightforgraph)) # sum of heights per glyph if reports[glyphName]['height'].sum > maxheight: maxheight = reports[glyphName]['height'].sum if reports[glyphName]['height'].max > maxsingleheight: maxsingleheight = reports[glyphName]['height'].max # BBox overthetop = 20000 bbox = g.bounds if bbox.size.width < -1*overthetop or bbox.size.width > overthetop: reports[glyphName]['bboxwidth'].addvalue((0, widthforgraph, heightforgraph)) else: reports[glyphName]['bboxwidth'].addvalue((bbox.size.width, widthforgraph, heightforgraph)) if bbox.size.height < -1*overthetop or bbox.size.height > overthetop: reports[glyphName]['bboxheight'].addvalue((0, widthforgraph, heightforgraph)) else: reports[glyphName]['bboxheight'].addvalue((bbox.size.height, widthforgraph, heightforgraph)) if (bbox.origin.y + bbox.size.height) < -1*overthetop or (bbox.origin.y + bbox.size.height) > overthetop: reports[glyphName]['highestpoint'].addvalue((0, widthforgraph, heightforgraph)) else: reports[glyphName]['highestpoint'].addvalue((bbox.origin.y + bbox.size.height, widthforgraph, heightforgraph)) if bbox.origin.y < -1*overthetop or bbox.origin.y > overthetop: reports[glyphName]['lowestpoint'].addvalue((0, widthforgraph, heightforgraph)) else: reports[glyphName]['lowestpoint'].addvalue((bbox.origin.y, widthforgraph, heightforgraph)) # L + R sidebearing reports[glyphName]['leftsidebearing'].addvalue((g.LSB, widthforgraph, heightforgraph)) reports[glyphName]['rightsidebearing'].addvalue((g.RSB, widthforgraph, heightforgraph)) # Recalculate drawing boards numberoftables = 0 # GSNotImplemented # for table in availablegraphs: # if eval('myDialog.graph_' + table): # numberoftables += 1 if numberoftables < 3: numberoftables = 3 try: r = 2.0 / numberoftables except: r = .8 SetScrapBoard(r) # Calculate ratio global ratio if Glyphs.intDefaults["com_yanone_Autopsy_PageOrientation"] == Portrait: ratio = (scrapboard['top'] - scrapboard['bottom']) / maxheight * mm ratio2 = (scrapboard['right'] - scrapboard['left']) / maxsinglewidth * mm maxratio = 0.3 if ratio > maxratio: ratio = maxratio if ratio > ratio2: ratio = ratio2 else: ratio = (scrapboard['right'] - scrapboard['left']) / maxwidth * mm ratio2 = (scrapboard['top'] - scrapboard['bottom']) / maxsingleheight * mm maxratio = 0.3 if ratio > maxratio: ratio = maxratio if ratio > ratio2: ratio = ratio2 # PDF Init stuff filename = Glyphs.defaults["com_yanone_Autopsy_filename"] tempFileName = NSTemporaryDirectory()+"%d.pdf"%random.randint(1000,100000) pageRect = CGRectMake (0, 0, pagewidth, pageheight) fileURL = NSURL.fileURLWithPath_(tempFileName) pdfContext = CGPDFContextCreateWithURL(fileURL, pageRect, None) CGPDFContextBeginPage(pdfContext, None) pdfNSGraphicsContext = NSGraphicsContext.graphicsContextWithGraphicsPort_flipped_(pdfContext, False) NSGraphicsContext.saveGraphicsState() NSGraphicsContext.setCurrentContext_(pdfNSGraphicsContext) try: drawTitlePage(fonts) CGPDFContextEndPage(pdfContext) ### MAIN PAGES ### for i, glyphName in enumerate(glyphNames): CGPDFContextBeginPage(pdfContext, None) drawGlyph(fonts, glyphName, i, ratio, reports) # End page CGPDFContextEndPage(pdfContext) except: print "__Main" print traceback.format_exc() finally: # close PDF NSGraphicsContext.restoreGraphicsState() CGPDFContextClose(pdfContext) output("time: " + str(time.time() - starttime) + "sec, ca." + str((time.time() - starttime) / len(glyphNames)) + "sec per glyph") if errors: print "__Errors", errors for error in errortexts: #print "__Message", error, programname dlg = message(error) # if not errors and fonts and myDialog.openPDF: if not errors and fonts: try: os.rename(tempFileName, filename) except: dlg = Message("Error", "Problem copying final pdf") if Glyphs.defaults["com_yanone_Autopsy_openPDF"]: launchfile(filename)
# Change this to whatever filepath you want: outfile=os.path.expanduser("~/Desktop/Clipboard.pdf") myFavoriteTypes = [NSPasteboardTypePDF, NSTIFFPboardType, NSPICTPboardType, 'com.adobe.encapsulated-postscript'] pb = NSPasteboard.generalPasteboard() best_type = pb.availableTypeFromArray_(myFavoriteTypes) if best_type: clipData = pb.dataForType_(best_type) if clipData: image = NSImage.alloc().initWithPasteboard_(pb) if image: page = Quartz.PDFPage.alloc().initWithImage_(image) if os.path.exists(outfile): pdfURL = NSURL.fileURLWithPath_(outfile) myFile = Quartz.PDFDocument.alloc().initWithURL_(pdfURL) if myFile: pagenum = myFile.pageCount() myFile.insertPage_atIndex_(page, pagenum) print "Image added to Clipboard file." else: pageData = page.dataRepresentation() myFile = Quartz.PDFDocument.alloc().initWithData_(pageData) myFile.writeToFile_(outfile) print "Clipboard file created." else: print ("No clipboard image data was retrieved.") # print ("These types were available:")
parser = argparse.ArgumentParser(description='Sets the desktop picture on all screens') parser.add_argument('--path', help='The path of the image') args = vars(parser.parse_args()) #already loggedin so we can skip any kind of security getusername = os.getlogin() #desktop_path = subprocess.check_output(['xdg-user-dir', 'DOCUMENTS']) #name of the file to be used. Store in the same folder as the script I recommend a nice one of hasselhoff file_name = 'background.jpg' #the directory where stuff will be copied tp directory_path = '/Users/' + getusername + '/Documents/' shutil.copy2(file_name, directory_path) #need th final picture path picture_path = '/Users/' + getusername + '/Documents/' + file_name # generate a fileURL for the desktop picture file_url = NSURL.fileURLWithPath_(picture_path) # make image options dictionary # we just make an empty one because the defaults are fine options = {} # 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)
def test_050_NSURL(self): """ GetURLResourceValuesForKeys """ url = NSURL.fileURLWithPath_("/") d1 = GetURLResourceValuesForKeys(url, [NSURLTotalFileSizeKey, NSURLContentModificationDateKey ]) self.assertEqual(d1[NSURLPathKey] , u'/') self.assertEqual(d1[NSFileSystemFolderNumber] , 1L) self.assertTrue(d1[NSURLIsDirectoryKey]) self.assertTrue(d1[NSURLIsVolumeKey]) self.assertEqual(d1[NSFileSystemFileNumber] , 2) # l = 'GetURLResourceValuesForKeys("")' # pdt(l, du, 28) url = NSURL.fileURLWithPath_("/Users/donb") d2 = GetURLResourceValuesForKeys(url, [NSURLTotalFileSizeKey, NSURLContentModificationDateKey ]) self.assertEqual( d2[NSURLPathKey] , u'/Users/donb' ) self.assertEqual( d2[NSFileSystemFolderNumber] , 48946 ) self.assertTrue( d2[NSURLIsDirectoryKey]) self.assertEqual( d2[NSURLTotalFileSizeKey], 0) self.assertTrue( d2[NSURLParentDirectoryURLKey], "file://localhost/Users/") self.assertFalse( d2[NSURLIsVolumeKey]) self.assertEqual( d2[NSFileSystemFileNumber] , 328394) # now with the full set of enumerator keys url = NSURL.fileURLWithPath_("/") d3 = GetURLResourceValuesForKeys(url, enumeratorURLKeys) self.assertEqual( d3[NSURLPathKey] ,u'/' ) self.assertEqual( d3[NSURLNameKey] , u'Genie' ) self.assertEqual( d3[NSFileSystemFolderNumber] , 1L ) self.assertTrue( d3[NSURLIsDirectoryKey]) self.assertEqual( d3[NSURLTotalFileSizeKey] , 0) with self.assertRaises(KeyError): # no NSURLVolumeURLKey for volume-level item d3[NSURLParentDirectoryURLKey] self.assertTrue( d3[NSURLIsVolumeKey]) self.assertEqual( d3[NSFileSystemFileNumber] , 2) self.assertEqual( d3[NSURLLocalizedTypeDescriptionKey] , u'Volume' ) self.assertEqual( d3[NSURLTypeIdentifierKey] , u'public.volume' ) # from Foundation import NSURLNameKey, NSURLTypeIdentifierKey d = {} for dk, fk in databaseAndURLKeys: if dk: if fk in [NSURLNameKey, NSURLTypeIdentifierKey]: d[dk] = d3[fk].encode('utf8') elif dk in ['file_create_date', 'file_mod_date']: d[dk] = str(d3[fk])[:-len(" +0000")] else: d[dk] = d3[fk] file1 = file_record( *(map (d.get , file_record_keys )) ) print file1 from dates import dateFormatters sa = dateFormatters[0]['df'].stringFromDate_(item_dict[NSURLContentModificationDateKey]) print sa pathname = item_dict["NSURLPathKey"] folder_id = item_dict['NSFileSystemFolderNumber'] filename = item_dict[NSURLNameKey] file_id = item_dict['NSFileSystemFileNumber'] # depth = i - n + 1 if options.verbose_level >= n: s = "%-12s %-8s %-7s %8d %8d %s %2d %s" % (l, itemsToDelete_repr(itemsToDelete), vol_id , folder_id, file_id, sa, depth, filename) print s # NSLog(s) vol_id = "vol0007" print "vol0007 42884672 42884713 Wed 2013.02.20 18:02 EST 2 __init__.py" , vol_id, file1.file_id
#!/usr/bin/python from AppKit import NSWorkspace, NSScreen from Foundation import NSURL import getpass network_user_path = "/Library/Desktop Pictures/network.jpg" ladmin_path = "/Library/Desktop Pictures/ladmin.jpg" luser_path = "/Library/Desktop Pictures/luser.jpg" # generate a fileURL nu_file_url = NSURL.fileURLWithPath_(network_user_path) la_file_url = NSURL.fileURLWithPath_(ladmin_path) lu_file_url = NSURL.fileURLWithPath_(luser_path) username=getpass.getuser() options = {} ws = NSWorkspace.sharedWorkspace() # next I should try and not hard code the user name but rather # check if she's local admin etc with dseditgroup -o checkmember -m $??? admin # have to use subprocess.check_output I guess. if username == 'opti': for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_( lu_file_url, screen, options, None) elif username == 'ri': for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_( la_file_url, screen, options, None) elif username == 'eleve':
def export_one(schema, filename, canvasname, format='pdf', force=False): def _checksum(filepath): assert os.path.isfile(filepath), '%s is not a file' % filepath c = hashlib.md5() with open(filepath, 'rb') as f: for chunk in iter(lambda: f.read(128), ''): c.update(chunk) return c.hexdigest() 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 chsum = None attrs = pdfdoc.documentAttributes() if PDFKit.PDFDocumentSubjectAttribute in attrs: chksum = pdfdoc.documentAttributes()[PDFKit.PDFDocumentSubjectAttribute] else: return None if not chksum.startswith(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE): return None else: return chksum[len(OmniGraffleSchema.PDF_CHECKSUM_ATTRIBUTE):] def _compute_canvas_checksum(canvasname): tmpfile = tempfile.mkstemp(suffix='.png')[1] os.unlink(tmpfile) export_one(schema, tmpfile, canvasname, 'png') try: chksum = _checksum(tmpfile) return chksum finally: os.unlink(tmpfile) # checksum chksum = None if os.path.isfile(filename) and not force: existing_chksum = _checksum(filename) if format != 'pdf' \ else _checksum_pdf(filename) new_chksum = _compute_canvas_checksum(canvasname) if existing_chksum == new_chksum and existing_chksum != None: logging.debug( 'Not exporting `%s` into `%s` as `%s` - canvas has not been changed' % (canvasname, filename, format)) return False else: chksum = new_chksum elif format == 'pdf': chksum = _compute_canvas_checksum(canvasname) try: schema.export(canvasname, filename, format=format) except RuntimeError as e: print >> sys.stderr, e.message return False # update checksum if format == 'pdf': # save the checksum url = NSURL.fileURLWithPath_(filename) 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_(filename) return True
def change_desktop_background(file): file_url = NSURL.fileURLWithPath_(file) ws = NSWorkspace.sharedWorkspace() for screen in NSScreen.screens(): (result, error) = ws.setDesktopImageURL_forScreen_options_error_(file_url, screen, {}, None)