def change_bundle_id(filename, new_bundle_id): keyToModify = 'CFBundleIdentifier' plist = NSMutableDictionary.dictionaryWithContentsOfFile_(filename) if plist != None and keyToModify in plist.allKeys(): plist[keyToModify] = new_bundle_id plist.writeToFile_atomically_(filename, 1)
def initialize(self): paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() paraStyle.setAlignment_(NSCenterTextAlignment) self.badgeAttributes = NSMutableDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(8), NSFontAttributeName, NSColor.whiteColor(), NSForegroundColorAttributeName, paraStyle, NSParagraphStyleAttributeName)
def fixSpotlight (): DISABLED_ITEMS=set(["MENU_WEBSEARCH", "MENU_SPOTLIGHT_SUGGESTIONS", "OTHER", "BOOKMARKS", "MESSAGES"]) REQUIRED_ITEM_KEYS=set(["enabled", "name"]) BUNDLE_ID="com.apple.Spotlight" PREF_NAME="orderedItems" DEFAULT_VALUE=[ {'enabled' : True, 'name' : 'APPLICATIONS'}, {'enabled' : False, 'name' : 'MENU_SPOTLIGHT_SUGGESTIONS'}, {'enabled' : True, 'name' : 'MENU_CONVERSION'}, {'enabled' : True, 'name' : 'MENU_EXPRESSION'}, {'enabled' : True, 'name' : 'MENU_DEFINITION'}, {'enabled' : True, 'name' : 'SYSTEM_PREFS'}, {'enabled' : True, 'name' : 'DOCUMENTS'}, {'enabled' : True, 'name' : 'DIRECTORIES'}, {'enabled' : True, 'name' : 'PRESENTATIONS'}, {'enabled' : True, 'name' : 'SPREADSHEETS'}, {'enabled' : True, 'name' : 'PDF'}, {'enabled' : False, 'name' : 'MESSAGES'}, {'enabled' : True, 'name' : 'CONTACT'}, {'enabled' : True, 'name' : 'EVENT_TODO'}, {'enabled' : True, 'name' : 'IMAGES'}, {'enabled' : False, 'name' : 'BOOKMARKS'}, {'enabled' : True, 'name' : 'MUSIC'}, {'enabled' : True, 'name' : 'MOVIES'}, {'enabled' : True, 'name' : 'FONTS'}, {'enabled' : False, 'name' : 'MENU_OTHER'}, {'enabled' : False, 'name' : 'MENU_WEBSEARCH'} ] items = CFPreferencesCopyValue(PREF_NAME, BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) newItems = None if items is None or len(items) is 0: # Actual preference values are populated on demand; if the user # hasn't previously configured Spotlight, the preference value # will be unavailable newItems = DEFAULT_VALUE else: newItems = NSMutableArray.new() for item in items: print item['name'] missing_keys = [] for key in REQUIRED_ITEM_KEYS: if not item.has_key(key): missing_keys.append(key) if len(missing_keys) != 0: print "Preference item %s is missing expected keys (%s), skipping" % (item, missing_keys) newItems.append(item) continue if item["name"] not in DISABLED_ITEMS: newItems.append(item) continue newItem = NSMutableDictionary.dictionaryWithDictionary_(item) newItem.setObject_forKey_(0, "enabled") newItems.append(newItem) CFPreferencesSetValue(PREF_NAME, newItems, BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) CFPreferencesSynchronize(BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
def write_keys(path, keys, test=False): """ Write key structure and its values to the given property list. If a key does not exist in the target plist, it is created as a dictionary by default. path An absolute path to a property list (.plist) file, including the extension keys A dict describing a structure and value(s) that should exist inside the target plist test If test is true, no changes will be written, but you will receive a dict containing the changes that would have been performed. """ dataObject = _read_plist(path) if dataObject is None: dataObject = NSMutableDictionary() changed = {} _set_objects_for_keys(dataObject, keys, changed) if test == False: _write_plist(dataObject, path) return changed
def write_key(path, key, nstype, value): ''' Write the value of a key contained within the Property List file specified. If the property list file does not exist, the default behaviour is to create it with the keys/values given. path An absolute path to a property list (.plist) file, including the extension key The path specification for the key to modify. A list of keys separated by a colon. nstype The value type to write, one of 'string', 'int', 'float', 'bool' value The property value. If not specified it will be set to an empty value. CLI Example: .. code-block:: bash salt '*' plist.write <path> <key> <nstype> [value] ''' dataObject = _readPlist(path) keys = key.split(':') if type(keys) is str: keys = list(keys) if dataObject is None: dataObject = NSMutableDictionary() _setObjectForKeyList(dataObject, keys, _valueToNSObject(value, nstype)) _writePlist(dataObject, path)
def renderDailyEntries(self, results): getFirstContactMatchingURI = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI self.dayly_entries = NSMutableArray.array() for result in results: display_name = None try: found_contact = self.contact_cache[result[2]] except KeyError: found_contact = getFirstContactMatchingURI(result[2], exact_match=True) self.contact_cache[result[2]] = found_contact if found_contact: display_name = found_contact.name remote_uri = '%s <%s>' % (display_name, result[2]) if '@' in result[2] else display_name else: try: display_name = self.display_name_cache[result[2]] except KeyError: remote_uri = result[2] else: remote_uri = '%s <%s>' % (display_name, result[2]) if '@' in result[2] else display_name entry = NSMutableDictionary.dictionaryWithObjectsAndKeys_(result[1], "local_uri", remote_uri, "remote_uri", result[2], "remote_uri_sql", result[0], 'date', result[3], 'type', display_name, "display_name") self.dayly_entries.addObject_(entry) self.dayly_entries.sortUsingDescriptors_(self.indexTable.sortDescriptors()) self.indexTable.reloadData() if self.search_uris and not self.dayly_entries: self.contactTable.deselectAll_(True)
def notification(title, subtitle, message, data=None, sound=True): """Send a notification to Notification Center (OS X 10.8+). If running on a version of macOS that does not support notifications, a ``RuntimeError`` will be raised. Apple says, "The userInfo content must be of reasonable serialized size (less than 1k) or an exception will be thrown." So don't do that! :param title: text in a larger font. :param subtitle: text in a smaller font below the `title`. :param message: text representing the body of the notification below the `subtitle`. :param data: will be passed to the application's "notification center" (see :func:`rumps.notifications`) when this notification is clicked. :param sound: whether the notification should make a noise when it arrives. """ if not _NOTIFICATIONS: raise RuntimeError('OS X 10.8+ is required to send notifications') if data is not None and not isinstance(data, Mapping): raise TypeError('notification data must be a mapping') _require_string_or_none(title, subtitle, message) notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(message) infoDict = NSMutableDictionary.alloc().init() infoDict.setDictionary_({} if data is None else data) notification.setUserInfo_(infoDict) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setDeliveryDate_(NSDate.dateWithTimeInterval_sinceDate_(0, NSDate.date())) notification_center = _default_user_notification_center() notification_center.scheduleNotification_(notification)
def _set_objects_for_keys(dict, keys, changed=None): """Set plist values using a given dict. Recursively finds or creates keys given and sets their values. This can be used to maintain a partial or complete override of any given property list file. Args: dict (NSMutableDictionary): The current dictionary being operated on. For a non existent file this will be blank. keys: A dict representing a hierarchy with leaf node values. """ if changed is None: changed = dict() for key, value in keys.items(): existing_value = dict.objectForKey_(key) if type(value) is dict: # Value unavailable, so create structure if existing_value is None: child = NSMutableDictionary() dict.setObject_forKey_(child, key) changed[key] = {} _set_objects_for_keys(child, value, changed[key]) else: if existing_value != value: dict.setObject_forKey_(value, key) changed[key] = value
def _setupPaths(self): ''' Read the path setting from ~/.pyupconfig ''' self.settingPath = PreferenceSetting.settingPath() settings = PreferenceSetting.load() self.data = NSMutableDictionary.dictionaryWithDictionary_(settings)
def _object_for_key_list(dict, keys, create=False): ''' Get an object inside a nested NSDictionary structure, using a list of keys to traverse. If create is true, then missing elements are automatically created as NSMutableDictionary objects. ''' key = keys.pop(0) # User accidentally supplies zero length key if len(key) == 0: return dict if len(keys) > 0: value = dict.objectForKey_(key) if value is None: if create: created = NSMutableDictionary() dict.setObject_forKey_(created, key) return _object_for_key_list(created, keys, create) else: # Just return None if path was not found log.debug('No key found in Property List: {0}'.format(key)) return None else: return _object_for_key_list(dict.objectForKey_(key), keys, create) else: # TODO: special case for array index notation [x] if current object is NSArray # if dict.isKindOfClass_(NSArray.class_()): # return return dict.objectForKey_(key)
def testFunctions(self): ref = SCPreferencesCreate(None, "pyobjc.test", "pyobjc.test") self.assertIsInstance(ref, SCPreferencesRef) r = SCPreferencesAddValue( ref, "use", NSMutableDictionary.dictionaryWithDictionary_({ "python2": True, "python3": False })) self.assertTrue(r) v = SCPreferencesPathCreateUniqueChild(ref, "/") self.assertIsInstance(v, unicode) v = SCPreferencesPathGetValue(ref, "/use") self.assertIsInstance(v, NSDictionary) v = SCPreferencesPathSetValue(ref, "/use", dict(python2=True, python3=True)) self.assertTrue(v is True) v = SCPreferencesPathSetLink(ref, "/use_python", "/use") self.assertTrue(v is True) v = SCPreferencesPathGetLink(ref, "/use_python") self.assertEqual(v, "/use") v = SCPreferencesPathRemoveValue(ref, "/use") self.assertTrue(v is True)
def notify( title: str, subtitle: str, info_text: str, delay: int = 0, sound: bool = False, user_info: Dict[str, str] = None, ) -> None: """ Python method to show a desktop notification on Mountain Lion. Where: title: Title of notification subtitle: Subtitle of notification info_text: Informative text of notification delay: Delay (in seconds) before showing the notification sound: Play the default notification sound userInfo: a dictionary that can be used to handle clicks in your app's applicationDidFinishLaunching:aNotification method """ notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(info_text) user_info = user_info or {} user_info = NSMutableDictionary.alloc().init().setDictionary_(user_info) notification.setUserInfo_(user_info) if sound: notification.setSoundName_("NSUserNotificationDefaultSoundName") center = NSUserNotificationCenter.defaultUserNotificationCenter() if center is not None: center.deliverNotification_(notification)
def testFunctions(self): ref = SCPreferencesCreate(None, "pyobjc.test", "pyobjc.test") self.assertIsInstance(ref, SCPreferencesRef) r = SCPreferencesAddValue(ref, "use", NSMutableDictionary.dictionaryWithDictionary_( { "python2": True, "python3": False })) self.assertTrue(r) v = SCPreferencesPathCreateUniqueChild(ref, "/") self.assertIsInstance(v, unicode) v = SCPreferencesPathGetValue(ref, "/use") self.assertIsInstance(v, NSDictionary) v = SCPreferencesPathSetValue(ref, "/use", dict(python2=True, python3=True)) self.assertTrue(v is True) v = SCPreferencesPathSetLink(ref, "/use_python", "/use") self.assertTrue(v is True) v = SCPreferencesPathGetLink(ref, "/use_python") self.assertEqual(v, "/use") v = SCPreferencesPathRemoveValue(ref, "/use") self.assertTrue(v is True)
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 createMovFile(fullfilepath): MEDIA_SPECS = [ ### specs in media header 'QTMovieCurrentSizeAttribute', 'QTMovieCreationTimeAttribute', 'QTMovieHasAudioAttribute', 'QTMovieHasVideoAttribute', 'QTMovieTimeScaleAttribute' ] TRACK_SPECS = [ ### specs in track header 'QTTrackDisplayNameAttribute', 'QTTrackBoundsAttribute', 'QTTrackFormatSummaryAttribute', 'QTTrackIDAttribute', 'QTTrackMediaTypeAttribute' ] attribs = NSMutableDictionary.dictionary() attribs['QTMovieFileNameAttribute'] = fullfilepath file = nbc.NBCFile(fullfilepath) mov, error = QTKit.QTMovie.alloc().initWithAttributes_error_( attribs, objc.nil) #init mov object if error: print error, file else: for track in mov.tracks(): #pull individual tracks try: tracktype = track.trackAttributes( )['QTTrackMediaTypeAttribute'] if (tracktype == TIMECODE): file.tctrack = track elif (tracktype == VIDEO): file.videotrack = track file.codec = 'PRH' #file.videotrack.trackAttributes()['QTTrackFormatSummaryAttribute'] #get codec elif (tracktype == AUDIO): file.audiotracks.append( track.trackAttributes()['QTTrackDisplayNameAttribute']) except KeyError, e: continue try: frameRate = mov.duration()[1] #set framerate duration = mov.duration()[0] # print frameRate #print duration durMinutes = duration / frameRate / 60 #get minutes of duration durSeconds = int( (round(duration / frameRate / 60.00, 2) - (duration / frameRate / 60)) * 60 ) #get seconds of duration(fraction of minutes multiplied by 60 to get actual seconds) #print durMinutes ##print durSeconds file.minutes = durMinutes file.seconds = durSeconds if ((frameRate == 2500) or (frameRate == 25)): file.timecode = 'E' if ((frameRate == 23976) or (frameRate == 24000)): file.timecode = 'P' if ((frameRate == 30000) or (frameRate == 2997)): file.timecode = 'D' except Exception, e: print e
def get_version(self, dry=False): info = Folder(self.app.path).child('Contents/Info.plist') if not File(info).exists: self.fail("InfoPlist not found at :" + info) from Foundation import NSMutableDictionary plist = NSMutableDictionary.dictionaryWithContentsOfFile_(info) self.app.build_version = plist['CFBundleVersion'] self.app.marketing_version = plist.get('CFBundleShortVersionString', self.app.build_version)
def initialize(self): paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() paraStyle.setAlignment_(NSCenterTextAlignment) self.badgeAttributes = NSMutableDictionary.dictionaryWithObjectsAndKeys_( NSFont.boldSystemFontOfSize_(8), NSFontAttributeName, NSColor.whiteColor(), NSForegroundColorAttributeName, paraStyle, NSParagraphStyleAttributeName)
def SetPathValue(self, path, value): """Sets the path value for a given path.""" base = os.path.basename(path) if not base: raise SysconfigError('Updating %s not permitted.' % path) tree = os.path.dirname(path) settings = SCPreferencesPathGetValue(self.session, tree) if not settings: settings = NSMutableDictionary.alloc().init() settings[base] = value SCPreferencesPathSetValue(self.session, tree, settings)
def userNotificationCenter_didActivateNotification_( self, center: NSUserNotificationCenter, notification: NSMutableDictionary) -> None: info = notification.userInfo() if info and "uuid" not in info: return notifications = self.manager.notification_service.get_notifications() if (info["uuid"] not in notifications or notifications[info["uuid"]].is_discard_on_trigger()): center.removeDeliveredNotification_(notification) self.manager.notification_service.trigger_notification(info["uuid"])
def _common_init(self): """_common_init""" self.userNS = NSMutableDictionary.dictionary() self.waitingForEngine = False self.lines = {} self.tabSpaces = 4 self.tabUsesSpaces = True self.currentBlockID = self.next_block_ID() self.blockRanges = {} # blockID=>CellBlock
def SetPlistKey(plist, key, value): """Sets the value for a given key in a plist. Args: plist: plist to operate on key: key to change value: value to set Returns: boolean: success Raises: MissingImportsError: if NSMutableDictionary is missing """ if NSMutableDictionary: mach_info = NSMutableDictionary.dictionaryWithContentsOfFile_(plist) if not mach_info: mach_info = NSMutableDictionary.alloc().init() mach_info[key] = value return mach_info.writeToFile_atomically_(plist, True) else: raise MissingImportsError('NSMutableDictionary not imported successfully.')
def increment_release_version(filename, version): keyToModify = 'CFBundleVersion' plist = NSMutableDictionary.dictionaryWithContentsOfFile_(filename) if keyToModify in plist.allKeys(): versionString = plist[keyToModify] versionList = versionString.split(".") versionList.append(version) versionString = ".".join(versionList) plist[keyToModify] = versionString plist.writeToFile_atomically_(filename, 1) return versionString
def _ns_update_attributed_title(self): if self._color: ns_button = self._ns_view ns_attrs = NSMutableDictionary.alloc().init() ns_attrs[NSFontAttributeName] = ns_button.font() ns_attrs[NSForegroundColorAttributeName] = self._color._ns_color ns_parstyle = NSMutableParagraphStyle.alloc().init() ns_parstyle.setAlignment_(ns_button.alignment()) ns_attrs[NSParagraphStyleAttributeName] = ns_parstyle ns_attstr = NSAttributedString.alloc().initWithString_attributes_( ns_button.title(), ns_attrs) ns_button.setAttributedTitle_(ns_attstr)
def modify_ncprefs_plist(key, value, item_index): # make an immutuble copy of the 'apps' array in ncprefs new_apps_array = NSMutableArray.alloc().initWithArray_(pl) # make a mutable copy of the target dict within the array new_dict = NSMutableDictionary.alloc().initWithDictionary_copyItems_( new_apps_array[item_index], True) # set the value new_dict[key] = value # replace the mutible dict within the mutable array new_apps_array.replaceObjectAtIndex_withObject_(item_index, new_dict) # replace the array in the ncprefs plist CFPreferencesSetAppValue("apps", new_apps_array, NCPREFS_PLIST)
def userNotificationCenter_didActivateNotification_( self, center: NSUserNotificationCenter, notification: NSMutableDictionary ) -> None: info = notification.userInfo() if info and "uuid" not in info: return notifications = self._manager.notification_service.get_notifications() if ( info["uuid"] not in notifications or notifications[info["uuid"]].is_discard_on_trigger() ): center.removeDeliveredNotification_(notification) self._manager.notification_service.trigger_notification(info["uuid"])
def getItemView(self): array = NSMutableArray.array() context = NSMutableDictionary.dictionary() context.setObject_forKey_(self, NSNibOwner) context.setObject_forKey_(array, NSNibTopLevelObjects) path = NSBundle.mainBundle().pathForResource_ofType_("AlertPanelView", "nib") if not NSBundle.loadNibFile_externalNameTable_withZone_(path, context, self.zone()): raise RuntimeError("Internal Error. Could not find AlertPanelView.nib") for obj in array: if isinstance(obj, NSBox): return obj else: raise RuntimeError("Internal Error. Could not find NSBox in AlertPanelView.nib")
def increment_development_version(filename, version): keyToModify = 'CFBundleShortVersionString' plist = NSMutableDictionary.dictionaryWithContentsOfFile_(filename) if keyToModify in plist.allKeys(): versionString = plist[keyToModify] versionList = versionString.split(".") lastVersionNumber = int(versionList[-1]) versionList.append(version) versionString = ".".join(versionList) plist[keyToModify] = versionString plist.writeToFile_atomically_(filename, 1) return versionString
def change_provisioning_profile(filename, build_conf_name, provisioning_profile): pbx_dict = NSMutableDictionary.dictionaryWithContentsOfFile_(filename) configurations = [x for x in pbx_dict['objects'] if pbx_dict['objects'][x]['isa'] == "XCBuildConfiguration" and pbx_dict['objects'][x]['name'] == "Release" and "PROVISIONING_PROFILE" in pbx_dict['objects'][x]['buildSettings'].allKeys()] profiles_to_replace = [] for config in configurations: profiles_to_replace.append(pbx_dict['objects'][config]['buildSettings']['PROVISIONING_PROFILE']) profiles_to_replace.append(pbx_dict['objects'][config]['buildSettings']['PROVISIONING_PROFILE[sdk=iphoneos*]']) for profile in profiles_to_replace: print "%s was replaced with %s in %s" % (profile, provisioning_profile, filename) replace(filename, profile, provisioning_profile)
def createMovFile(fullfilepath): MEDIA_SPECS = [ ### specs in media header 'QTMovieCurrentSizeAttribute', 'QTMovieCreationTimeAttribute', 'QTMovieHasAudioAttribute', 'QTMovieHasVideoAttribute', 'QTMovieTimeScaleAttribute'] TRACK_SPECS = [ ### specs in track header 'QTTrackDisplayNameAttribute', 'QTTrackBoundsAttribute', 'QTTrackFormatSummaryAttribute', 'QTTrackIDAttribute', 'QTTrackMediaTypeAttribute'] attribs = NSMutableDictionary.dictionary() attribs['QTMovieFileNameAttribute'] = fullfilepath file = nbc.NBCFile(fullfilepath) mov, error = QTKit.QTMovie.alloc().initWithAttributes_error_(attribs,objc.nil) #init mov object if error: print error, file else: for track in mov.tracks(): #pull individual tracks try: tracktype = track.trackAttributes()['QTTrackMediaTypeAttribute'] if (tracktype == TIMECODE): file.tctrack = track elif (tracktype == VIDEO): file.videotrack = track file.codec = 'PRH' #file.videotrack.trackAttributes()['QTTrackFormatSummaryAttribute'] #get codec elif (tracktype == AUDIO): file.audiotracks.append(track.trackAttributes()['QTTrackDisplayNameAttribute']) except KeyError, e: continue try: frameRate = mov.duration()[1] #set framerate duration = mov.duration()[0] # print frameRate #print duration durMinutes = duration/frameRate/60 #get minutes of duration durSeconds = int((round(duration/frameRate/60.00,2)-(duration/frameRate/60))*60) #get seconds of duration(fraction of minutes multiplied by 60 to get actual seconds) #print durMinutes ##print durSeconds file.minutes = durMinutes file.seconds = durSeconds if ((frameRate == 2500) or (frameRate == 25)): file.timecode = 'E' if ((frameRate == 23976) or (frameRate == 24000)): file.timecode = 'P' if ((frameRate == 30000) or (frameRate == 2997)): file.timecode = 'D' except Exception, e: print e
def printAttributes(self): #print out various attributes attribs = NSMutableDictionary.dictionary() attribs['QTMovieFileNameAttribute'] = self.filename mov, error = QTKit.QTMovie.alloc().initWithAttributes_error_(attribs,objc.nil) if error: print error else: print 'Duration:',mov.duration()[0]/mov.duration()[1]/60.0 for i in self.MEDIA_SPECS: print i,":", type(mov.movieAttributes()[i]) for i in mov.tracks(): for j in self.TRACK_SPECS: try: print i.trackAttributes()[j] except KeyError, e: continue
def printAttributes(self): #print out various attributes attribs = NSMutableDictionary.dictionary() attribs['QTMovieFileNameAttribute'] = self.filename mov, error = QTKit.QTMovie.alloc().initWithAttributes_error_( attribs, objc.nil) if error: print error else: print 'Duration:', mov.duration()[0] / mov.duration()[1] / 60.0 for i in self.MEDIA_SPECS: print i, ":", type(mov.movieAttributes()[i]) for i in mov.tracks(): for j in self.TRACK_SPECS: try: print i.trackAttributes()[j] except KeyError, e: continue
def SetProxy(self, enable=True, pac=CORP_PROXY): """Set proxy autoconfig.""" proxies = NSMutableDictionary.dictionaryWithDictionary_( self.ReadProxySettings()) logging.debug('initial proxy settings: %s', proxies) proxies['ProxyAutoConfigURLString'] = pac if enable: proxies['ProxyAutoConfigEnable'] = 1 else: proxies['ProxyAutoConfigEnable'] = 0 logging.debug('Setting ProxyAutoConfigURLString to %s and ' 'ProxyAutoConfigEnable to %s', pac, enable) result = SCDynamicStoreSetValue(self.store, 'State:/Network/Global/Proxies', proxies) logging.debug('final proxy settings: %s', self.ReadProxySettings()) return result
def get_file_urls_from_pasteboard(pasteboard, uti_type_filter=None): """Return the file NSURL objects in the pasteboard with an optional UTI type filter. :param NSPasteboard pasteboard: pasteboard :param uti_type_filter: a list of UTIs in string form :type uti_type_filter: list of Uniform Type Identifier strings :return: NSURL objects satisfying the UTI restriction (if any) :rtype: list of NSURL """ options = NSMutableDictionary.dictionaryWithCapacity_(2) options.setObject_forKey_(NSNumber.numberWithBool_(True), NSPasteboardURLReadingFileURLsOnlyKey) if uti_type_filter: options.setObject_forKey_( uti_type_filter, NSPasteboardURLReadingContentsConformToTypesKey) nsurls = pasteboard.readObjectsForClasses_options_([NSURL], options) return nsurls
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 saveSettings(self): ''' Save the path setting to setting file ''' jsonData = NSMutableDictionary.dictionaryWithDictionary_(self.data) paths = NSMutableArray.array() for directory in self.data['paths']: paths.addObject_(directory.directoryToDict()) jsonData['paths'] = paths data = NSJSONSerialization.dataWithJSONObject_options_error_( jsonData, 0, None) if len(data) > 0 and not data[0].writeToFile_atomically_( self.settingPath, True): alert = NSAlert.alertWithMessageText_defaultButton_alternateButton_otherButton_informativeTextWithFormat_( "Error", "Confirm", None, None, "Save setting failed.") alert.runModal() else: # Notify the app to reload settings self.callback(*self.args)
def write_key(path, key, nstype, value): ''' Write the value of a key contained within the Property List file specified. If the property list file does not exist, the default behaviour is to create it with the keys/values given. path An absolute path to a property list (.plist) file, including the extension key The path specification for the key to modify. A list of keys separated by a colon. nstype The value type to write, one of 'string', 'int', 'float', 'bool', 'data' value The property value. If not specified it will be set to an empty value. CLI Example: .. code-block:: bash salt '*' plist.write <path> <key> <nstype> [value] ''' log.debug('Reading original plist for modification at path: %s' % path) dataObject = _read_plist(path) log.debug('Deriving key hierarchy from colon separated string') keys = key.split(':') if type(keys) is str: keys = list(keys) if dataObject is None: dataObject = NSMutableDictionary() log.debug('Performing string to NSObject conversion') nsval = _value_to_nsobject(value, nstype) log.debug('Setting object value in hierarchy') _set_object_for_key_list(dataObject, keys, nsval) log.debug('Writing out plist to original path') _write_plist(dataObject, path)
def ModifyPlist( target_inf ): vardict = target_inf['vars'] filePath = vardict['xcodeplist_path'] print "\nModifying " + filePath plist = NSMutableDictionary.dictionaryWithContentsOfFile_( filePath ) plist['CFBundleDisplayName'] = vardict['name'] plist['CFBundleIdentifier'] = vardict['id'] plist['CFBundleVersion'] = vardict['version'] plist['CFBundleShortVersionString'] = vardict['major_version'] plist['UIViewControllerBasedStatusBarAppearance'] = False batch_config.ModifyPlist( plist, vardict['build_mode'] ) # save plist file plist.writeToFile_atomically_( filePath, 1 ) #print "-----------------------------------------------------------------" #os.system("cat " + filePath) #print "-----------------------------------------------------------------" return
def load(cls): ''' Load the all paths from setting file :return An array which contain all the directory model ''' settingPath = cls.settingPath() fm = NSFileManager.defaultManager() paths = NSMutableArray.array() settings = NSMutableDictionary.dictionary() if fm.fileExistsAtPath_isDirectory_(settingPath, None)[0]: settingFile = NSData.dataWithContentsOfFile_(settingPath) jsonData = NSJSONSerialization.JSONObjectWithData_options_error_( settingFile, 0, None)[0] settings['startup'] = jsonData['startup'] settings['api_key'] = jsonData['api_key'] for item in jsonData['paths']: directory = Directory.alloc().initWithDict_(item) paths.addObject_(directory) settings['paths'] = paths else: settings['startup'] = True settings['api_key'] = '' settings['paths'] = paths return settings
elif opt in ("-t", "--plist-app-title"): PLIST_APP_TITLE = arg elif opt in ("-s", "--plist-app-subtitle"): PLIST_APP_SUBTITLE = arg elif opt in ("-n", "--plist-name"): PLIST_NAME = arg elif opt in ("-i", "--bundle-ident-suffix"): PLIST_BUNDLE_IDENTIFIER_SUFFIX = arg from Foundation import NSMutableDictionary from Foundation import NSMutableArray if not PLIST_APPLICATION_INFO_LOCATION: print '[ERROR] Cannot find plist file %(PLIST_APPLICATION_INFO_LOCATION)' sys.exit(1) application_info = NSMutableDictionary.dictionaryWithContentsOfFile_(PLIST_APPLICATION_INFO_LOCATION) PLIST_BUNDLE_IDENTIFIER = application_info.objectForKey_('CFBundleIdentifier') if PLIST_BUNDLE_IDENTIFIER_SUFFIX != '': PLIST_BUNDLE_IDENTIFIER = PLIST_BUNDLE_IDENTIFIER + PLIST_BUNDLE_IDENTIFIER_SUFFIX PLIST_BUNDLE_VERSION = application_info.objectForKey_('CFBundleVersion') print '[DEBUG] Bundle identifier = %(PLIST_BUNDLE_IDENTIFIER)s' % vars() print '[DEBUG] Bundle version = %(PLIST_BUNDLE_VERSION)s' % vars() root = NSMutableDictionary.dictionary() items = NSMutableArray.array() root.setObject_forKey_(items,'items') main_item = NSMutableDictionary.dictionary() items.addObject_(main_item) assets = NSMutableArray.array()
def __init__(self): self.id = "com.apple.sidebarlists" self.favoriteservers = NSMutableDictionary.alloc().initWithDictionary_copyItems_(CoreFoundation.CFPreferencesCopyAppValue("favoriteservers", self.id), True) self.items = NSMutableArray.alloc().initWithArray_(self.favoriteservers["CustomListItems"] if self.favoriteservers.get("CustomListItems") else list()) self.labels = [item["Name"] for item in self.items]
NSURLBookmarkCreationMinimalBookmark, [], None, None) # check if the file exists already ls_prefs = os.path.join( NSHomeDirectory(), u'Library/Preferences/com.apple.LaunchServices/com.apple.LaunchServices') ls_prefs_plist = ls_prefs + u'.plist' if os.path.isfile(ls_prefs_plist): # read it in current_prefs = CFPreferencesCopyMultiple(None, ls_prefs, kCFPreferencesAnyUser, kCFPreferencesCurrentHost) else: # make a new dictionary current_prefs = NSMutableDictionary() # Get any existing key or a new blank dict if not present magnified = current_prefs.get(u'LSHighResolutionModeIsMagnified', NSMutableDictionary()) magnified_editable = NSMutableDictionary.dictionaryWithDictionary_(magnified) # Build our values options = NSMutableArray.alloc().init() options.append(bookmark) # A value of 3 = enabled, value of 2 = disabled options.append(3) magnified_editable[lowres_app_id] = options # Update the setting update_dict = NSMutableDictionary() update_dict[u'LSHighResolutionModeIsMagnified'] = magnified_editable
def fixSpotlight(): DISABLED_ITEMS = set(["MENU_WEBSEARCH", "MENU_SPOTLIGHT_SUGGESTIONS"]) REQUIRED_ITEM_KEYS = set(["enabled", "name"]) BUNDLE_ID = "com.apple.Spotlight" PREF_NAME = "orderedItems" DEFAULT_VALUE = [{ 'enabled': True, 'name': 'APPLICATIONS' }, { 'enabled': False, 'name': 'MENU_SPOTLIGHT_SUGGESTIONS' }, { 'enabled': True, 'name': 'MENU_CONVERSION' }, { 'enabled': True, 'name': 'MENU_EXPRESSION' }, { 'enabled': True, 'name': 'MENU_DEFINITION' }, { 'enabled': True, 'name': 'SYSTEM_PREFS' }, { 'enabled': True, 'name': 'DOCUMENTS' }, { 'enabled': True, 'name': 'DIRECTORIES' }, { 'enabled': True, 'name': 'PRESENTATIONS' }, { 'enabled': True, 'name': 'SPREADSHEETS' }, { 'enabled': True, 'name': 'PDF' }, { 'enabled': True, 'name': 'MESSAGES' }, { 'enabled': True, 'name': 'CONTACT' }, { 'enabled': True, 'name': 'EVENT_TODO' }, { 'enabled': True, 'name': 'IMAGES' }, { 'enabled': True, 'name': 'BOOKMARKS' }, { 'enabled': True, 'name': 'MUSIC' }, { 'enabled': True, 'name': 'MOVIES' }, { 'enabled': True, 'name': 'FONTS' }, { 'enabled': True, 'name': 'MENU_OTHER' }, { 'enabled': False, 'name': 'MENU_WEBSEARCH' }] items = CFPreferencesCopyValue(PREF_NAME, BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) newItems = None if items is None or len(items) is 0: # Actual preference values are populated on demand; if the user # hasn't previously configured Spotlight, the preference value # will be unavailable newItems = DEFAULT_VALUE else: newItems = NSMutableArray.new() for item in items: missing_keys = [] for key in REQUIRED_ITEM_KEYS: if not item.has_key(key): missing_keys.append(key) if len(missing_keys) != 0: print "Preference item %s is missing expected keys (%s), skipping" % ( item, missing_keys) newItems.append(item) continue if item["name"] not in DISABLED_ITEMS: newItems.append(item) continue newItem = NSMutableDictionary.dictionaryWithDictionary_(item) newItem.setObject_forKey_(0, "enabled") newItems.append(newItem) CFPreferencesSetValue(PREF_NAME, newItems, BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost) CFPreferencesSynchronize(BUNDLE_ID, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
def AxisMapperMain(self, sender=None): try: # clear macro window log: Glyphs.clearLog() # update settings to the latest user input: if not self.SavePreferences(): print("Note: 'Axis Mapper' could not write preferences.") thisFont = Glyphs.font # frontmost font if thisFont is None: Message( title="No Font Open", message= "The script requires a font. Open a font and run the script again.", OKButton=None) else: print("Axis Mapper Report for %s" % thisFont.familyName) if thisFont.filepath: print(thisFont.filepath) else: print("⚠️ The font file has not been saved yet.") print() minValue = float( Glyphs.defaults["com.mekkablue.AxisMapper.minValue"]) maxValue = float( Glyphs.defaults["com.mekkablue.AxisMapper.maxValue"]) mappingRecipe = Glyphs.defaults[ "com.mekkablue.AxisMapper.mappingRecipe"] axisTag = Glyphs.defaults[ "com.mekkablue.AxisMapper.axisPicker"] print("🔠 Building Mapping for: %s" % axisTag) axisMapping = NSMutableDictionary.alloc().init() # axis extremes must be there: nativeLow, nativeHigh = extremeMasterValuesNative( thisFont, axisTag=axisTag) for masterExtreme in (nativeLow, nativeHigh): axisMapping.addObject_forKey_(masterExtreme, masterExtreme) print("✅ Added axis extremes to mapping: %i→%i, %i→%i" % (nativeLow, nativeLow, nativeHigh, nativeHigh)) # process line for line in mappingRecipe.splitlines(): if "#" in line: line = line[:line.find("#")] if "->" in line: line = line.strip() userValue, targetValue = [ float(v.strip()) for v in line.split("->") ] userCoeff = coefficient(userValue, minValue, maxValue) targetCoeff = coefficient(targetValue, minValue, maxValue) nativeUserValue = valueForCoefficient( userCoeff, nativeLow, nativeHigh) nativeTargetValue = valueForCoefficient( targetCoeff, nativeLow, nativeHigh) axisMapping.addObject_forKey_(nativeTargetValue, nativeUserValue) print("✅ Translating %i→%i to %i→%i" % (userValue, targetValue, nativeUserValue, nativeTargetValue)) parameterName = "Axis Mappings" mappings = Font.customParameters[parameterName] if not mappings: print("🙌 Adding new %s parameter" % parameterName) mappings = NSMutableDictionary.alloc( ).initWithObject_forKey_(axisMapping, "wght") mappings.addObject_forKey_(axisMapping, axisTag) else: print("🧩 Inserting %s mapping into existing %s parameter" % (axisTag, parameterName)) mappings.setObject_forKey_(axisMapping, axisTag) thisFont.customParameters[parameterName] = mappings # Final report: Glyphs.showNotification( "‘%s’ mapping for %s" % (axisTag, thisFont.familyName), "Inserted ‘%s’ mapping with %i entries. Details in Macro Window" % (axisTag, len(axisMapping.allKeys())), ) print("\nDone.") except Exception as e: # brings macro window to front and reports error: Glyphs.showMacroWindow() print("Axis Mapper Error: %s" % e) import traceback print(traceback.format_exc())
'a replacement items list. ' 'Is this OS version supported?') # Update entries that already exist for item in items: replace = item.valueForKey_('replace') if importedData.has_key(replace): importedItem = importedData[replace] item.setObject_forKey_(importedItem['enabled'], 'on') item.setObject_forKey_(importedItem['replacement'], 'with') del importedData[replace] updated += 1 # Add new entries for key, importedItem in importedData.iteritems(): item = NSMutableDictionary.dictionary() item.setObject_forKey_(importedItem['enabled'], 'on') item.setObject_forKey_(key, 'replace') item.setObject_forKey_(importedItem['replacement'], 'with') items.addObject_(item) added += 1 # Update the preferences prefs.setPersistentDomain_forName_(globalPrefs, '.GlobalPreferences') prefs.synchronize() # Release the preferences from memory NSUserDefaults.resetStandardUserDefaults() # Build notification userInfo object userInfo = {}
def createMovFile(fullfilepath): MEDIA_SPECS = [ ### specs in media header 'QTMovieCurrentSizeAttribute', 'QTMovieCreationTimeAttribute', 'QTMovieHasAudioAttribute', 'QTMovieHasVideoAttribute', 'QTMovieTimeScaleAttribute'] TRACK_SPECS = [ ### specs in track header 'QTTrackDisplayNameAttribute', 'QTTrackBoundsAttribute', 'QTTrackFormatSummaryAttribute', 'QTTrackIDAttribute', 'QTTrackMediaTypeAttribute'] attribs = NSMutableDictionary.dictionary() attribs['QTMovieFileNameAttribute'] = fullfilepath file = nbc.NBCFile(fullfilepath) mov, error = QTKit.QTMovie.alloc().initWithAttributes_error_(attribs,objc.nil) #init mov object if error: print error else: for track in mov.tracks(): #pull individual tracks try: tracktype = track.trackAttributes()['QTTrackMediaTypeAttribute'] if (tracktype == TIMECODE): file.tctrack = track elif (tracktype == VIDEO): file.videotrack = track file.codec = 'PRH' #file.videotrack.trackAttributes()['QTTrackFormatSummaryAttribute'] #get codec elif (tracktype == AUDIO): file.audiotracks.append(track.trackAttributes()['QTTrackDisplayNameAttribute']) except KeyError, e: continue frameRate = mov.duration()[1] #set framerate duration = mov.duration()[0] print frameRate #print duration durMinutes = duration/frameRate/60 #get minutes of duration durSeconds = int((round(duration/frameRate/60.00,2)-(duration/frameRate/60))*60) #get seconds of duration(fraction of minutes multiplied by 60 to get actual seconds) #print durMinutes ##print durSeconds file.minutes = durMinutes file.seconds = durSeconds if ((frameRate == 2500) or (frameRate == 25)): file.timecode = 'E' if (frameRate == 23976): file.timecode = 'P' if (frameRate == 30000): file.timecode = 'D' if (file.videotrack.currentSize().height > 1050 and file.videotrack.currentSize().height < 1110): #set standard with height if (file.timecode == 'P'): file.standard = 3 #MVIS CODES: 3 - 1080-2398 if (file.timecode == 'E'): file.standard = 2 #... 2 - 1080 50i if (file.timecode == 'D'): file.standard = 1 #... 1 - 1080 5994i elif (file.videotrack.currentSize().height > 470 and file.videotrack.currentSize().height < 490): file.standard = 'N' #... N - NTSC elif (file.videotrack.currentSize().height > 560 and file.videotrack.currentSize().height < 590): file.standard = 'P' #... P - PAL else: file.standard = None
def export(self, canvasname, filename, format='pdf', force=False): """ Exports one canvas named {@code canvasname} """ # canvas name if not canvasname or len(canvasname) == 0: raise Exception('canvasname is missing') logging.debug('Exporting canvas: %s ' % canvasname) # format if not format or len(format) == 0: format = 'pdf' else: format = format.lower() if format not in OmniGraffleSchema.EXPORT_FORMATS: raise Exception('Unknown format: %s' % format) logging.debug('Exporting into format: %s ' % format) filename = os.path.abspath(filename) # suffix if filename[filename.rfind('.')+1:].lower() != format: filename = '%s.%s' % (filename, format) logging.debug('Exporting into: %s ' % filename) # checksum chksum = None if os.path.isfile(filename) and not force: existing_chksum = checksum(filename) if format != 'pdf' \ else checksum_pdf(filename) 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) if self._export_internal(canvasname, filename, format): if self.verbose: print "%s" % filename else: print >> sys.stderr, 'Failed to export canvas: %s to %s' % \ (canvasname, filename) # 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
pass from Foundation import NSMutableDictionary if os.environ["CONFIGURATION"] == "Development": status, output = commands.getstatusoutput("bash -l -c 'LANGUAGE=C svn info'") if status != 0: sys.exit(status) for line in output.split("\n"): if len(line.strip()) == 0 or ":" not in line: continue key, value = [x.lower().strip() for x in line.split(":", 1)] if key == "revision": revision = "svn" + value break else: revision = time.strftime("%Y%m%d") revision="1.0.0.20110909" buildDir = os.environ["BUILT_PRODUCTS_DIR"] infoFile = os.environ["INFOPLIST_PATH"] path = os.path.join(buildDir, infoFile) plist = NSMutableDictionary.dictionaryWithContentsOfFile_(path) version = open("version.txt").read().strip() % {"extra": revision} print "Updating versions:", infoFile, version plist["CFBundleShortVersionString"] = version plist["CFBundleGetInfoString"] = version plist["CFBundleVersion"] = version plist.writeToFile_atomically_(path, 1)
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 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
import os import csv from subprocess import Popen, PIPE from Foundation import NSMutableDictionary build_number = os.popen4("git rev-parse --short HEAD")[1].read() info_plist = os.environ['BUILT_PRODUCTS_DIR'] + "/" + os.environ[ 'WRAPPER_NAME'] + "/Info.plist" # Open the plist and write the short commit hash as the bundle version plist = NSMutableDictionary.dictionaryWithContentsOfFile_(info_plist) core_version = csv.reader([plist['CFBundleVersion'].rstrip()], delimiter=" ").next()[0] full_version = ''.join([core_version, ' build ', build_number]) plist['CFBundleVersion'] = full_version.rstrip() plist.writeToFile_atomically_(info_plist, 1)
# "Negative": "NEGA" # } # # newParam = GSCustomParameter.alloc().init() # # font.addCustomParameter_(newParam) # # font.addCustomParameter_("Axes") # # add them to the font # font.setCustomParameter_forKey_(fontAxes, "Axes") # print(font.customParameterForKey_("Axes")) from Foundation import NSMutableDictionary, NSMutableArray fontAxes = NSMutableArray.arrayWithArray_([ NSMutableDictionary.dictionaryWithDictionary_({ "Name": "Weight", "Tag": "wght" }), NSMutableDictionary.dictionaryWithDictionary_({ "Name": "Negative", "Tag": "NEGA" }) ]) font.setCustomParameter_forKey_(fontAxes, "Axes") # ============================================================================ # remove old masters ========================================================= # just do it twice for now to delete original two – would need more flexibility to be abstracted to other fonts font.removeFontMasterAtIndex_(0) font.removeFontMasterAtIndex_(0)
# -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__ = """ Inserts (or resets) a default Axis Mappings parameter for all style values currently present in the font. Ignores style values outside the designspace bounds defined by the masters. """ from Foundation import NSMutableDictionary from axisMethods import * if Glyphs.versionNumber < 3.0: Message(title="Glyphs Version Error", message="This script requires Glyphs 3.0 or later.", OKButton=None) # return mappings = NSMutableDictionary.alloc().init() font = Glyphs.font for axis in font.axes: axisTag = axis.axisTag minAxisPos, maxAxisPos = extremeMasterValuesNative(font, axisTag=axisTag) # add axis extremes: axisMapping = NSMutableDictionary.alloc().init() for masterExtreme in nativeMasterExtremes: axisMapping.addObject_forKey_(masterExtreme, masterExtreme) # add style positions for style in font.instances: styleValue = styleValueForAxisTag(style, axisTag) if minAxisPos < styleValue < maxAxisPos: axisMapping.addObject_forKey_(styleValue, styleValue)