view.v

19.9 KB · raw

1//! The history view: the saves and checkpoints list, full screen.2//!3//! On a terminal `koh view` opens this instead of printing; `--checkpoints`4//! opens it on the checkpoints tab. The look and the keys are Koh 2's5//! (`src/commands/history.zig`): a tab bar, evenly spaced entries between6//! separators, and a status bar with the hints for the current mode.7//!8//! The view only reads — history, flags and diffs — and hands any decision back9//! to the caller as an `Action`, so the command layer stays the only thing that10//! changes anything. `frame_lines` turns a `Session` into the rows of one frame,11//! which keeps the interesting part testable without a terminal.1213module view1415import encoding.base6416import os17import strings18import src.events19import src.fmt20import src.history21import src.snapshot22import src.storage2324pub enum Tab {25	all26	saves27	checkpoints28}2930pub enum ActionKind {31	none32	load33	flag34	clear_flag35}3637pub struct Action {38pub mut:39	kind    ActionKind40	save_id string41	reason  string42}4344// TabCounts is what the tab bar shows: how many saves are in each list before45// the search narrows anything.46pub struct TabCounts {47pub mut:48	all         int49	saves       int50	checkpoints int51}5253// Screen is what the list shows.54pub struct Screen {55pub mut:56	tab      Tab57	items    []history.Save58	counts   TabCounts59	selected int60	query    string61	status   string62	head     string63	flags    map[string]events.Flag64	on_line  map[string]bool65	rows     int66	cols     int67}6869enum Mode {70	list71	search72	detail73	reason74	confirm75}7677// Session is everything the event loop changes: what is on screen, which mode78// it is in, and what the current action is about.79struct Session {80mut:81	screen  Screen82	mode    Mode83	target  history.Save84	typed   string85	pending Action86	detail  []string87	// set when an action changed history, so the lists are read again88	stale bool89	// the detail is worked out once per save rather than per key90	detail_for string91}9293// run shows the view until the user leaves it. `act` performs a confirmed94// action and returns the message for the status bar, so the view itself never95// changes history.96pub fn run(store &storage.Store, start Tab, act fn (store &storage.Store, action Action) string) ! {97	enter_screen()98	defer {99		leave_screen()100	}101	mut every := []history.Save{}102	mut session := Session{103		screen: Screen{104			tab: start105		}106		stale:  true107	}108	// A resize arrives as no key at all, so the loop waits for one only so109	// long and then looks at the window size instead of blocking on stdin.110	wait_ms := 250111	mut dirty := true112	for {113		if session.stale {114			// A load appends a save and a flag changes a mark: read both again.115			every = history.all_saves(store)!116			session.screen.head = history.head_id(store)117			session.screen.on_line = on_line_set(store)118			session.screen.flags = events.latest_flags(store)!119			session.screen.counts = count_tabs(every, session.screen.on_line)120			session.detail_for = ''121			session.stale = false122			dirty = true123		}124		if dirty {125			session.screen.rows, session.screen.cols = terminal_size()126			session.screen.items = filter_saves(every, session.screen.tab, session.screen.on_line,127				session.screen.query)128			session.screen.selected = move_selection(session.screen.selected, 0,129				session.screen.items.len)130			if session.mode in [.detail, .reason, .confirm]131				&& session.detail_for != session.target.id {132				session.detail = detail_lines(session.target, session.screen.head, diff_of(store,133					session.target), session.screen.flags[session.target.id] or { events.Flag{} })134				session.detail_for = session.target.id135			}136			paint(render(frame_lines(session)))137			// A status message is shown for one frame, as in Koh 2.138			session.screen.status = ''139			dirty = false140		}141		key, timed_out := read_key_timeout(wait_ms)142		if timed_out {143			// Repaint only when the size moved: an idle view must not redraw144			// four times a second for nothing.145			rows, cols := terminal_size()146			if rows != session.screen.rows || cols != session.screen.cols {147				dirty = true148			}149			continue150		}151		if key.kind in [.interrupt, .eof] {152			return153		}154		if handle_key(mut session, store, key, act) {155			return156		}157		dirty = true158	}159}160161// handle_key applies one key and reports whether to leave the view.162fn handle_key(mut session Session, store &storage.Store, key Key, act fn (store &storage.Store, action Action) string) bool {163	return match session.mode {164		.list { list_key(mut session, key) }165		.search { search_key(mut session, key) }166		.detail { detail_key(mut session, key) }167		.reason { reason_key(mut session, key) }168		.confirm { confirm_key(mut session, store, key, act) }169	}170}171172// list_key: Tab switches tabs; up/down and j/k move; g is the oldest save, G the newest (the list is newest173// first); Enter opens the detail; / searches; c copies the ID; q leaves, and Esc drops a kept filter before174// it leaves. Only selection, tab, query and mode change here.175fn list_key(mut session Session, key Key) bool {176	count := session.screen.items.len177	match key.kind {178		.tab {179			session.screen.tab = next_tab(session.screen.tab)180			session.screen.selected = 0181		}182		.down {183			session.screen.selected = move_selection(session.screen.selected, 1, count)184		}185		.up {186			session.screen.selected = move_selection(session.screen.selected, -1, count)187		}188		.enter {189			if count > 0 {190				session.target = session.screen.items[session.screen.selected]191				session.mode = .detail192			}193		}194		// Esc goes back one step: a kept search filter first, then the view.195		.escape {196			if session.screen.query == '' {197				return true198			}199			session.screen.query = ''200			session.screen.selected = 0201		}202		.rune {203			match key.text {204				'q' {205					return true206				}207				'j' {208					session.screen.selected = move_selection(session.screen.selected, 1, count)209				}210				'k' {211					session.screen.selected = move_selection(session.screen.selected, -1,212						count)213				}214				// The list is newest first: g is the oldest save, G the newest.215				'g' {216					session.screen.selected = move_selection(count, -1, count)217				}218				'G' {219					session.screen.selected = 0220				}221				'/' {222					session.mode = .search223				}224				'c' {225					if count > 0 {226						copy_selected(mut session.screen,227							session.screen.items[session.screen.selected].id)228					}229				}230				else {}231			}232		}233		else {}234	}235	return false236}237238// search_key edits the query. Every key is text here, q included, so a239// search can begin with q; Esc is the way out.240fn search_key(mut session Session, key Key) bool {241	match key.kind {242		.rune {243			session.screen.query += key.text244			session.screen.selected = 0245		}246		.backspace {247			session.screen.query = trim_last(session.screen.query)248			session.screen.selected = 0249		}250		.escape {251			session.screen.query = ''252			session.screen.selected = 0253			session.mode = .list254		}255		.enter {256			session.mode = .list257		}258		else {}259	}260	return false261}262263// detail_key: l loads this save, and f flags it, or clears an existing flag. Both go on to confirm_key, which264// is the only place an action runs; an unflagged save asks for a reason first. c copies the ID, Esc goes back.265fn detail_key(mut session Session, key Key) bool {266	match key.kind {267		.escape {268			session.mode = .list269		}270		.rune {271			match key.text {272				'q' {273					return true274				}275				'l' {276					session.pending = Action{277						kind:    .load278						save_id: session.target.id279					}280					session.mode = .confirm281				}282				'f' {283					if is_flagged(session.screen, session.target.id) {284						session.pending = Action{285							kind:    .clear_flag286							save_id: session.target.id287						}288						session.mode = .confirm289					} else {290						session.typed = ''291						session.mode = .reason292					}293				}294				'c' {295					copy_selected(mut session.screen, session.target.id)296				}297				else {}298			}299		}300		else {}301	}302	return false303}304305// reason_key collects a flag's reason. Every key is text here, q included:306// a reason may well say "quick hack".307fn reason_key(mut session Session, key Key) bool {308	match key.kind {309		.rune {310			session.typed += key.text311		}312		.backspace {313			session.typed = trim_last(session.typed)314		}315		.escape {316			session.typed = ''317			session.mode = .detail318		}319		.enter {320			if session.typed != '' {321				session.pending = Action{322					kind:    .flag323					save_id: session.target.id324					reason:  session.typed325				}326				session.typed = ''327				session.mode = .confirm328			}329		}330		else {}331	}332	return false333}334335fn confirm_key(mut session Session, store &storage.Store, key Key, act fn (store &storage.Store, action Action) string) bool {336	if key.kind == .rune && key.text in ['y', 'Y'] {337		session.screen.status = act(store, session.pending)338		session.stale = true339	}340	session.pending = Action{}341	session.mode = .list342	return false343}344345// filter_saves applies a tab and the search text. `on_line` marks the saves346// still on the line: a replayed-away save exists in history but belongs to347// neither the saves nor the checkpoints list.348pub fn filter_saves(items []history.Save, tab Tab, on_line map[string]bool, query string) []history.Save {349	mut out := []history.Save{}350	needle := query.to_lower()351	for save in items {352		live := save.id in on_line353		if tab == .saves && (!live || save.is_checkpoint) {354			continue355		}356		if tab == .checkpoints && (!live || !save.is_checkpoint) {357			continue358		}359		if needle != '' && !searchable(save).contains(needle) {360			continue361		}362		out << save363	}364	return out365}366367// searchable is what a search matches: ID, message, agent and session, without regard to case.368fn searchable(save history.Save) string {369	return '${save.id} ${save.message} ${save.agent} ${save.session}'.to_lower()370}371372pub fn count_tabs(items []history.Save, on_line map[string]bool) TabCounts {373	return TabCounts{374		all:         filter_saves(items, .all, on_line, '').len375		saves:       filter_saves(items, .saves, on_line, '').len376		checkpoints: filter_saves(items, .checkpoints, on_line, '').len377	}378}379380// move_selection clamps a move to the ends of the list.381pub fn move_selection(index int, delta int, length int) int {382	if length <= 0 {383		return 0384	}385	moved := index + delta386	if moved < 0 {387		return 0388	}389	if moved >= length {390		return length - 1391	}392	return moved393}394395// render writes a frame over the last one: each row is cleared before it is396// drawn, and the last row has no newline, so the terminal never scrolls.397pub fn render(lines []string) string {398	mut out := strings.new_builder(4096)399	out.write_string('\x1b[H')400	for i, line in lines {401		out.write_string('\x1b[2K${line}')402		if i < lines.len - 1 {403			out.write_string('\r\n')404		}405	}406	return out.str()407}408409// frame_lines is one whole frame, exactly as tall as the screen and no line410// wider than it: the tab bar, a gap, the body, the status bar.411fn frame_lines(session Session) []string {412	screen := session.screen413	rows := if screen.rows > 4 { screen.rows } else { 4 }414	cols := if screen.cols > 10 { screen.cols } else { 10 }415	body := rows - 3416	mut lines := [tab_bar(screen, session.mode), '']417	if session.mode in [.detail, .reason, .confirm] {418		lines << session.detail#[..body]419	} else {420		lines << list_body(screen, body, cols)421	}422	for lines.len < rows - 1 {423		lines << ''424	}425	lines << status_bar(session, cols)426	return lines.map(fmt.fit(it, cols))427}428429// list_body lays the entries out in up to seven equal blocks, each a header,430// a message, the selected entry's details and a separator, with the spare rows431// split above and below so the list fills the screen. Koh 2 had six; seven is432// the 15% tighter spacing June asked for, without leaving an empty band.433fn list_body(screen Screen, body int, cols int) []string {434	if screen.items.len == 0 {435		return ['  ${fmt.muted('no results')}']436	}437	slots := if body / 4 < 7 { body / 4 } else { 7 }438	if slots == 0 {439		return [entry_header(screen.items[screen.selected], true, screen)]440	}441	separator := fmt.muted('─'.repeat(cols))442	start := window_start(screen.selected, slots, screen.items.len)443	mut lines := []string{}444	for slot in 0 .. slots {445		height := body / slots + if slot < body % slots { 1 } else { 0 }446		spare := if height > 4 { height - 4 } else { 0 }447		for _ in 0 .. spare / 2 {448			lines << ''449		}450		index := start + slot451		if index < screen.items.len {452			entry := screen.items[index]453			selected := index == screen.selected454			lines << entry_header(entry, selected, screen)455			lines << entry_message(entry, screen)456			lines << if selected { entry_meta(entry) } else { '' }457		} else {458			lines << ['', '', '']459		}460		lines << separator461		for _ in 0 .. spare - spare / 2 {462			lines << ''463		}464	}465	return lines466}467468// window_start keeps the selected entry near the middle of the visible blocks.469fn window_start(selected int, slots int, count int) int {470	if count <= slots {471		return 0472	}473	mut start := if selected > slots / 2 { selected - slots / 2 } else { 0 }474	if start + slots > count {475		start = count - slots476	}477	return start478}479480// entry_header is the mark, ID, time and date. HEAD has its own mark; every481// other save is a dot. As in Koh 2, only the ID tells the selected save apart:482// gold when selected, grey otherwise, while time, date and message stay plain.483fn entry_header(save history.Save, selected bool, screen Screen) string {484	head := save.id == screen.head485	flagged := is_flagged(screen, save.id)486	mark := if head { fmt.blue('▸') } else { fmt.muted('·') }487	mut line := '  ${mark} '488	line += if flagged {489		fmt.red(save.id)490	} else if selected {491		fmt.gold(save.id)492	} else {493		fmt.muted(save.id)494	}495	if head {496		line += '  ${fmt.blue('HEAD')}'497	}498	mut labels := []string{}499	if selected && save.is_checkpoint {500		labels << '[checkpoint]'501	}502	if flagged {503		labels << '[flagged]'504	}505	if save.id !in screen.on_line {506		labels << '[replayed away]'507	}508	if labels.len > 0 {509		line += '  ${labels.join(' ')}'510	}511	return line + '  ${fmt.hour_of(save.created_at)}  ${fmt.date_of(save.created_at)}'512}513514fn entry_message(save history.Save, screen Screen) string {515	warning := if is_flagged(screen, save.id) { fmt.red('⚠ ') } else { '' }516	return '    ${warning}${fmt.safe_text(save.message)}'517}518519fn entry_meta(save history.Save) string {520	agent := if save.agent == '' { 'unknown' } else { fmt.safe_text(save.agent) }521	session := if save.session == '' { 'no session' } else { fmt.safe_text(save.session) }522	return '    ${fmt.human_bytes(save.size_bytes)} · ${agent} · ${session}'523}524525fn tab_bar(screen Screen, mode Mode) string {526	names := ['all', 'saves', 'checkpoints']527	counts := [screen.counts.all, screen.counts.saves, screen.counts.checkpoints]528	mut bar := ''529	for i, name in names {530		if tab_at(i) == screen.tab {531			bar += fmt.gold(' [${name} (${counts[i]})] ')532		} else {533			bar += fmt.muted(' ${name} (${counts[i]}) ')534		}535	}536	bar += fmt.muted('│ ')537	if mode == .search {538		bar += '/${screen.query}_'539	} else if screen.query != '' {540		bar += '/${screen.query}'541	} else {542		bar += fmt.muted('/ search')543	}544	return bar545}546547fn status_bar(session Session, cols int) string {548	hint := match session.mode {549		.search {550			'type to filter · enter keep · esc clear'551		}552		.detail {553			flag_word := if is_flagged(session.screen, session.target.id) {554				'clear flag'555			} else {556				'flag'557			}558			'esc back · l load · f ${flag_word} · c copy · q'559		}560		.reason {561			'flag reason: ${session.typed}_ · enter confirm · esc cancel'562		}563		.confirm {564			'${action_word(session.pending.kind)} [${session.pending.save_id}]? y yes · n/esc cancel'565		}566		.list {567			'↑↓ nav · / search · tab mode · c copy · enter detail · q/esc'568		}569	}570	left := ' view: ${tab_name(session.screen.tab)} · ${hint}'571	right := if session.screen.status != '' {572		session.screen.status573	} else if session.mode == .list || session.mode == .search {574		'${session.screen.items.len} shown'575	} else {576		''577	}578	if right == '' {579		return fmt.muted(left)580	}581	// The hints give way to the count or the result of an action, which is582	// the one thing worth reading right after a key.583	room := cols - fmt.visible_width(right) - 1584	shown := fmt.fit(left, if room > 0 { room } else { 0 })585	gap := cols - fmt.visible_width(shown) - fmt.visible_width(right)586	return fmt.muted('${shown}${' '.repeat(if gap > 0 { gap } else { 0 })}${right}')587}588589fn action_word(kind ActionKind) string {590	return match kind {591		.load { 'load' }592		.flag { 'flag' }593		.clear_flag { 'clear the flag on' }594		.none { '' }595	}596}597598// detail_lines describes one save: what it was, and what it changed.599pub fn detail_lines(save history.Save, head string, deltas []snapshot.Delta, flag events.Flag) []string {600	mut title := '  ${fmt.gold(save.id)}'601	if save.id == head {602		title += '  ${fmt.blue('HEAD')}'603	}604	if save.is_checkpoint {605		title += '  [checkpoint]'606	}607	if flag.flagged {608		title += '  [flagged]'609	}610	mut lines := [611		title,612		'  ${fmt.safe_text(save.message)}',613		'',614		detail_row('time', '${fmt.date_of(save.created_at)} · ${fmt.clock_of(save.created_at)}'),615		detail_row('size', fmt.human_bytes(save.size_bytes)),616		detail_row('agent', if save.agent == '' { 'unknown' } else { fmt.safe_text(save.agent) }),617		detail_row('session', if save.session == '' { 'none' } else { fmt.safe_text(save.session) }),618		detail_row('parent', if save.parent == '' { 'root' } else { save.parent }),619		detail_row('checksum', save.id),620	]621	if flag.flagged {622		lines << detail_row('flag', fmt.safe_text(flag.reason))623	}624	lines << ''625	if save.parent == '' {626		lines << '  initial save — no parent to diff against'627		return lines628	}629	lines << '  ${deltas.len} files changed'630	mut totals := snapshot.Delta{}631	for delta in deltas {632		lines << '  ${change_mark(delta)} ${delta.path}  ${line_stats(delta)}'633		if !delta.binary {634			totals.added += delta.added635			totals.removed += delta.removed636		}637	}638	lines << ['', '  total  ${line_stats(totals)}']639	return lines640}641642fn detail_row(label string, value string) string {643	return '  ${fmt.muted(label + ' '.repeat(9 - label.len))}${value}'644}645646fn line_stats(delta snapshot.Delta) string {647	if delta.binary {648		return fmt.muted('(binary)')649	}650	return '${fmt.green('+' + delta.added.str())}  ${fmt.red('-' + delta.removed.str())}'651}652653fn change_mark(delta snapshot.Delta) string {654	return match delta.kind {655		'added' { fmt.green('A') }656		'removed' { fmt.red('R') }657		else { fmt.gold('M') }658	}659}660661fn is_flagged(screen Screen, save_id string) bool {662	return (screen.flags[save_id] or { events.Flag{} }).flagged663}664665// diff_of compares a save with its parent. A failed read shows an empty diff instead of closing the screen.666fn diff_of(store &storage.Store, save history.Save) []snapshot.Delta {667	return snapshot.diff_trees(store, parent_tree(store, save), child_tree(store, save)) or {668		[]snapshot.Delta{}669	}670}671672fn trim_last(text string) string {673	runes := text.runes()674	if runes.len == 0 {675		return text676	}677	return runes[..runes.len - 1].string()678}679680// copy_selected puts the ID on the clipboard through OSC 52, which works over681// ssh and in any terminal without a helper program.682fn copy_selected(mut screen Screen, save_id string) {683	paint('\x1b]52;c;${base64.encode(save_id.bytes())}\a')684	screen.status = 'copied ${save_id}'685}686687fn parent_tree(store &storage.Store, save history.Save) snapshot.Tree {688	if save.parent == '' {689		return snapshot.Tree{}690	}691	return snapshot.Tree{692		files: history.files_of(store, save.parent) or { []snapshot.FileEntry{} }693	}694}695696fn child_tree(store &storage.Store, save history.Save) snapshot.Tree {697	return snapshot.Tree{698		files: history.files_of(store, save.id) or { []snapshot.FileEntry{} }699	}700}701702// on_line_set marks the saves on the current line; the all tab also lists those replayed off it.703fn on_line_set(store &storage.Store) map[string]bool {704	mut ids := map[string]bool{}705	for save in history.line(store) or { []history.Save{} } {706		ids[save.id] = true707	}708	return ids709}710711// enter_screen and leave_screen are a pair: run defers leave_screen so every exit restores the terminal.712fn enter_screen() {713	paint('\x1b[?1049h\x1b[?25l')714	raw_mode(true)715}716717fn leave_screen() {718	raw_mode(false)719	paint('\x1b[?25h\x1b[?1049l')720}721722fn paint(text string) {723	os.fd_write(1, text)724}725726fn tab_at(index int) Tab {727	return match index {728		0 { Tab.all }729		1 { Tab.saves }730		else { Tab.checkpoints }731	}732}733734fn tab_name(tab Tab) string {735	return match tab {736		.all { 'all' }737		.saves { 'saves' }738		else { 'checkpoints' }739	}740}741742fn next_tab(tab Tab) Tab {743	return match tab {744		.all { Tab.saves }745		.saves { Tab.checkpoints }746		else { Tab.all }747	}748}