window.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #include "lumacs/window.hpp"
  2. namespace lumacs {
  3. Window::Window(std::shared_ptr<Buffer> buffer)
  4. : buffer_(std::move(buffer))
  5. {
  6. }
  7. void Window::set_buffer(std::shared_ptr<Buffer> buffer) {
  8. buffer_ = std::move(buffer);
  9. cursor_ = {0, 0};
  10. viewport_.scroll_offset = 0;
  11. }
  12. void Window::set_cursor(Position pos) {
  13. cursor_ = buffer_->clamp_position(pos);
  14. adjust_scroll();
  15. }
  16. void Window::move_up() {
  17. if (cursor_.line > 0) {
  18. cursor_.line--;
  19. clamp_cursor();
  20. adjust_scroll();
  21. }
  22. }
  23. void Window::move_down() {
  24. if (cursor_.line < buffer_->line_count() - 1) {
  25. cursor_.line++;
  26. clamp_cursor();
  27. adjust_scroll();
  28. }
  29. }
  30. void Window::move_left() {
  31. if (cursor_.column > 0) {
  32. cursor_.column--;
  33. } else if (cursor_.line > 0) {
  34. cursor_.line--;
  35. cursor_.column = buffer_->line(cursor_.line).size();
  36. adjust_scroll();
  37. }
  38. }
  39. void Window::move_right() {
  40. const auto& line = buffer_->line(cursor_.line);
  41. if (cursor_.column < line.size()) {
  42. cursor_.column++;
  43. } else if (cursor_.line < buffer_->line_count() - 1) {
  44. cursor_.line++;
  45. cursor_.column = 0;
  46. adjust_scroll();
  47. }
  48. }
  49. void Window::move_to_line_start() {
  50. cursor_.column = 0;
  51. }
  52. void Window::move_to_line_end() {
  53. cursor_.column = buffer_->line(cursor_.line).size();
  54. }
  55. void Window::set_viewport_size(int width, int height) {
  56. viewport_.width = std::max(1, width);
  57. viewport_.height = std::max(1, height);
  58. adjust_scroll();
  59. }
  60. void Window::adjust_scroll() {
  61. viewport_.height = std::max(10, viewport_.height);
  62. if (static_cast<int>(cursor_.line) >= viewport_.scroll_offset + viewport_.height - SCROLL_MARGIN) {
  63. viewport_.scroll_offset = static_cast<int>(cursor_.line) - viewport_.height + SCROLL_MARGIN + 1;
  64. }
  65. if (static_cast<int>(cursor_.line) < viewport_.scroll_offset + SCROLL_MARGIN) {
  66. viewport_.scroll_offset = (cursor_.line >= static_cast<size_t>(SCROLL_MARGIN))
  67. ? static_cast<int>(cursor_.line) - SCROLL_MARGIN
  68. : 0;
  69. }
  70. viewport_.scroll_offset = std::max(0, viewport_.scroll_offset);
  71. }
  72. std::pair<size_t, size_t> Window::visible_line_range() const {
  73. size_t start = viewport_.scroll_offset;
  74. size_t end = std::min(buffer_->line_count(),
  75. static_cast<size_t>(viewport_.scroll_offset + viewport_.height));
  76. return {start, end};
  77. }
  78. void Window::clamp_cursor() {
  79. cursor_ = buffer_->clamp_position(cursor_);
  80. }
  81. } // namespace lumacs