ConfigFile.h 2.5 KB

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