Sessions: Add os_window_position and save_as_session --os-window-geometry

The geometry of fullscreen OS Windows is the one from before they were made
fullscreen. On macOS this is now also recorded when using native fullscreen
via the window buttons/menu.
This commit is contained in:
Kovid Goyal 2026-10-16 11:29:28 +05:30
parent beca032240
commit d4eb2b34e6
No known key found for this signature in database
GPG key ID: 06BC317B515ACE7C
9 changed files with 124 additions and 12 deletions

View file

@ -231,6 +231,10 @@ Detailed list of changes
0.50.0 [future]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- Sessions: A new ``os_window_position`` keyword and a new
``--os-window-geometry`` option for :ac:`save_as_session` to save the size,
position and state of OS Windows in session files
- Ignore initial OS Window positions that are not on any connected monitor, for
example, because the monitor was disconnected

View file

@ -157,6 +157,8 @@ all the major keywords you can use in kitty session files:
new_os_window
# Set new window size to 80x24 cells
os_window_size 80c 24c
# Place the new window at x=100, y=50 on the screen
os_window_position 100x50
# Set the --title for the new OS window
os_window_title my fancy os window
# Set the --class for the new OS window
@ -351,6 +353,12 @@ documentation for them.
``os_window_name``
Set the name part of WM_CLASS or Wayland Window tag for the current OS Window
``os_window_position``
Set the position of the current OS Window on the screen. For example:
``100x50``. This may or may not work depending on the policies of the
desktop environment/window manager. It never works on Wayland. If the
position is not on any connected monitor, it is ignored.
``os_window_size``
Set the size of the current OS Window, can be specified in pixels or cells.
For example: 80c 24c is a window of width 80 cells by 24 cells.

View file

@ -510,6 +510,8 @@ class Boss:
wtitle = override_title or getattr(startup_session, 'os_window_title', None) or self.args.title
window_state = window_state or getattr(startup_session, 'os_window_state', None)
wstate = parse_os_window_state(window_state) if window_state is not None else None
if x is None and y is None and startup_session is not None and startup_session.os_window_position is not None and not is_wayland():
x, y = startup_session.os_window_position
with startup_notification_handler(do_notify=startup_id is not None, startup_id=startup_id) as pre_show_callback:
os_window_id = create_os_window(
initial_window_size_func(size_data, self.cached_values),

View file

@ -894,6 +894,16 @@ def cocoa_set_menubar_title(title: str) -> None:
def change_os_window_state(state: int, os_window_id: Optional[int] = 0) -> None:
pass
class OSWindowGeometry(TypedDict):
x: int
y: int
width: int
height: int
state: int
def get_os_window_geometry(os_window_id: int) -> Optional[OSWindowGeometry]:
pass
def change_background_opacity(os_window_id: int, opacity: float) -> bool:
pass

View file

@ -1887,8 +1887,17 @@ static bool
intercept_cocoa_fullscreen(GLFWwindow *w) {
if (!set_callback_window(w)) return false;
if (!OPT(macos_traditional_fullscreen)) {
OSWindow *osw = global_state.callback_os_window;
const bool is_fullscreen = is_os_window_fullscreen(osw);
if (!is_fullscreen) {
// Remember the geometry from before macOS makes the window fullscreen, as do_toggle_fullscreen() does
glfwGetWindowSize(w, &osw->before_fullscreen.w, &osw->before_fullscreen.h);
glfwGetWindowPos(w, &osw->before_fullscreen.x, &osw->before_fullscreen.y);
osw->before_fullscreen.was_maximized = glfwGetWindowAttrib(w, GLFW_MAXIMIZED);
osw->before_fullscreen.is_set = true;
}
// In non traditional fullscreen macOS forces the window to opaque
global_state.callback_os_window->background_opacity.os_forces_opaque = !is_os_window_fullscreen(global_state.callback_os_window);
osw->background_opacity.os_forces_opaque = !is_fullscreen;
return false;
}
// macOS Split View uses Cocoa fullscreen internally, so the window
@ -3142,6 +3151,27 @@ change_os_window_state(PyObject *self UNUSED, PyObject *args) {
Py_RETURN_NONE;
}
static PyObject *
get_os_window_geometry(PyObject *self UNUSED, PyObject *args) {
// The geometry needed to re-create the OS Window, for fullscreen windows this is the geometry from before they were made fullscreen
id_type wid;
if (!PyArg_ParseTuple(args, "K", &wid)) return NULL;
OSWindow *w = os_window_for_id(wid);
if (!w || !w->handle || w->is_layer_shell) Py_RETURN_NONE;
int x = 0, y = 0, width = 0, height = 0, state = WINDOW_NORMAL;
glfwGetWindowSize(w->handle, &width, &height);
if (!global_state.is_wayland) glfwGetWindowPos(w->handle, &x, &y);
if (is_os_window_fullscreen(w)) {
state = WINDOW_FULLSCREEN;
if (w->before_fullscreen.is_set) {
width = w->before_fullscreen.w; height = w->before_fullscreen.h;
x = w->before_fullscreen.x; y = w->before_fullscreen.y;
}
} else if (glfwGetWindowAttrib(w->handle, GLFW_ICONIFIED)) state = WINDOW_MINIMIZED;
else if (glfwGetWindowAttrib(w->handle, GLFW_MAXIMIZED)) state = WINDOW_MAXIMIZED;
return Py_BuildValue("{si si si si si}", "x", x, "y", y, "width", width, "height", height, "state", state);
}
void
request_window_attention(id_type kitty_window_id, bool audio_bell) {
OSWindow *w = os_window_for_kitty_window(kitty_window_id);
@ -4026,6 +4056,7 @@ static PyMethodDef module_methods[] = {
METHODB(toggle_fullscreen, METH_VARARGS),
METHODB(toggle_maximized, METH_VARARGS),
METHODB(change_os_window_state, METH_VARARGS),
METHODB(get_os_window_geometry, METH_VARARGS),
METHODB(glfw_window_hint, METH_VARARGS),
METHODB(x11_display, METH_NOARGS),
METHODB(wayland_compositor_data, METH_NOARGS),

View file

@ -298,15 +298,6 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
if args.grab_keyboard:
grab_keyboard(True)
with cached_values_for(run_app.cached_values_name) as cached_values:
if not _is_panel_kitten and not is_wayland():
if opts.remember_window_position:
cached_workarea = tuple(tuple(x) for x in cached_values.get('monitor-workarea', ()))
if cached_workarea and glfw_get_monitor_workarea() == tuple(cached_workarea):
pos_x, pos_y = cached_values.get('window-pos', (None, None))
if args.position:
from .launch import parse_os_window_position
pos_x, pos_y = parse_os_window_position(args.position)
startup_session_error: tuple[Exception, str] | None = None
try:
startup_sessions = tuple(create_sessions(opts, args, default_session=opts.startup_session))
@ -315,6 +306,17 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
if getattr(args, 'session', ''):
args.session = ''
startup_sessions = tuple(create_sessions(opts, args))
if not _is_panel_kitten and not is_wayland():
if opts.remember_window_position:
cached_workarea = tuple(tuple(x) for x in cached_values.get('monitor-workarea', ()))
if cached_workarea and glfw_get_monitor_workarea() == tuple(cached_workarea):
pos_x, pos_y = cached_values.get('window-pos', (None, None))
if startup_sessions and startup_sessions[0].os_window_position is not None:
pos_x, pos_y = startup_sessions[0].os_window_position
if args.position:
from .launch import parse_os_window_position
pos_x, pos_y = parse_os_window_position(args.position)
wincls = (startup_sessions[0].os_window_class if startup_sessions else '') or args.cls or appname
winname = (startup_sessions[0].os_window_name if startup_sessions else '') or args.name or wincls or appname
window_state = (args.start_as if args.start_as and args.start_as != 'normal' else None) or ( # ty: ignore[redundant-condition]

View file

@ -90,6 +90,7 @@ class Session:
self.focus_tab_spec: str | None = None
self.default_title = default_title
self.os_window_size: WindowSizes | None = None
self.os_window_position: tuple[int, int] | None = None
self.os_window_class: str | None = None
self.os_window_name: str | None = None
self.os_window_state: str | None = None
@ -278,6 +279,11 @@ def parse_session(
elif cmd == 'os_window_size':
w, h = map(window_size, rest.split(maxsplit=1))
ans.os_window_size = WindowSizes(WindowSize(*w), WindowSize(*h))
elif cmd == 'os_window_position':
x, sep, y = rest.lower().partition('x')
if not sep:
raise ValueError(f'Invalid os_window_position: {rest!r}, must be of the form XxY, for example: 100x50')
ans.os_window_position = int(x), int(y)
elif cmd == 'os_window_class':
ans.os_window_class = rest
elif cmd == 'os_window_name':
@ -688,6 +694,13 @@ working directory. This is useful when kitty is launched from locations where th
is not your home directory, such as from system-wide shortcuts. Note that :code:`--relocatable` is
typically not used with :code:`--base-dir`, since relocatable is meant for session files that are
co-located with their project directories.
--os-window-geometry
type=bool-set
Save the size, position and state (maximized, fullscreen, etc.) of OS Windows, so that they
are restored as they are now when the session is loaded. Note that positions are not
saved on Wayland as it does not allow applications to position their windows.
"""

View file

@ -12,17 +12,20 @@ from collections.abc import Callable, Generator, Iterable, Iterator, Sequence
from contextlib import suppress
from functools import wraps
from gettext import gettext as _
from typing import Any, Concatenate, Deque, Literal, NamedTuple, Optional, ParamSpec, TypeVar, cast
from typing import TYPE_CHECKING, Any, Concatenate, Deque, Literal, NamedTuple, Optional, ParamSpec, TypeVar, cast
from .borders import Border, Borders
from .child import Child
from .cli_stub import CLIOptions, SaveAsSessionOptions
from .constants import appname
from .constants import appname, is_wayland
from .fast_data_types import (
GLFW_MOUSE_BUTTON_LEFT,
GLFW_MOUSE_BUTTON_MIDDLE,
GLFW_PRESS,
GLFW_RELEASE,
WINDOW_FULLSCREEN,
WINDOW_MAXIMIZED,
WINDOW_MINIMIZED,
add_tab,
add_timer,
attach_window,
@ -33,6 +36,7 @@ from .fast_data_types import (
get_boss,
get_click_interval,
get_options,
get_os_window_geometry,
get_tab_being_dragged,
get_window_being_dragged,
is_tab_bar_visible,
@ -65,6 +69,9 @@ from .utils import cmdline_for_hold, color_as_int, log_error, natsort_key, platf
from .window import CwdRequest, Watchers, Window, WindowCreationSpec, WindowDict, global_watchers
from .window_list import WindowGroup, WindowList
if TYPE_CHECKING:
from .fast_data_types import OSWindowGeometry
P = ParamSpec('P')
T = TypeVar('T')
@ -174,6 +181,15 @@ def SpecialWindow(
return SpecialWindowInstance(cmd, stdin, override_title, cwd_from, cwd, overlay_for, env, watchers, overlay_behind, hold)
def os_window_geometry_as_session(g: 'OSWindowGeometry', include_position: bool = True) -> list[str]:
ans = [f'os_window_size {g["width"]} {g["height"]}']
if include_position:
ans.append(f'os_window_position {g["x"]}x{g["y"]}')
state = {WINDOW_FULLSCREEN: 'fullscreen', WINDOW_MAXIMIZED: 'maximized', WINDOW_MINIMIZED: 'minimized'}.get(g['state'], 'normal')
ans.append(f'os_window_state {state}')
return ans
def add_active_id_to_history(items: Deque[int], item_id: int, maxlen: int = 64) -> None:
with suppress(ValueError):
items.remove(item_id)
@ -1763,6 +1779,8 @@ class TabManager: # {{{
prefix.append(f'os_window_class {self.wm_class}')
if self.wm_name and self.wm_name != appname:
prefix.append(f'os_window_name {self.wm_name}')
if ser_opts.os_window_geometry:
prefix.extend(self.serialize_geometry_as_session())
ans = prefix + ans
# Add focus_tab command to preserve the active tab
if active_tab_index >= 0:
@ -1770,6 +1788,10 @@ class TabManager: # {{{
ans.append(f'focus_tab {active_tab_index}')
return ans
def serialize_geometry_as_session(self) -> list[str]:
g = get_os_window_geometry(self.os_window_id)
return [] if g is None else os_window_geometry_as_session(g, include_position=not is_wayland())
@property
def active_tab(self) -> Tab | None:
return self.tabs[self.active_tab_idx] if 0 <= self.active_tab_idx < len(self.tabs) else None

View file

@ -20,3 +20,23 @@ class TestSessions(BaseTest):
sd = get_os_window_sizing_data(opts, session)
self.assertTrue(sd.remember_window_size)
self.ae(initial_window_size_func(sd, remembered)(10, 20, 72, 72, 1, 1), (900, 600))
def test_session_os_window_geometry(self) -> None:
from kitty.fast_data_types import WINDOW_FULLSCREEN, WINDOW_MAXIMIZED, WINDOW_NORMAL
from kitty.tabs import os_window_geometry_as_session
opts = self.set_options()
first, second = parse_session('os_window_position -1200x80\nlaunch\nnew_os_window\nlaunch', opts)
self.ae((first.os_window_position, second.os_window_position), ((-1200, 80), None))
with self.assertRaises(ValueError):
tuple(parse_session('os_window_position 100\nlaunch', opts))
g = {'x': -1200, 'y': 80, 'width': 1180, 'height': 760, 'state': WINDOW_MAXIMIZED}
lines = os_window_geometry_as_session(g)
self.ae(lines, ['os_window_size 1180 760', 'os_window_position -1200x80', 'os_window_state maximized'])
self.ae(os_window_geometry_as_session(g, include_position=False), [lines[0], lines[2]])
(s,) = parse_session('\n'.join(lines + ['launch']), opts)
size = WindowSizes(WindowSize(1180, 'px'), WindowSize(760, 'px'))
self.ae((s.os_window_size, s.os_window_position, s.os_window_state), (size, (-1200, 80), 'maximized'))
for state, name in ((WINDOW_FULLSCREEN, 'fullscreen'), (WINDOW_NORMAL, 'normal')):
self.ae(os_window_geometry_as_session({**g, 'state': state})[-1], f'os_window_state {name}')