Besides the --session=last startup option, the saved state can now be brought back in a running kitty with restore_last_session, mapped to kitty_mod+alt+r. The option types are regenerated so the shortcut is actually part of the default configuration.
163 lines
5.6 KiB
Python
163 lines
5.6 KiB
Python
#!/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
|