def makeDragImage(self): if self.delegate is None: return image = NSImage.alloc().initWithSize_(self.frame().size) image.lockFocus() frame = self.frame() frame.origin = NSZeroPoint rect = NSInsetRect(frame, 1.5, 1.5) if self.conferencing and not self.draggedOut: NSColor.selectedControlColor().colorWithAlphaComponent_(0.7).set() else: NSColor.whiteColor().colorWithAlphaComponent_(0.7).set() path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(rect, 5.0, 5.0) path.fill() if self.selected: path.setLineWidth_(3) NSColor.grayColor().set() else: path.setLineWidth_(1) NSColor.grayColor().set() path.stroke() NSColor.blackColor().set() point = NSMakePoint(8, NSMaxY(frame)-20) uri = format_identity_to_string(self.delegate.sessionController.remotePartyObject, check_contact=False, format='compact') NSString.stringWithString_(uri).drawAtPoint_withAttributes_(point, NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.boldSystemFontOfSize_(12), NSFontAttributeName)) point = NSMakePoint(8, 6) if self.conferencing: NSString.stringWithString_(NSLocalizedString("Drop outside to remove from conference", "Audio session label")).drawAtPoint_withAttributes_(point, NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName)) else: audio_sessions = [sess.hasStreamOfType("audio") for sess in NSApp.delegate().contactsWindowController.sessionControllersManager.sessionControllers] if self.delegate.transferEnabled: text = NSLocalizedString("Drop this over a session or contact", "Audio session label") if len(audio_sessions) > 1 else NSLocalizedString("Drop this over a contact to transfer", "Audio session label") else: text = NSLocalizedString("Drop this over a session to conference", "Audio session label") NSString.stringWithString_(text).drawAtPoint_withAttributes_(point, NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(10), NSFontAttributeName)) icon = NSImage.imageNamed_("NSEveryone") rect = frame s = icon.size() p = NSMakePoint(NSWidth(rect) - s.width - 8, rect.size.height - s.height - 8) r = NSMakeRect(0, 0, s.width, s.height) icon.drawAtPoint_fromRect_operation_fraction_(p, r, NSCompositeSourceOver, 0.5) image.unlockFocus() return image
class ConferenceFileCell(NSTextFieldCell): conference_file = None nameAttrs = NSDictionary.dictionaryWithObjectsAndKeys_( NSFont.systemFontOfSize_(12.0), NSFontAttributeName) nameAttrs_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_( NSFont.systemFontOfSize_(12.0), NSFontAttributeName, NSColor.whiteColor(), NSForegroundColorAttributeName) infoAttrs = NSDictionary.dictionaryWithObjectsAndKeys_( NSFont.systemFontOfSize_(NSFont.labelFontSize()-1), NSFontAttributeName, NSColor.grayColor(), NSForegroundColorAttributeName) infoAttrs_highlighted = NSDictionary.dictionaryWithObjectsAndKeys_( NSFont.systemFontOfSize_(NSFont.labelFontSize()-1), NSFontAttributeName, NSColor.whiteColor(), NSForegroundColorAttributeName) def drawingRectForBounds_(self, rect): return rect @objc.python_method def cellSize(self): if self.conference_file is None: return objc.super(ConferenceFileCell, self).cellSize() return NSMakeSize(100, 30) def drawWithFrame_inView_(self, frame, view): if self.conference_file is None: tmp = frame return objc.super(ConferenceFileCell, self).drawWithFrame_inView_(tmp, view) self.drawIcon(self.conference_file.icon, 2, frame.origin.y+3, 28, 28) # 1st line: file name frame.origin.x = 35 frame.origin.y += 2 attrs = self.nameAttrs if not self.isHighlighted() else self.nameAttrs_highlighted self.conference_file.name.drawAtPoint_withAttributes_(frame.origin, attrs) # 2nd line: file sender point = frame.origin point.y += 15 attrs = self.infoAttrs if not self.isHighlighted() else self.infoAttrs_highlighted self.conference_file.sender.drawAtPoint_withAttributes_(point, attrs) @objc.python_method def drawIcon(self, icon, origin_x, origin_y, size_x, size_y): size = icon.size() rect = NSMakeRect(0, 0, size.width, size.height) trect = NSMakeRect(origin_x, origin_y, (size_y/size.height) * size.width, size_x) icon.drawInRect_fromRect_operation_fraction_respectFlipped_hints_(trect, rect, NSCompositeSourceOver, 1.0, True, None)
def centralManager_didDiscoverPeripheral_advertisementData_RSSI_( self, central: CBCentralManager, peripheral: CBPeripheral, advertisementData: NSDictionary, RSSI: NSNumber, ): # Note: this function might be called several times for same device. # Example a first time with the following keys in advertisementData: # ['kCBAdvDataLocalName', 'kCBAdvDataIsConnectable', 'kCBAdvDataChannel'] # ... and later a second time with other keys (and values) such as: # ['kCBAdvDataServiceUUIDs', 'kCBAdvDataIsConnectable', 'kCBAdvDataChannel'] # # i.e it is best not to trust advertisementData for later use and data # from it should be copied. # # This behaviour could be affected by the # CBCentralManagerScanOptionAllowDuplicatesKey global setting. uuid_string = peripheral.identifier().UUIDString() if uuid_string in self.devices: device = self.devices[uuid_string] else: address = uuid_string name = peripheral.name() or None details = peripheral device = BLEDeviceCoreBluetooth(address, name, details) self.devices[uuid_string] = device device._rssi = float(RSSI) device._update(advertisementData) logger.debug("Discovered device {}: {} @ RSSI: {} (kCBAdvData {})".format( uuid_string, device.name, RSSI, advertisementData.keys()))
def read_aae_file(path): plist = NSDictionary.dictionaryWithContentsOfFile_(path) if plist["adjustmentFormatIdentifier"] != "com.apple.photo": print "-- bad format identifier:", plist["adjustmentFormatIdentifier"] return None, None data = plist["adjustmentData"] d = ipaPASS.archiveFromData_error_(data, None) adjustments = d["adjustments"] orientation = d["metadata"]["orientation"] effect_names = [ d_["settings"]["effectName"] for d_ in d["adjustments"] if d_["identifier"] == "Effect"] if len(effect_names) == 0: print "-- no effect name" return None, None filter_name = "CIPhotoEffect" + effect_names[0] print "-- filter:", filter_name return filter_name, orientation
def loadGlyphsInfo(): try: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace( ).URLForApplicationWithBundleIdentifier_( "com.schriftgestaltung.GlyphsMini") GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: GlyphsInfoPath = GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" WeightCodesPath = GlyphsPath + "/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/weights.plist" parseGlyphDataFile(GlyphsInfoPath) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_( "/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath) global weightCodes weightCodes = NSDictionary.alloc().initWithContentsOfFile_(WeightCodesPath)
def init(self): self = objc.super(NotificationManager, self).init() self.notification_center = NSUserNotificationCenter.defaultUserNotificationCenter( ) self.notification_center.setDelegate_(self) myDict = NSDictionary.dictionary() return self
def readGlyphsFile(filePath): print "Import Glyphs File" pool = NSAutoreleasePool.alloc().init() GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath) loadGlyphsInfo() from FL import fl, Font folder, base = os.path.split(filePath) base = base.replace(".glyphs", ".vfb") dest = os.path.join(folder, base) f = Font() fl.Add(f) global convertName try: convertName = GlyphsDoc["disablesNiceNames"] != None except: pass if not setFontInfo(f, GlyphsDoc): return False readGlyphs(f, GlyphsDoc) readKerning(f, GlyphsDoc) setLegacyNames(f) readFeatures(f, GlyphsDoc) fl.UpdateFont() f.modified = 0 pool.drain()
def readGlyphsFile(filePath): print "Import Glyphs File" pool = NSAutoreleasePool.alloc().init() GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath) if GlyphsDoc is None: print "Could not load .glyphs file." pool.drain() return loadGlyphsInfo() from FL import fl, Font folder, base = os.path.split(filePath) base = base.replace(".glyphs", ".vfb") dest = os.path.join(folder, base) f = Font( ) fl.Add(f) global convertName try: convertName = GlyphsDoc["disablesNiceNames"] != None except: pass if not setFontInfo(f, GlyphsDoc): return False readGlyphs(f, GlyphsDoc) readKerning(f, GlyphsDoc) setLegacyNames(f) readFeatures(f, GlyphsDoc) fl.UpdateFont() f.modified = 0 pool.drain()
def GetAppInfo(self, user_info): """Grabs the application info from the user_info dictionary. Args: user_info: dictionary of application info Returns: tuple of bundle_id, app_version, app_path """ bundle_id, app_version, app_path = None, None, None try: bundle_id = user_info['NSApplicationBundleIdentifier'] except KeyError: # Malformed applications may not have NSApplicationBundleIdentifier # Return NSApplicationName instead logging.error('Error reading bundle identifier: %s', user_info) bundle_id = user_info['NSApplicationName'] try: app_path = user_info['NSApplicationPath'] except KeyError: # Malformed applications may not have NSApplicationPath logging.error('Error reading application path: %s', user_info) if app_path: try: app_info_plist = NSDictionary.dictionaryWithContentsOfFile_( '%s/Contents/Info.plist' % app_path) if app_info_plist: app_version = app_info_plist['CFBundleVersion'] except KeyError: logging.error('Error reading application version from %s', app_path) return bundle_id, app_version, app_path
def _submit_job(job_dict): """Call SMJobSubmit to submit a launchd job description. No return""" authref = __salt__['authorization.create'](kSMRightModifySystemDaemons) error = CFErrorRef() log.debug(job_dict) job_dict_p = NSDictionary(job_dict) domain = CFStringCreateWithCString(None, kSMDomainSystemLaunchd, kCFStringEncodingUTF8) ok = SMJobSubmit(domain, byref(job_dict_p), authref, byref(error)) if not ok: error_desc = NSString() error_desc = CFErrorCopyDescription(error) log.error(error_desc) #raise DaemonInstallException("SMJobSubmit error (see above)") __salt__['authorization.free'](authref) return ok
def __init__(self): """Create a new Preferences object from the current settings. Examples: >>> preferences = Preferences() >>> keys = ['latexViewer', 'latexEngine', 'latexUselatexmk', ... 'latexVerbose', 'latexDebug', 'latexAutoView', ... 'latexKeepLogWin', 'latexEngineOptions'] >>> all([key in preferences.prefs for key in keys]) True """ tm_preference_file = ('{}.plist'.format(environ['TM_APP_IDENTIFIER']) if 'TM_APP_IDENTIFIER' in environ else 'com.macromates.textmate.plist') self.default_values = { 'latexAutoView': 1, 'latexEngine': "pdflatex", 'latexEngineOptions': "", 'latexVerbose': 0, 'latexUselatexmk': 0, 'latexViewer': "TextMate", 'latexKeepLogWin': 1, 'latexDebug': 0, } self.prefs = self.default_values.copy() tm_prefs = NSDictionary.dictionaryWithContentsOfFile_( "{}/Library/Preferences/{}".format(environ["HOME"], tm_preference_file)) # Only save the values we really need for key in self.prefs: if key in tm_prefs: self.prefs[key] = tm_prefs[key]
def loadGlyphsInfo(): try: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs2") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.GeorgSeifert.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.Glyphs") if GlyphsPath is None: GlyphsPath = NSWorkspace.sharedWorkspace().URLForApplicationWithBundleIdentifier_("com.schriftgestaltung.GlyphsMini") GlyphsPath = GlyphsPath.path() except: return if GlyphsPath is not None: GlyphsInfoPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/GlyphData.xml" WeightCodesPath = GlyphsPath+"/Contents/Frameworks/GlyphsCore.framework/Versions/A/Resources/weights.plist" parseGlyphDataFile(GlyphsInfoPath) CustomGlyphsInfoPath = applicationSupportFolder() if CustomGlyphsInfoPath: CustomGlyphsInfoPath = CustomGlyphsInfoPath.stringByAppendingPathComponent_("/Info/GlyphData.xml") if os.path.isfile(CustomGlyphsInfoPath): parseGlyphDataFile(CustomGlyphsInfoPath) global weightCodes weightCodes = NSDictionary.alloc().initWithContentsOfFile_(WeightCodesPath)
def awakeFromNib(self): smileys = SmileyManager().get_smiley_list() menu = self.smileyButton.menu() while menu.numberOfItems() > 0: menu.removeItemAtIndex_(0) bigText = NSAttributedString.alloc().initWithString_attributes_( " ", NSDictionary.dictionaryWithObject_forKey_( NSFont.systemFontOfSize_(16), NSFontAttributeName)) for text, file in smileys: image = NSImage.alloc().initWithContentsOfFile_(file) if not image: print("cant load %s" % file) continue image.setScalesWhenResized_(True) image.setSize_(NSMakeSize(16, 16)) atext = bigText.mutableCopy() atext.appendAttributedString_( NSAttributedString.alloc().initWithString_(text)) item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_( text, "insertSmiley:", "") menu.addItem_(item) item.setTarget_(self) item.setAttributedTitle_(atext) item.setRepresentedObject_( NSAttributedString.alloc().initWithString_(text)) item.setImage_(image)
def rename_project(project_dir, new_project_name, bundle_id): search_string = "find %s -name *.xcodeproj" % project_dir name_to_change = os.popen(search_string).readlines()[0].rstrip().split("/")[-1].split(".")[0] project_directories = os.walk( project_dir ) # [y for x in os.walk(project_dir) for y in glob(os.path.join(x[0], ''))] for directory in project_directories: if "git" in directory[0]: continue expression = re.compile(re.escape(name_to_change), re.IGNORECASE) new_directory = expression.sub(new_project_name, directory[0]) print "creating %s" % new_directory os.makedirs(new_directory) files = [os.path.join(directory[0], x) for x in directory[2]] for dir_file in files: new_filename = expression.sub(new_project_name, dir_file) shutil.copyfile(dir_file, new_filename) replace_all(new_filename, name_to_change, new_project_name) plist_files = os.popen("find %s -name *Info.plist" % project_dir) for plist_file in plist_files: plist_file = plist_file.rstrip() plist = NSDictionary.dictionaryWithContentsOfFile_(plist_file) plist["CFBundleIdentifier"] = bundle_id plist.writeToFile_atomically_(plist_file, True)
def open_app_at_startup(enabled=True): """ This function adds/removes the current app bundle from Login items in macOS """ if sys.platform == 'darwin': from Foundation import NSDictionary from Cocoa import NSBundle, NSURL from CoreFoundation import kCFAllocatorDefault # CF = CDLL(find_library('CoreFoundation')) from LaunchServices import (LSSharedFileListCreate, kLSSharedFileListSessionLoginItems, LSSharedFileListInsertItemURL, kLSSharedFileListItemHidden, kLSSharedFileListItemLast, LSSharedFileListItemRemove) app_path = NSBundle.mainBundle().bundlePath() url = NSURL.alloc().initFileURLWithPath_(app_path) login_items = LSSharedFileListCreate( kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None) props = NSDictionary.dictionaryWithObject_forKey_( True, kLSSharedFileListItemHidden) new_item = LSSharedFileListInsertItemURL(login_items, kLSSharedFileListItemLast, None, None, url, props, None) if not enabled: LSSharedFileListItemRemove(login_items, new_item)
def notify(title, subtitle, text, bundleid=None, url=None): if bundleid: # fake our bundleid set_fake_bundleid(bundleid) # create a new user notification notification = NSUserNotification.alloc().init() notification.setTitle_(title) notification.setSubtitle_(subtitle) notification.setInformativeText_(text) if url: userInfo = NSDictionary.dictionaryWithDictionary_({ 'action': u'open_url', 'value': unicode(url) }) notification.setUserInfo_(userInfo) notification.setHasActionButton_(True) notification.setActionButtonTitle_('Details') # get the default User Notification Center nc = NSUserNotificationCenter.defaultUserNotificationCenter() # create a delegate object that implements our delegate methods my_delegate = NotificationCenterDelegate.alloc().init() nc.setDelegate_(my_delegate) nc.removeAllDeliveredNotifications() # deliver the notification nc.deliverNotification_(notification) # keep running until the notification is activated while (my_delegate.keepRunning): NSRunLoop.currentRunLoop().runUntilDate_( NSDate.dateWithTimeIntervalSinceNow_(0.1))
def _update_manufacturer(self, advertisementData: NSDictionary): mfg_bytes = advertisementData.get("kCBAdvDataManufacturerData") if not mfg_bytes: return mfg_id = int.from_bytes(mfg_bytes[0:2], byteorder="little") mfg_val = bytes(mfg_bytes[2:]) self.metadata["manufacturer_data"] = {mfg_id: mfg_val}
def main(): parser = build_parser() options, args = parser.parse_args() if not args: parser.print_help() return if len(args) != 2: parser.error("Must specify both a source and destination") return if options.verbose: hdlr = logging.StreamHandler() fmt = logging.Formatter('%(message)s') hdlr.setFormatter(fmt) logger = logging.getLogger() logger.addHandler(hdlr) logger.setLevel(logging.INFO) else: logging.basicConfig() source, dest = map(os.path.normpath, args) if source == dest: parser.error("Source and destination may not be the same.") return if os.path.exists(dest): if options.killDest: deletePath(dest) else: parser.error("Destination already exists. -k to destroy or use different destination.") return if options.templateFile and (not os.path.exists(options.templateFile)): parser.error("Template file specified, but does not exist.") return info("Copying from '%s' to '%s'....", source, dest) shutil.copytree(source, dest) simplePathWalker(dest, killNasties, options) simplePathWalker(dest, doSubstitutions, options) if options.templateFile: options.template = NSDictionary.dictionaryWithContentsOfFile_(options.templateFile) if not options.template: parser.error("Failed to read template: %s" % options.templateFile) sys.exit(1) filesToRename = options.template['FilesToRename'] for k in filesToRename: leftPath = os.path.join(dest, k) rightPath = os.path.join(dest, filesToRename[k]) if not options.doReverse: info("rename %s ==> %s", rightPath, leftPath) os.rename(rightPath, leftPath) else: info("rename %s ==> %s", leftPath, rightPath) os.rename(leftPath, rightPath)
def save_favservers(favs, path): # Prior to running code through NSKeyedArchiver, we want to strip out custom pyObjC subclass types temp_keys = favs.keys() fixed_values = [purify(favs[x]) for x in temp_keys] fixed_keys = [purify(x) for x in temp_keys] # Once everything is cleaned up, put it into a new NSDictionary formatted_favs = NSDictionary.alloc().initWithObjects_forKeys_( fixed_values, fixed_keys) return NSKeyedArchiver.archiveRootObject_toFile_(formatted_favs, path)
def refreshLibrary(self): if not self.history: return settings = SIPSimpleSettings() own_icon_path = settings.presence_state.icon selected_icon = None def md5sum(filename): md5 = hashlib.md5() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(128 * md5.block_size), b''): md5.update(chunk) return md5.hexdigest() if os.path.exists(self.storage_folder): files = os.listdir(self.storage_folder) else: files = [] array = NSMutableArray.array() knownFiles = set() for item in self.contentArrayController.arrangedObjects(): knownFiles.add(str(item.objectForKey_("path"))) seen_md5sum = {} i = 0 for f in files: if not f.startswith('user_icon') and not f.startswith( 'photo') and f != 'default_user_icon.tiff': continue p = os.path.normpath(self.storage_folder + "/" + f) if p not in knownFiles: photos_folder = unicodedata.normalize('NFC', self.storage_folder) filename = os.path.join(photos_folder, f) checksum = md5sum(filename) try: seen_md5sum[filename] except KeyError: seen_md5sum[filename] = checksum image = NSImage.alloc().initWithContentsOfFile_(p) if not image: continue item = NSDictionary.dictionaryWithObjectsAndKeys_( image, "picture", p, "path") array.addObject_(item) if own_icon_path is not None and filename == str( own_icon_path): selected_icon = i i += 1 if array.count() > 0: self.contentArrayController.addObjects_(array) if selected_icon is not None: self.libraryCollectionView.setSelectionIndexes_( NSIndexSet.indexSetWithIndex_(selected_icon))
def load_puzzles(): if len(sys.argv) == 1: puzzles = load_puzzles_from_ipa() if not puzzles: print "Couldn't find the Lights Off app in your iTunes library. Please specify a valid puzzles.plist file path." sys.exit(1) return puzzles if not os.path.isfile(sys.argv[1]): print "Please specify a valid puzzles.plist file path." sys.exit(1) return NSDictionary.dictionaryWithContentsOfFile_(sys.argv[1])['puzzles']
def __init__(self, plist_path=BOOKS_PLIST_PATH): if FMT_BINARY is None: if not NSDictionary is None: self.plist = NSDictionary.alloc().initWithContentsOfFile_(plist_path) else: self.plist = Ibex._ibex_plutil_read_xml(plist_path) else: self.plist = readPlist(plist_path) if self.plist is None: raise IbexError('%s: failed to read property list' % plist_path)
def _update_uuids(self, advertisementData: NSDictionary): cbuuids = advertisementData.get("kCBAdvDataServiceUUIDs", []) if not cbuuids: return chuuids = [cb_uuid_to_str(u) for u in cbuuids] if "uuids" in self.metadata: for uuid in chuuids: if not uuid in self.metadata["uuids"]: self.metadata["uuids"].append(uuid) else: self.metadata["uuids"] = chuuids
def readGlyphsFile(filePath): print "Import Glyphs File" pool = None try: from Foundation import NSAutoreleasePool, NSDictionary except ImportError: # on Windows, PyObjC is not available with open(filePath, "rb") as f: data = f.read() if data.startswith("<?xml"): # use the built-in plistlib module for XML plist from plistlib import readPlistFromString GlyphsDoc = readPlistFromString(data) else: # use glyphsLib's Parser for ASCII plist. # Download it from: https://github.com/googlei18n/glyphsLib from glyphsLib.parser import Parser GlyphsDoc = Parser(dict_type=dict).parse(data) else: # on OS X, use NSDictionary pool = NSAutoreleasePool.alloc().init() GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath) if not GlyphsDoc: print "Could not load .glyphs file." if pool: pool.drain() return from FL import fl, Font folder, base = os.path.split(filePath) base = base.replace(".glyphs", ".vfb") dest = os.path.join(folder, base) f = Font() fl.Add(f) global convertName try: convertName = GlyphsDoc["disablesNiceNames"] != None except: pass if not setFontInfo(f, GlyphsDoc): return False readGlyphs(f, GlyphsDoc) readKerning(f, GlyphsDoc) setLegacyNames(f) readFeatures(f, GlyphsDoc) fl.UpdateFont() f.modified = 0 if pool: pool.drain()
def create_favitem(url=None, name=None): if name is None: # Make the display name the same as the URL by default name = url props = { NSString.stringWithString_('com.apple.LSSharedFileList.OverrideIcon.OSType'): NSString.stringWithString_(u'srvr') } props = NSDictionary.alloc().initWithDictionary_(props) return SFLListItem.alloc().initWithName_URL_properties_( name, NSURL.alloc().initWithString_(url), props)
def _update_uuids(self, advertisementData: NSDictionary): cbuuids = advertisementData.get("kCBAdvDataServiceUUIDs", []) if not cbuuids: return # converting to lower case to match other platforms chuuids = [str(u).lower() for u in cbuuids] if "uuids" in self.metadata: for uuid in chuuids: if not uuid in self.metadata["uuids"]: self.metadata["uuids"].append(uuid) else: self.metadata["uuids"] = chuuids
def load_puzzles_from_ipa(): for ipa in glob("/Users/*/Music/iTunes/iTunes*/Mobile Applications/Lights Off*ipa"): try: z = ZipFile(open(ipa, "r")) with NamedTemporaryFile() as f: f.write(z.read('Payload/Lights Off.app/puzzles.plist')) f.flush() print f.name return NSDictionary.dictionaryWithContentsOfFile_(f.name)['puzzles'] except: continue return None
def paramsDictionary(self): self.fCutoff = min(self.fCutoff, self.sampleRate/2.) return NSDictionary.dictionaryWithObjectsAndKeys_( self.mean, BLWN_MEAN_KEY, self.var, BLWN_VAR_KEY, self.fCutoff, BLWN_FREQ_KEY, self.nPoles, BLWN_NPOLES_KEY, self.sampleRate, BLWN_SAMPLE_RATE_KEY, self.length, BLWN_LENGTH_KEY, pickle.dumps(self.rSource.get_state()[:3]), BLWN_RANDOM_STATE_KEY, numpy.__version__, 'numpyVersion', None)
def __init__(self): """return existing singleton or create a new one""" if hasattr(self, "context"): return """ initialize CIContext """ context_options = NSDictionary.dictionaryWithDictionary_({ "workingColorSpace": Quartz.CoreGraphics.kCGColorSpaceExtendedSRGB, "workingFormat": Quartz.kCIFormatRGBAh, }) self.context = Quartz.CIContext.contextWithOptions_(context_options)
def open_app_at_startup(enabled=True): """ This function adds/removes the current app bundle from Login items in macOS or most Linux desktops """ if sys.platform == 'darwin': from Foundation import NSDictionary from Cocoa import NSBundle, NSURL from CoreFoundation import kCFAllocatorDefault # CF = CDLL(find_library('CoreFoundation')) from LaunchServices import (LSSharedFileListCreate, kLSSharedFileListSessionLoginItems, LSSharedFileListInsertItemURL, kLSSharedFileListItemHidden, kLSSharedFileListItemLast, LSSharedFileListItemRemove) app_path = NSBundle.mainBundle().bundlePath() url = NSURL.alloc().initFileURLWithPath_(app_path) login_items = LSSharedFileListCreate( kCFAllocatorDefault, kLSSharedFileListSessionLoginItems, None) props = NSDictionary.dictionaryWithObject_forKey_( True, kLSSharedFileListItemHidden) new_item = LSSharedFileListInsertItemURL(login_items, kLSSharedFileListItemLast, None, None, url, props, None) if not enabled: LSSharedFileListItemRemove(login_items, new_item) elif sys.platform.startswith('linux'): autostart_path = Path.home() / '.config' / 'autostart' if not autostart_path.exists(): autostart_path.mkdir() autostart_file_path = autostart_path / 'vorta.desktop' if enabled: if Path('/.flatpak-info').exists(): # Vorta runs as flatpak autostart_file_path.write_text( LINUX_STARTUP_FILE.format( 'flatpak run com.borgbase.vorta')) else: autostart_file_path.write_text( LINUX_STARTUP_FILE.format('vorta')) else: if autostart_file_path.exists(): autostart_file_path.unlink()
def readGlyphsFile(filePath): print "Import Glyphs File" pool = None try: from Foundation import NSAutoreleasePool, NSDictionary except ImportError: # on Windows, PyObjC is not available with open(filePath, 'rb') as f: data = f.read() if data.startswith("<?xml"): # use the built-in plistlib module for XML plist from plistlib import readPlistFromString GlyphsDoc = readPlistFromString(data) else: # use glyphsLib's Parser for ASCII plist. # Download it from: https://github.com/googlei18n/glyphsLib from glyphsLib.parser import Parser GlyphsDoc = Parser(dict_type=dict).parse(data) else: # on OS X, use NSDictionary pool = NSAutoreleasePool.alloc().init() GlyphsDoc = NSDictionary.alloc().initWithContentsOfFile_(filePath) if not GlyphsDoc: print "Could not load .glyphs file." if pool: pool.drain() return from FL import fl, Font folder, base = os.path.split(filePath) base = base.replace(".glyphs", ".vfb") dest = os.path.join(folder, base) f = Font( ) fl.Add(f) global convertName try: convertName = GlyphsDoc["disablesNiceNames"] != None except: pass if not setFontInfo(f, GlyphsDoc): return False readGlyphs(f, GlyphsDoc) readKerning(f, GlyphsDoc) setLegacyNames(f) readFeatures(f, GlyphsDoc) fl.UpdateFont() f.modified = 0 if pool: pool.drain()
def purify(obj): # This code ensures that certain data types are very definitely the ObjC versions d = dir(obj) if '__reversed__' in d: # list / NSArray return NSArray.alloc().initWithArray_(obj) elif 'items' in d: # dictionary / NSDictionary return NSDictionary.alloc().initWithDictionary_(obj) elif 'strip' in d: # string / NSString return NSString.alloc().initWithString_(obj) # Unhandled return obj
def GetPlist(plist): """Returns a dictionary from a given plist. Args: plist: plist to operate on Returns: Contents of the plist as a dict-like object. Raises: MissingImportsError: if NSDictionary is missing """ if NSDictionary: return NSDictionary.dictionaryWithContentsOfFile_(plist) else: raise MissingImportsError('NSDictionary not imported successfully.')
def show(self, title, text): notification = NSUserNotification.alloc().init() notification.setTitle_(str(title)) #notification.setIdentifier_("ID_1") notification.setInformativeText_(str(text)) notification.setSoundName_("NSUserNotificationDefaultSoundName") notification.setHasActionButton_(False) #notification.setActionButtonTitle_("View") payload = NSDictionary.dictionary() notification.setUserInfo_(payload) self.notification_center.scheduleNotification_(notification) return notification
def refreshLibrary(self): if not self.history: return settings = SIPSimpleSettings() own_icon_path = settings.presence_state.icon selected_icon = None def md5sum(filename): md5 = hashlib.md5() with open(filename,'rb') as f: for chunk in iter(lambda: f.read(128*md5.block_size), b''): md5.update(chunk) return md5.hexdigest() if os.path.exists(self.storage_folder): files = os.listdir(self.storage_folder) else: files = [] array = NSMutableArray.array() knownFiles = set() for item in self.contentArrayController.arrangedObjects(): knownFiles.add(unicode(item.objectForKey_("path"))) seen_md5sum = {} i = 0 for f in files: if not f.startswith('user_icon') and not f.startswith('photo') and f != 'default_user_icon.tiff': continue p = os.path.normpath(self.storage_folder + "/" + f) if p not in knownFiles: photos_folder = unicodedata.normalize('NFC', self.storage_folder) filename = os.path.join(photos_folder, f) checksum = md5sum(filename) try: seen_md5sum[filename] except KeyError: seen_md5sum[filename] = checksum image = NSImage.alloc().initWithContentsOfFile_(p) if not image: continue item = NSDictionary.dictionaryWithObjectsAndKeys_(image, "picture", p, "path") array.addObject_(item) if own_icon_path is not None and filename == unicode(own_icon_path): selected_icon = i i += 1 if array.count() > 0: self.contentArrayController.addObjects_(array) if selected_icon is not None: self.libraryCollectionView.setSelectionIndexes_(NSIndexSet.indexSetWithIndex_(selected_icon))
def did_discover_peripheral( self, central: CBCentralManager, peripheral: CBPeripheral, advertisementData: NSDictionary, RSSI: NSNumber, ): # Note: this function might be called several times for same device. # This can happen for instance when an active scan is done, and the # second call with contain the data from the BLE scan response. # Example a first time with the following keys in advertisementData: # ['kCBAdvDataLocalName', 'kCBAdvDataIsConnectable', 'kCBAdvDataChannel'] # ... and later a second time with other keys (and values) such as: # ['kCBAdvDataServiceUUIDs', 'kCBAdvDataIsConnectable', 'kCBAdvDataChannel'] # # i.e it is best not to trust advertisementData for later use and data # from it should be copied. # # This behaviour could be affected by the # CBCentralManagerScanOptionAllowDuplicatesKey global setting. uuid_string = peripheral.identifier().UUIDString() if uuid_string in self.devices: device = self.devices[uuid_string] # It could be the device did not have a name previously but now it does. if peripheral.name(): device.name = peripheral.name() else: address = uuid_string name = peripheral.name() or None details = peripheral device = BLEDeviceCoreBluetooth(address, name, details, delegate=self) self.devices[uuid_string] = device device.rssi = RSSI device._update(advertisementData) for callback in self.callbacks.values(): if callback: callback(peripheral, advertisementData, RSSI) logger.debug( "Discovered device {}: {} @ RSSI: {} (kCBAdvData {}) and Central: {}" .format(uuid_string, device.name, RSSI, advertisementData.keys(), central))
def add(self, label, uri, index=-1): if label in self.labels: return if index == -1 or index > len(self.items): index = len(self.items) elif index < -1: index = 0 new_item = NSDictionary.alloc().initWithDictionary_( dict( Name=NSString.alloc().initWithString_(label), URL=NSString.alloc().initWithString_(uri) ) ) self.items.insert(index, new_item) self.labels.append(label)
def notdefLayer( self ): try: from Foundation import NSBundle, NSClassFromString, NSDictionary bundle = NSBundle.bundleForClass_(NSClassFromString("GSExportInstanceOperation")) if bundle: path = bundle.pathForResource_ofType_("notDef","plist") layerDict = NSDictionary.dictionaryWithContentsOfFile_(path) layer = GSLayer.alloc().initWithDict_format_(layerDict,1) return layer return None except Exception as e: import traceback print(traceback.format_exc()) self.logToConsole( "notdefLayer: %s" % str(e) ) return None
def __init__(self): """ return existing singleton or create a new one """ if hasattr(self, "context"): return """ initialize CIContext """ context_options = NSDictionary.dictionaryWithDictionary_({ "workingColorSpace": Quartz.CoreGraphics.kCGColorSpaceExtendedSRGB, "workingFormat": Quartz.kCIFormatRGBAh, }) mtldevice = Metal.MTLCreateSystemDefaultDevice() self.context = Quartz.CIContext.contextWithMTLDevice_options_( mtldevice, context_options)
def _extractClassesFromNibFromPath(self, path): path = os.path.normpath(path) if self.parsedNibs.has_key(path): return # we've already parsed this nib nibName = os.path.basename(path) nibInfo = NSDictionary.dictionaryWithContentsOfFile_( os.path.join(path, 'classes.nib')) if nibInfo is None: raise NibLoaderError("Invalid NIB file [%s]" % path) if not nibInfo.has_key('IBVersion'): raise NibLoaderError("Invalid NIB info") if nibInfo['IBVersion'] != '1': raise NibLoaderError("Unsupported NIB version") for rawClsInfo in nibInfo['IBClasses']: self._addClass(nibName, rawClsInfo) self.parsedNibs[path] = 1
def detect_text(img_path: str, orientation: Optional[int] = None) -> List: """process image at img_path with VNRecognizeTextRequest and return list of results Args: img_path: path to the image file orientation: optional EXIF orientation (if known, passing orientation may improve quality of results) """ if not vision: logging.warning( f"detect_text not implemented for this version of macOS") return [] with objc.autorelease_pool(): input_url = NSURL.fileURLWithPath_(img_path) with pipes() as (out, err): # capture stdout and stderr from system calls # otherwise, Quartz.CIImage.imageWithContentsOfURL_ # prints to stderr something like: # 2020-09-20 20:55:25.538 python[73042:5650492] Creating client/daemon connection: B8FE995E-3F27-47F4-9FA8-559C615FD774 # 2020-09-20 20:55:25.652 python[73042:5650492] Got the query meta data reply for: com.apple.MobileAsset.RawCamera.Camera, response: 0 input_image = Quartz.CIImage.imageWithContentsOfURL_(input_url) vision_options = NSDictionary.dictionaryWithDictionary_({}) if orientation is not None: if not 1 <= orientation <= 8: raise ValueError("orientation must be between 1 and 8") vision_handler = Vision.VNImageRequestHandler.alloc( ).initWithCIImage_orientation_options_(input_image, orientation, vision_options) else: vision_handler = ( Vision.VNImageRequestHandler.alloc().initWithCIImage_options_( input_image, vision_options)) results = [] handler = make_request_handler(results) vision_request = (Vision.VNRecognizeTextRequest.alloc(). initWithCompletionHandler_(handler)) error = vision_handler.performRequests_error_([vision_request], None) vision_request.dealloc() vision_handler.dealloc() for result in results: result[0] = str(result[0]) return results
def renderDailyEntries(self, results): getFirstContactMatchingURI = NSApp.delegate().contactsWindowController.getFirstContactMatchingURI self.dayly_entries = NSMutableArray.array() for result in results: contact = getFirstContactMatchingURI(result[2], exact_match=True) if contact: remote_uri = '%s <%s>' % (contact.name, result[2]) else: remote_uri = result[2] entry = NSDictionary.dictionaryWithObjectsAndKeys_(result[1], "local_uri", remote_uri, "remote_uri", result[2], "remote_uri_sql", result[0], 'date', result[3], 'type') 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 init_with_sucatalog(sucatalog, pkg_re = "^.*/XProtectPlistConfigData.*\.pkg$"): meta = None data = None pkg_url = None u = NSURL.URLWithString_(sucatalog) d = NSDictionary.dictionaryWithContentsOfURL_(u) if not d: raise Exception("Invalid CatalogURL.", sucatalog) for k, v in d["Products"].items(): for package in v["Packages"]: r = re.compile(pkg_re) if r.findall(package["URL"]) != []: pkg_url = package["URL"] if not pkg_url: raise Exception("Package not found.", sucatalog, pkg_name) tmp_t = "%f" % time.time() tmp_pkg = "/tmp/xplist_%s.pkg" % tmp_t tmp_dir = "/tmp/xplist_%s" % tmp_t tmp_tar = "/tmp/xplist_%s/Payload" % tmp_t cmds = [ "/usr/bin/curl -s -o '%s' '%s'" %(tmp_pkg, pkg_url), "/usr/sbin/pkgutil --expand '%s' '%s'" %(tmp_pkg, tmp_dir), "/usr/bin/tar xf '%s' -C '%s' -s '|.*/||' --include '*.plist'" %(tmp_tar, tmp_dir) ] for cmd in cmds: retcode = os.system(cmd) if retcode != 0: raise Exception("Error processing package.", pkg_url, retcode, cmd) fmeta = "%s/XProtect.meta.plist" % tmp_dir fdata = "%s/XProtect.plist" % tmp_dir if os.path.exists(fmeta) and os.path.exists(fdata): meta, data = init_with_files(fmeta, fdata) return meta, data, pkg_url
def awakeFromNib(self): smileys = SmileyManager().get_smiley_list() menu = self.smileyButton.menu() while menu.numberOfItems() > 0: menu.removeItemAtIndex_(0) bigText = NSAttributedString.alloc().initWithString_attributes_(" ", NSDictionary.dictionaryWithObject_forKey_(NSFont.systemFontOfSize_(16), NSFontAttributeName)) for text, file in smileys: image = NSImage.alloc().initWithContentsOfFile_(file) if not image: print "cant load %s"%file continue image.setScalesWhenResized_(True) image.setSize_(NSMakeSize(16, 16)) atext = bigText.mutableCopy() atext.appendAttributedString_(NSAttributedString.alloc().initWithString_(text)) item = NSMenuItem.alloc().initWithTitle_action_keyEquivalent_(text, "insertSmiley:", "") menu.addItem_(item) item.setTarget_(self) item.setAttributedTitle_(atext) item.setRepresentedObject_(NSAttributedString.alloc().initWithString_(text)) item.setImage_(image)
def build_settings_dict(pbxfile, shared_scheme, build_action, configuration): action_scheme_dict = {'build' : 'BuildAction', 'test' : 'TestAction', 'archive' : 'ArchiveAction'} scheme_dir = "%s/xcshareddata/xcschemes/%s.xcscheme" % (os.path.dirname(os.path.realpath(pbxfile)), shared_scheme) scheme_xml = ET.parse(scheme_dir) action_node = scheme_xml.getiterator(action_scheme_dict[build_action])[0] buildable_node = action_node.getiterator("BuildableReference")[0] target_hash = buildable_node.get("BlueprintIdentifier") product_name = buildable_node.get("BlueprintName") pbxproj_plist = NSDictionary.dictionaryWithContentsOfFile_(pbxfile)['objects'] build_conf_for_target = pbxproj_plist[target_hash]['buildConfigurationList'] build_conf_list = pbxproj_plist[build_conf_for_target]['buildConfigurations'] build_conf_dict_for_target = [pbxproj_plist[build_conf] for build_conf in build_conf_list if pbxproj_plist[build_conf]['name'] == configuration][0] conf_atom = build_conf_dict_for_target['buildSettings'] atom = PBXAtom(conf_atom) return atom, product_name
def __init__(self, sessionController): self.notification_center = NotificationCenter() self.notification_center.add_observer(self, name='CFGSettingsObjectDidChange') self.sessionController = None self.audio_stream = None self.video_stream = None self.chat_stream = None self.add_session(sessionController) self.add_audio_stream() self.add_video_stream() self.add_chat_stream() self.timer = NSTimer.timerWithTimeInterval_target_selector_userInfo_repeats_(1.0, self, "updateTimer:", None, True) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSModalPanelRunLoopMode) NSRunLoop.currentRunLoop().addTimer_forMode_(self.timer, NSDefaultRunLoopMode) NSBundle.loadNibNamed_owner_("SessionInfoPanel", self) sessionBoxTitle = NSAttributedString.alloc().initWithString_attributes_(NSLocalizedString("SIP Session", "Label"), NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.sessionBox.setTitle_(sessionBoxTitle) audioBoxTitle = NSAttributedString.alloc().initWithString_attributes_(NSLocalizedString("Audio Stream", "Label"), NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.audioBox.setTitle_(audioBoxTitle) videoBoxTitle = NSAttributedString.alloc().initWithString_attributes_(NSLocalizedString("Video Stream", "Label"), NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.videoBox.setTitle_(videoBoxTitle) chatBoxTitle = NSAttributedString.alloc().initWithString_attributes_(NSLocalizedString("Chat Stream", "Label"), NSDictionary.dictionaryWithObject_forKey_(NSColor.orangeColor(), NSForegroundColorAttributeName)) self.chatBox.setTitle_(chatBoxTitle) settings = SIPSimpleSettings() self.audio_rtt_graph.setLineWidth_(1.0) self.audio_rtt_graph.setLineSpacing_(1.0) self.audio_rtt_graph.setAboveLimit_(settings.gui.rtt_threshold) # if higher show red color self.audio_rtt_graph.setMinimumHeigth_(settings.gui.rtt_threshold) self.audio_packet_loss_graph.setLineWidth_(1.0) self.audio_packet_loss_graph.setLineSpacing_(1.0) self.audio_packet_loss_graph.setAboveLimit_(3) # if higher than 3% show red color self.audio_packet_loss_graph.setLineColor_(NSColor.greenColor()) self.audio_packet_loss_graph.setMinimumHeigth_(5) self.rx_speed_graph.setLineWidth_(1.0) self.rx_speed_graph.setLineSpacing_(0.0) self.rx_speed_graph.setLineColor_(NSColor.greenColor()) self.rx_speed_graph.setMinimumHeigth_(100000) self.rx_speed_graph.setAboveLimit_(120000) self.tx_speed_graph.setLineWidth_(1.0) self.tx_speed_graph.setLineSpacing_(0.0) self.tx_speed_graph.setLineColor_(NSColor.blueColor()) self.tx_speed_graph.setMinimumHeigth_(100000) self.tx_speed_graph.setAboveLimit_(120000) self.video_rx_speed_graph.setLineWidth_(1.0) self.video_rx_speed_graph.setLineSpacing_(0.0) self.video_rx_speed_graph.setLineColor_(NSColor.greenColor()) self.video_rx_speed_graph.setMinimumHeigth_(100000) self.video_rx_speed_graph.setAboveLimit_(1200000) self.video_tx_speed_graph.setLineWidth_(1.0) self.video_tx_speed_graph.setLineSpacing_(0.0) self.video_tx_speed_graph.setLineColor_(NSColor.blueColor()) self.video_tx_speed_graph.setMinimumHeigth_(100000) self.video_tx_speed_graph.setAboveLimit_(1200000) self.resetSession() self.updatePanelValues()
def append_error_line(self, textView, line): red = NSDictionary.dictionaryWithObject_forKey_(NSColor.redColor(), NSForegroundColorAttributeName) textView.textStorage().appendAttributedString_(NSAttributedString.alloc().initWithString_attributes_(line+"\n", red)) textView.scrollRangeToVisible_(NSMakeRange(textView.textStorage().length()-1, 1))
def readDictionary(filepath): """ Use Foundation calls to read a property list (dictionary) from disk. """ return NSDictionary.dictionaryWithContentsOfFile_(filepath)
def copyFile(thePath): theSourcePath = os.path.join(theLibraryPath, thePath) theDestinationPath = os.path.join(thePhonePath, thePath) theDestinationDirectory = os.path.split(theDestinationPath)[0] if not os.path.exists(theDestinationDirectory): os.makedirs(theDestinationDirectory) if not os.path.exists(theDestinationPath): shutil.copyfile(theSourcePath, theDestinationPath) ######################################################################## try: from Foundation import (NSDictionary) d = NSDictionary.dictionaryWithContentsOfFile_(theLibraryFile) except: d = plistlib.readPlist(theLibraryFile) theTracks = d['Tracks'] ######################################################################## libraryPaths = [] phonePaths = [] addingPaths = [] removingPaths = [] validKinds = ['Matched AAC audio file', 'Purchased AAC audio file', 'AAC audio file', 'MPEG audio file'] count = 0 for theKey in theTracks: theTrack = theTracks[theKey]
def _readlib(path): return NSDictionary.dictionaryWithContentsOfFile_(path)
def updateButtons(self): for button in (self.holdButton, self.hangupButton, self.chatButton, self.infoButton, self.muteButton, self.aspectButton, self.contactsButton, self.fullscreenButton, self.myvideoButton, self.pauseButton): lightGrayTitle = NSAttributedString.alloc().initWithString_attributes_(button.label(), NSDictionary.dictionaryWithObject_forKey_(NSColor.lightGrayColor(), NSForegroundColorAttributeName)) button.setLabel_(lightGrayTitle)
def idealWidth(self): attribs = NSDictionary.dictionaryWithObject_forKey_(NSFont.systemFontOfSize_(11), NSFontAttributeName) size = self.label.sizeWithAttributes_(attribs) return size.width + 14 + 20
def drawRect_(self, rect): r = self.bounds() r.size.width -= 0.5 r.size.height += 4 if self.draggedOut: NSColor.colorWithDeviceWhite_alpha_(0.4, 1.0).set() path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(r, 5, 5) path.fill() else: if self == self.switcher.activeItem(): NSColor.controlColor().set() else: NSColor.colorWithDeviceWhite_alpha_(0.6, 1.0).set() path = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(r, 5, 5) path.fill() NSColor.colorWithDeviceRed_green_blue_alpha_(0.3, 0.3, 0.3, 1.0).set() path.stroke() if self.badgeLabel and not self.mouseInside and not self.busyIndicator and not self.composing: # draw the number in redbadge indicator gradient = NSGradient.alloc().initWithStartingColor_endingColor_( NSColor.colorWithDeviceRed_green_blue_alpha_(0.9, 0.2, 0.2, 1), NSColor.colorWithDeviceRed_green_blue_alpha_(1.0, 0.2, 0.2, 1)) size = self.badgeLabel.size() size.width += 4 if size.width < 12: size.width = 12 bez = NSBezierPath.bezierPathWithRoundedRect_xRadius_yRadius_(NSMakeRect(3, 5, size.width, 12), 6, 6) gradient.drawInBezierPath_angle_(bez, 90+45) self.badgeLabel.drawInRect_(NSMakeRect(3, 5, size.width, 12)) if not self.mouseInside and not self.busyIndicator and self.composing: rect = NSZeroRect.copy() rect.size = self.composeIcon.size() self.composeIcon.drawAtPoint_fromRect_operation_fraction_(NSMakePoint(1, 3), rect, NSCompositeSourceOver, 1) if not self.busyIndicator and self.screen_sharing_active: rect = NSZeroRect.copy() rect.size = self.screenIcon.size() self.screenIcon.drawAtPoint_fromRect_operation_fraction_(NSMakePoint(17, 3), rect, NSCompositeSourceOver, 1) if not self.draggedOut: shadow = NSShadow.alloc().init() shadow.setShadowOffset_(NSMakeSize(0, -1)) if self == self.switcher.activeItem(): shadow.setShadowColor_(NSColor.whiteColor()) else: shadow.setShadowColor_(NSColor.colorWithDeviceWhite_alpha_(0.7, 1.0)) para = NSParagraphStyle.defaultParagraphStyle().mutableCopy() para.setLineBreakMode_(NSLineBreakByTruncatingTail) para.setAlignment_(NSCenterTextAlignment) attribs = NSDictionary.dictionaryWithObjectsAndKeys_(NSFont.systemFontOfSize_(11), NSFontAttributeName, shadow, NSShadowAttributeName, para, NSParagraphStyleAttributeName) rect = self.bounds() rect.origin.y -= 3 rect.origin.x += 20 rect.origin.x = rect.origin.x + 12 if self.screen_sharing_active else rect.origin.x rect.size.width -= 46 rect.size.width = rect.size.width - 12 if self.screen_sharing_active else rect.size.width self.label.drawInRect_withAttributes_(rect, attribs)
def writeDictionary(dict, filepath): """ Write dictionary to disk using Foundation call. """ dictObj = NSDictionary.dictionaryWithDictionary_(dict) dictObj.writeToFile_atomically_(filepath, 1)