Add independent resize strategy settings and in-page controls

This commit is contained in:
白鸽 2026-10-09 19:54:02 +08:00
parent ee7d3d604b
commit c6bedb393a
5 changed files with 509 additions and 48 deletions

View file

@ -7,6 +7,7 @@ import (
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"strings"
@ -14,17 +15,23 @@ import (
"github.com/kovidgoyal/kitty/tools/cli/markup"
"github.com/kovidgoyal/kitty/tools/tui"
"github.com/kovidgoyal/kitty/tools/tui/loop"
"github.com/kovidgoyal/kitty/tools/utils"
)
var _ = fmt.Print
type handler struct {
lp *loop.Loop
opts *Options
ctx *markup.Context
original_size loop.ScreenSize
print_on_fail string
fraction float64
lp *loop.Loop
opts *Options
ctx *markup.Context
original_size loop.ScreenSize
print_on_fail string
fraction float64
settings resize_settings
settings_path string
page string
fraction_input string
status string
}
func parse_fraction(value string) (float64, error) {
@ -128,50 +135,47 @@ func (h *handler) on_rc_response(raw []byte) error {
return nil
}
if json_is_truthy(response.Data) {
if hooks := h.active_hooks(); hooks != nil && hooks.OnResponse != nil {
if handled, err := hooks.OnResponse(h, response); err != nil || handled {
return err
}
}
h.lp.Beep()
}
return nil
}
func (h *handler) on_text(text string) error {
func (h *handler) window_on_text(text string) error {
modifier := loop.KeyModifiers(0)
if text != strings.ToLower(text) {
modifier = loop.SHIFT
}
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, 0)
multiplier, fraction := h.resize_step(modifier)
if text == "R" {
multiplier, fraction = 1, 0
}
return h.do_window_resize(text == "N" || text == "S", text == "W" || text == "N", text == "R", multiplier, fraction)
case "Q":
h.lp.Quit(0)
}
return nil
}
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
}
func (h *handler) window_on_key(e *loop.KeyEvent) error {
for _, k := range []string{"w", "n", "t", "s"} {
if e.MatchesPressOrRepeat("alt+" + k) {
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) || e.MatchesPressOrRepeat("alt+"+k) || e.MatchesPressOrRepeat("ctrl+"+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, 0)
}
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) {
e.Handled = true
return h.on_text(k)
multiplier, fraction := h.resize_step(e.Mods)
return h.do_window_resize(k == "n" || k == "s", k == "w" || k == "n", false, multiplier, fraction)
}
}
for _, k := range []string{"r", "q"} {
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) {
e.Handled = true
return h.on_text(k)
return h.window_on_text(k)
}
}
return nil
@ -182,19 +186,48 @@ func (h *handler) draw_screen() {
lp.StartAtomicUpdate()
defer lp.EndAtomicUpdate()
lp.ClearScreen()
lp.Println(lp.SprintStyled("bold fg=white", "Resize this window"))
lp.Println()
lp.Println("Press one of the following keys:")
lp.Println(" " + ctx.Green("W") + "ider")
lp.Println(" " + ctx.Green("N") + "arrower")
lp.Println(" " + ctx.Green("T") + "aller")
lp.Println(" " + ctx.Green("S") + "horter")
lp.Println(" " + ctx.Red("R") + "eset")
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")
if h.page != "" {
h.draw_settings_page()
return
}
title := "Resize this window"
if h.active_strategy() == "edge" {
title = "Resize an edge"
}
lp.Println(lp.SprintStyled("bold fg=white", title))
window, edge := "1: Window", "2: Edge"
if h.active_strategy() == "window" {
window = ctx.Green(window)
} else {
edge = ctx.Green(edge)
}
lp.Println("Strategy: " + window + " " + edge)
p := h.active_preferences()
modifier := "Alt"
if p.Modifier == "shift" {
modifier = "Shift"
}
lp.Println(ctx.Green("M") + ": " + modifier + " " + ctx.Green("F") + ": " + p.Fraction + " (change settings)")
lp.Println()
if h.active_strategy() == "window" {
lp.Println(" " + ctx.Green("W") + "ider")
lp.Println(" " + ctx.Green("N") + "arrower")
lp.Println(" " + ctx.Green("T") + "aller")
lp.Println(" " + ctx.Green("S") + "horter")
lp.Println(" " + ctx.Red("R") + "eset")
} else if hooks := h.active_hooks(); hooks != nil && hooks.Draw != nil {
hooks.Draw(h)
} else {
lp.Println("Edge strategy is not available yet.")
lp.Println("Its modifier and fraction can still be saved.")
}
lp.Println(lp.SprintStyled("italic", "Esc") + ": quit " + lp.SprintStyled("italic", "Ctrl") + ": double step size")
lp.Println(lp.SprintStyled("italic", modifier) + ": " + p.Fraction + " of the remaining steps")
status := "Settings saved automatically"
if h.status != "" {
status = h.status
}
lp.Println(status)
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)
if sz, err := lp.ScreenSize(); err == nil {
@ -203,8 +236,8 @@ func (h *handler) draw_screen() {
}
}
func run_loop(opts *Options) (rc int, err error) {
fraction, err := parse_fraction(opts.Fraction)
func run_loop(opts *Options, seen map[string]bool) (rc int, err error) {
_, err = parse_fraction(opts.Fraction)
if err != nil {
return 1, err
}
@ -212,7 +245,23 @@ func run_loop(opts *Options) (rc int, err error) {
if err != nil {
return 1, err
}
h := &handler{lp: lp, opts: opts, fraction: fraction, ctx: markup.New(true)}
path := filepath.Join(utils.ConfigDir(), "resize-window.json")
settings, load_err := load_settings(path)
if seen["Strategy"] {
settings.Strategy = opts.Strategy
}
if seen["Fraction"] {
p := settings.preferences(settings.Strategy)
p.Fraction = opts.Fraction
settings.Strategies[settings.Strategy] = p
}
h := &handler{lp: lp, opts: opts, settings: settings, settings_path: path, ctx: markup.New(true)}
if load_err != nil {
h.status = "Could not load settings: " + load_err.Error()
}
if err := h.sync_preferences(); err != nil {
return 1, err
}
lp.OnInitialize = func() (string, error) {
sz, err := lp.ScreenSize()
if err != nil {
@ -222,11 +271,16 @@ func run_loop(opts *Options) (rc int, err error) {
lp.SetCursorVisible(false)
lp.AllowLineWrapping(false)
h.draw_screen()
if hooks := h.active_hooks(); hooks != nil && hooks.OnActivate != nil {
if err := hooks.OnActivate(h); err != nil {
return "", err
}
}
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 {
if in_bracketed_paste {
if in_bracketed_paste && h.page != "edit-fraction" {
return nil
}
return h.on_text(text)
@ -246,7 +300,7 @@ func run_loop(opts *Options) (rc int, err error) {
}
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
return run_loop(opts)
return run_loop(opts, cmd.OptionsSeenOnCommandLine())
}
func EntryPoint(parent *cli.Command) {

View file

@ -18,10 +18,22 @@ The base vertical increment.
--fraction
default=1/3
The fraction of the remaining resize steps to take when holding Alt.
The fraction of the remaining resize steps to take with the chosen modifier.
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.
space remains. When explicitly given, overrides the saved fraction for this
invocation. Use F inside the resize page to change and save the fraction.
--strategy
type=choices
choices=window,edge
default=window
Choose the initial resize strategy. Window changes pane width or height;
edge selects a specific pane edge when an edge implementation is available.
When omitted, uses the strategy saved from the resize page. Inside the page,
1 and 2 choose a strategy, M switches its Alt/Shift modifier, and F changes
its fraction. Each strategy's settings are saved separately.
""".format
help_text = 'Resize the current window'
usage = ''

View file

@ -0,0 +1,141 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package resize_window
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"strings"
"github.com/kovidgoyal/kitty/tools/utils"
"golang.org/x/sys/unix"
)
type strategy_settings struct {
Modifier string `json:"modifier"`
Fraction string `json:"fraction"`
}
type resize_settings struct {
Version int `json:"version"`
Strategy string `json:"strategy"`
Strategies map[string]strategy_settings `json:"strategies"`
}
func default_settings() resize_settings {
return resize_settings{Version: 1, Strategy: "window", Strategies: map[string]strategy_settings{
"window": {Modifier: "alt", Fraction: "1/3"},
"edge": {Modifier: "shift", Fraction: "1/3"},
}}
}
func (s *resize_settings) preferences(strategy string) strategy_settings {
if p, ok := s.Strategies[strategy]; ok {
return p
}
return default_settings().Strategies[strategy]
}
func (s *resize_settings) normalize() error {
defaults := default_settings()
if s.Version == 0 {
s.Version = 1
}
if s.Version != 1 {
return fmt.Errorf("unsupported resize settings version: %d", s.Version)
}
if s.Strategy == "" {
s.Strategy = defaults.Strategy
}
if s.Strategy != "window" && s.Strategy != "edge" {
return fmt.Errorf("unknown resize strategy: %q", s.Strategy)
}
if s.Strategies == nil {
s.Strategies = make(map[string]strategy_settings)
}
for name, fallback := range defaults.Strategies {
p := s.Strategies[name]
if p.Modifier == "" {
p.Modifier = fallback.Modifier
}
if p.Modifier != "alt" && p.Modifier != "shift" {
return fmt.Errorf("invalid %s modifier: %q", name, p.Modifier)
}
p.Fraction = strings.TrimSpace(p.Fraction)
if p.Fraction == "" {
p.Fraction = fallback.Fraction
}
if _, err := parse_fraction(p.Fraction); err != nil {
return fmt.Errorf("invalid %s fraction: %w", name, err)
}
s.Strategies[name] = p
}
return nil
}
func load_settings(path string) (resize_settings, error) {
s := default_settings()
raw, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return s, nil
}
if err != nil {
return s, err
}
if err := json.Unmarshal(raw, &s); err != nil {
return default_settings(), err
}
if err := s.normalize(); err != nil {
return default_settings(), err
}
return s, nil
}
// Merge one changed field with the latest saved settings. Separate resize
// windows must not overwrite each other's strategy preferences.
func update_settings(path, strategy, field, value string) (resize_settings, error) {
if strategy != "window" && strategy != "edge" {
return resize_settings{}, fmt.Errorf("unknown resize strategy: %q", strategy)
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return resize_settings{}, err
}
lock, err := os.OpenFile(path+".lock", os.O_CREATE|os.O_RDWR, 0o600)
if err != nil {
return resize_settings{}, err
}
defer lock.Close()
if err := unix.Flock(int(lock.Fd()), unix.LOCK_EX); err != nil {
return resize_settings{}, err
}
defer unix.Flock(int(lock.Fd()), unix.LOCK_UN)
s, err := load_settings(path)
if err != nil {
return s, err
}
p := s.preferences(strategy)
switch field {
case "strategy":
s.Strategy = strategy
case "modifier":
p.Modifier = value
case "fraction":
p.Fraction = value
default:
return s, fmt.Errorf("unknown resize setting: %q", field)
}
s.Strategies[strategy] = p
if err := s.normalize(); err != nil {
return s, err
}
raw, err := json.MarshalIndent(s, "", " ")
if err != nil {
return s, err
}
raw = append(raw, '\n')
return s, utils.AtomicWriteFile(path, bytes.NewReader(raw), 0o600)
}

View file

@ -0,0 +1,203 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package resize_window
import (
"fmt"
"strings"
"github.com/kovidgoyal/kitty/tools/tui/loop"
)
var fraction_presets = []string{"1/2", "1/3", "1/4", "1/5", "1/10", "1"}
func (h *handler) sync_preferences() error {
p := h.active_preferences()
fraction, err := parse_fraction(p.Fraction)
if err == nil {
h.fraction = fraction
h.opts.Fraction = p.Fraction
h.opts.Strategy = h.active_strategy()
}
return err
}
func (h *handler) change_setting(field, value string) error {
strategy := h.active_strategy()
if field == "strategy" {
strategy = value
}
saved, err := update_settings(h.settings_path, strategy, field, value)
if err != nil {
h.status = "Could not save: " + err.Error()
h.draw_screen()
return nil
}
// A command-line override remains active for this invocation until the user
// changes that field. Save operations merge against disk, not stale UI state.
if field == "strategy" {
if hooks := h.active_hooks(); hooks != nil && hooks.OnDeactivate != nil {
if err := hooks.OnDeactivate(h); err != nil {
return err
}
}
h.settings.Strategy = saved.Strategy
h.settings.Strategies[strategy] = saved.preferences(strategy)
} else {
p := h.active_preferences()
if field == "modifier" {
p.Modifier = saved.preferences(strategy).Modifier
} else {
p.Fraction = saved.preferences(strategy).Fraction
}
h.settings.Strategies[strategy] = p
}
if err := h.sync_preferences(); err != nil {
return err
}
h.page, h.status = "", "Saved"
if field == "strategy" {
if hooks := h.active_hooks(); hooks != nil && hooks.OnActivate != nil {
if err := hooks.OnActivate(h); err != nil {
return err
}
}
}
h.draw_screen()
return nil
}
func (h *handler) on_text(text string) error {
if h.page == "edit-fraction" {
if len(h.fraction_input)+len(text) <= 32 && strings.Trim(text, "0123456789./eE+- ") == "" {
h.fraction_input += text
h.status = ""
h.draw_screen()
}
return nil
}
key := strings.ToLower(text)
if h.page == "fraction" {
if len(key) == 1 && key[0] >= '1' && int(key[0]-'1') < len(fraction_presets) {
return h.change_setting("fraction", fraction_presets[key[0]-'1'])
}
if key == "c" {
h.page, h.fraction_input, h.status = "edit-fraction", "", ""
h.draw_screen()
}
return nil
}
switch key {
case "1":
return h.change_setting("strategy", "window")
case "2":
return h.change_setting("strategy", "edge")
case "m":
modifier := "shift"
if h.active_preferences().Modifier == "shift" {
modifier = "alt"
}
return h.change_setting("modifier", modifier)
case "f":
h.page, h.status = "fraction", ""
h.draw_screen()
return nil
}
if h.active_strategy() == "edge" {
if hooks := h.active_hooks(); hooks != nil && hooks.OnText != nil {
return hooks.OnText(h, text)
}
return nil
}
return h.window_on_text(text)
}
func (h *handler) on_key(e *loop.KeyEvent) error {
if e.Type == loop.RELEASE {
e.Handled = true
return nil
}
if h.page != "" {
if e.MatchesPressOrRepeat("esc") {
e.Handled = true
h.page, h.status = "", ""
h.draw_screen()
return nil
}
if h.page == "edit-fraction" {
if e.MatchesPressOrRepeat("enter") {
e.Handled = true
value := strings.TrimSpace(h.fraction_input)
if _, err := parse_fraction(value); err != nil {
h.status = "Use a fraction greater than 0 and at most 1"
h.draw_screen()
return nil
}
return h.change_setting("fraction", value)
}
if e.MatchesPressOrRepeat("backspace") || e.MatchesPressOrRepeat("ctrl+u") {
e.Handled = true
if e.MatchesPressOrRepeat("ctrl+u") {
h.fraction_input = ""
} else if len(h.fraction_input) > 0 {
h.fraction_input = h.fraction_input[:len(h.fraction_input)-1]
}
h.status = ""
h.draw_screen()
return nil
}
}
if e.Mods & ^(loop.SHIFT|loop.CAPS_LOCK|loop.NUM_LOCK) == 0 && len(e.Key) == 1 {
e.Handled = true
if e.Text != "" {
return h.on_text(e.Text)
}
return h.on_text(e.Key)
}
return nil
}
for _, key := range []string{"1", "2", "m", "f"} {
if e.MatchesPressOrRepeat(key) {
e.Handled = true
if e.Type == loop.PRESS {
return h.on_text(key)
}
return nil
}
}
if h.active_strategy() == "edge" {
if hooks := h.active_hooks(); hooks != nil && hooks.OnKey != nil {
if err := hooks.OnKey(h, e); err != nil || e.Handled {
return err
}
}
} else if err := h.window_on_key(e); err != nil || e.Handled {
return err
}
if e.MatchesPressOrRepeat("esc") || e.MatchesPressOrRepeat("q") {
e.Handled = true
h.lp.Quit(0)
}
return nil
}
func (h *handler) draw_settings_page() {
lp, ctx := h.lp, h.ctx
lp.Println(lp.SprintStyled("bold fg=white", "Choose a fraction"))
lp.Println("For the " + h.active_strategy() + " strategy")
lp.Println()
if h.page == "edit-fraction" {
lp.Println("Enter a ratio or decimal, e.g. 1/7 or 0.2")
lp.Println("Fraction: " + ctx.Magenta(h.fraction_input) + "_")
lp.Println("Enter: save Esc: cancel Ctrl+U: clear")
} else {
for i, fraction := range fraction_presets {
lp.Println(fmt.Sprintf("%d: %s", i+1, ctx.Green(fraction)))
}
lp.Println("C: custom fraction Esc: cancel")
lp.Println("Current: " + ctx.Magenta(h.active_preferences().Fraction))
}
if h.status != "" {
lp.Println(h.status)
}
}

View file

@ -0,0 +1,51 @@
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
package resize_window
import "github.com/kovidgoyal/kitty/tools/tui/loop"
// The edge implementation can register these hooks from its own file's init().
// Settings keys and persistence are shared; all edge operations stay in that
// implementation. A nil registration is an unavailable strategy, never a
// fallback to resizing the whole window.
type strategy_hooks struct {
OnActivate func(*handler) error
OnDeactivate func(*handler) error
OnKey func(*handler, *loop.KeyEvent) error
OnText func(*handler, string) error
OnResponse func(*handler, rc_response) (bool, error)
Draw func(*handler)
}
var edge_strategy *strategy_hooks
func (h *handler) active_strategy() string {
if h.settings.Strategy == "edge" {
return "edge"
}
return "window"
}
func (h *handler) active_hooks() *strategy_hooks {
if h.active_strategy() == "edge" {
return edge_strategy
}
return nil
}
func (h *handler) active_preferences() strategy_settings {
return h.settings.preferences(h.active_strategy())
}
// Also used by an edge strategy when turning a key into a move request.
func (h *handler) resize_step(mods loop.KeyModifiers) (multiplier int, fraction float64) {
mods &= ^(loop.CAPS_LOCK | loop.NUM_LOCK)
if mods == loop.CTRL {
return 2, 0
}
p := h.active_preferences()
if (p.Modifier == "alt" && mods == loop.ALT) || (p.Modifier == "shift" && mods == loop.SHIFT) {
return 1, h.fraction
}
return 1, 0
}