CommonLocationsProvider.cpp 2.3 KB

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