CommonLocationsProvider.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) 2021, Dex♪ <dexes.ttp@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/DeprecatedString.h>
  7. #include <AK/JsonArray.h>
  8. #include <AK/JsonObject.h>
  9. #include <AK/Vector.h>
  10. #include <LibCore/File.h>
  11. #include <LibCore/StandardPaths.h>
  12. #include <LibFileSystem/FileSystem.h>
  13. #include <LibGUI/CommonLocationsProvider.h>
  14. #include <unistd.h>
  15. namespace GUI {
  16. static bool s_initialized = false;
  17. static Vector<CommonLocationsProvider::CommonLocation> s_common_locations;
  18. static void initialize_if_needed()
  19. {
  20. if (s_initialized)
  21. return;
  22. auto user_config = DeprecatedString::formatted("{}/CommonLocations.json", Core::StandardPaths::config_directory());
  23. if (FileSystem::exists(user_config)) {
  24. auto maybe_error = CommonLocationsProvider::load_from_json(user_config);
  25. if (!maybe_error.is_error())
  26. return;
  27. dbgln("Unable to read Common Locations file: {}", maybe_error.error());
  28. dbgln("Using the default set instead.");
  29. }
  30. // Fallback : If the user doesn't have custom locations, use some default ones.
  31. s_common_locations.append({ "Root", "/" });
  32. s_common_locations.append({ "Home", Core::StandardPaths::home_directory() });
  33. s_common_locations.append({ "Downloads", Core::StandardPaths::downloads_directory() });
  34. s_initialized = true;
  35. }
  36. ErrorOr<void> CommonLocationsProvider::load_from_json(StringView json_path)
  37. {
  38. auto file = TRY(Core::File::open(json_path, Core::File::OpenMode::Read));
  39. auto json = JsonValue::from_string(TRY(file->read_until_eof()));
  40. if (json.is_error())
  41. return Error::from_string_literal("File is not a valid JSON");
  42. if (!json.value().is_array())
  43. return Error::from_string_literal("File must contain a JSON array");
  44. s_common_locations.clear();
  45. auto const& contents = json.value().as_array();
  46. for (size_t i = 0; i < contents.size(); ++i) {
  47. auto entry_value = contents.at(i);
  48. if (!entry_value.is_object())
  49. continue;
  50. auto entry = entry_value.as_object();
  51. auto name = entry.get_deprecated_string("name"sv).value_or({});
  52. auto path = entry.get_deprecated_string("path"sv).value_or({});
  53. TRY(s_common_locations.try_append({ name, path }));
  54. }
  55. s_initialized = true;
  56. return {};
  57. }
  58. Vector<CommonLocationsProvider::CommonLocation> const& CommonLocationsProvider::common_locations()
  59. {
  60. initialize_if_needed();
  61. return s_common_locations;
  62. }
  63. }