window.hpp 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #pragma once
  2. #include "lumacs/buffer.hpp"
  3. #include <memory>
  4. #include <utility>
  5. #include <algorithm>
  6. namespace lumacs {
  7. /// @brief Represents the visible area of the buffer in a window.
  8. struct Viewport {
  9. int width = 0; ///< Width in characters.
  10. int height = 0; ///< Height in lines.
  11. int scroll_offset = 0; ///< Vertical scroll (top-most visible line index).
  12. int horizontal_offset = 0; ///< Horizontal scroll (left-most visible column index).
  13. };
  14. /// @brief Represents a window displaying a buffer.
  15. ///
  16. /// A Window holds a reference to a Buffer, a cursor position, and viewport settings.
  17. /// It manages scrolling and cursor movement within the bounds of the buffer.
  18. /// Multiple windows can display the same buffer.
  19. class Window {
  20. public:
  21. /// @brief Create a window displaying the given buffer.
  22. Window(std::shared_ptr<Buffer> buffer);
  23. /// @brief Change the buffer displayed in this window.
  24. void set_buffer(std::shared_ptr<Buffer> buffer);
  25. // Accessors
  26. std::shared_ptr<Buffer> buffer_ptr() const { return buffer_; }
  27. Buffer& buffer() { return *buffer_; }
  28. const Buffer& buffer() const { return *buffer_; }
  29. /// @brief Set the cursor position, clamping it to valid buffer bounds.
  30. void set_cursor(Position pos);
  31. /// @brief Get the current cursor position.
  32. Position cursor() const { return cursor_; }
  33. // Movement
  34. void move_up();
  35. void move_down();
  36. void move_left();
  37. void move_right();
  38. void move_to_line_start();
  39. void move_to_line_end();
  40. // Viewport
  41. /// @brief Update the viewport dimensions (called by UI on resize).
  42. void set_viewport_size(int width, int height);
  43. /// @brief Get the current viewport state.
  44. const Viewport& viewport() const { return viewport_; }
  45. /// @brief Adjust scroll offset to keep cursor visible (auto-scroll).
  46. void adjust_scroll();
  47. /// @brief Explicitly scroll the view by a number of lines.
  48. /// @param lines Number of lines to scroll (positive = down, negative = up).
  49. void scroll_lines(int lines);
  50. /// @brief Get the range of line indices currently visible in the viewport.
  51. /// @return Pair of {start_line, end_line} (end_line is exclusive).
  52. std::pair<size_t, size_t> visible_line_range() const;
  53. private:
  54. void clamp_cursor();
  55. std::shared_ptr<Buffer> buffer_;
  56. Position cursor_;
  57. Viewport viewport_;
  58. static constexpr int SCROLL_MARGIN = 3; ///< Lines of context to keep visible when scrolling.
  59. };
  60. } // namespace lumacs