def displaypath(self, pathvar, entryfield): entryfield['state'] = tk.NORMAL # must be writable to update entryfield.delete(0, tk.END) if platform=='win32': start = pathvar.get().lower().startswith(config.home.lower()) and len(config.home.split('\\')) or 0 display = [] components = normpath(pathvar.get()).split('\\') buf = ctypes.create_unicode_buffer(MAX_PATH) pidsRes = ctypes.c_int() for i in range(start, len(components)): try: if (not SHGetLocalizedName('\\'.join(components[:i+1]), buf, MAX_PATH, ctypes.byref(pidsRes)) and LoadString(ctypes.WinDLL(expandvars(buf.value))._handle, pidsRes.value, buf, MAX_PATH)): display.append(buf.value) else: display.append(components[i]) except: display.append(components[i]) entryfield.insert(0, '\\'.join(display)) elif platform=='darwin' and NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get()): # None if path doesn't exist if pathvar.get().startswith(config.home): display = ['~'] + NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get())[len(NSFileManager.defaultManager().componentsToDisplayForPath_(config.home)):] else: display = NSFileManager.defaultManager().componentsToDisplayForPath_(pathvar.get()) entryfield.insert(0, '/'.join(display)) else: if pathvar.get().startswith(config.home): entryfield.insert(0, '~' + pathvar.get()[len(config.home):]) else: entryfield.insert(0, pathvar.get()) entryfield['state'] = 'readonly'
def url_from_metadata(path: str) -> Optional[str]: """Try to determine the download URL from the spotlight attributes if the local machine is a mac.""" try: from Foundation import NSFileManager, NSPropertyListSerialization except: return None fm = NSFileManager.defaultManager() attrs, err = fm.attributesOfItemAtPath_error_(path, None) if err: return None if 'NSFileExtendedAttributes' not in attrs: return None extd_attrs = attrs['NSFileExtendedAttributes'] if 'com.apple.metadata:kMDItemWhereFroms' not in extd_attrs: return None else: plist_data: bytes = extd_attrs['com.apple.metadata:kMDItemWhereFroms'] value: List[str] = plistlib.loads(plist_data) if len(value) > 0: return value.pop(0) else: return None
def get_app_name(bundle_id): app_path = NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_(bundle_id) if not app_path: app_name = "SYSTEM" else: app_name = NSFileManager.defaultManager().displayNameAtPath_(app_path) return app_name
def get_app_name(bundle_id): '''Get display name for app specified by bundle_id''' from AppKit import NSWorkspace from Foundation import NSFileManager app_path = NSWorkspace.sharedWorkspace( ).absolutePathForAppBundleWithIdentifier_(bundle_id) if app_path: return NSFileManager.defaultManager().displayNameAtPath_(app_path) return bundle_id
def send2trash(paths): paths = preprocess_paths(paths) paths = [ path.decode("utf-8") if not isinstance(path, text_type) else path for path in paths ] for path in paths: file_url = NSURL.fileURLWithPath_(path) fm = NSFileManager.defaultManager() op_result = fm.trashItemAtURL_resultingItemURL_error_(file_url, None, None) check_op_result(op_result)
def _set_type(self, file_type): creator = file_type.mac_creator type = file_type.mac_type if creator is not None or type is not None: fm = NSFileManager.defaultManager() attrs = {} if creator is not None: attrs[NSFileHFSCreatorCode] = four_char_code(creator) if type is not None: attrs[NSFileHFSTypeCode] = four_char_code(type) #print "FileRef: Setting attributes of %r to %s" % ( ### # self.path, attrs) ### fm.changeFileAttributes_atPath_(attrs, self.path)
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
# NSURLVolumeIsRemovableKey; # NSURLVolumeIsInternalKey ?? # NSURLVolumeIsAutomountedKey; # NSURLVolumeIsLocalKey; # NSURLVolumeIsReadOnlyKey; # NSURLVolumeCreationDateKey; # NSURLVolumeURLForRemountingKey; # NSURLVolumeNameKey; # NSURLVolumeLocalizedNameKey; # print asdf(NSURL,42) sharedFM = NSFileManager.defaultManager() def df2fk(v): # v = itemDict[fk] t = type(v) if isinstance(v, objc.pyobjc_unicode): return unicode(v) # .encode('utf8') # elif isinstance(v, NSDate): # return str(v) # yeah, could be a python datetime? str() works. date needed for timezone formatting? elif isinstance(v, (objc._pythonify.OC_PythonLong, int)): return int(v) else: return v # (type(itemDict[fk]), itemDict[fk]) class MyError(Exception):
from urllib.parse import urlparse, urlunparse, quote from Foundation import NSObject, NSRunLoop, NSDate from Foundation import NSFileManager, NSCachesDirectory, NSUserDomainMask from Foundation import NSURL, NSURLSession, NSURLSessionConfiguration from Foundation import NSURLRequest, NSURLRequestUseProtocolCachePolicy from Foundation import NSURLRequestReturnCacheDataElseLoad, NSURLCache from Foundation import NSURLResponse, NSCachedURLResponse from PyObjCTools.AppHelper import callAfter logger = logging.getLogger('URLReader') USER_CACHE_DIRECTORY_URL, _ = NSFileManager.defaultManager().\ URLForDirectory_inDomain_appropriateForURL_create_error_( NSCachesDirectory, NSUserDomainMask, None, True, None ) CACHE_DIRECTORY_URL = USER_CACHE_DIRECTORY_URL.\ URLByAppendingPathComponent_isDirectory_('URLReader', True) quote_r = re.compile('%[A-Za-z0-9]{2}') def callback(url, data, error): """URLReader prototype callback By providing a function with the same signature as this to URLReader.fetch(), code can be notified when the background URL fetching operation has been completed and manipulate the resulting data. The callback will be called on the main thread. """