Merge branch 'feat/session-restore'
Restore the tabs, layouts and working directories of the last session with kitty --session=last, from state saved on exit.
This commit is contained in:
9 files changed
+388
-1
No files matched your search
@@ -2530,6 +2530,7 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED)
|
||||
return
|
||||
@@ -2559,9 +2560,20 @@ class Boss:
|
||||
if not self._call_on_quit_watchers({'confirmed': True}):
|
||||
set_application_quit_request(NO_CLOSE_REQUESTED)
|
||||
return
|
||||
self.save_last_session()
|
||||
self.save_session_if_logging_out()
|
||||
set_application_quit_request(IMPERATIVE_CLOSE_REQUESTED if confirmed else NO_CLOSE_REQUESTED)
|
||||
|
||||
def save_last_session(self) -> None:
|
||||
# Must run before the quit request is set: the C side then closes the windows and there is
|
||||
# nothing left to serialize. Saving an empty session is a no-op, so this never clobbers a
|
||||
# good state with a torn down one.
|
||||
from .main import is_panel_kitten
|
||||
from .session_restore import save_session_of
|
||||
|
||||
if not is_panel_kitten():
|
||||
save_session_of(self)
|
||||
|
||||
def save_session_if_logging_out(self) -> None:
|
||||
from .logout_session import is_logout_in_progress
|
||||
|
||||
@@ -3991,6 +4003,13 @@ class Boss:
|
||||
def goto_session(self, *cmdline: str) -> None:
|
||||
goto_session(self, cmdline)
|
||||
|
||||
@ac('session', 'Restore the tabs and windows of the session saved when kitty last quit. See :ref:`sessions`.')
|
||||
def restore_last_session(self) -> None:
|
||||
from .session_restore import restore_last_session_into
|
||||
|
||||
if not restore_last_session_into(self):
|
||||
self.ring_bell_if_allowed()
|
||||
|
||||
@ac('session', 'Save the current kitty state as a session file. See :ref:`save_as_session`.')
|
||||
def save_as_session(self, *cmdline: str) -> None:
|
||||
save_as_session(self, cmdline)
|
||||
|
||||
@@ -68,6 +68,7 @@ from .options.types import Options
|
||||
from .options.utils import DELETE_ENV_VAR
|
||||
from .os_window_size import edge_spacing, initial_window_size_func
|
||||
from .session import create_sessions, get_os_window_sizing_data
|
||||
from .session_restore import save_session_of
|
||||
from .shaders.slang import load_shader_programs
|
||||
from .types import LayerShellConfig
|
||||
from .utils import (
|
||||
@@ -394,6 +395,8 @@ def _run_app(opts: Options, args: CLIOptions, bad_lines: Sequence[BadLine] = (),
|
||||
try:
|
||||
boss.child_monitor.main_loop()
|
||||
finally:
|
||||
if not _is_panel_kitten:
|
||||
save_session_of(boss)
|
||||
boss.destroy()
|
||||
|
||||
|
||||
|
||||
@@ -4661,6 +4661,23 @@ shortcuts. For a full description see :doc:`hints kitten </kittens/hints>`.
|
||||
""") # }}}
|
||||
|
||||
|
||||
# shortcuts.session {{{
|
||||
agr('shortcuts.session', 'Sessions')
|
||||
|
||||
map(
|
||||
'Restore the last session',
|
||||
'restore_last_session --allow-fallback=shifted,ascii kitty_mod+alt+r restore_last_session',
|
||||
long_text="""
|
||||
Restores the tabs, windows, layouts and working directories of the session that
|
||||
was saved when kitty last quit, without restarting kitty. The state is written
|
||||
by :code:`quit`; see :ref:`sessions`. If there is nothing to restore, a bell is
|
||||
rung instead.
|
||||
""",
|
||||
)
|
||||
|
||||
egr() # }}}
|
||||
|
||||
|
||||
# shortcuts.misc {{{
|
||||
agr('shortcuts.misc', 'Miscellaneous')
|
||||
|
||||
|
||||
Generated
+2
@@ -1028,6 +1028,8 @@ defaults.map = [
|
||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=110),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type linenum'),
|
||||
# open_selected_hyperlink
|
||||
KeyDefinition(is_sequence=True, trigger=SingleKey(mods=256, key=112), rest=(SingleKey(key=121),), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='kitten hints --type hyperlink'),
|
||||
# restore_last_session
|
||||
KeyDefinition(trigger=SingleKey(mods=258, key=114), options=KeyMapOptions(when_focus_on='', new_mode='', mode='', on_unknown='beep', on_action='keep', timeout=None, allow_fallback=(KeyFallbackType.shifted, KeyFallbackType.alternate)), definition='restore_last_session'),
|
||||
# show_kitty_doc
|
||||
KeyDefinition(trigger=SingleKey(mods=256, key=57364), definition='show_kitty_doc overview'),
|
||||
# command_palette
|
||||
|
||||
+9
-1
@@ -327,7 +327,15 @@ def create_sessions(
|
||||
env_when_no_session: dict[str, str] | None = None,
|
||||
) -> Iterator[Session]:
|
||||
if args and args.session:
|
||||
if args.session == 'none':
|
||||
if args.session == 'last':
|
||||
from .session_restore import load_last_session, state_path
|
||||
|
||||
raw = load_last_session()
|
||||
if raw:
|
||||
yield from parse_session(raw, opts, session_arg='last', session_path=state_path())
|
||||
return
|
||||
log_error('There is no saved session to restore, starting a new session instead')
|
||||
elif args.session == 'none':
|
||||
default_session = 'none'
|
||||
else:
|
||||
session_arg = args.session
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
# Keep the state of the session that was last in use so that `kitty --session=last` can restore it.
|
||||
#
|
||||
# The state is stored in the XDG state directory, is bounded in size and is only ever read when the
|
||||
# user explicitly asks for it, since restoring an unexpected state is worse than not restoring
|
||||
# anything. Anything that cannot be read back is discarded instead of preventing startup.
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from contextlib import suppress
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from .config import atomic_save
|
||||
from .utils import log_error
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .typing_compat import BossType
|
||||
|
||||
STATE_VERSION = 1
|
||||
MAX_STATE_SIZE = 1024 * 1024
|
||||
STATE_FILE_NAME = 'last-session.json'
|
||||
|
||||
|
||||
def state_dir() -> str:
|
||||
base = os.environ.get('XDG_STATE_HOME') or os.path.join(os.path.expanduser('~'), '.local', 'state')
|
||||
return os.path.join(base, 'kitty')
|
||||
|
||||
|
||||
def state_path() -> str:
|
||||
return os.path.join(state_dir(), STATE_FILE_NAME)
|
||||
|
||||
|
||||
def serialize_state(session: str, saved_at: float | None = None) -> bytes:
|
||||
state = {'version': STATE_VERSION, 'saved_at': time.time() if saved_at is None else saved_at, 'session': session}
|
||||
return json.dumps(state, ensure_ascii=False).encode('utf-8')
|
||||
|
||||
|
||||
def save_last_session(session: str) -> bool:
|
||||
"""Store the session text, returning False when it cannot be stored."""
|
||||
if not session.strip():
|
||||
return False
|
||||
if len(session) > MAX_STATE_SIZE:
|
||||
log_error(f'Not saving the last session as it is larger than {MAX_STATE_SIZE} characters, use save_as_session for large sessions')
|
||||
return False
|
||||
path = state_path()
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
atomic_save(serialize_state(session), path)
|
||||
except OSError as e:
|
||||
log_error(f'Failed to save the last session to {path}: {e}')
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def prune_missing_directories(session: str) -> tuple[str, int]:
|
||||
"""Drop cd directives whose directory is gone, so that a stale state does not fail to restore."""
|
||||
lines: list[str] = []
|
||||
pruned = 0
|
||||
for line in session.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith('cd ') and stripped[3:].strip():
|
||||
raw = stripped[3:].strip().strip('"\'')
|
||||
path = os.path.expanduser(raw)
|
||||
if os.path.isabs(path) and not os.path.isdir(path):
|
||||
pruned += 1
|
||||
continue
|
||||
lines.append(line)
|
||||
return '\n'.join(lines), pruned
|
||||
|
||||
|
||||
def discard_last_session() -> None:
|
||||
try:
|
||||
os.remove(state_path())
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
except OSError as e:
|
||||
log_error(f'Failed to delete the unreadable last session: {e}')
|
||||
|
||||
|
||||
def parse_state(raw: bytes) -> str:
|
||||
try:
|
||||
parsed: Any = json.loads(raw)
|
||||
except (ValueError, UnicodeDecodeError) as e:
|
||||
raise ValueError(f'not valid JSON: {e}') from e
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError('not a JSON object')
|
||||
version = parsed.get('version')
|
||||
if not isinstance(version, int):
|
||||
raise ValueError('missing state version')
|
||||
if version > STATE_VERSION:
|
||||
raise ValueError(f'state version {version} is newer than the supported version {STATE_VERSION}')
|
||||
session = parsed.get('session')
|
||||
if not isinstance(session, str):
|
||||
raise ValueError('missing session text')
|
||||
return session
|
||||
|
||||
|
||||
def load_last_session() -> str:
|
||||
"""Return the stored session text, or an empty string when there is nothing usable."""
|
||||
path = state_path()
|
||||
try:
|
||||
with open(path, 'rb') as f:
|
||||
raw = f.read(MAX_STATE_SIZE + 1)
|
||||
except FileNotFoundError:
|
||||
return ''
|
||||
except OSError as e:
|
||||
log_error(f'Failed to read the last session from {path}: {e}')
|
||||
return ''
|
||||
if len(raw) > MAX_STATE_SIZE:
|
||||
log_error(f'Discarding the last session in {path} as it is larger than {MAX_STATE_SIZE} bytes')
|
||||
discard_last_session()
|
||||
return ''
|
||||
try:
|
||||
session = parse_state(raw)
|
||||
except ValueError as e:
|
||||
log_error(f'Discarding the last session in {path} as it cannot be read: {e}')
|
||||
discard_last_session()
|
||||
return ''
|
||||
session, pruned = prune_missing_directories(session)
|
||||
if pruned:
|
||||
log_error(f'Dropped {pruned} working directory directive(s) from the last session as the directories no longer exist')
|
||||
return session
|
||||
|
||||
|
||||
def save_session_of(boss: 'BossType') -> None:
|
||||
"""Save the state of a running kitty instance, never raising so that it cannot break quitting."""
|
||||
from .session import default_save_as_session_opts
|
||||
|
||||
try:
|
||||
opts = default_save_as_session_opts()
|
||||
opts.os_window_geometry = True
|
||||
session = '\n'.join(boss.serialize_state_as_session('', opts))
|
||||
save_last_session(session)
|
||||
except Exception as e:
|
||||
log_error(f'Failed to save the last session: {e}')
|
||||
|
||||
|
||||
def restore_last_session_into(boss: 'BossType') -> bool:
|
||||
"""Add the tabs and windows of the last saved session to a running kitty.
|
||||
|
||||
Returns False when there is nothing to restore. The saved state is a JSON document, so it is
|
||||
handed to the session parser through a short lived file rather than duplicating the parsing.
|
||||
"""
|
||||
raw = load_last_session()
|
||||
if not raw:
|
||||
return False
|
||||
import tempfile
|
||||
|
||||
from .session import create_session
|
||||
|
||||
fd, path = tempfile.mkstemp(prefix='last-session-', suffix='.kitty-session')
|
||||
try:
|
||||
with open(fd, 'w', encoding='utf-8') as f:
|
||||
f.write(raw)
|
||||
create_session(boss, path)
|
||||
finally:
|
||||
with suppress(OSError):
|
||||
os.unlink(path)
|
||||
return True
|
||||
Reference in new issue
Block a user