mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-11-16 13:08:25 +00:00
Add configurable fractional steps to window resizing
This commit is contained in:
parent
fa9f8dac18
commit
ee7d3d604b
15 changed files with 464 additions and 20 deletions
|
|
@ -202,6 +202,10 @@ Detailed list of changes
|
|||
0.50.0 [future]
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
- Window resizing: Hold Alt with a resize letter to take a fraction of the
|
||||
remaining resize steps. Configure the fraction with the resize-window
|
||||
kitten's :code:`--fraction` option.
|
||||
|
||||
- Allow docking kitty windows to the edges of other windows or of the tab, for
|
||||
status bars, file trees, etc. Create them with :code:`launch --type=window-dock`
|
||||
or :code:`launch --type=tab-dock`, see :ref:`docks`
|
||||
|
|
|
|||
|
|
@ -360,6 +360,18 @@ window wider/narrower, but not taller/shorter. Note that what you are resizing
|
|||
is actually not a window, but a row/column in the layout, all windows in that
|
||||
row/column will be resized.
|
||||
|
||||
Hold :kbd:`Alt` with :kbd:`W`, :kbd:`N`, :kbd:`T`, or :kbd:`S` to take a fraction
|
||||
of the remaining resize steps in that direction. The default is one third,
|
||||
rounded up: five remaining steps become two, and one remaining step becomes
|
||||
one. Resizing stops at the layout's size limit. Ordinary letters (including
|
||||
uppercase letters) keep their normal step size, and :kbd:`Ctrl` doubles it.
|
||||
To choose a different fraction, pass :code:`--fraction`
|
||||
to the resize kitten, for example::
|
||||
|
||||
map kitty_mod+r kitten resize_window --fraction=1/4
|
||||
# macOS
|
||||
map cmd+r kitten resize_window --fraction=1/3
|
||||
|
||||
You can also define shortcuts in :file:`kitty.conf` to make the active window
|
||||
wider, narrower, taller, or shorter by mapping to the :ac:`resize_window`
|
||||
action, for example::
|
||||
|
|
|
|||
66
kittens/resize_window/fraction_test.go
Normal file
66
kittens/resize_window/fraction_test.go
Normal file
|
|
@ -0,0 +1,66 @@
|
|||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
func TestResizeFractionParsing(t *testing.T) {
|
||||
for value, want := range map[string]float64{"1/3": 1.0 / 3, "1/4": 0.25, "0.5": 0.5, "1": 1, "2/6": 1.0 / 3, " 1 / 3 ": 1.0 / 3} {
|
||||
got, err := parse_fraction(value)
|
||||
if err != nil || math.Abs(got-want) > 1e-12 {
|
||||
t.Fatalf("%q: got %v, %v; want %v", value, got, err, want)
|
||||
}
|
||||
}
|
||||
for _, value := range []string{"", "0", "-1", "1.1", "4/3", "1/0", "-1/-3", "1/-3", "1/NaN", "1/Inf", "NaN", "Inf", "1/2/3", "abc"} {
|
||||
if _, err := parse_fraction(value); err == nil {
|
||||
t.Fatalf("accepted invalid fraction %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeFractionKeys(t *testing.T) {
|
||||
for _, key := range []string{"w", "n", "t", "s"} {
|
||||
for _, mods := range []loop.KeyModifiers{0, loop.SHIFT, loop.CTRL, loop.ALT} {
|
||||
for _, eventType := range []loop.KeyEventType{loop.PRESS, loop.REPEAT, loop.RELEASE} {
|
||||
h := &handler{lp: &loop.Loop{}, opts: &Options{HorizontalIncrement: 2, VerticalIncrement: 2}, fraction: 1.0 / 3}
|
||||
e := &loop.KeyEvent{Key: key, Mods: mods, Type: eventType}
|
||||
if err := h.on_key(e); err != nil || !e.Handled {
|
||||
t.Fatalf("%s mods=%v type=%v: handled=%v error=%v", key, mods, eventType, e.Handled, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeFractionPayload(t *testing.T) {
|
||||
for _, fraction := range []float64{0, 1.0 / 3, 1} {
|
||||
ec, err := resize_command_escape_code(2, "horizontal", fraction)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cmd struct {
|
||||
Payload map[string]json.RawMessage `json:"payload"`
|
||||
}
|
||||
body := strings.TrimSuffix(strings.TrimPrefix(ec, "\x1bP@kitty-cmd"), "\x1b\\")
|
||||
if err := json.Unmarshal([]byte(body), &cmd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, present := cmd.Payload["fraction"]
|
||||
if present != (fraction != 0) {
|
||||
t.Fatalf("fraction %v: unexpected presence %v", fraction, present)
|
||||
}
|
||||
if present {
|
||||
var got float64
|
||||
if err := json.Unmarshal(raw, &got); err != nil || got != fraction {
|
||||
t.Fatalf("fraction %v: got %s, %v", fraction, raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -5,7 +5,9 @@ package resize_window
|
|||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
|
|
@ -22,6 +24,30 @@ type handler struct {
|
|||
ctx *markup.Context
|
||||
original_size loop.ScreenSize
|
||||
print_on_fail string
|
||||
fraction float64
|
||||
}
|
||||
|
||||
func parse_fraction(value string) (float64, error) {
|
||||
parts := strings.Split(value, "/")
|
||||
if len(parts) > 2 {
|
||||
return 0, fmt.Errorf("invalid fraction: %q", value)
|
||||
}
|
||||
n, err := strconv.ParseFloat(strings.TrimSpace(parts[0]), 64)
|
||||
if err == nil && len(parts) == 2 {
|
||||
var d float64
|
||||
d, err = strconv.ParseFloat(strings.TrimSpace(parts[1]), 64)
|
||||
if err == nil {
|
||||
if d <= 0 || math.IsNaN(d) || math.IsInf(d, 0) {
|
||||
err = fmt.Errorf("invalid denominator")
|
||||
} else {
|
||||
n /= d
|
||||
}
|
||||
}
|
||||
}
|
||||
if err != nil || math.IsNaN(n) || math.IsInf(n, 0) || n <= 0 || n > 1 {
|
||||
return 0, fmt.Errorf("--fraction must be greater than zero and at most one, got %q", value)
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
type rc_response struct {
|
||||
|
|
@ -31,7 +57,7 @@ type rc_response struct {
|
|||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
func (h *handler) do_window_resize(is_decrease, is_horizontal, reset bool, multiplier int) error {
|
||||
func (h *handler) do_window_resize(is_decrease, is_horizontal, reset bool, multiplier int, fraction float64) error {
|
||||
increment := h.opts.HorizontalIncrement
|
||||
if !is_horizontal {
|
||||
increment = h.opts.VerticalIncrement
|
||||
|
|
@ -48,7 +74,7 @@ func (h *handler) do_window_resize(is_decrease, is_horizontal, reset bool, multi
|
|||
axis = "vertical"
|
||||
}
|
||||
}
|
||||
ec, err := resize_command_escape_code(increment, axis)
|
||||
ec, err := resize_command_escape_code(increment, axis, fraction)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
|
@ -111,7 +137,7 @@ func (h *handler) on_text(text string) error {
|
|||
text = strings.ToUpper(text)
|
||||
switch text {
|
||||
case "W", "N", "T", "S", "R":
|
||||
return h.do_window_resize(text == "N" || text == "S", text == "W" || text == "N", text == "R", 1)
|
||||
return h.do_window_resize(text == "N" || text == "S", text == "W" || text == "N", text == "R", 1, 0)
|
||||
case "Q":
|
||||
h.lp.Quit(0)
|
||||
}
|
||||
|
|
@ -119,15 +145,33 @@ func (h *handler) on_text(text string) error {
|
|||
}
|
||||
|
||||
func (h *handler) on_key(e *loop.KeyEvent) error {
|
||||
if e.Type == loop.RELEASE {
|
||||
e.Handled = true
|
||||
return nil
|
||||
}
|
||||
if e.MatchesPressOrRepeat("esc") {
|
||||
e.Handled = true
|
||||
h.lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
for _, k := range []string{"w", "n", "t", "s"} {
|
||||
if e.MatchesPressOrRepeat("alt+" + k) {
|
||||
e.Handled = true
|
||||
return h.do_window_resize(k == "n" || k == "s", k == "w" || k == "n", false, 1, h.fraction)
|
||||
}
|
||||
if e.MatchesPressOrRepeat("ctrl+" + k) {
|
||||
e.Handled = true
|
||||
return h.do_window_resize(k == "n" || k == "s", k == "w" || k == "n", false, 2)
|
||||
return h.do_window_resize(k == "n" || k == "s", k == "w" || k == "n", false, 2, 0)
|
||||
}
|
||||
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) {
|
||||
e.Handled = true
|
||||
return h.on_text(k)
|
||||
}
|
||||
}
|
||||
for _, k := range []string{"r", "q"} {
|
||||
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) {
|
||||
e.Handled = true
|
||||
return h.on_text(k)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
|
|
@ -149,6 +193,7 @@ func (h *handler) draw_screen() {
|
|||
lp.Println()
|
||||
lp.Println("Press " + lp.SprintStyled("italic", "Esc") + " to quit resize mode")
|
||||
lp.Println("Hold down " + lp.SprintStyled("italic", "Ctrl") + " to double step size")
|
||||
lp.Println("Hold down " + lp.SprintStyled("italic", "Alt") + " to take " + h.opts.Fraction + " of the remaining steps")
|
||||
lp.Println()
|
||||
lp.Println(lp.SprintStyled("bold fg=white", "Sizes"))
|
||||
lp.Printf("Original: %d rows %d cols\r\n", h.original_size.HeightCells, h.original_size.WidthCells)
|
||||
|
|
@ -159,11 +204,15 @@ func (h *handler) draw_screen() {
|
|||
}
|
||||
|
||||
func run_loop(opts *Options) (rc int, err error) {
|
||||
fraction, err := parse_fraction(opts.Fraction)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp, err := loop.New(loop.FullKeyboardProtocol)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
h := &handler{lp: lp, opts: opts, ctx: markup.New(true)}
|
||||
h := &handler{lp: lp, opts: opts, fraction: fraction, ctx: markup.New(true)}
|
||||
lp.OnInitialize = func() (string, error) {
|
||||
sz, err := lp.ScreenSize()
|
||||
if err != nil {
|
||||
|
|
@ -176,7 +225,12 @@ func run_loop(opts *Options) (rc int, err error) {
|
|||
return "", nil
|
||||
}
|
||||
lp.OnResize = func(old, new loop.ScreenSize) error { h.draw_screen(); return nil }
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error { return h.on_text(text) }
|
||||
lp.OnText = func(text string, from_key_event, in_bracketed_paste bool) error {
|
||||
if in_bracketed_paste {
|
||||
return nil
|
||||
}
|
||||
return h.on_text(text)
|
||||
}
|
||||
lp.OnKeyEvent = h.on_key
|
||||
lp.OnRCResponse = h.on_rc_response
|
||||
err = lp.Run()
|
||||
|
|
|
|||
|
|
@ -14,6 +14,14 @@ The base horizontal increment.
|
|||
default=2
|
||||
type=int
|
||||
The base vertical increment.
|
||||
|
||||
|
||||
--fraction
|
||||
default=1/3
|
||||
The fraction of the remaining resize steps to take when holding Alt.
|
||||
Can be a decimal or a ratio such as :code:`1/3`, and must be greater than zero
|
||||
and at most one. The step count is rounded up, with at least one step when
|
||||
space remains.
|
||||
""".format
|
||||
help_text = 'Resize the current window'
|
||||
usage = ''
|
||||
|
|
|
|||
|
|
@ -10,15 +10,16 @@ import (
|
|||
)
|
||||
|
||||
type resize_payload struct {
|
||||
Increment int `json:"increment"`
|
||||
Axis string `json:"axis"`
|
||||
Self bool `json:"self"`
|
||||
Increment int `json:"increment"`
|
||||
Axis string `json:"axis"`
|
||||
Self bool `json:"self"`
|
||||
Fraction float64 `json:"fraction,omitempty"`
|
||||
}
|
||||
|
||||
func resize_command_escape_code(increment int, axis string) (string, error) {
|
||||
func resize_command_escape_code(increment int, axis string, fraction float64) (string, error) {
|
||||
rc := utils.RemoteControlCmd{
|
||||
Cmd: "resize-window", Version: at.ProtocolVersion,
|
||||
Payload: resize_payload{Increment: increment, Axis: axis, Self: true},
|
||||
Payload: resize_payload{Increment: increment, Axis: axis, Self: true, Fraction: fraction},
|
||||
}
|
||||
data, err := json.Marshal(rc)
|
||||
if err != nil {
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@ import (
|
|||
)
|
||||
|
||||
func TestResizeCommandEscapeCode(t *testing.T) {
|
||||
ec, err := resize_command_escape_code(-4, "vertical")
|
||||
ec, err := resize_command_escape_code(-4, "vertical", 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1995,14 +1995,14 @@ class Boss:
|
|||
if overlay_window is not None:
|
||||
overlay_window.allow_remote_control = True
|
||||
|
||||
def resize_layout_window(self, window: Window, increment: float, is_horizontal: bool, reset: bool = False) -> bool | None | str:
|
||||
def resize_layout_window(self, window: Window, increment: float, is_horizontal: bool, reset: bool = False, fraction: float = 0) -> bool | None | str:
|
||||
tab = window.tabref()
|
||||
if tab is None or not increment:
|
||||
return False
|
||||
if reset:
|
||||
tab.reset_window_sizes()
|
||||
return None
|
||||
return tab.resize_window_by(window.id, increment, is_horizontal)
|
||||
return tab.resize_window_by(window.id, increment, is_horizontal, fraction)
|
||||
|
||||
def resize_os_window(self, os_window_id: int, width: int, height: int, unit: str, incremental: bool = False, metrics: 'None | OSWindowSize' = None) -> None:
|
||||
if not incremental and (width < 0 or height < 0):
|
||||
|
|
@ -2581,7 +2581,7 @@ class Boss:
|
|||
action_on_removal: Callable[[int, 'Boss'], None] | None = None,
|
||||
default_data: dict[str, Any] | None = None,
|
||||
) -> Any:
|
||||
from kittens.runner import CLIOnlyKitten, KittenMetadata, create_kitten_handler
|
||||
from kittens.runner import CLIOnlyKitten, KittenMetadata, create_kitten_handler, resolved_kitten
|
||||
|
||||
is_wrapped = kitten in wrapped_kitten_names()
|
||||
if window is None:
|
||||
|
|
@ -2673,6 +2673,10 @@ class Boss:
|
|||
wid = w.id
|
||||
overlay_window.actions_on_close.append(partial(self.on_kitten_finish, wid, custom_callback or end_kitten.handle_result, default_data=default_data))
|
||||
overlay_window.open_url_handler = end_kitten.open_url_handler
|
||||
if resolved_kitten(kitten) == 'resize_window':
|
||||
# The resize kitten sends commands over the overlay's terminal.
|
||||
# Also allow it when launched directly with configurable options.
|
||||
overlay_window.allow_remote_control = True
|
||||
if action_on_removal is not None:
|
||||
|
||||
def callback_wrapper(*a: Any) -> None:
|
||||
|
|
|
|||
|
|
@ -2,9 +2,11 @@
|
|||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
|
||||
from copy import copy, deepcopy
|
||||
from enum import Enum
|
||||
from functools import partial
|
||||
from itertools import repeat
|
||||
from math import ceil, isfinite
|
||||
from typing import Any, ClassVar, NamedTuple, cast
|
||||
|
||||
from kitty.borders import BorderColor
|
||||
|
|
@ -63,6 +65,10 @@ class LayoutGlobalData:
|
|||
lgd = LayoutGlobalData()
|
||||
|
||||
|
||||
def fractional_resize_steps(remaining: int, fraction: float) -> int:
|
||||
return max(1, ceil(remaining * fraction - 1e-9)) if remaining > 0 else 0
|
||||
|
||||
|
||||
def idx_for_id(win_id: int, windows: Iterable[WindowType]) -> int | None:
|
||||
for i, w in enumerate(windows):
|
||||
if w.id == win_id:
|
||||
|
|
@ -397,6 +403,34 @@ class Layout:
|
|||
return False
|
||||
return self.apply_bias(idx, increment, all_windows, is_horizontal)
|
||||
|
||||
def apply_fractional_bias(self, window_idx: int, increment: float, all_windows: WindowList, is_horizontal: bool) -> bool:
|
||||
return self.apply_bias(window_idx, increment, all_windows, is_horizontal)
|
||||
|
||||
def modify_size_of_window_by_fraction(self, all_windows: WindowList, window_id: int, increment: float, is_horizontal: bool, fraction: float) -> bool:
|
||||
if window_id not in all_windows.id_map:
|
||||
return False
|
||||
idx = all_windows.group_idx_for_window(window_id)
|
||||
if idx is None or all_windows.num_groups < 2 or not increment or not isfinite(increment) or not 0 < fraction <= 1:
|
||||
return False
|
||||
# Probe private layout state, without changing windows or rendering every
|
||||
# intermediate step. This follows each layout's ordinary resize rules.
|
||||
probe = copy(self)
|
||||
state = deepcopy(self.layout_state())
|
||||
state['opts'] = self.layout_opts.serialized()
|
||||
if not probe.set_layout_state(state, lambda group_id: group_id):
|
||||
return False
|
||||
remaining = 0
|
||||
# Biases span at most one unit; allow two for clamping/normalization.
|
||||
# The bound also prevents future layout implementations from looping.
|
||||
for _ in range(max(1, ceil(2 / abs(increment)))):
|
||||
if not probe.apply_fractional_bias(idx, increment, all_windows, is_horizontal):
|
||||
break
|
||||
remaining += 1
|
||||
steps = fractional_resize_steps(remaining, fraction)
|
||||
for _ in range(steps):
|
||||
self.apply_fractional_bias(idx, increment, all_windows, is_horizontal)
|
||||
return bool(steps)
|
||||
|
||||
def drag_resize_window(self, all_windows: WindowList, window_id: int, increment: float, is_horizontal: bool = True) -> float:
|
||||
"""Resize by a number of cells, returning the number of cells actually applied.
|
||||
|
||||
|
|
|
|||
|
|
@ -125,6 +125,22 @@ class Grid(Layout):
|
|||
setattr(self, attr, candidate)
|
||||
return True
|
||||
|
||||
def apply_fractional_bias(self, window_idx: int, increment: float, all_windows: WindowList, is_horizontal: bool) -> bool:
|
||||
num = all_windows.num_groups
|
||||
ncols, nrows, special_rows, special_col = calc_grid_size(num)
|
||||
|
||||
def geometry() -> tuple[tuple[LayoutData, LayoutData], ...]:
|
||||
return tuple((x, y) for _, x, y in self.layout_windows(num, nrows, ncols, special_rows, special_col))
|
||||
|
||||
before = geometry()
|
||||
before_rows, before_cols = self.biased_rows, self.biased_cols
|
||||
if not self.apply_bias(window_idx, increment, all_windows, is_horizontal):
|
||||
return False
|
||||
if geometry() == before:
|
||||
self.biased_rows, self.biased_cols = before_rows, before_cols
|
||||
return False
|
||||
return True
|
||||
|
||||
def layout_windows(
|
||||
self, num_windows: int, nrows: int, ncols: int, special_rows: int, special_col: int, on_col_done: Callable[[list[int]], None] = lambda col_windows: None
|
||||
) -> Generator[tuple[int, LayoutData, LayoutData], None, None]:
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@
|
|||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from collections.abc import Collection, Generator, Iterator, Sequence
|
||||
from math import ceil, isfinite
|
||||
from typing import Any, Optional, TypedDict, Union
|
||||
|
||||
from kitty.borders import BorderColor
|
||||
|
|
@ -11,7 +12,7 @@ from kitty.types import Edges, NeighborsMap, WindowGeometry, WindowMapper, Windo
|
|||
from kitty.typing_compat import EdgeLiteral, WindowType
|
||||
from kitty.window_list import WindowGroup, WindowList
|
||||
|
||||
from .base import BorderLine, DragOverlayMode, Layout, LayoutOpts, lgd, window_geometry_from_layouts
|
||||
from .base import BorderLine, DragOverlayMode, Layout, LayoutOpts, fractional_resize_steps, lgd, window_geometry_from_layouts
|
||||
|
||||
|
||||
def child_axis_units(child: 'Pair | int | None', horizontal: bool) -> int:
|
||||
|
|
@ -840,6 +841,46 @@ class Splits(Layout):
|
|||
which = 1 if pair.one == grp.id else 2
|
||||
return pair.modify_size_of_child(which, increment, is_horizontal, self)
|
||||
|
||||
def modify_size_of_window_by_fraction(self, all_windows: WindowList, window_id: int, increment: float, is_horizontal: bool, fraction: float) -> bool:
|
||||
if window_id not in all_windows.id_map:
|
||||
return False
|
||||
group = all_windows.group_for_window(window_id)
|
||||
if group is None or not increment or not isfinite(increment) or not 0 < fraction <= 1:
|
||||
return False
|
||||
path = self.pairs_root.find_window_in_tree(group.id)
|
||||
if not path:
|
||||
return False
|
||||
for pair, in_one in reversed(path):
|
||||
if not pair.is_redundant and pair.horizontal == is_horizontal:
|
||||
break
|
||||
else:
|
||||
return False
|
||||
size = pair.width if is_horizontal else pair.height
|
||||
if size <= 0:
|
||||
return False
|
||||
groups = {g.id: g for g in all_windows.iter_all_layoutable_groups()}
|
||||
|
||||
def minimum(child: Pair | int | None) -> int:
|
||||
if isinstance(child, Pair):
|
||||
return child.minimum_width(groups) if is_horizontal else child.minimum_height(groups)
|
||||
return lgd.cell_width if is_horizontal else lgd.cell_height
|
||||
|
||||
# Match layout_pair's limits, including nested children and borders.
|
||||
# Pixel midpoints avoid instability from integer truncation at a limit.
|
||||
low = (minimum(pair.one) + pair.border_width + 0.5) / size
|
||||
high = (size - minimum(pair.two) - pair.border_width + 0.5) / size
|
||||
if high <= low:
|
||||
return False
|
||||
current = max(low, min(pair.bias, high))
|
||||
delta = increment if in_one else -increment
|
||||
room = high - current if delta > 0 else current - low
|
||||
if room * size < 0.5:
|
||||
return False
|
||||
remaining = ceil(room / abs(delta) - 1e-9)
|
||||
steps = fractional_resize_steps(remaining, fraction)
|
||||
pair.bias = max(low, min(current + steps * delta, high))
|
||||
return True
|
||||
|
||||
def remove_all_biases(self) -> bool:
|
||||
for pair in self.pairs_root.self_and_descendants():
|
||||
pair.bias = 0.5
|
||||
|
|
|
|||
|
|
@ -180,6 +180,19 @@ class Tall(Layout):
|
|||
self.biased_map = candidate
|
||||
return before != after
|
||||
|
||||
def apply_fractional_bias(self, window_idx: int, increment: float, all_windows: WindowList, is_horizontal: bool) -> bool:
|
||||
# Main-axis biases can keep changing after the visible size stops
|
||||
# changing. Do not count those changes as remaining resize steps.
|
||||
layout = self.simple_layout if all_windows.num_groups <= self.num_full_size_windows + 1 else self.full_layout
|
||||
before_layout = tuple((x, y) for _, x, y, _ in layout(all_windows))
|
||||
before_bias, before_map = self.main_bias, self.biased_map
|
||||
if not self.apply_bias(window_idx, increment, all_windows, is_horizontal):
|
||||
return False
|
||||
if before_layout == tuple((x, y) for _, x, y, _ in layout(all_windows)):
|
||||
self.main_bias, self.biased_map = before_bias, before_map
|
||||
return False
|
||||
return True
|
||||
|
||||
def simple_layout(self, all_windows: WindowList) -> Generator[tuple[WindowGroup, LayoutData, LayoutData, bool], None, None]:
|
||||
num = all_windows.num_groups
|
||||
is_fat = not self.main_is_horizontal
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from math import isfinite
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .base import MATCH_WINDOW_OPTION, ArgsType, Boss, PayloadGetType, PayloadType, RCOptions, RemoteCommand, ResponseType, Window
|
||||
|
|
@ -14,6 +15,7 @@ class ResizeWindow(RemoteCommand):
|
|||
match/str: Which window to resize
|
||||
self/bool: Boolean indicating whether to resize the window the command is run in
|
||||
increment/int: Integer specifying the resize increment
|
||||
fraction/float: Fraction of the remaining resize steps to take, or zero for ordinary resizing
|
||||
axis/choices.horizontal.vertical.reset: One of :code:`horizontal, vertical` or :code:`reset`
|
||||
"""
|
||||
|
||||
|
|
@ -28,6 +30,13 @@ default=2
|
|||
The number of cells to change the size by, can be negative to decrease the size.
|
||||
|
||||
|
||||
--fraction
|
||||
type=float
|
||||
default=0
|
||||
Take this fraction of the remaining resize steps, rounding up. Must be between
|
||||
zero and one. Zero uses ordinary resizing. The increment sets the base step size.
|
||||
|
||||
|
||||
--axis -a
|
||||
type=choices
|
||||
choices=horizontal,vertical,reset
|
||||
|
|
@ -46,14 +55,26 @@ Resize the window this command is run in, rather than the active window.
|
|||
string_return_is_error = True
|
||||
|
||||
def message_to_kitty(self, global_opts: RCOptions, opts: 'CLIOptions', args: ArgsType) -> PayloadType:
|
||||
return {'match': opts.match, 'increment': opts.increment, 'axis': opts.axis, 'self': opts.self}
|
||||
self.validate_fraction(opts.fraction)
|
||||
return {'match': opts.match, 'increment': opts.increment, 'axis': opts.axis, 'self': opts.self, 'fraction': opts.fraction}
|
||||
|
||||
@staticmethod
|
||||
def validate_fraction(fraction: float) -> None:
|
||||
if not isfinite(fraction) or not 0 <= fraction <= 1:
|
||||
raise ValueError('Resize fraction must be between zero and one')
|
||||
|
||||
def response_from_kitty(self, boss: Boss, window: Window | None, payload_get: PayloadGetType) -> ResponseType:
|
||||
windows = self.windows_for_match_payload(boss, window, payload_get)
|
||||
fraction = payload_get('fraction', missing=0)
|
||||
self.validate_fraction(fraction)
|
||||
resized: bool | None | str = False
|
||||
if windows and windows[0]:
|
||||
resized = boss.resize_layout_window(
|
||||
windows[0], increment=payload_get('increment'), is_horizontal=payload_get('axis') == 'horizontal', reset=payload_get('axis') == 'reset'
|
||||
windows[0],
|
||||
increment=payload_get('increment'),
|
||||
is_horizontal=payload_get('axis') == 'horizontal',
|
||||
reset=payload_get('axis') == 'reset',
|
||||
fraction=fraction,
|
||||
)
|
||||
return resized
|
||||
|
||||
|
|
|
|||
|
|
@ -702,9 +702,13 @@ class Tab: # {{{
|
|||
else:
|
||||
self.goto_layout(layout_name)
|
||||
|
||||
def resize_window_by(self, window_id: int, increment: float, is_horizontal: bool) -> str | None:
|
||||
def resize_window_by(self, window_id: int, increment: float, is_horizontal: bool, fraction: float = 0) -> str | None:
|
||||
increment_as_percent = self.current_layout.bias_increment_for_cell(self.windows, is_horizontal) * increment
|
||||
if self.current_layout.modify_size_of_window(self.windows, window_id, increment_as_percent, is_horizontal):
|
||||
if fraction:
|
||||
changed = self.current_layout.modify_size_of_window_by_fraction(self.windows, window_id, increment_as_percent, is_horizontal, fraction)
|
||||
else:
|
||||
changed = self.current_layout.modify_size_of_window(self.windows, window_id, increment_as_percent, is_horizontal)
|
||||
if changed:
|
||||
self.relayout()
|
||||
return None
|
||||
return 'Could not resize'
|
||||
|
|
|
|||
166
kitty_tests/resize_fraction.py
Normal file
166
kitty_tests/resize_fraction.py
Normal file
|
|
@ -0,0 +1,166 @@
|
|||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
from copy import deepcopy
|
||||
from math import ceil
|
||||
from types import SimpleNamespace
|
||||
|
||||
from kitty.fast_data_types import Region
|
||||
from kitty.layout.base import lgd
|
||||
from kitty.layout.interface import Fat, Grid, Horizontal, Stack, Tall, Vertical
|
||||
from kitty.rc.base import PayloadGetter
|
||||
from kitty.rc.resize_window import resize_window
|
||||
from kitty.tabs import Tab
|
||||
|
||||
from . import layout as geometry_tests
|
||||
|
||||
|
||||
class TestFractionalResize(geometry_tests.BaseSplitGeometryTest):
|
||||
make_layout = geometry_tests.TestSplitDragGeometry.make_layout
|
||||
|
||||
def resize(self, tab, window_id, increment, horizontal, fraction=1 / 3):
|
||||
return Tab.resize_window_by(tab, window_id, increment, horizontal, fraction) is None
|
||||
|
||||
def test_fractional_splits_steps(self):
|
||||
for horizontal in (True, False):
|
||||
for window_id in (1, 2):
|
||||
for increment in (-2, 2):
|
||||
for remaining in (0, 1, 2, 3, 4, 5, 6, 10):
|
||||
with self.subTest(axis=horizontal, window=window_id, increment=increment, remaining=remaining):
|
||||
layout, windows, tab = self.make_layout({'horizontal': horizontal, 'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
size = pair.width if horizontal else pair.height
|
||||
cell = lgd.cell_width if horizontal else lgd.cell_height
|
||||
low = (cell + pair.border_width + 0.5) / size
|
||||
high = (size - cell - pair.border_width + 0.5) / size
|
||||
delta = layout.bias_increment_for_cell(windows, horizontal) * increment * (1 if window_id == 1 else -1)
|
||||
pair.bias = (high if delta > 0 else low) - remaining * delta
|
||||
tab.relayout()
|
||||
before = pair.bias
|
||||
self.ae(self.resize(tab, window_id, increment, horizontal), bool(remaining))
|
||||
self.assertAlmostEqual(pair.bias, before + delta * ((remaining + 2) // 3))
|
||||
self.check_extents_fit(layout)
|
||||
while self.resize(tab, window_id, increment, horizontal):
|
||||
self.check_extents_fit(layout)
|
||||
at_limit = pair.bias
|
||||
for _ in range(3):
|
||||
self.assertFalse(self.resize(tab, window_id, increment, horizontal))
|
||||
self.ae(pair.bias, at_limit)
|
||||
self.assertTrue(self.resize(tab, window_id, -increment, horizontal))
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_fractional_splits_partial_step_and_options(self):
|
||||
for fraction in (1 / 4, 1 / 3, 1 / 2, 1):
|
||||
for increment in (-2, 2):
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
pair = layout.pairs_root
|
||||
delta = layout.bias_increment_for_cell(windows, True) * increment
|
||||
limit = (
|
||||
(pair.width - lgd.cell_width - pair.border_width + 0.5) / pair.width
|
||||
if delta > 0
|
||||
else (lgd.cell_width + pair.border_width + 0.5) / pair.width
|
||||
)
|
||||
pair.bias = limit - 9.75 * delta
|
||||
tab.relayout()
|
||||
before = pair.bias
|
||||
self.assertTrue(self.resize(tab, 1, increment, True, fraction))
|
||||
expected = before + ceil(10 * fraction) * delta
|
||||
self.assertAlmostEqual(pair.bias, min(expected, limit) if delta > 0 else max(expected, limit))
|
||||
pair.bias = limit - 0.25 * delta
|
||||
tab.relayout()
|
||||
self.assertTrue(self.resize(tab, 1, increment, True, fraction))
|
||||
self.assertAlmostEqual(pair.bias, limit)
|
||||
self.assertFalse(self.resize(tab, 1, increment, True, fraction))
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def test_fractional_splits_nested_and_saturated(self):
|
||||
shape = {'one': 1, 'two': {'horizontal': False, 'one': 2, 'two': {'one': 3, 'two': 4}}}
|
||||
for minimal in (True, False):
|
||||
for increment in (-2, 2):
|
||||
layout, _windows, tab = self.make_layout(shape, minimal)
|
||||
pair = layout.pairs_root
|
||||
others = {id(p): p.bias for p in pair.self_and_descendants() if p is not pair}
|
||||
pair.bias = 0 if increment > 0 else 1
|
||||
tab.relayout()
|
||||
self.assertTrue(self.resize(tab, 2, -increment, True))
|
||||
self.assertGreater(pair.bias, 0.1)
|
||||
self.assertLess(pair.bias, 0.9)
|
||||
self.ae({id(p): p.bias for p in pair.self_and_descendants() if p is not pair}, others)
|
||||
self.check_extents_fit(layout)
|
||||
|
||||
def other_layout(self, cls, num, opts=''):
|
||||
layout = geometry_tests.create_layout(cls)
|
||||
if opts:
|
||||
layout.layout_opts = layout.parse_layout_opts(opts)
|
||||
layout.remove_all_biases()
|
||||
windows = geometry_tests.create_windows(layout, num)
|
||||
self.stub_dimensions(layout, Region((0, 0, 1499, 1099, 1500, 1100)))
|
||||
layout(windows)
|
||||
return layout, windows
|
||||
|
||||
def test_fractional_all_layouts(self):
|
||||
# Compare with actual ordinary resizing and rendered geometries. This
|
||||
# catches incorrect counts and accidental mutation during the probe.
|
||||
for cls in (Tall, Fat, Grid, Vertical, Horizontal):
|
||||
for num in (2, 5):
|
||||
for horizontal in (True, False):
|
||||
for increment in (-2, 2):
|
||||
for window_id in (1, num):
|
||||
with self.subTest(layout=cls.name, windows=num, axis=horizontal, increment=increment, window=window_id):
|
||||
reference, ref_windows = self.other_layout(cls, num)
|
||||
step = reference.bias_increment_for_cell(ref_windows, horizontal) * increment
|
||||
states = []
|
||||
for _ in range(500):
|
||||
before = tuple(w.geometry for w in ref_windows)
|
||||
if not reference.modify_size_of_window(ref_windows, window_id, step, horizontal):
|
||||
break
|
||||
reference(ref_windows)
|
||||
if tuple(w.geometry for w in ref_windows) == before:
|
||||
break
|
||||
states.append(deepcopy(reference.layout_state()))
|
||||
else:
|
||||
self.fail('Ordinary resizing did not stop')
|
||||
layout, windows = self.other_layout(cls, num)
|
||||
before = deepcopy(layout.layout_state())
|
||||
changed = layout.modify_size_of_window_by_fraction(windows, window_id, step, horizontal, 1 / 3)
|
||||
self.ae(changed, bool(states))
|
||||
self.ae(layout.layout_state(), states[(len(states) + 2) // 3 - 1] if states else before)
|
||||
|
||||
def test_fractional_tall_full_size_and_mirrored(self):
|
||||
for cls in (Tall, Fat):
|
||||
for opts in ('full_size=2', 'full_size=3;mirrored=yes'):
|
||||
for window_id in (1, 5):
|
||||
layout, windows = self.other_layout(cls, 5, opts)
|
||||
step = layout.bias_increment_for_cell(windows, cls.main_is_horizontal) * 2
|
||||
self.assertTrue(layout.modify_size_of_window_by_fraction(windows, window_id, step, cls.main_is_horizontal, 1 / 3))
|
||||
layout(windows)
|
||||
self.assertTrue(all(w.geometry.xnum > 0 and w.geometry.ynum > 0 for w in windows))
|
||||
|
||||
def test_fractional_unavailable_and_invalid(self):
|
||||
for cls in (Stack, Tall, Fat, Grid, Vertical, Horizontal):
|
||||
layout, windows = self.other_layout(cls, 1)
|
||||
before = deepcopy(layout.layout_state())
|
||||
self.assertFalse(layout.modify_size_of_window_by_fraction(windows, 1, 0.1, True, 1 / 3))
|
||||
self.ae(layout.layout_state(), before)
|
||||
layout, windows, tab = self.make_layout({'one': 1, 'two': 2}, num=2)
|
||||
for window_id, increment, horizontal in ((999, 2, True), (1, 0, True), (1, 2, False)):
|
||||
self.assertFalse(self.resize(tab, window_id, increment, horizontal))
|
||||
for fraction in (0, -1, 1.1, float('nan'), float('inf')):
|
||||
self.assertFalse(layout.modify_size_of_window_by_fraction(windows, 1, 0.1, True, fraction))
|
||||
|
||||
def test_fractional_remote_validation_and_compatibility(self):
|
||||
calls = []
|
||||
boss = SimpleNamespace(resize_layout_window=lambda *a, **kw: calls.append(kw))
|
||||
window = SimpleNamespace(id=1)
|
||||
original = resize_window.windows_for_match_payload
|
||||
resize_window.windows_for_match_payload = lambda *a: [window]
|
||||
self.addCleanup(lambda: setattr(resize_window, 'windows_for_match_payload', original))
|
||||
for fraction in (None, 0, 1 / 3, 1):
|
||||
payload = {'increment': 2, 'axis': 'horizontal'}
|
||||
if fraction is not None:
|
||||
payload['fraction'] = fraction
|
||||
resize_window.response_from_kitty(boss, window, PayloadGetter(resize_window, payload))
|
||||
self.ae(calls[-1]['fraction'], fraction or 0)
|
||||
for fraction in (-1, 1.1, float('nan'), float('inf')):
|
||||
with self.assertRaises(ValueError):
|
||||
resize_window.response_from_kitty(boss, window, PayloadGetter(resize_window, {'fraction': fraction}))
|
||||
Loading…
Add table
Add a link
Reference in a new issue