windows.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. """Windows."""
  2. from __future__ import annotations
  3. import os
  4. import sys
  5. from functools import lru_cache
  6. from typing import TYPE_CHECKING
  7. from .api import PlatformDirsABC
  8. if TYPE_CHECKING:
  9. from collections.abc import Callable
  10. class Windows(PlatformDirsABC):
  11. """
  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. """
  21. :return: data directory tied to the user, e.g.
  22. ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname`` (not roaming) or
  23. ``%USERPROFILE%\\AppData\\Roaming\\$appauthor\\$appname`` (roaming)
  24. """
  25. const = "CSIDL_APPDATA" if self.roaming else "CSIDL_LOCAL_APPDATA"
  26. path = os.path.normpath(get_win_folder(const))
  27. return self._append_parts(path)
  28. def _append_parts(self, path: str, *, opinion_value: str | None = None) -> str:
  29. params = []
  30. if self.appname:
  31. if self.appauthor is not False:
  32. author = self.appauthor or self.appname
  33. params.append(author)
  34. params.append(self.appname)
  35. if opinion_value is not None and self.opinion:
  36. params.append(opinion_value)
  37. if self.version:
  38. params.append(self.version)
  39. path = os.path.join(path, *params) # noqa: PTH118
  40. self._optionally_create_directory(path)
  41. return path
  42. @property
  43. def site_data_dir(self) -> str:
  44. """:return: data directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname``"""
  45. path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
  46. return self._append_parts(path)
  47. @property
  48. def user_config_dir(self) -> str:
  49. """:return: config directory tied to the user, same as `user_data_dir`"""
  50. return self.user_data_dir
  51. @property
  52. def site_config_dir(self) -> str:
  53. """:return: config directory shared by the users, same as `site_data_dir`"""
  54. return self.site_data_dir
  55. @property
  56. def user_cache_dir(self) -> str:
  57. """
  58. :return: cache directory tied to the user (if opinionated with ``Cache`` folder within ``$appname``) e.g.
  59. ``%USERPROFILE%\\AppData\\Local\\$appauthor\\$appname\\Cache\\$version``
  60. """
  61. path = os.path.normpath(get_win_folder("CSIDL_LOCAL_APPDATA"))
  62. return self._append_parts(path, opinion_value="Cache")
  63. @property
  64. def site_cache_dir(self) -> str:
  65. """:return: cache directory shared by users, e.g. ``C:\\ProgramData\\$appauthor\\$appname\\Cache\\$version``"""
  66. path = os.path.normpath(get_win_folder("CSIDL_COMMON_APPDATA"))
  67. return self._append_parts(path, opinion_value="Cache")
  68. @property
  69. def user_state_dir(self) -> str:
  70. """:return: state directory tied to the user, same as `user_data_dir`"""
  71. return self.user_data_dir
  72. @property
  73. def user_log_dir(self) -> str:
  74. """:return: log directory tied to the user, same as `user_data_dir` if not opinionated else ``Logs`` in it"""
  75. path = self.user_data_dir
  76. if self.opinion:
  77. path = os.path.join(path, "Logs") # noqa: PTH118
  78. self._optionally_create_directory(path)
  79. return path
  80. @property
  81. def user_documents_dir(self) -> str:
  82. """:return: documents directory tied to the user e.g. ``%USERPROFILE%\\Documents``"""
  83. return os.path.normpath(get_win_folder("CSIDL_PERSONAL"))
  84. @property
  85. def user_downloads_dir(self) -> str:
  86. """:return: downloads directory tied to the user e.g. ``%USERPROFILE%\\Downloads``"""
  87. return os.path.normpath(get_win_folder("CSIDL_DOWNLOADS"))
  88. @property
  89. def user_pictures_dir(self) -> str:
  90. """:return: pictures directory tied to the user e.g. ``%USERPROFILE%\\Pictures``"""
  91. return os.path.normpath(get_win_folder("CSIDL_MYPICTURES"))
  92. @property
  93. def user_videos_dir(self) -> str:
  94. """:return: videos directory tied to the user e.g. ``%USERPROFILE%\\Videos``"""
  95. return os.path.normpath(get_win_folder("CSIDL_MYVIDEO"))
  96. @property
  97. def user_music_dir(self) -> str:
  98. """:return: music directory tied to the user e.g. ``%USERPROFILE%\\Music``"""
  99. return os.path.normpath(get_win_folder("CSIDL_MYMUSIC"))
  100. @property
  101. def user_desktop_dir(self) -> str:
  102. """:return: desktop directory tied to the user, e.g. ``%USERPROFILE%\\Desktop``"""
  103. return os.path.normpath(get_win_folder("CSIDL_DESKTOPDIRECTORY"))
  104. @property
  105. def user_runtime_dir(self) -> str:
  106. """
  107. :return: runtime directory tied to the user, e.g.
  108. ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
  109. """
  110. path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp")) # noqa: PTH118
  111. return self._append_parts(path)
  112. @property
  113. def site_runtime_dir(self) -> str:
  114. """:return: runtime directory shared by users, same as `user_runtime_dir`"""
  115. return self.user_runtime_dir
  116. def get_win_folder_from_env_vars(csidl_name: str) -> str:
  117. """Get folder from environment variables."""
  118. result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
  119. if result is not None:
  120. return result
  121. env_var_name = {
  122. "CSIDL_APPDATA": "APPDATA",
  123. "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
  124. "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
  125. }.get(csidl_name)
  126. if env_var_name is None:
  127. msg = f"Unknown CSIDL name: {csidl_name}"
  128. raise ValueError(msg)
  129. result = os.environ.get(env_var_name)
  130. if result is None:
  131. msg = f"Unset environment variable: {env_var_name}"
  132. raise ValueError(msg)
  133. return result
  134. def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:
  135. """Get a folder for a CSIDL name that does not exist as an environment variable."""
  136. if csidl_name == "CSIDL_PERSONAL":
  137. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents") # noqa: PTH118
  138. if csidl_name == "CSIDL_DOWNLOADS":
  139. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads") # noqa: PTH118
  140. if csidl_name == "CSIDL_MYPICTURES":
  141. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures") # noqa: PTH118
  142. if csidl_name == "CSIDL_MYVIDEO":
  143. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos") # noqa: PTH118
  144. if csidl_name == "CSIDL_MYMUSIC":
  145. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music") # noqa: PTH118
  146. return None
  147. def get_win_folder_from_registry(csidl_name: str) -> str:
  148. """
  149. Get folder from the registry.
  150. This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
  151. for all CSIDL_* names.
  152. """
  153. shell_folder_name = {
  154. "CSIDL_APPDATA": "AppData",
  155. "CSIDL_COMMON_APPDATA": "Common AppData",
  156. "CSIDL_LOCAL_APPDATA": "Local AppData",
  157. "CSIDL_PERSONAL": "Personal",
  158. "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
  159. "CSIDL_MYPICTURES": "My Pictures",
  160. "CSIDL_MYVIDEO": "My Video",
  161. "CSIDL_MYMUSIC": "My Music",
  162. }.get(csidl_name)
  163. if shell_folder_name is None:
  164. msg = f"Unknown CSIDL name: {csidl_name}"
  165. raise ValueError(msg)
  166. if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows
  167. raise NotImplementedError
  168. import winreg # noqa: PLC0415
  169. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
  170. directory, _ = winreg.QueryValueEx(key, shell_folder_name)
  171. return str(directory)
  172. def get_win_folder_via_ctypes(csidl_name: str) -> str:
  173. """Get folder with ctypes."""
  174. # There is no 'CSIDL_DOWNLOADS'.
  175. # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
  176. # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
  177. import ctypes # noqa: PLC0415
  178. csidl_const = {
  179. "CSIDL_APPDATA": 26,
  180. "CSIDL_COMMON_APPDATA": 35,
  181. "CSIDL_LOCAL_APPDATA": 28,
  182. "CSIDL_PERSONAL": 5,
  183. "CSIDL_MYPICTURES": 39,
  184. "CSIDL_MYVIDEO": 14,
  185. "CSIDL_MYMUSIC": 13,
  186. "CSIDL_DOWNLOADS": 40,
  187. "CSIDL_DESKTOPDIRECTORY": 16,
  188. }.get(csidl_name)
  189. if csidl_const is None:
  190. msg = f"Unknown CSIDL name: {csidl_name}"
  191. raise ValueError(msg)
  192. buf = ctypes.create_unicode_buffer(1024)
  193. windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker
  194. windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
  195. # Downgrade to short path name if it has high-bit chars.
  196. if any(ord(c) > 255 for c in buf): # noqa: PLR2004
  197. buf2 = ctypes.create_unicode_buffer(1024)
  198. if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
  199. buf = buf2
  200. if csidl_name == "CSIDL_DOWNLOADS":
  201. return os.path.join(buf.value, "Downloads") # noqa: PTH118
  202. return buf.value
  203. def _pick_get_win_folder() -> Callable[[str], str]:
  204. try:
  205. import ctypes # noqa: PLC0415
  206. except ImportError:
  207. pass
  208. else:
  209. if hasattr(ctypes, "windll"):
  210. return get_win_folder_via_ctypes
  211. try:
  212. import winreg # noqa: PLC0415, F401
  213. except ImportError:
  214. return get_win_folder_from_env_vars
  215. else:
  216. return get_win_folder_from_registry
  217. get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
  218. __all__ = [
  219. "Windows",
  220. ]