chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
@@ -0,0 +1,250 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
type edge_state struct {
|
||||
Edges []string `json:"edges"`
|
||||
Selected string `json:"selected"`
|
||||
Divider string `json:"divider"`
|
||||
Status string `json:"status"`
|
||||
Failed bool `json:"failed"`
|
||||
}
|
||||
|
||||
type edge_input struct {
|
||||
key string
|
||||
multiplier int
|
||||
fraction float64
|
||||
}
|
||||
|
||||
var edge_keys = []struct{ key, edge, arrow string }{
|
||||
{"h", "left", "left"}, {"j", "bottom", "down"},
|
||||
{"k", "top", "up"}, {"l", "right", "right"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
edge_strategy = &strategy_hooks{
|
||||
OnActivate: func(h *handler) error {
|
||||
h.edge_queue = nil
|
||||
return h.send_edge_command("start", "none", 0, 0)
|
||||
},
|
||||
OnDeactivate: func(h *handler) error { h.edge_queue = nil; return nil },
|
||||
OnSettings: func(h *handler) { h.edge_queue = nil },
|
||||
OnKey: func(h *handler, e *loop.KeyEvent) error { return h.on_edge_key(e) },
|
||||
OnText: func(h *handler, text string) error {
|
||||
mods := loop.KeyModifiers(0)
|
||||
if text != strings.ToLower(text) {
|
||||
mods = loop.SHIFT
|
||||
}
|
||||
multiplier, fraction := h.resize_step(mods)
|
||||
return h.edge_action(edge_input{strings.ToLower(text), multiplier, fraction})
|
||||
},
|
||||
OnResponse: func(h *handler, response rc_response) (bool, error) {
|
||||
var data string
|
||||
if json.Unmarshal(response.Data, &data) != nil {
|
||||
return false, nil
|
||||
}
|
||||
var fields map[string]json.RawMessage
|
||||
if json.Unmarshal([]byte(data), &fields) != nil {
|
||||
return false, nil
|
||||
}
|
||||
if _, found := fields["edges"]; !found {
|
||||
return false, nil
|
||||
}
|
||||
return true, h.on_edge_response(response.Data)
|
||||
},
|
||||
Draw: func(h *handler) { h.draw_edge_screen() },
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) send_edge_command(operation, edge string, increment int, fraction float64) error {
|
||||
ec, err := edge_command_escape_code(operation, edge, h.edge_state.Divider, increment, fraction)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.edge_pending = true
|
||||
h.lp.QueueWriteString(ec)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) edge_action(input edge_input) error {
|
||||
if input.key == "q" || input.key == "enter" {
|
||||
h.edge_queue = nil
|
||||
h.lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
if h.edge_pending || !h.edge_ready {
|
||||
h.edge_queue = append(h.edge_queue, input)
|
||||
return nil
|
||||
}
|
||||
switch input.key {
|
||||
case "esc":
|
||||
if h.edge_state.Selected == "" {
|
||||
h.lp.Quit(0)
|
||||
return nil
|
||||
}
|
||||
return h.send_edge_command("state", "none", 0, 0)
|
||||
case "r":
|
||||
return h.send_edge_command("reset", "none", 0, 0)
|
||||
}
|
||||
for _, k := range edge_keys {
|
||||
if input.key != k.key {
|
||||
continue
|
||||
}
|
||||
if h.edge_state.Selected == "" {
|
||||
return h.send_edge_command("select", k.edge, 0, 0)
|
||||
}
|
||||
horizontal := h.edge_state.Selected == "left" || h.edge_state.Selected == "right"
|
||||
if horizontal != (k.edge == "left" || k.edge == "right") {
|
||||
h.edge_state.Status = "Use J/K to move this edge"
|
||||
if horizontal {
|
||||
h.edge_state.Status = "Use H/L to move this edge"
|
||||
}
|
||||
h.draw_screen()
|
||||
return nil
|
||||
}
|
||||
increment := h.opts.HorizontalIncrement
|
||||
if !horizontal {
|
||||
increment = h.opts.VerticalIncrement
|
||||
}
|
||||
increment *= input.multiplier
|
||||
if k.edge == "left" || k.edge == "top" {
|
||||
increment = -increment
|
||||
}
|
||||
return h.send_edge_command("move", h.edge_state.Selected, increment, input.fraction)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) on_edge_key(e *loop.KeyEvent) error {
|
||||
for _, k := range edge_keys {
|
||||
for _, key := range []string{k.key, k.arrow} {
|
||||
for _, modifier := range []string{"alt+", "ctrl+", "", "shift+"} {
|
||||
if e.MatchesPressOrRepeat(modifier + key) {
|
||||
e.Handled = true
|
||||
multiplier, fraction := h.resize_step(e.Mods)
|
||||
input := edge_input{key: k.key, multiplier: multiplier, fraction: fraction}
|
||||
return h.edge_action(input)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"esc", "enter", "r", "q"} {
|
||||
if e.MatchesPressOrRepeat(key) || e.MatchesPressOrRepeat("shift+"+key) {
|
||||
e.Handled = true
|
||||
return h.edge_action(edge_input{key: key, multiplier: 1})
|
||||
}
|
||||
}
|
||||
if e.Mods.WithoutLocks() & ^loop.SHIFT != 0 && !e.MatchesPressOrRepeat("ctrl+c") && !e.MatchesPressOrRepeat("ctrl+z") {
|
||||
e.Handled = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) on_edge_response(raw json.RawMessage) error {
|
||||
var data string
|
||||
if err := json.Unmarshal(raw, &data); err != nil {
|
||||
return err
|
||||
}
|
||||
var state edge_state
|
||||
if err := json.Unmarshal([]byte(data), &state); err != nil {
|
||||
return err
|
||||
}
|
||||
h.edge_state = state
|
||||
h.edge_pending, h.edge_ready = false, true
|
||||
if state.Status != "" {
|
||||
// Newer than any local message, which would otherwise hide it
|
||||
h.status = ""
|
||||
}
|
||||
if state.Failed {
|
||||
h.lp.Beep()
|
||||
}
|
||||
h.draw_screen()
|
||||
if h.active_strategy() != "edge" || h.page != "" {
|
||||
h.edge_queue = nil
|
||||
return nil
|
||||
}
|
||||
for len(h.edge_queue) > 0 && !h.edge_pending && h.active_strategy() == "edge" && h.page == "" {
|
||||
input := h.edge_queue[0]
|
||||
h.edge_queue = h.edge_queue[1:]
|
||||
if err := h.edge_action(input); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) draw_edge_screen() {
|
||||
lp := h.lp
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
lp.ClearScreen()
|
||||
title := "Choose an edge"
|
||||
if h.edge_state.Selected != "" {
|
||||
title = "Move the " + h.edge_state.Selected + " edge"
|
||||
}
|
||||
lines := []string{lp.SprintStyled("bold fg=white", title)}
|
||||
sz, err := lp.ScreenSize()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
p := h.active_preferences()
|
||||
modifier := "Alt"
|
||||
if p.Modifier == "shift" {
|
||||
modifier = "Shift"
|
||||
}
|
||||
lines = append(lines, "Strategy: 1: Window "+h.ctx.Green("2: Edge"), h.ctx.Green("M")+": "+modifier+" "+h.ctx.Green("F")+": "+p.Fraction+" (change settings)")
|
||||
label := func(edge, text string) string {
|
||||
style := "fg=bright-black"
|
||||
for _, available := range h.edge_state.Edges {
|
||||
if edge == available {
|
||||
style = "fg=green"
|
||||
}
|
||||
}
|
||||
if edge == h.edge_state.Selected {
|
||||
style = "bold fg=yellow"
|
||||
}
|
||||
return lp.SprintStyled(style, text)
|
||||
}
|
||||
if sz.HeightCells >= 16 {
|
||||
lines = append(lines,
|
||||
" "+label("top", "K / ↑"),
|
||||
" "+label("top", "┌────────┐"),
|
||||
label("left", "H / ←")+" "+label("left", "│")+" pane "+label("right", "│")+" "+label("right", "L / →"),
|
||||
" "+label("bottom", "└────────┘"),
|
||||
" "+label("bottom", "J / ↓"))
|
||||
}
|
||||
if h.edge_state.Selected == "" {
|
||||
lines = append(lines, "H J K L / arrows: choose an internal edge", "Gray = outside edge Esc / Q: finish")
|
||||
if h.edge_ready && len(h.edge_state.Edges) == 0 {
|
||||
lines = append(lines, "No internal edges in this layout")
|
||||
}
|
||||
} else {
|
||||
keys := "J / K / ↓ / ↑"
|
||||
if h.edge_state.Selected == "left" || h.edge_state.Selected == "right" {
|
||||
keys = "H / L / ← / →"
|
||||
}
|
||||
lines = append(lines, h.ctx.Green(keys)+": move the selected divider", "Esc: choose edge Enter / Q: finish")
|
||||
}
|
||||
lines = append(lines, modifier+": "+p.Fraction+" remaining steps Ctrl: 2x", "R: restore original sizes")
|
||||
if sz.HeightCells >= 18 {
|
||||
lines = append(lines, fmt.Sprintf("Original: %d rows %d cols", h.original_size.HeightCells, h.original_size.WidthCells))
|
||||
}
|
||||
lines = append(lines, fmt.Sprintf("Current: %s rows %s cols", h.ctx.Magenta(fmt.Sprint(sz.HeightCells)), h.ctx.Magenta(fmt.Sprint(sz.WidthCells))))
|
||||
limit := max(1, int(sz.HeightCells)-1)
|
||||
status := h.edge_state.Status
|
||||
if h.status != "" {
|
||||
status = h.status
|
||||
}
|
||||
if status != "" {
|
||||
lines = append(lines[:min(len(lines), max(1, limit-1))], status)
|
||||
}
|
||||
lp.QueueWriteString(strings.Join(lines[:min(len(lines), limit)], "\r\n"))
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli/markup"
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
func TestEdgeResizeKeys(t *testing.T) {
|
||||
for _, modifier := range []string{"alt", "shift"} {
|
||||
for _, key := range []string{"h", "j", "k", "l", "LEFT", "RIGHT", "UP", "DOWN"} {
|
||||
for _, mods := range []loop.KeyModifiers{0, loop.SHIFT, loop.CTRL, loop.ALT, loop.CTRL | loop.SHIFT} {
|
||||
for _, typ := range []loop.KeyEventType{loop.PRESS, loop.REPEAT, loop.RELEASE} {
|
||||
settings := default_settings()
|
||||
settings.Strategy = "edge"
|
||||
settings.Strategies["edge"] = strategy_settings{modifier, "1/4"}
|
||||
h := &handler{lp: &loop.Loop{}, opts: &Options{Strategy: "edge", HorizontalIncrement: 3, VerticalIncrement: 2}, settings: settings, fraction: 0.25, edge_pending: true}
|
||||
e := &loop.KeyEvent{Key: key, Mods: mods, Type: typ}
|
||||
if err := h.on_key(e); err != nil || !e.Handled {
|
||||
t.Fatalf("%s mods=%v type=%v: handled=%v err=%v", key, mods, typ, e.Handled, err)
|
||||
}
|
||||
if typ == loop.RELEASE || mods == loop.CTRL|loop.SHIFT {
|
||||
if len(h.edge_queue) != 0 {
|
||||
t.Fatal("release or unsupported modifiers produced an action")
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(h.edge_queue) != 1 {
|
||||
t.Fatal("key did not queue exactly one action")
|
||||
}
|
||||
input := h.edge_queue[0]
|
||||
fraction, multiplier := 0.0, 1
|
||||
if (modifier == "alt" && mods == loop.ALT) || (modifier == "shift" && mods == loop.SHIFT) {
|
||||
fraction = 0.25
|
||||
}
|
||||
if mods == loop.CTRL {
|
||||
multiplier = 2
|
||||
}
|
||||
if input.fraction != fraction || input.multiplier != multiplier {
|
||||
t.Fatalf("%s mods=%v: got %+v", key, mods, input)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeSettingsCancelQueuedMoves(t *testing.T) {
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := default_settings()
|
||||
settings.Strategy = "edge"
|
||||
h := &handler{lp: lp, ctx: markup.New(true), opts: &Options{HorizontalIncrement: 2}, settings: settings, edge_ready: true, edge_pending: true}
|
||||
if err := h.on_text("l"); err != nil || len(h.edge_queue) != 1 {
|
||||
t.Fatalf("key was not queued: %v", err)
|
||||
}
|
||||
if err := h.on_text("f"); err != nil || len(h.edge_queue) != 0 || h.page != "fraction" {
|
||||
t.Fatalf("settings did not cancel queued movement: %v", err)
|
||||
}
|
||||
state, _ := json.Marshal(edge_state{Edges: []string{"right"}, Selected: "right", Divider: "123"})
|
||||
raw, _ := json.Marshal(string(state))
|
||||
response, _ := json.Marshal(rc_response{Ok: true, Data: raw})
|
||||
if err := h.on_rc_response(response); err != nil || h.edge_pending {
|
||||
t.Fatalf("reply while editing settings: %v", err)
|
||||
}
|
||||
e := &loop.KeyEvent{Key: "ESCAPE", Type: loop.PRESS}
|
||||
if err := h.on_key(e); err != nil || h.page != "" || len(h.edge_queue) != 0 || h.edge_pending {
|
||||
t.Fatalf("closing settings replayed canceled keys: %v", err)
|
||||
}
|
||||
if h.edge_state.Selected != "right" {
|
||||
t.Fatal("settings lost the selected edge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeLateResponseAfterStrategySwitch(t *testing.T) {
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := &handler{lp: lp, ctx: markup.New(true), settings: default_settings(), edge_pending: true, edge_queue: []edge_input{{key: "l", multiplier: 1}}}
|
||||
state, _ := json.Marshal(edge_state{Edges: []string{"right"}, Selected: "right", Divider: "123"})
|
||||
raw, _ := json.Marshal(string(state))
|
||||
response, _ := json.Marshal(rc_response{Ok: true, Data: raw})
|
||||
if err := h.on_rc_response(response); err != nil || len(h.edge_queue) != 0 || h.edge_pending {
|
||||
t.Fatalf("late edge reply was not consumed: %v", err)
|
||||
}
|
||||
if h.active_strategy() != "window" {
|
||||
t.Fatal("late edge reply changed the active strategy")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeResizeSelectBeforeQueuedMove(t *testing.T) {
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := default_settings()
|
||||
settings.Strategy = "edge"
|
||||
h := &handler{lp: lp, opts: &Options{Strategy: "edge", HorizontalIncrement: 2}, settings: settings, edge_ready: true}
|
||||
if err := h.on_text("l"); err != nil || !h.edge_pending {
|
||||
t.Fatalf("first key did not select: %v", err)
|
||||
}
|
||||
if err := h.on_text("h"); err != nil || len(h.edge_queue) != 1 {
|
||||
t.Fatalf("second key did not wait for selection: %v", err)
|
||||
}
|
||||
state, _ := json.Marshal(edge_state{Edges: []string{"right"}, Selected: "right", Divider: "123"})
|
||||
raw, _ := json.Marshal(string(state))
|
||||
if err := h.on_edge_response(raw); err != nil || !h.edge_pending || len(h.edge_queue) != 0 {
|
||||
t.Fatalf("queued move did not run after selection: %v", err)
|
||||
}
|
||||
if h.edge_state.Selected != "right" || h.edge_state.Divider != "123" {
|
||||
t.Fatal("selection identity was lost")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeResizePayload(t *testing.T) {
|
||||
ec, err := edge_command_escape_code("move", "left", "123", -3, 0.25)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cmd struct {
|
||||
Cmd string `json:"cmd"`
|
||||
Payload struct {
|
||||
Operation string `json:"operation"`
|
||||
Edge string `json:"edge"`
|
||||
Divider string `json:"divider"`
|
||||
Increment int `json:"increment"`
|
||||
Fraction float64 `json:"fraction"`
|
||||
Self bool `json:"self"`
|
||||
} `json:"payload"`
|
||||
}
|
||||
body := strings.TrimSuffix(strings.TrimPrefix(ec, "\x1bP@kitty-cmd"), "\x1b\\")
|
||||
if err := json.Unmarshal([]byte(body), &cmd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p := cmd.Payload
|
||||
if cmd.Cmd != "resize-window-edge" || p.Operation != "move" || p.Edge != "left" || p.Divider != "123" || p.Increment != -3 || p.Fraction != 0.25 || !p.Self {
|
||||
t.Fatalf("unexpected edge command: %+v", cmd)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEdgeStatusReplacesOlderLocalStatus(t *testing.T) {
|
||||
lp, err := loop.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings := default_settings()
|
||||
settings.Strategy = "edge"
|
||||
h := &handler{lp: lp, ctx: markup.New(true), opts: &Options{}, settings: settings, edge_pending: true, status: "Could not load settings: bad"}
|
||||
state, _ := json.Marshal(edge_state{Edges: []string{"right"}})
|
||||
if err := h.on_edge_response(must_marshal(t, string(state))); err != nil || h.status == "" {
|
||||
t.Fatalf("a reply without a status cleared the local status: %v", err)
|
||||
}
|
||||
state, _ = json.Marshal(edge_state{Edges: []string{"right"}, Selected: "right", Status: "At size limit; move the other way", Failed: true})
|
||||
if err := h.on_edge_response(must_marshal(t, string(state))); err != nil || h.status != "" || !h.edge_state.Failed {
|
||||
t.Fatalf("a newer edge status was hidden by an older local status: %q %v", h.status, err)
|
||||
}
|
||||
}
|
||||
|
||||
func must_marshal(t *testing.T, v any) json.RawMessage {
|
||||
raw, err := json.Marshal(v)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"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
|
||||
settings resize_settings
|
||||
settings_path string
|
||||
page string
|
||||
fraction_input string
|
||||
status string
|
||||
saved_timer loop.IdType
|
||||
edge_state edge_state
|
||||
edge_pending bool
|
||||
edge_ready bool
|
||||
edge_queue []edge_input
|
||||
}
|
||||
|
||||
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 {
|
||||
Ok bool `json:"ok"`
|
||||
Error string `json:"error"`
|
||||
Tb string `json:"tb"`
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
increment *= multiplier
|
||||
if is_decrease {
|
||||
increment = -increment
|
||||
}
|
||||
axis := "restore"
|
||||
if !reset {
|
||||
if is_horizontal {
|
||||
axis = "horizontal"
|
||||
} else {
|
||||
axis = "vertical"
|
||||
}
|
||||
}
|
||||
ec, err := resize_command_escape_code(increment, axis, fraction)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
h.lp.QueueWriteString(ec)
|
||||
return nil
|
||||
}
|
||||
|
||||
// json_is_truthy mirrors Python's truthiness test (`if value:`) for a decoded
|
||||
// JSON value, so on_rc_response's "beep if data is truthy" check matches the
|
||||
// behavior of kittens/resize_window/main.py's on_kitty_cmd_response. The
|
||||
// resize-window RC command returns bool | None | str for "data" (see
|
||||
// kitty/rc/resize_window.py), so False/None/"" must all be treated as falsy.
|
||||
func json_is_truthy(raw json.RawMessage) bool {
|
||||
if len(raw) == 0 {
|
||||
return false
|
||||
}
|
||||
var v any
|
||||
if err := json.Unmarshal(raw, &v); err != nil {
|
||||
return false
|
||||
}
|
||||
switch val := v.(type) {
|
||||
case nil:
|
||||
return false
|
||||
case bool:
|
||||
return val
|
||||
case float64:
|
||||
return val != 0
|
||||
case string:
|
||||
return val != ""
|
||||
case []any:
|
||||
return len(val) != 0
|
||||
case map[string]any:
|
||||
return len(val) != 0
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) on_rc_response(raw []byte) error {
|
||||
var response rc_response
|
||||
if err := json.Unmarshal(raw, &response); err != nil {
|
||||
return err
|
||||
}
|
||||
if !response.Ok {
|
||||
emsg := response.Error
|
||||
if response.Tb != "" {
|
||||
emsg += "\n" + response.Tb
|
||||
}
|
||||
h.print_on_fail = emsg
|
||||
h.lp.Quit(1)
|
||||
return nil
|
||||
}
|
||||
if edge_strategy != nil && edge_strategy.OnResponse != nil {
|
||||
if handled, err := edge_strategy.OnResponse(h, response); err != nil || handled {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if json_is_truthy(response.Data) {
|
||||
var message string
|
||||
if json.Unmarshal(response.Data, &message) == nil && message != "" {
|
||||
h.status = message
|
||||
h.draw_screen()
|
||||
}
|
||||
h.lp.Beep()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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":
|
||||
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) window_on_key(e *loop.KeyEvent) error {
|
||||
for _, k := range []string{"w", "n", "t", "s"} {
|
||||
if e.MatchesPressOrRepeat(k) || e.MatchesPressOrRepeat("shift+"+k) || e.MatchesPressOrRepeat("alt+"+k) || e.MatchesPressOrRepeat("ctrl+"+k) {
|
||||
e.Handled = true
|
||||
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.window_on_text(k)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *handler) draw_screen() {
|
||||
if h.page == "" && h.active_strategy() == "edge" {
|
||||
h.active_hooks().Draw(h)
|
||||
return
|
||||
}
|
||||
lp, ctx := h.lp, h.ctx
|
||||
lp.StartAtomicUpdate()
|
||||
defer lp.EndAtomicUpdate()
|
||||
lp.ClearScreen()
|
||||
if h.page != "" {
|
||||
h.draw_settings_page()
|
||||
return
|
||||
}
|
||||
lp.Println(lp.SprintStyled("bold fg=white", "Resize this window"))
|
||||
lp.Println("Strategy: " + ctx.Green("1: Window") + " 2: 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()
|
||||
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.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 {
|
||||
lp.Printf("Current: %s rows %s cols\r\n",
|
||||
ctx.Magenta(fmt.Sprint(sz.HeightCells)), ctx.Magenta(fmt.Sprint(sz.WidthCells)))
|
||||
}
|
||||
}
|
||||
|
||||
func run_loop(opts *Options, seen map[string]bool) (rc int, err error) {
|
||||
_, err = parse_fraction(opts.Fraction)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp, err := loop.New(loop.FullKeyboardProtocol)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
path := filepath.Join(utils.ConfigDir(), "resize-window.json")
|
||||
settings, load_err := settings_for_invocation(path, opts, seen)
|
||||
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 {
|
||||
return "", err
|
||||
}
|
||||
h.original_size = sz
|
||||
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 && h.page != "edit-fraction" {
|
||||
return nil
|
||||
}
|
||||
return h.on_text(text)
|
||||
}
|
||||
lp.OnKeyEvent = h.on_key
|
||||
lp.OnRCResponse = h.on_rc_response
|
||||
err = lp.Run()
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
lp.KillIfSignalled()
|
||||
if h.print_on_fail != "" {
|
||||
fmt.Fprintln(os.Stderr, h.print_on_fail)
|
||||
tui.HoldTillEnter(false)
|
||||
}
|
||||
return lp.ExitCode(), nil
|
||||
}
|
||||
|
||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
return run_loop(opts, cmd.OptionsSeenOnCommandLine())
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import sys
|
||||
|
||||
OPTIONS = r"""
|
||||
--horizontal-increment
|
||||
default=2
|
||||
type=int
|
||||
The base horizontal increment.
|
||||
|
||||
|
||||
--vertical-increment
|
||||
default=2
|
||||
type=int
|
||||
The base vertical increment.
|
||||
|
||||
|
||||
--fraction
|
||||
default=1/3
|
||||
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. 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 an internal pane edge with H/J/K/L or arrow keys, then moves its
|
||||
divider along that axis. A sole available edge is selected automatically.
|
||||
In Splits, either strategy uses R to restore the proportions saved when resize
|
||||
mode opened. Switching strategies preserves this snapshot. Edge resizing uses
|
||||
the Splits layout; other layouts retain Window's usual reset behavior.
|
||||
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 = ''
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This should be run as kitten resize-window')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = OPTIONS
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Resize the current window interactively'
|
||||
@@ -0,0 +1,53 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cmd/at"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
type resize_payload struct {
|
||||
Increment int `json:"increment"`
|
||||
Axis string `json:"axis"`
|
||||
Self bool `json:"self"`
|
||||
Fraction float64 `json:"fraction,omitempty"`
|
||||
Restore bool `json:"restore_entry_layout,omitempty"`
|
||||
}
|
||||
|
||||
func resize_command_escape_code(increment int, axis string, fraction float64) (string, error) {
|
||||
restore := axis == "restore"
|
||||
if restore {
|
||||
axis = "reset"
|
||||
}
|
||||
rc := utils.RemoteControlCmd{
|
||||
Cmd: "resize-window", Version: at.ProtocolVersion,
|
||||
Payload: resize_payload{Increment: increment, Axis: axis, Self: true, Fraction: fraction, Restore: restore},
|
||||
}
|
||||
data, err := json.Marshal(rc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "\x1bP@kitty-cmd" + string(data) + "\x1b\\", nil
|
||||
}
|
||||
|
||||
func edge_command_escape_code(operation, edge, divider string, increment int, fraction float64) (string, error) {
|
||||
rc := utils.RemoteControlCmd{
|
||||
Cmd: "resize-window-edge", Version: at.ProtocolVersion,
|
||||
Payload: struct {
|
||||
Operation string `json:"operation"`
|
||||
Edge string `json:"edge"`
|
||||
Divider string `json:"divider,omitempty"`
|
||||
Increment int `json:"increment"`
|
||||
Fraction float64 `json:"fraction,omitempty"`
|
||||
Self bool `json:"self"`
|
||||
}{operation, edge, divider, increment, fraction, true},
|
||||
}
|
||||
data, err := json.Marshal(rc)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "\x1bP@kitty-cmd" + string(data) + "\x1b\\", nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResizeCommandEscapeCode(t *testing.T) {
|
||||
ec, err := resize_command_escape_code(-4, "vertical", 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(ec, "\x1bP@kitty-cmd") || !strings.HasSuffix(ec, "\x1b\\") {
|
||||
t.Fatalf("bad framing: %q", ec)
|
||||
}
|
||||
var cmd struct {
|
||||
Cmd string `json:"cmd"`
|
||||
Version [3]int `json:"version"`
|
||||
Payload struct {
|
||||
Increment int `json:"increment"`
|
||||
Axis string `json:"axis"`
|
||||
Self bool `json:"self"`
|
||||
} `json:"payload"`
|
||||
}
|
||||
body := strings.TrimSuffix(strings.TrimPrefix(ec, "\x1bP@kitty-cmd"), "\x1b\\")
|
||||
if err := json.Unmarshal([]byte(body), &cmd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cmd.Cmd != "resize-window" || cmd.Payload.Increment != -4 || cmd.Payload.Axis != "vertical" || !cmd.Payload.Self {
|
||||
t.Fatalf("bad command: %+v", cmd)
|
||||
}
|
||||
if cmd.Version == [3]int{} {
|
||||
t.Fatal("version not set")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeResetUsesEntrySnapshotOnlyWhenRequested(t *testing.T) {
|
||||
for _, axis := range []string{"restore", "reset"} {
|
||||
ec, err := resize_command_escape_code(2, axis, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var cmd struct {
|
||||
Payload resize_payload `json:"payload"`
|
||||
}
|
||||
body := strings.TrimSuffix(strings.TrimPrefix(ec, "\x1bP@kitty-cmd"), "\x1b\\")
|
||||
if err := json.Unmarshal([]byte(body), &cmd); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cmd.Payload.Axis != "reset" || cmd.Payload.Restore != (axis == "restore") {
|
||||
t.Fatalf("reset source was not preserved: %+v", cmd.Payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
// 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: "alt", 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
|
||||
}
|
||||
|
||||
func settings_for_invocation(path string, opts *Options, seen map[string]bool) (resize_settings, error) {
|
||||
s, err := load_settings(path)
|
||||
if seen["Strategy"] {
|
||||
s.Strategy = opts.Strategy
|
||||
}
|
||||
if seen["Fraction"] {
|
||||
p := s.preferences(s.Strategy)
|
||||
p.Fraction = opts.Fraction
|
||||
s.Strategies[s.Strategy] = p
|
||||
}
|
||||
return s, err
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
)
|
||||
|
||||
func TestResizeSettingsPersistence(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "kitty", "resize-window.json")
|
||||
s, err := load_settings(path)
|
||||
if err != nil || !reflect.DeepEqual(s, default_settings()) {
|
||||
t.Fatalf("missing settings: %+v, %v", s, err)
|
||||
}
|
||||
changes := [][3]string{
|
||||
{"window", "modifier", "shift"}, {"window", "fraction", "1/7"},
|
||||
{"edge", "modifier", "alt"}, {"edge", "fraction", "1/4"}, {"edge", "strategy", "edge"},
|
||||
}
|
||||
for _, change := range changes {
|
||||
if _, err := update_settings(path, change[0], change[1], change[2]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s, err = load_settings(path)
|
||||
if err != nil || s.Strategy != "edge" || s.Strategies["window"] != (strategy_settings{"shift", "1/7"}) ||
|
||||
s.Strategies["edge"] != (strategy_settings{"alt", "1/4"}) {
|
||||
t.Fatalf("profiles did not persist independently: %+v, %v", s, err)
|
||||
}
|
||||
if _, err := update_settings(path, "window", "strategy", "window"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
reopened, err := load_settings(path)
|
||||
if err != nil || reopened.Strategy != "window" || !reflect.DeepEqual(reopened.Strategies, s.Strategies) {
|
||||
t.Fatalf("switching strategy changed its preferences: %+v, %v", reopened, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeSettingsValidation(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resize-window.json")
|
||||
for _, raw := range []string{
|
||||
`{`, `{"version":2}`, `{"strategy":"unknown"}`,
|
||||
`{"strategies":{"window":{"modifier":"meta"}}}`,
|
||||
`{"strategies":{"edge":{"fraction":"0"}}}`,
|
||||
`{"strategies":{"window":{"fraction":"NaN"}}}`,
|
||||
`{"strategies":{"window":{"fraction":"4/3"}}}`,
|
||||
} {
|
||||
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := load_settings(path); err == nil {
|
||||
t.Fatalf("accepted invalid settings %s", raw)
|
||||
}
|
||||
if _, err := update_settings(path, "window", "modifier", "shift"); err == nil {
|
||||
t.Fatalf("overwrote invalid settings %s", raw)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != raw {
|
||||
t.Fatalf("changed invalid file: %s, %v", data, err)
|
||||
}
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, change := range [][3]string{{"window", "modifier", "meta"}, {"edge", "fraction", "-1"}, {"unknown", "strategy", "unknown"}} {
|
||||
if _, err := update_settings(path, change[0], change[1], change[2]); err == nil {
|
||||
t.Fatalf("accepted invalid update %v", change)
|
||||
}
|
||||
}
|
||||
if _, err := os.Stat(path); !os.IsNotExist(err) {
|
||||
t.Fatal("invalid update created a settings file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeSettingsDefaultsAndOverrides(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resize-window.json")
|
||||
raw := `{"strategy":"edge","strategies":{"window":{"fraction":"1/4"},"edge":{"fraction":"1/5"}}}`
|
||||
if err := os.WriteFile(path, []byte(raw), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
opts := &Options{Fraction: "1/3", Strategy: "window"}
|
||||
s, err := settings_for_invocation(path, opts, nil)
|
||||
if err != nil || s.Strategy != "edge" || s.preferences("edge") != (strategy_settings{"alt", "1/5"}) ||
|
||||
s.preferences("window") != (strategy_settings{"alt", "1/4"}) {
|
||||
t.Fatalf("defaults masked saved preferences: %+v, %v", s, err)
|
||||
}
|
||||
s, err = settings_for_invocation(path, opts, map[string]bool{"Fraction": true, "Strategy": true})
|
||||
if err != nil || s.Strategy != "window" || s.preferences("window").Fraction != "1/3" || s.preferences("edge").Fraction != "1/5" {
|
||||
t.Fatalf("explicit options did not override only the active profile: %+v, %v", s, err)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil || string(data) != raw {
|
||||
t.Fatal("command-line overrides changed the saved settings")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeSettingsMerge(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resize-window.json")
|
||||
// Two pages opened with the same initial values, then edit different fields.
|
||||
first, _ := load_settings(path)
|
||||
second, _ := load_settings(path)
|
||||
if !reflect.DeepEqual(first, second) {
|
||||
t.Fatal("different starting state")
|
||||
}
|
||||
if _, err := update_settings(path, first.Strategy, "fraction", "1/2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := update_settings(path, second.Strategy, "modifier", "shift"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s, err := load_settings(path)
|
||||
if err != nil || s.preferences("window") != (strategy_settings{"shift", "1/2"}) {
|
||||
t.Fatalf("a stale page overwrote another page's change: %+v, %v", s, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeSettingsModifiers(t *testing.T) {
|
||||
for _, strategy := range []string{"window", "edge"} {
|
||||
for _, modifier := range []string{"alt", "shift"} {
|
||||
s := default_settings()
|
||||
s.Strategy = strategy
|
||||
s.Strategies[strategy] = strategy_settings{Modifier: modifier, Fraction: "1/7"}
|
||||
h := &handler{opts: &Options{}, settings: s}
|
||||
if err := h.sync_preferences(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, mods := range []loop.KeyModifiers{0, loop.SHIFT, loop.ALT, loop.CTRL, loop.CTRL | loop.SHIFT} {
|
||||
multiplier, fraction := h.resize_step(mods | loop.CAPS_LOCK)
|
||||
wantMultiplier, wantFraction := 1, 0.0
|
||||
if mods == loop.CTRL {
|
||||
wantMultiplier = 2
|
||||
} else if (modifier == "alt" && mods == loop.ALT) || (modifier == "shift" && mods == loop.SHIFT) {
|
||||
wantFraction = 1.0 / 7
|
||||
}
|
||||
if multiplier != wantMultiplier || fraction != wantFraction {
|
||||
t.Fatalf("%s %s mods=%v: got %d/%v", strategy, modifier, mods, multiplier, fraction)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeStrategyHooks(t *testing.T) {
|
||||
old := edge_strategy
|
||||
t.Cleanup(func() { edge_strategy = old })
|
||||
if edge_strategy == nil || edge_strategy.OnKey == nil || edge_strategy.OnText == nil || edge_strategy.Draw == nil {
|
||||
t.Fatal("Edge strategy is missing its interaction handlers")
|
||||
}
|
||||
s := default_settings()
|
||||
s.Strategy = "edge"
|
||||
// No loop: accidentally routing Window keys to a resize would panic.
|
||||
h := &handler{settings: s, opts: &Options{}, edge_ready: true}
|
||||
for _, text := range []string{"w", "W", "n", "t", "s"} {
|
||||
if err := h.on_text(text); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
e := &loop.KeyEvent{Key: "w", Type: loop.PRESS}
|
||||
if err := h.on_key(e); err != nil || e.Handled {
|
||||
t.Fatalf("Edge handled a Window resize key: %v", err)
|
||||
}
|
||||
keys, texts := 0, 0
|
||||
edge_strategy = &strategy_hooks{
|
||||
OnKey: func(h *handler, e *loop.KeyEvent) error { keys++; e.Handled = true; return nil },
|
||||
OnText: func(h *handler, text string) error { texts++; return nil },
|
||||
}
|
||||
if err := h.on_key(e); err != nil || !e.Handled || keys != 1 {
|
||||
t.Fatalf("registered key hook not used: %v", err)
|
||||
}
|
||||
if err := h.on_text("h"); err != nil || texts != 1 {
|
||||
t.Fatalf("registered text hook not used: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResizeStrategySwitchKeepsCommandLineOverride(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "resize-window.json")
|
||||
opts := &Options{Fraction: "1/4", Strategy: "window"}
|
||||
s, err := settings_for_invocation(path, opts, map[string]bool{"Fraction": true, "Strategy": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
h := &handler{opts: opts, settings: s, settings_path: path}
|
||||
if err := h.sync_preferences(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, strategy := range []string{"edge", "window"} {
|
||||
saved, err := update_settings(path, strategy, "strategy", strategy)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := h.apply_saved_setting(strategy, "strategy", saved); err != nil || h.active_strategy() != strategy {
|
||||
t.Fatalf("did not switch to %s: %v", strategy, err)
|
||||
}
|
||||
}
|
||||
if h.active_preferences().Fraction != "1/4" || h.fraction != 0.25 {
|
||||
t.Fatalf("switching strategy discarded the --fraction override: %+v", h.active_preferences())
|
||||
}
|
||||
saved, err := load_settings(path)
|
||||
if err != nil || saved.preferences("window").Fraction != "1/3" {
|
||||
t.Fatalf("the --fraction override was saved: %+v, %v", saved, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"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) clear_saved_status() bool {
|
||||
if h.status != "Saved" {
|
||||
return false
|
||||
}
|
||||
h.status = ""
|
||||
if h.saved_timer != 0 {
|
||||
h.lp.RemoveTimer(h.saved_timer)
|
||||
h.saved_timer = 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *handler) show_saved_status() error {
|
||||
if h.saved_timer != 0 {
|
||||
h.lp.RemoveTimer(h.saved_timer)
|
||||
}
|
||||
h.status = "Saved"
|
||||
id, err := h.lp.AddTimer(2*time.Second, false, func(id loop.IdType) error {
|
||||
if h.saved_timer == id {
|
||||
h.saved_timer = 0
|
||||
if h.status == "Saved" {
|
||||
h.status = ""
|
||||
h.draw_screen()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
h.saved_timer = id
|
||||
return err
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// A command-line override remains active for this invocation until the user
|
||||
// changes that field. Save operations merge against disk, not stale UI state.
|
||||
func (h *handler) apply_saved_setting(strategy, field string, saved resize_settings) error {
|
||||
if field == "strategy" {
|
||||
// Keep the in-memory preferences, which include any command-line override
|
||||
h.settings.Strategy = saved.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
|
||||
}
|
||||
return h.sync_preferences()
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
if field == "strategy" {
|
||||
if hooks := h.active_hooks(); hooks != nil && hooks.OnDeactivate != nil {
|
||||
if err := hooks.OnDeactivate(h); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := h.apply_saved_setting(strategy, field, saved); err != nil {
|
||||
return err
|
||||
}
|
||||
h.page = ""
|
||||
if err := h.show_saved_status(); err != nil {
|
||||
return err
|
||||
}
|
||||
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.clear_saved_status() {
|
||||
h.draw_screen()
|
||||
}
|
||||
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":
|
||||
if hooks := h.active_hooks(); hooks != nil && hooks.OnSettings != nil {
|
||||
hooks.OnSettings(h)
|
||||
}
|
||||
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.clear_saved_status() {
|
||||
h.draw_screen()
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package resize_window
|
||||
|
||||
import "github.com/kovidgoyal/kitty/tools/tui/loop"
|
||||
|
||||
// Edge interaction uses these hooks while settings keys and persistence are
|
||||
// shared with Window resizing.
|
||||
type strategy_hooks struct {
|
||||
OnActivate func(*handler) error
|
||||
OnDeactivate func(*handler) error
|
||||
OnSettings func(*handler)
|
||||
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
|
||||
}
|
||||
Reference in new issue
Block a user