CommonLocationsProvider.cpp 2.3 KB

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