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 getRunningBlockingApps(appnames): """Given a list of app names, return a list of dicts for apps in the list that are running. Each dict contains username, pathname, display_name""" proc_list = getRunningProcessesWithUsers() running_apps = [] filemanager = NSFileManager.alloc().init() for appname in appnames: matching_items = [] if appname.startswith("/"): # search by exact path matching_items = [item for item in proc_list if item["pathname"] == appname] elif appname.endswith(".app"): # search by filename matching_items = [item for item in proc_list if "/" + appname + "/Contents/MacOS/" in item["pathname"]] else: # check executable name matching_items = [item for item in proc_list if item["pathname"].endswith("/" + appname)] if not matching_items: # try adding '.app' to the name and check again matching_items = [item for item in proc_list if "/" + appname + ".app/Contents/MacOS/" in item["pathname"]] # matching_items = set(matching_items) for item in matching_items: path = item["pathname"] while "/Contents/" in path or path.endswith("/Contents"): path = os.path.dirname(path) # ask NSFileManager for localized name since end-users # will see this name item["display_name"] = filemanager.displayNameAtPath_(path) running_apps.append(item) return running_apps
def getRunningBlockingApps(appnames): """Given a list of app names, return a list of friendly names for apps in the list that are running""" proc_list = getRunningProcesses() running_apps = [] filemanager = NSFileManager.alloc().init() for appname in appnames: matching_items = [] if appname.startswith('/'): # search by exact path matching_items = [item for item in proc_list if item == appname] elif appname.endswith('.app'): # search by filename matching_items = [item for item in proc_list if '/'+ appname + '/Contents/MacOS/' in item] else: # check executable name matching_items = [item for item in proc_list if item.endswith('/' + appname)] if not matching_items: # try adding '.app' to the name and check again matching_items = [item for item in proc_list if '/' + appname + '.app/Contents/MacOS/' in item] matching_items = set(matching_items) for path in matching_items: while '/Contents/' in path or path.endswith('/Contents'): path = os.path.dirname(path) # ask NSFileManager for localized name since end-users # will see this name running_apps.append(filemanager.displayNameAtPath_(path)) return list(set(running_apps))
def getRunningBlockingApps(appnames): """Given a list of app names, return a list of friendly names for apps in the list that are running""" proc_list = getRunningProcesses() running_apps = [] filemanager = NSFileManager.alloc().init() for appname in appnames: matching_items = [] if appname.endswith('.app'): # search by filename matching_items = [item for item in proc_list if '/'+ appname + '/' in item] else: # check executable name matching_items = [item for item in proc_list if item.endswith('/' + appname)] if not matching_items: # try adding '.app' to the name and check again matching_items = [item for item in proc_list if '/' + appname + '.app/' in item] matching_items = set(matching_items) for path in matching_items: while '/Contents/' in path or path.endswith('/Contents'): path = os.path.dirname(path) # ask NSFileManager for localized name since end-users # will see this name running_apps.append(filemanager.displayNameAtPath_(path)) return list(set(running_apps))
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 get_mounted_network_volumes(): '''Uses Foundation.NSFileManager to get mounted volumes. is_network_volume() is called to filter out volumes that are not of type "smbfs"''' #pylint: disable=C0103 fm = NSFileManager.alloc().init() mounts = fm.mountedVolumeURLsIncludingResourceValuesForKeys_options_( None, 0) mount_paths = [] for mount in mounts: mount_path = mount.fileSystemRepresentation() if is_network_volume(mount_path): mount_paths.append(mount_path) return mount_paths
def getRunningBlockingApps(appnames): """Given a list of app names, return a list of dicts for apps in the list that are running. Each dict contains username, pathname, display_name""" proc_list = getRunningProcessesWithUsers() running_apps = [] filemanager = NSFileManager.alloc().init() for appname in appnames: matching_items = [] if appname.startswith('/'): # search by exact path matching_items = [ item for item in proc_list if item['pathname'] == appname ] elif appname.endswith('.app'): # search by filename matching_items = [ item for item in proc_list if '/' + appname + '/Contents/MacOS/' in item['pathname'] ] else: # check executable name matching_items = [ item for item in proc_list if item['pathname'].endswith('/' + appname) ] if not matching_items: # try adding '.app' to the name and check again matching_items = [ item for item in proc_list if '/' + appname + '.app/Contents/MacOS/' in item['pathname'] ] #matching_items = set(matching_items) for item in matching_items: path = item['pathname'] while '/Contents/' in path or path.endswith('/Contents'): path = os.path.dirname(path) # ask NSFileManager for localized name since end-users # will see this name item['display_name'] = filemanager.displayNameAtPath_(path) running_apps.append(item) return running_apps
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. """