TextRange.h 2.2 KB

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