window.hpp 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. ~Window();
  24. /// @brief Change the buffer displayed in this window.
  25. void set_buffer(std::shared_ptr<Buffer> buffer);
  26. // Accessors
  27. std::shared_ptr<Buffer> buffer_ptr() const { return buffer_; }
  28. Buffer& buffer() { return *buffer_; }
  29. const Buffer& buffer() const { return *buffer_; }
  30. /// @brief Set the cursor position, clamping it to valid buffer bounds.
  31. void set_cursor(Position pos);
  32. /// @brief Get the current cursor position.
  33. Position cursor() const { return cursor_; }
  34. // Movement
  35. void move_up();
  36. void move_down();
  37. void move_left();
  38. void move_right();
  39. void move_to_line_start();
  40. void move_to_line_end();
  41. // Viewport
  42. /// @brief Update the viewport dimensions (called by UI on resize).
  43. void set_viewport_size(int width, int height);
  44. /// @brief Get the current viewport state.
  45. const Viewport& viewport() const { return viewport_; }
  46. /// @brief Adjust scroll offset to keep cursor visible (auto-scroll).
  47. void adjust_scroll();
  48. /// @brief Explicitly scroll the view by a number of lines.
  49. /// @param lines Number of lines to scroll (positive = down, negative = up).
  50. void scroll_lines(int lines);
  51. /// @brief Get the range of line indices currently visible in the viewport.
  52. /// @return Pair of {start_line, end_line} (end_line is exclusive).
  53. std::pair<size_t, size_t> visible_line_range() const;
  54. private:
  55. void clamp_cursor();
  56. std::shared_ptr<Buffer> buffer_;
  57. Position cursor_;
  58. Viewport viewport_;
  59. static constexpr int SCROLL_MARGIN = 3; ///< Lines of context to keep visible when scrolling.
  60. };
  61. } // namespace lumacs