ConfigFile.h 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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 NonnullRefPtr<ConfigFile> open_for_lib(String const& lib_name, AllowWriting = AllowWriting::No);
  23. static NonnullRefPtr<ConfigFile> open_for_app(String const& app_name, AllowWriting = AllowWriting::No);
  24. static NonnullRefPtr<ConfigFile> open_for_system(String const& app_name, AllowWriting = AllowWriting::No);
  25. static NonnullRefPtr<ConfigFile> open(String const& filename, AllowWriting = AllowWriting::No);
  26. static 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. bool 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. explicit ConfigFile(String const& filename, AllowWriting);
  48. explicit ConfigFile(String const& filename, int fd);
  49. void reparse();
  50. NonnullRefPtr<File> m_file;
  51. HashMap<String, HashMap<String, String>> m_groups;
  52. bool m_dirty { false };
  53. };
  54. }