windows.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. """Windows."""
  2. from __future__ import annotations
  3. import os
  4. import sys
  5. from typing import TYPE_CHECKING, Final
  6. from .api import PlatformDirsABC
  7. if TYPE_CHECKING:
  8. from collections.abc import Callable
  9. # Not exposed by CPython; defined in the Windows SDK (shlobj_core.h)
  10. _KF_FLAG_DONT_VERIFY: Final[int] = 0x00004000
  11. class Windows(PlatformDirsABC): # noqa: PLR0904
  12. """`MSDN on where to store app data files <https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid>`_.
  13. Makes use of the `appname <platformdirs.api.PlatformDirsABC.appname>`, `appauthor
  14. <platformdirs.api.PlatformDirsABC.appauthor>`, `version <platformdirs.api.PlatformDirsABC.version>`, `roaming
  15. <platformdirs.api.PlatformDirsABC.roaming>`, `opinion <platformdirs.api.PlatformDirsABC.opinion>`, `ensure_exists
  16. <platformdirs.api.PlatformDirsABC.ensure_exists>`.
  17. """
  18. @property
  19. def user_data_dir(self) -> str:
  20. r""":returns: data directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname`` (not roaming) or ``%USERPROFILE%\AppData\Roaming\$appauthor\$appname`` (roaming)"""
  21. const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
  22. path = os.path.normpath(get_win_folder(const))
  23. return self._append_parts(path)
  24. def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
  25. params = []
  26. if self.appname:
  27. if self.appauthor is not False:
  28. author = self.appauthor or self.appname
  29. params.append(author)
  30. params.append(self.appname)
  31. if opinion_value is not None and self.opinion:
  32. params.append(opinion_value)
  33. if self.version:
  34. params.append(self.version)
  35. path = os.path.join(path, *params) # noqa: PTH118
  36. self._optionally_create_directory(path)
  37. return path
  38. @property
  39. def site_data_dir(self) -> str:
  40. r""":returns: data directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname``"""
  41. path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
  42. return self._append_parts(path)
  43. @property
  44. def user_config_dir(self) -> str:
  45. """:returns: config directory tied to the user, same as `user_data_dir`"""
  46. return self.user_data_dir
  47. @property
  48. def site_config_dir(self) -> str:
  49. """:returns: config directory shared by users, same as `site_data_dir`"""
  50. return self.site_data_dir
  51. @property
  52. def user_cache_dir(self) -> str:
  53. r""":returns: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g. ``%USERPROFILE%\AppData\Local\$appauthor\$appname\Cache\$version``"""
  54. path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
  55. return self._append_parts(path, opinion_value="Cache")
  56. @property
  57. def site_cache_dir(self) -> str:
  58. r""":returns: cache directory shared by users, e.g. ``C:\ProgramData\$appauthor\$appname\Cache\$version``"""
  59. path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
  60. return self._append_parts(path, opinion_value="Cache")
  61. @property
  62. def user_state_dir(self) -> str:
  63. """:returns: state directory tied to the user, same as `user_data_dir`"""
  64. return self.user_data_dir
  65. @property
  66. def site_state_dir(self) -> str:
  67. """:returns: state directory shared by users, same as `site_data_dir`"""
  68. return self.site_data_dir
  69. @property
  70. def user_log_dir(self) -> str:
  71. """:returns: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
  72. path = self.user_data_dir
  73. if self.opinion:
  74. path = os.path.join(path, "Logs") # noqa: PTH118
  75. self._optionally_create_directory(path)
  76. return path
  77. @property
  78. def site_log_dir(self) -> str:
  79. """:returns: log directory shared by users, same as `site_data_dir` if not opinionated else ``Logs`` in it"""
  80. path = self.site_data_dir
  81. if self.opinion:
  82. path = os.path.join(path, "Logs") # noqa: PTH118
  83. self._optionally_create_directory(path)
  84. return path
  85. @property
  86. def user_documents_dir(self) -> str:
  87. r""":returns: documents directory tied to the user e.g. ``%USERPROFILE%\Documents``"""
  88. return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
  89. @property
  90. def user_downloads_dir(self) -> str:
  91. r""":returns: downloads directory tied to the user e.g. ``%USERPROFILE%\Downloads``"""
  92. return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
  93. @property
  94. def user_pictures_dir(self) -> str:
  95. r""":returns: pictures directory tied to the user e.g. ``%USERPROFILE%\Pictures``"""
  96. return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
  97. @property
  98. def user_videos_dir(self) -> str:
  99. r""":returns: videos directory tied to the user e.g. ``%USERPROFILE%\Videos``"""
  100. return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
  101. @property
  102. def user_music_dir(self) -> str:
  103. r""":returns: music directory tied to the user e.g. ``%USERPROFILE%\Music``"""
  104. return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
  105. @property
  106. def user_desktop_dir(self) -> str:
  107. r""":returns: desktop directory tied to the user, e.g. ``%USERPROFILE%\Desktop``"""
  108. return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
  109. @property
  110. def user_bin_dir(self) -> str:
  111. r""":returns: bin directory tied to the user, e.g. ``%LOCALAPPDATA%\Programs``"""
  112. return os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Programs")) # noqa: PTH118
  113. @property
  114. def site_bin_dir(self) -> str:
  115. """:returns: bin directory shared by users, e.g. ``C:\\ProgramData\bin``"""
  116. return os.path.normpath(os.path.join(get_win_folder("CSIDL_COMMON_APPDATA"), "bin")) # noqa: PTH118
  117. @property
  118. def user_applications_dir(self) -> str:
  119. r""":returns: applications directory tied to the user, e.g. ``Start Menu\Programs``"""
  120. return os.path.normpath(get_win_folder("CSIDL_PROGRAMS"))
  121. @property
  122. def site_applications_dir(self) -> str:
  123. r""":returns: applications directory shared by users, e.g. ``C:\ProgramData\Microsoft\Windows\Start Menu\Programs``"""
  124. return os.path.normpath(get_win_folder("CSIDL_COMMON_PROGRAMS"))
  125. @property
  126. def user_runtime_dir(self) -> str:
  127. r""":returns: runtime directory tied to the user, e.g. ``%USERPROFILE%\AppData\Local\Temp\$appauthor\$appname``"""
  128. path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp")) # noqa: PTH118
  129. return self._append_parts(path)
  130. @property
  131. def site_runtime_dir(self) -> str:
  132. """:returns: runtime directory shared by users, same as `user_runtime_dir`"""
  133. return self.user_runtime_dir
  134. def get_win_folder_from_env_vars(csidl_name: str) -> str:
  135. """Get folder from environment variables."""
  136. result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
  137. if result is not None:
  138. return result
  139. env_var_name = {
  140. "CSIDL_APPDATA": "APPDATA",
  141. "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
  142. "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
  143. }.get(csidl_name)
  144. if env_var_name is None:
  145. msg = f"Unknown CSIDL name: {csidl_name}"
  146. raise ValueError(msg)
  147. result = os.environ.get(env_var_name)
  148. if result is None:
  149. msg = f"Unset environment variable: {env_var_name}"
  150. raise ValueError(msg)
  151. return result
  152. def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None: # noqa: PLR0911
  153. """Get a folder for a CSIDL name that does not exist as an environment variable."""
  154. if csidl_name == "CSIDL_PERSONAL":
  155. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents") # noqa: PTH118
  156. if csidl_name == "CSIDL_DOWNLOADS":
  157. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads") # noqa: PTH118
  158. if csidl_name == "CSIDL_MYPICTURES":
  159. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures") # noqa: PTH118
  160. if csidl_name == "CSIDL_MYVIDEO":
  161. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos") # noqa: PTH118
  162. if csidl_name == "CSIDL_MYMUSIC":
  163. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music") # noqa: PTH118
  164. if csidl_name == "CSIDL_PROGRAMS":
  165. return os.path.join( # noqa: PTH118
  166. os.path.normpath(os.environ["APPDATA"]),
  167. "Microsoft",
  168. "Windows",
  169. "Start Menu",
  170. "Programs",
  171. )
  172. if csidl_name == "CSIDL_COMMON_PROGRAMS":
  173. return os.path.join( # noqa: PTH118
  174. os.path.normpath(os.environ.get("PROGRAMDATA", os.environ.get("ALLUSERSPROFILE", "C:\\ProgramData"))),
  175. "Microsoft",
  176. "Windows",
  177. "Start Menu",
  178. "Programs",
  179. )
  180. return None
  181. def get_win_folder_from_registry(csidl_name: str) -> str:
  182. """Get folder from the registry.
  183. This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
  184. for all CSIDL_* names.
  185. """
  186. machine_names = {
  187. "CSIDL_COMMON_APPDATA",
  188. "CSIDL_COMMON_PROGRAMS",
  189. }
  190. shell_folder_name = {
  191. "CSIDL_APPDATA": "AppData",
  192. "CSIDL_COMMON_APPDATA": "Common AppData",
  193. "CSIDL_LOCAL_APPDATA": "Local AppData",
  194. "CSIDL_PERSONAL": "Personal",
  195. "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
  196. "CSIDL_MYPICTURES": "My Pictures",
  197. "CSIDL_MYVIDEO": "My Video",
  198. "CSIDL_MYMUSIC": "My Music",
  199. "CSIDL_PROGRAMS": "Programs",
  200. "CSIDL_COMMON_PROGRAMS": "Common Programs",
  201. }.get(csidl_name)
  202. if shell_folder_name is None:
  203. msg = f"Unknown CSIDL name: {csidl_name}"
  204. raise ValueError(msg)
  205. if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows
  206. raise NotImplementedError
  207. import winreg # noqa: PLC0415
  208. # Use HKEY_LOCAL_MACHINE for system-wide folders, HKEY_CURRENT_USER for user-specific folders
  209. hkey = winreg.HKEY_LOCAL_MACHINE if csidl_name in machine_names else winreg.HKEY_CURRENT_USER
  210. key = winreg.OpenKey(hkey, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
  211. directory, _ = winreg.QueryValueEx(key, shell_folder_name)
  212. return str(directory)
  213. _KNOWN_FOLDER_GUIDS: dict[str, str] = {
  214. "CSIDL_APPDATA": "{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}",
  215. "CSIDL_COMMON_APPDATA": "{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}",
  216. "CSIDL_LOCAL_APPDATA": "{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}",
  217. "CSIDL_PERSONAL": "{FDD39AD0-238F-46AF-ADB4-6C85480369C7}",
  218. "CSIDL_MYPICTURES": "{33E28130-4E1E-4676-835A-98395C3BC3BB}",
  219. "CSIDL_MYVIDEO": "{18989B1D-99B5-455B-841C-AB7C74E4DDFC}",
  220. "CSIDL_MYMUSIC": "{4BD8D571-6D19-48D3-BE97-422220080E43}",
  221. "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
  222. "CSIDL_DESKTOPDIRECTORY": "{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}",
  223. "CSIDL_PROGRAMS": "{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}",
  224. "CSIDL_COMMON_PROGRAMS": "{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}",
  225. }
  226. def get_win_folder_via_ctypes(csidl_name: str) -> str:
  227. """Get folder via :func:`SHGetKnownFolderPath`.
  228. See https://learn.microsoft.com/en-us/windows/win32/api/shlobj_core/nf-shlobj_core-shgetknownfolderpath.
  229. """
  230. if sys.platform != "win32": # only needed for type checker to know that this code runs only on Windows
  231. raise NotImplementedError
  232. from ctypes import HRESULT, POINTER, Structure, WinDLL, byref, create_unicode_buffer, wintypes # noqa: PLC0415
  233. class _GUID(Structure):
  234. _fields_ = [
  235. ("Data1", wintypes.DWORD),
  236. ("Data2", wintypes.WORD),
  237. ("Data3", wintypes.WORD),
  238. ("Data4", wintypes.BYTE * 8),
  239. ]
  240. ole32 = WinDLL("ole32")
  241. ole32.CLSIDFromString.restype = HRESULT
  242. ole32.CLSIDFromString.argtypes = [wintypes.LPCOLESTR, POINTER(_GUID)]
  243. ole32.CoTaskMemFree.restype = None
  244. ole32.CoTaskMemFree.argtypes = [wintypes.LPVOID]
  245. shell32 = WinDLL("shell32")
  246. shell32.SHGetKnownFolderPath.restype = HRESULT
  247. shell32.SHGetKnownFolderPath.argtypes = [POINTER(_GUID), wintypes.DWORD, wintypes.HANDLE, POINTER(wintypes.LPWSTR)]
  248. kernel32 = WinDLL("kernel32")
  249. kernel32.GetShortPathNameW.restype = wintypes.DWORD
  250. kernel32.GetShortPathNameW.argtypes = [wintypes.LPWSTR, wintypes.LPWSTR, wintypes.DWORD]
  251. folder_guid = _KNOWN_FOLDER_GUIDS.get(csidl_name)
  252. if folder_guid is None:
  253. msg = f"Unknown CSIDL name: {csidl_name}"
  254. raise ValueError(msg)
  255. guid = _GUID()
  256. ole32.CLSIDFromString(folder_guid, byref(guid))
  257. path_ptr = wintypes.LPWSTR()
  258. shell32.SHGetKnownFolderPath(byref(guid), _KF_FLAG_DONT_VERIFY, None, byref(path_ptr))
  259. result = path_ptr.value
  260. ole32.CoTaskMemFree(path_ptr)
  261. if result is None:
  262. msg = f"SHGetKnownFolderPath returned NULL for {csidl_name}"
  263. raise ValueError(msg)
  264. if any(ord(c) > 255 for c in result): # noqa: PLR2004
  265. buf = create_unicode_buffer(1024)
  266. if kernel32.GetShortPathNameW(result, buf, 1024):
  267. result = buf.value
  268. return result
  269. def _pick_get_win_folder() -> Callable[[str], str]:
  270. """Select the best method to resolve Windows folder paths: ctypes, then registry, then environment variables."""
  271. try:
  272. import ctypes # noqa: PLC0415, F401
  273. except ImportError:
  274. pass
  275. else:
  276. return get_win_folder_via_ctypes
  277. try:
  278. import winreg # noqa: PLC0415, F401
  279. except ImportError:
  280. return get_win_folder_from_env_vars
  281. else:
  282. return get_win_folder_from_registry
  283. _resolve_win_folder = _pick_get_win_folder()
  284. def get_win_folder(csidl_name: str) -> str:
  285. """Get a Windows folder path, checking for ``WIN_PD_OVERRIDE_*`` environment variable overrides first.
  286. For example, ``CSIDL_LOCAL_APPDATA`` can be overridden by setting ``WIN_PD_OVERRIDE_LOCAL_APPDATA``.
  287. """
  288. env_var = f"WIN_PD_OVERRIDE_{csidl_name.removeprefix('CSIDL_')}"
  289. if override := os.environ.get(env_var, "").strip():
  290. return override
  291. return _resolve_win_folder(csidl_name)
  292. __all__ = [
  293. "Windows",
  294. ]