StandardPaths.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedString.h>
  7. #include <AK/LexicalPath.h>
  8. #include <AK/Platform.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/StandardPaths.h>
  11. #include <pwd.h>
  12. #include <stdlib.h>
  13. #include <unistd.h>
  14. namespace Core {
  15. DeprecatedString StandardPaths::home_directory()
  16. {
  17. if (auto* home_env = getenv("HOME"))
  18. return LexicalPath::canonicalized_path(home_env);
  19. auto* pwd = getpwuid(getuid());
  20. DeprecatedString path = pwd ? pwd->pw_dir : "/";
  21. endpwent();
  22. return LexicalPath::canonicalized_path(path);
  23. }
  24. DeprecatedString StandardPaths::desktop_directory()
  25. {
  26. StringBuilder builder;
  27. builder.append(home_directory());
  28. builder.append("/Desktop"sv);
  29. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  30. }
  31. DeprecatedString StandardPaths::documents_directory()
  32. {
  33. StringBuilder builder;
  34. builder.append(home_directory());
  35. builder.append("/Documents"sv);
  36. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  37. }
  38. DeprecatedString StandardPaths::downloads_directory()
  39. {
  40. StringBuilder builder;
  41. builder.append(home_directory());
  42. builder.append("/Downloads"sv);
  43. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  44. }
  45. DeprecatedString StandardPaths::config_directory()
  46. {
  47. if (auto* config_directory = getenv("XDG_CONFIG_HOME"))
  48. return LexicalPath::canonicalized_path(config_directory);
  49. StringBuilder builder;
  50. builder.append(home_directory());
  51. #if defined(AK_OS_MACOS)
  52. builder.append("/Library/Preferences"sv);
  53. #else
  54. builder.append("/.config"sv);
  55. #endif
  56. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  57. }
  58. DeprecatedString StandardPaths::data_directory()
  59. {
  60. if (auto* data_directory = getenv("XDG_DATA_HOME"))
  61. return LexicalPath::canonicalized_path(data_directory);
  62. StringBuilder builder;
  63. builder.append(home_directory());
  64. #if defined(AK_OS_SERENITY)
  65. builder.append("/.data"sv);
  66. #elif defined(AK_OS_MACOS)
  67. builder.append("/Library/Application Support"sv);
  68. #else
  69. builder.append("/.local/share"sv);
  70. #endif
  71. return LexicalPath::canonicalized_path(builder.to_deprecated_string());
  72. }
  73. DeprecatedString StandardPaths::tempfile_directory()
  74. {
  75. return "/tmp";
  76. }
  77. }