TextRange.h 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2022, the SerenityOS developers.
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <LibGUI/TextPosition.h>
  9. namespace GUI {
  10. class TextRange {
  11. public:
  12. TextRange() = default;
  13. TextRange(TextPosition const& start, TextPosition const& end)
  14. : m_start(start)
  15. , m_end(end)
  16. {
  17. }
  18. bool is_valid() const { return m_start.is_valid() && m_end.is_valid() && m_start != m_end; }
  19. void clear()
  20. {
  21. m_start = {};
  22. m_end = {};
  23. }
  24. TextPosition& start() { return m_start; }
  25. TextPosition& end() { return m_end; }
  26. TextPosition const& start() const { return m_start; }
  27. TextPosition const& end() const { return m_end; }
  28. TextRange normalized() const { return TextRange(normalized_start(), normalized_end()); }
  29. void set_start(TextPosition const& position) { m_start = position; }
  30. void set_end(TextPosition const& position) { m_end = position; }
  31. void set(TextPosition const& start, TextPosition const& end)
  32. {
  33. m_start = start;
  34. m_end = end;
  35. }
  36. bool operator==(TextRange const& other) const
  37. {
  38. return m_start == other.m_start && m_end == other.m_end;
  39. }
  40. bool contains(TextPosition const& position) const
  41. {
  42. if (!(position.line() > m_start.line() || (position.line() == m_start.line() && position.column() >= m_start.column())))
  43. return false;
  44. if (!(position.line() < m_end.line() || (position.line() == m_end.line() && position.column() <= m_end.column())))
  45. return false;
  46. return true;
  47. }
  48. private:
  49. TextPosition normalized_start() const { return m_start < m_end ? m_start : m_end; }
  50. TextPosition normalized_end() const { return m_start < m_end ? m_end : m_start; }
  51. TextPosition m_start;
  52. TextPosition m_end;
  53. };
  54. }
  55. template<>
  56. struct AK::Formatter<GUI::TextRange> : AK::Formatter<FormatString> {
  57. ErrorOr<void> format(FormatBuilder& builder, GUI::TextRange const& value)
  58. {
  59. if (value.is_valid())
  60. return Formatter<FormatString>::format(builder, "{}-{}", value.start(), value.end());
  61. return Formatter<FormatString>::format(builder, "GUI::TextRange(Invalid)");
  62. }
  63. };