diff --git a/CHANGELOG.md b/CHANGELOG.md index ca17ca4a..a2b30c01 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -27,6 +27,8 @@ (https://codeberg.org/dnkl/foot/issues/146). * Color flashes when changing the color palette with OSC 4,10,11 (https://codeberg.org/dnkl/foot/issues/141). +* Scrollback position is now retained when resizing the window + (https://codeberg.org/dnkl/foot/issues/142). ### Security diff --git a/grid.c b/grid.c index e4b7c063..a79b4493 100644 --- a/grid.c +++ b/grid.c @@ -6,6 +6,7 @@ #define LOG_MODULE "grid" #define LOG_ENABLE_DBG 0 #include "log.h" +#include "macros.h" #include "sixel.h" #include "util.h" #include "xmalloc.h" @@ -65,6 +66,9 @@ grid_reflow(struct grid *grid, int new_rows, int new_cols, const int old_rows = grid->num_rows; const int old_cols = grid->num_cols; + /* Is viewpoint tracking current grid offset? */ + const bool view_follows = grid->view == grid->offset; + int new_col_idx = 0; int new_row_idx = 0; @@ -97,9 +101,14 @@ grid_reflow(struct grid *grid, int new_rows, int new_cols, tll_push_back(tracking_points, &cursor); tll_push_back(tracking_points, &saved_cursor); + struct coord viewport = {0, grid->view}; + if (!view_follows) + tll_push_back(tracking_points, &viewport); + for (size_t i = 0; i < tracking_points_count; i++) tll_push_back(tracking_points, _tracking_points[i]); + /* * Walk the old grid */ @@ -308,7 +317,6 @@ grid_reflow(struct grid *grid, int new_rows, int new_cols, grid->offset += new_rows; while (new_grid[grid->offset] == NULL) grid->offset = (grid->offset + 1) & (new_rows - 1); - grid->view = grid->offset; /* Ensure all visible rows have been allocated */ for (int r = 0; r < new_screen_rows; r++) { @@ -317,6 +325,23 @@ grid_reflow(struct grid *grid, int new_rows, int new_cols, new_grid[idx] = grid_row_alloc(new_cols, true); } + grid->view = view_follows ? grid->offset : viewport.row; + + /* If enlarging the window, the old viewport may be too far down, + * with unallocated rows. Make sure this cannot happen */ + while (true) { + int idx = (grid->view + new_screen_rows - 1) & (new_rows - 1); + if (new_grid[idx] != NULL) + break; + grid->view--; + if (grid->view < 0) + grid->view += new_rows; + } + for (size_t r = 0; r < new_screen_rows; r++) { + int UNUSED idx = (grid->view + r) & (new_rows - 1); + assert(new_grid[idx] != NULL); + } + /* Free old grid */ for (int r = 0; r < grid->num_rows; r++) grid_row_free(old_grid[r]);