Aluode/PerceptionLabPortable
0
1"""Windows."""2 3from __future__ import annotations4 5import os6import sys7from functools import lru_cache8from typing import TYPE_CHECKING9 10from .api import PlatformDirsABC11 12if TYPE_CHECKING:13 from collections.abc import Callable14 15 16class Windows(PlatformDirsABC):17 """18 `MSDN on where to store app data files <https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_.19 20 Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `appauthor21 <platformdirs.api.PlatformDirsABC.appauthor>`, `version <platformdirs.api.PlatformDirsABC.version>`, `roaming22 <platformdirs.api.PlatformDirsABC.roaming>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists23 <platformdirs.api.PlatformDirsABC.ensure_exists>`.24 25 """26 27 @property28 def user_data_dir(self) -> str:29 """30 :return: data directory tied to the user, e.g.31 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or32 ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)33 """34 const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"35 path = os.path.normpath(get_win_folder(const))36 return self._append_parts(path)37 38 def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:39 params = []40 if self.appname:41 if self.appauthor is not False:42 author = self.appauthor or self.appname43 params.append(author)44 params.append(self.appname)45 if opinion_value is not None and self.opinion:46 params.append(opinion_value)47 if self.version:48 params.append(self.version)49 path = os.path.join(path, *params) # noqa: PTH11850 self._optionally_create_directory(path)51 return path52 53 @property54 def site_data_dir(self) -> str:55 """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""56 path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))57 return self._append_parts(path)58 59 @property60 def user_config_dir(self) -> str:61 """:return: config directory tied to the user, same as `user_data_dir`"""62 return self.user_data_dir63 64 @property65 def site_config_dir(self) -> str:66 """:return: config directory shared by the users, same as `site_data_dir`"""67 return self.site_data_dir68 69 @property70 def user_cache_dir(self) -> str:71 """72 :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.73 ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``74 """75 path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))76 return self._append_parts(path, opinion_value="Cache")77 78 @property79 def site_cache_dir(self) -> str:80 """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""81 path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))82 return self._append_parts(path, opinion_value="Cache")83 84 @property85 def user_state_dir(self) -> str:86 """:return: state directory tied to the user, same as `user_data_dir`"""87 return self.user_data_dir88 89 @property90 def user_log_dir(self) -> str:91 """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""92 path = self.user_data_dir93 if self.opinion:94 path = os.path.join(path, "Logs") # noqa: PTH11895 self._optionally_create_directory(path)96 return path97 98 @property99 def user_documents_dir(self) -> str:100 """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""101 return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))102 103 @property104 def user_downloads_dir(self) -> str:105 """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""106 return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))107 108 @property109 def user_pictures_dir(self) -> str:110 """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""111 return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))112 113 @property114 def user_videos_dir(self) -> str:115 """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""116 return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))117 118 @property119 def user_music_dir(self) -> str:120 """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""121 return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))122 123 @property124 def user_desktop_dir(self) -> str:125 """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""126 return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))127 128 @property129 def user_runtime_dir(self) -> str:130 """131 :return: runtime directory tied to the user, e.g.132 ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``133 """134 path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp")) # noqa: PTH118135 return self._append_parts(path)136 137 @property138 def site_runtime_dir(self) -> str:139 """:return: runtime directory shared by users, same as `user_runtime_dir`"""140 return self.user_runtime_dir141 142 143def get_win_folder_from_env_vars(csidl_name: str) -> str:144 """Get folder from environment variables."""145 result = get_win_folder_if_csidl_name_not_env_var(csidl_name)146 if result is not None:147 return result148 149 env_var_name = {150 "CSIDL_APPDATA": "APPDATA",151 "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",152 "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",153 }.get(csidl_name)154 if env_var_name is None:155 msg = f"Unknown CSIDL name: {csidl_name}"156 raise ValueError(msg)157 result = os.environ.get(env_var_name)158 if result is None:159 msg = f"Unset environment variable: {env_var_name}"160 raise ValueError(msg)161 return result162 163 164def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:165 """Get a folder for a CSIDL name that does not exist as an environment variable."""166 if csidl_name == "CSIDL_PERSONAL":167 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents") # noqa: PTH118168 169 if csidl_name == "CSIDL_DOWNLOADS":170 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads") # noqa: PTH118171 172 if csidl_name == "CSIDL_MYPICTURES":173 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures") # noqa: PTH118174 175 if csidl_name == "CSIDL_MYVIDEO":176 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos") # noqa: PTH118177 178 if csidl_name == "CSIDL_MYMUSIC":179 return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music") # noqa: PTH118180 return None181 182 183def get_win_folder_from_registry(csidl_name: str) -> str:184 """185 Get folder from the registry.186 187 This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer188 for all CSIDL_* names.189 190 """191 machine_names = {192 "CSIDL_COMMON_APPDATA",193 }194 shell_folder_name = {195 "CSIDL_APPDATA": "AppData",196 "CSIDL_COMMON_APPDATA": "Common AppData",197 "CSIDL_LOCAL_APPDATA": "Local AppData",198 "CSIDL_PERSONAL": "Personal",199 "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",200 "CSIDL_MYPICTURES": "My Pictures",201 "CSIDL_MYVIDEO": "My Video",202 "CSIDL_MYMUSIC": "My Music",203 }.get(csidl_name)204 if shell_folder_name is None:205 msg = f"Unknown CSIDL name: {csidl_name}"206 raise ValueError(msg)207 if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows208 raise NotImplementedError209 import winreg # noqa: PLC0415210 211 # Use HKEY_LOCAL_MACHINE for system-wide folders, HKEY_CURRENT_USER for user-specific folders212 hkey = winreg.HKEY_LOCAL_MACHINE if csidl_name in machine_names else winreg.HKEY_CURRENT_USER213 214 key = winreg.OpenKey(hkey, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")215 directory, _ = winreg.QueryValueEx(key, shell_folder_name)216 return str(directory)217 218 219def get_win_folder_via_ctypes(csidl_name: str) -> str:220 """Get folder with ctypes."""221 # There is no 'CSIDL_DOWNLOADS'.222 # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.223 # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid224 225 import ctypes # noqa: PLC0415226 227 csidl_const = {228 "CSIDL_APPDATA": 26,229 "CSIDL_COMMON_APPDATA": 35,230 "CSIDL_LOCAL_APPDATA": 28,231 "CSIDL_PERSONAL": 5,232 "CSIDL_MYPICTURES": 39,233 "CSIDL_MYVIDEO": 14,234 "CSIDL_MYMUSIC": 13,235 "CSIDL_DOWNLOADS": 40,236 "CSIDL_DESKTOPDIRECTORY": 16,237 }.get(csidl_name)238 if csidl_const is None:239 msg = f"Unknown CSIDL name: {csidl_name}"240 raise ValueError(msg)241 242 buf = ctypes.create_unicode_buffer(1024)243 windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker244 windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)245 246 # Downgrade to short path name if it has high-bit chars.247 if any(ord(c) > 255 for c in buf): # noqa: PLR2004248 buf2 = ctypes.create_unicode_buffer(1024)249 if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):250 buf = buf2251 252 if csidl_name == "CSIDL_DOWNLOADS":253 return os.path.join(buf.value, "Downloads") # noqa: PTH118254 255 return buf.value256 257 258def _pick_get_win_folder() -> Callable[[str], str]:259 try:260 import ctypes # noqa: PLC0415261 except ImportError:262 pass263 else:264 if hasattr(ctypes, "windll"):265 return get_win_folder_via_ctypes266 try:267 import winreg # noqa: PLC0415, F401268 except ImportError:269 return get_win_folder_from_env_vars270 else:271 return get_win_folder_from_registry272 273 274get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())275 276__all__ = [277 "Windows",278]279 