m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

255 lines
9.3 KiB

6 months ago
  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_runtime_dir(self) -> str:
  107. """
  108. :return: runtime directory tied to the user, e.g.
  109. ``%USERPROFILE%\\AppData\\Local\\Temp\\$appauthor\\$appname``
  110. """
  111. path = os.path.normpath(os.path.join(get_win_folder("CSIDL_LOCAL_APPDATA"), "Temp")) # noqa: PTH118
  112. return self._append_parts(path)
  113. def get_win_folder_from_env_vars(csidl_name: str) -> str:
  114. """Get folder from environment variables."""
  115. result = get_win_folder_if_csidl_name_not_env_var(csidl_name)
  116. if result is not None:
  117. return result
  118. env_var_name = {
  119. "CSIDL_APPDATA": "APPDATA",
  120. "CSIDL_COMMON_APPDATA": "ALLUSERSPROFILE",
  121. "CSIDL_LOCAL_APPDATA": "LOCALAPPDATA",
  122. }.get(csidl_name)
  123. if env_var_name is None:
  124. msg = f"Unknown CSIDL name: {csidl_name}"
  125. raise ValueError(msg)
  126. result = os.environ.get(env_var_name)
  127. if result is None:
  128. msg = f"Unset environment variable: {env_var_name}"
  129. raise ValueError(msg)
  130. return result
  131. def get_win_folder_if_csidl_name_not_env_var(csidl_name: str) -> str | None:
  132. """Get folder for a CSIDL name that does not exist as an environment variable."""
  133. if csidl_name == "CSIDL_PERSONAL":
  134. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Documents") # noqa: PTH118
  135. if csidl_name == "CSIDL_DOWNLOADS":
  136. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Downloads") # noqa: PTH118
  137. if csidl_name == "CSIDL_MYPICTURES":
  138. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Pictures") # noqa: PTH118
  139. if csidl_name == "CSIDL_MYVIDEO":
  140. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Videos") # noqa: PTH118
  141. if csidl_name == "CSIDL_MYMUSIC":
  142. return os.path.join(os.path.normpath(os.environ["USERPROFILE"]), "Music") # noqa: PTH118
  143. return None
  144. def get_win_folder_from_registry(csidl_name: str) -> str:
  145. """
  146. Get folder from the registry.
  147. This is a fallback technique at best. I'm not sure if using the registry for these guarantees us the correct answer
  148. for all CSIDL_* names.
  149. """
  150. shell_folder_name = {
  151. "CSIDL_APPDATA": "AppData",
  152. "CSIDL_COMMON_APPDATA": "Common AppData",
  153. "CSIDL_LOCAL_APPDATA": "Local AppData",
  154. "CSIDL_PERSONAL": "Personal",
  155. "CSIDL_DOWNLOADS": "{374DE290-123F-4565-9164-39C4925E467B}",
  156. "CSIDL_MYPICTURES": "My Pictures",
  157. "CSIDL_MYVIDEO": "My Video",
  158. "CSIDL_MYMUSIC": "My Music",
  159. }.get(csidl_name)
  160. if shell_folder_name is None:
  161. msg = f"Unknown CSIDL name: {csidl_name}"
  162. raise ValueError(msg)
  163. if sys.platform != "win32": # only needed for mypy type checker to know that this code runs only on Windows
  164. raise NotImplementedError
  165. import winreg
  166. key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders")
  167. directory, _ = winreg.QueryValueEx(key, shell_folder_name)
  168. return str(directory)
  169. def get_win_folder_via_ctypes(csidl_name: str) -> str:
  170. """Get folder with ctypes."""
  171. # There is no 'CSIDL_DOWNLOADS'.
  172. # Use 'CSIDL_PROFILE' (40) and append the default folder 'Downloads' instead.
  173. # https://learn.microsoft.com/en-us/windows/win32/shell/knownfolderid
  174. csidl_const = {
  175. "CSIDL_APPDATA": 26,
  176. "CSIDL_COMMON_APPDATA": 35,
  177. "CSIDL_LOCAL_APPDATA": 28,
  178. "CSIDL_PERSONAL": 5,
  179. "CSIDL_MYPICTURES": 39,
  180. "CSIDL_MYVIDEO": 14,
  181. "CSIDL_MYMUSIC": 13,
  182. "CSIDL_DOWNLOADS": 40,
  183. }.get(csidl_name)
  184. if csidl_const is None:
  185. msg = f"Unknown CSIDL name: {csidl_name}"
  186. raise ValueError(msg)
  187. buf = ctypes.create_unicode_buffer(1024)
  188. windll = getattr(ctypes, "windll") # noqa: B009 # using getattr to avoid false positive with mypy type checker
  189. windll.shell32.SHGetFolderPathW(None, csidl_const, None, 0, buf)
  190. # Downgrade to short path name if it has highbit chars.
  191. if any(ord(c) > 255 for c in buf): # noqa: PLR2004
  192. buf2 = ctypes.create_unicode_buffer(1024)
  193. if windll.kernel32.GetShortPathNameW(buf.value, buf2, 1024):
  194. buf = buf2
  195. if csidl_name == "CSIDL_DOWNLOADS":
  196. return os.path.join(buf.value, "Downloads") # noqa: PTH118
  197. return buf.value
  198. def _pick_get_win_folder() -> Callable[[str], str]:
  199. if hasattr(ctypes, "windll"):
  200. return get_win_folder_via_ctypes
  201. try:
  202. import winreg # noqa: F401
  203. except ImportError:
  204. return get_win_folder_from_env_vars
  205. else:
  206. return get_win_folder_from_registry
  207. get_win_folder = lru_cache(maxsize=None)(_pick_get_win_folder())
  208. __all__ = [
  209. "Windows",
  210. ]