ConfigFile.h 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Jakob-Niklas See <git@nwex.de>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/HashMap.h>
  9. #include <AK/RefCounted.h>
  10. #include <AK/RefPtr.h>
  11. #include <AK/String.h>
  12. #include <AK/Vector.h>
  13. #include <LibCore/File.h>
  14. #include <LibGfx/Color.h>
  15. namespace Core {
  16. class ConfigFile : public RefCounted<ConfigFile> {
  17. public:
  18. enum class AllowWriting {
  19. Yes,
  20. No,
  21. };
  22. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_lib(String const& lib_name, AllowWriting = AllowWriting::No);
  23. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_app(String const& app_name, AllowWriting = AllowWriting::No);
  24. static ErrorOr<NonnullRefPtr<ConfigFile>> open_for_system(String const& app_name, AllowWriting = AllowWriting::No);
  25. static ErrorOr<NonnullRefPtr<ConfigFile>> open(String const& filename, AllowWriting = AllowWriting::No);
  26. static ErrorOr<NonnullRefPtr<ConfigFile>> open(String const& filename, int fd);
  27. ~ConfigFile();
  28. bool has_group(String const&) const;
  29. bool has_key(String const& group, String const& key) const;
  30. Vector<String> groups() const;
  31. Vector<String> keys(String const& group) const;
  32. size_t num_groups() const { return m_groups.size(); }
  33. String read_entry(String const& group, String const& key, String const& default_value = String()) const;
  34. int read_num_entry(String const& group, String const& key, int default_value = 0) const;
  35. bool read_bool_entry(String const& group, String const& key, bool default_value = false) const;
  36. void write_entry(String const& group, String const& key, String const& value);
  37. void write_num_entry(String const& group, String const& key, int value);
  38. void write_bool_entry(String const& group, String const& key, bool value);
  39. void write_color_entry(String const& group, String const& key, Color value);
  40. void dump() const;
  41. bool is_dirty() const { return m_dirty; }
  42. ErrorOr<void> sync();
  43. void remove_group(String const& group);
  44. void remove_entry(String const& group, String const& key);
  45. String filename() const { return m_file->filename(); }
  46. private:
  47. ConfigFile(String const& filename, NonnullRefPtr<File> open_file);
  48. void reparse();
  49. NonnullRefPtr<File> m_file;
  50. HashMap<String, HashMap<String, String>> m_groups;
  51. bool m_dirty { false };
  52. };
  53. }