windows.py 9.8 KB

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