Merge pull request 'feat(tab-bar): add command status and cwd indicators, close and new tab buttons' (#34) from feat/tab-bar-indicators into main

Reviewed-on: #34
This commit was merged in pull request #34.
This commit is contained in:
BlackAngelTV committed 2026-11-11 20:19:40 +01:00
commit 02f43b2ee9
10 files changed
+263 -56

No files matched your search

+7 -6
View File
@@ -172,13 +172,13 @@ map ctrl+shift+e launch --type=overlay kitten file-manager
Un fichier validé s'ouvre dans un nouvel onglet, donc en pleine fenêtre même
depuis un dock, et le panneau reprend la main à la fermeture de l'éditeur. En
revanche, kitty ne rend jamais le résultat d'un `launch --type=window-dock` au
shell : valider un répertoire dans un dock ne peut donc pas faire de `cd`.
shell : `Ctrl+Entrée` dans un dock ne peut donc pas faire de `cd`.
### Raccourcis par défaut
| Touche | Action |
| --- | --- |
| `Entrée` | Change le répertoire du shell si la sélection est un répertoire, sinon ouvre le fichier dans l'éditeur, dans un nouvel onglet ; le panneau revient à la fermeture de l'éditeur |
| `Entrée` | Ouvre la sélection : entre dans le répertoire, ou ouvre le fichier dans l'éditeur dans un nouvel onglet ; le panneau revient à la fermeture de l'éditeur |
| `→` / `L` | Entre dans le répertoire sélectionné sans toucher au shell |
| `←` / `Retour arrière` / `H` | Remonte au répertoire parent |
| `Ctrl+Entrée` / `C` | Déplace le shell vers le répertoire affiché, sans tenir compte de la sélection |
@@ -202,9 +202,10 @@ Un clic gauche sélectionne une entrée. Tous les raccourcis sont redéfinissabl
### Limites à connaître
- `Entrée` et `Ctrl+Entrée` agissent sur la fenêtre qui a lancé le panneau. Dans
un dock ou un panneau du bureau, le changement de répertoire n'a personne à
qui s'appliquer : lancez l'explorateur depuis un shell pour `cd`.
- `Entrée` reste dans le panneau et fonctionne partout, dock compris.
`Ctrl+Entrée` agit sur la fenêtre qui a lancé le panneau : dans un dock ou un
panneau du bureau, le changement de répertoire n'a personne à qui s'appliquer,
lancez l'explorateur depuis un shell pour `cd`.
- L'éditeur s'ouvre toujours dans un nouvel onglet, plein écran ; fermer
l'éditeur referme l'onglet et rend le panneau tel qu'il était.
- L'édition passe par kitty : le fichier doit être accessible en lecture et en
@@ -309,7 +310,7 @@ automatisation) est détaillée dans `packaging/README.md`.
| `Unknown kitten: file-manager` ou l'aide ne le liste pas | Binaire `kitten` obsolète : relancer `./dev.sh build` et utiliser `kitty/launcher/kitten`. |
| `+file-manager is not a known kitten` | Le panneau s'appelle `kitten file-manager` (sans `+`). |
| `kitten: command not found` | Les binaires sont dans `kitty/launcher/` : chemin complet, `PATH` ou lien symbolique. |
| Le panneau se ferme sans changer de répertoire | Lancé dans un dock : `cd` n'a pas de shell cible. Utiliser `Ctrl+Entrée` depuis une fenêtre de shell. |
| `Ctrl+Entrée` ferme le panneau sans changer de répertoire | Lancé dans un dock : `cd` n'a pas de shell cible. Lancer l'explorateur depuis une fenêtre de shell. |
| `... is not readable and writeable` en ouvrant un fichier | L'édition passe par kitty et demande un accès en lecture et écriture. Ouvrir le fichier avec `sudo -e` depuis le shell. |
| Rien ne s'affiche / pas de fenêtre | Pas de serveur graphique : session X11/Wayland, WSLg, ou socket monté dans Docker. |
| `X11/extensions/XInput2.h: No such file` | Installer `libxi` (XInput2). |
+12 -11
View File
@@ -11,8 +11,9 @@ Gestionnaire de fichiers
Le gestionnaire de fichiers affiche le contenu d'un répertoire dans un panneau
latéral, pilotable entièrement au clavier, et change le répertoire courant du
shell qui l'a lancé. Il remplace la plupart des :code:`cd` : on descend dans
l'arborescence, on valide, le panneau se ferme et le shell se déplace, sans
perdre l'environnement, l'historique ni l'état de la session.
l'arborescence avec :kbd:`Entrée`, puis :kbd:`Ctrl+Entrée` ferme le panneau et
déplace le shell, sans perdre l'environnement, l'historique ni l'état de la
session.
Le raccourci par défaut :kbd:`Ctrl+Shift+E` ouvre le panneau dans un
:ref:`dock <docks>` à gauche de la fenêtre courante. On peut aussi le lancer
@@ -32,8 +33,9 @@ est passé en argument ou avec ``--start-dir``.
Le changement de répertoire ne peut viser que la fenêtre depuis laquelle le
panneau a été lancé. Lancé dans un dock ou un panneau du bureau, il ne change
donc pas le répertoire du shell : utilisez :kbd:`Ctrl+Entrée` dans une
fenêtre de shell.
donc pas le répertoire du shell : :kbd:`Ctrl+Entrée` ferme le panneau sans
déplacer le shell. Lancez le panneau depuis une fenêtre de shell pour changer
de répertoire.
L'ouverture d'un fichier, elle, fonctionne partout : le panneau confie le
fichier à kitty, qui lance l'éditeur dans un nouvel onglet. Le fichier
@@ -45,11 +47,10 @@ Actions
-------
:kbd:`Entrée`
Si la sélection est un répertoire, il devient le répertoire courant du
shell et le panneau se ferme. Si c'est un fichier, il est ouvert dans
l'éditeur de kitty (:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`)
dans un nouvel onglet ; le panneau reste ouvert et retrouve sa sélection
lorsque l'éditeur se ferme.
Si la sélection est un répertoire, le panneau y descend, exactement comme
avec :kbd:`→`. Si c'est un fichier, il est ouvert dans l'éditeur de kitty
(:opt:`editor`, :envvar:`VISUAL` ou :envvar:`EDITOR`) dans un nouvel onglet ;
le panneau reste ouvert et retrouve sa sélection lorsque l'éditeur se ferme.
Le nouvel onglet est ce qui donne au fichier toute la fenêtre : dans un
dock, exécuter l'éditeur dans le panneau le réduirait à la largeur du dock.
@@ -64,8 +65,8 @@ Actions
remonte au répertoire parent.
:kbd:`Ctrl+Entrée` ou :kbd:`C`
déplace le shell vers le répertoire affiché, sans tenir compte de la
sélection.
déplace le shell vers la sélection si c'est un répertoire, sinon vers le
répertoire affiché, puis ferme le panneau.
:kbd:`Tab` et :kbd:`Maj+Tab`
passent à l'entrée suivante, respectivement précédente, comme :kbd:`↓` et
+6 -6
View File
@@ -420,8 +420,9 @@ func (h *Handler) copy_selected_path() {
h.draw_screen()
}
// activate implements the primary action: the selected directory becomes the
// working directory of the shell, the selected file is opened in the editor.
// activate implements the primary action: the selected directory is opened in
// the panel, the selected file is opened in the editor. Enter used to quit the
// panel and cd the shell, which did nothing when the panel was docked.
func (h *Handler) activate() {
if h.input_purpose == input_search {
h.stop_search()
@@ -431,12 +432,11 @@ func (h *Handler) activate() {
h.lp.Beep()
return
}
path := entry_path(h.cwd, e.Name)
if e.IsDir {
h.change_shell_dir_to(path)
h.enter_dir()
return
}
h.open_file(path)
h.open_file(entry_path(h.cwd, e.Name))
}
// edit_args_in is the client side of kitty's edit protocol. The terminal opens
@@ -1129,7 +1129,7 @@ func (h *Handler) draw_screen() {
h.lp.QueueWriteString(h.lp.SprintStyled("bold fg=bright-red", fmt.Sprintf("Delete %s? [y/N] ", h.confirm_name)))
default:
h.lp.SetCursorVisible(false)
hints := "Enter: cd/open /: search :: actions ->: enter <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
hints := "Enter: open /: search :: actions ->: enter Ctrl+Enter: cd here <-: up .: hidden n: new file r: rename d: delete y: copy q: quit"
h.lp.QueueWriteString(h.lp.SprintStyled("dim", truncate_to_width(hints, width)))
}
}
+8 -7
View File
@@ -93,14 +93,15 @@ map('Select first entry', 'home --allow-fallback=shifted,ascii g home')
map('Select last entry', 'end end end')
map('Select last entry', 'end shift+g end')
map(
'Change shell directory or open selection',
'Open the selection',
'activate enter activate',
long_text="""
When the selection is a directory it becomes the working directory of the shell
that launched the panel. When it is a file, the panel opens it in kitty's editor
(:opt:`editor`, :envvar:`VISUAL` or :envvar:`EDITOR`) in a new tab, and is
drawn again with the same selection once the editor exits. The new tab is what
gives the file a whole window even when the panel runs in a dock.
When the selection is a directory it is opened in the panel, exactly like the
:ref:`enter_dir <file-manager-shortcuts>` shortcut. When it is a file, the panel
opens it in kitty's editor (:opt:`editor`, :envvar:`VISUAL` or
:envvar:`EDITOR`) in a new tab, and is drawn again with the same selection once
the editor exits. The new tab is what gives the file a whole window even when
the panel runs in a dock.
""",
)
map(
@@ -108,7 +109,7 @@ map(
'enter_dir right enter_dir',
long_text="""
Move the panel into the selected directory without changing the shell's working
directory. Use the :ref:`activate <file-manager-shortcuts>` shortcut to also
directory. Use the :ref:`cd_here <file-manager-shortcuts>` shortcut to also
change the shell's directory.
""",
)
+24 -11
View File
@@ -2318,18 +2318,18 @@ The alignment of the tab bar, can be one of: :code:`start`, :code:`center`,
opt(
'tab_bar_show_new_tab_button',
'no',
'yes',
option_type='to_bool',
long_text="""
When set to :code:`yes`, a :code:`+` button is always shown at the end of the
tab bar as a clickable shortcut to open a new tab. When set to :code:`no`
(the default), the button is hidden at rest but still appears temporarily
while a window is being dragged, so it can be used as a drop target to open
the window in a new tab.
When set to :code:`yes` (the default), a :code:`+` button is always shown at
the end of the tab bar as a clickable shortcut to open a new tab. When set to
:code:`no`, the button is hidden at rest but still appears temporarily while a
window is being dragged, so it can be used as a drop target to open the window
in a new tab.
""",
)
opt('tab_bar_min_tabs', '2', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
opt('tab_bar_min_tabs', '1', option_type='tab_bar_min_tabs', long_text='The minimum number of tabs that must exist before the tab bar is shown.')
opt(
'tab_switch_strategy',
@@ -2450,7 +2450,7 @@ lines is wrapped independently.
opt(
'tab_title_template',
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
'"{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}"',
option_type='tab_title_template',
long_text="""
A template to render the tab title. The default just renders the title with
@@ -2473,12 +2473,25 @@ use :code:`{sup.index}`. All data available is:
The number of windows in the tab.
:code:`num_window_groups`
The number of window groups (a window group is a window and all of its overlay windows) in the tab.
:code:`last_exit_code`
The exit status of the last command that finished in the active window of
the tab, or the empty string if it succeeded or no command has finished.
Requires :ref:`shell integration <shell_integration>`.
:code:`exit_status_symbol`
A cross followed by :code:`last_exit_code` when the last command failed,
empty otherwise. Requires :ref:`shell integration <shell_integration>`.
:code:`secure_input_symbol`
A key symbol when secure input is enabled on macOS and the tab is the active tab, empty otherwise.
:code:`tab.active_wd`
The working directory of the currently active window in the tab
(expensive, requires syscall). Use :code:`tab.active_oldest_wd` to get
the directory of the oldest foreground process rather than the newest.
:code:`tab.active_wd_abbreviated`
A compact form of :code:`tab.active_wd` suited to a tab title: the home
directory is shown as ``~``, intermediate directories are reduced to
their first letter and, when the result is still too long, middle
directories are replaced by an ellipsis. For example
``~/p/fws-kitty``. Has the same cost as :code:`tab.active_wd`.
:code:`tab.active_exe`
The name of the executable running in the foreground of the currently
active window in the tab (expensive, requires syscall). Use
@@ -2518,9 +2531,9 @@ use styling directives, for example:
Similarly, for bold and italic:
``{fmt.bold}bold{fmt.nobold}normal{fmt.italic}italic{fmt.noitalic}``.
The 256 eight terminal colors can be used as ``fmt.fg.color0`` through ``fmt.fg.color255``.
Note that for backward compatibility, if :code:`{bell_symbol}` or
:code:`{activity_symbol}` are not present in the template, they are prepended to
it.
Note that for backward compatibility, if :code:`{bell_symbol}`,
:code:`{activity_symbol}` or :code:`{exit_status_symbol}` are not present in
the template, they are prepended to it.
""",
)
+3 -3
View File
@@ -695,8 +695,8 @@ class Options:
tab_bar_margin_color: kitty.fast_data_types.Color | None = None
tab_bar_margin_height: TabBarMarginHeight = TabBarMarginHeight(outer=0, inner=0)
tab_bar_margin_width: float = 0
tab_bar_min_tabs: int = 2
tab_bar_show_new_tab_button: bool = False
tab_bar_min_tabs: int = 1
tab_bar_show_new_tab_button: bool = True
tab_bar_style: choices_for_tab_bar_style = 'fade'
tab_fade: tuple[float, ...] = (0.25, 0.5, 0.75, 1.0)
tab_powerline_style: choices_for_tab_powerline_style = 'angled'
@@ -704,7 +704,7 @@ class Options:
tab_switch_strategy: choices_for_tab_switch_strategy = 'previous'
tab_title_max_length: int = 0
tab_title_max_lines: int = 1
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
tab_title_template: str = '{fmt.fg.red}{bell_symbol}{activity_symbol}{exit_status_symbol}{secure_input_symbol}{fmt.fg.tab}{tab.last_focused_progress_percent}{title}'
tab_title_wrap: int = 0
term: str = 'xterm-kitty'
terminfo_type: choices_for_terminfo_type = 'path'
+101 -3
View File
@@ -260,6 +260,17 @@ class TabAccessor:
tab = get_boss().tab_for_id(self.tab_id)
return os.path.basename((tab.get_exe_of_active_window(oldest=True) if tab else '') or '')
@property
def active_wd_abbreviated(self) -> str:
tab = get_boss().tab_for_id(self.tab_id)
return abbreviate_path((tab.get_cwd_of_active_window() if tab else '') or '')
@property
def last_cmd_exit_status(self) -> int:
tab = get_boss().tab_for_id(self.tab_id)
w = tab.active_window if tab else None
return w.last_cmd_exit_status if w else 0
@property
def last_focused_progress_percent(self) -> str:
tab = get_boss().tab_for_id(self.tab_id)
@@ -337,6 +348,10 @@ def template_uses_max_title_length(template: str) -> bool:
# Not across updates, as templates can use state not in TabBarData, such as
# the progress of the windows in the tab.
title_cache: dict[tuple[DrawData, TabBarData, int, int], str] | None = None
# Cells occupied by the close buttons drawn in the last layout pass, mapped to
# the id of the tab they close. None while titles are being measured, so that
# only the cells of the final drawing are kept.
close_button_cells: dict[tuple[int, int], int] | None = None
@contextmanager
@@ -384,6 +399,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
ColorFormatter.draw_data = draw_data
ColorFormatter.tab_data = tab
boss = get_boss()
last_cmd_exit_status = ta.last_cmd_exit_status
eval_locals = {
'index': index,
'layout_name': tab.layout_name,
@@ -400,6 +416,8 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
'bell_symbol': draw_data.bell_on_tab if tab.needs_attention else '',
'secure_input_symbol': si,
'activity_symbol': draw_data.tab_activity_symbol if tab.has_activity_since_last_focus else '',
'last_exit_code': str(last_cmd_exit_status) if last_cmd_exit_status else '',
'exit_status_symbol': exit_status_indicator(last_cmd_exit_status),
'max_title_length': max_title_length,
'keyboard_mode': boss.mappings.current_keyboard_mode_name,
}
@@ -407,7 +425,7 @@ def evaluate_title_template(draw_data: DrawData, tab: TabBarData, index: int, ma
if tab.is_active and draw_data.active_title_template is not None:
template = draw_data.active_title_template
prefix = ''
for default_prefix in ('bell_symbol', 'activity_symbol', 'secure_input_symbol'):
for default_prefix in ('bell_symbol', 'activity_symbol', 'exit_status_symbol', 'secure_input_symbol'):
if eval_locals[default_prefix] and not template_has_field(template, default_prefix):
prefix += '{' + default_prefix + '}'
if prefix:
@@ -498,8 +516,65 @@ def truncate_line(line: str, width: int) -> str:
return out + '…'
def exit_status_indicator(exit_status: int) -> str:
"""A short indicator for the exit status of the last command, empty on success."""
return f'✘ {exit_status} ' if exit_status else ''
def abbreviate_path(path: str, home: str | None = None, max_length: int = 0) -> str:
"""Return a compact representation of path for use in a tab title.
The home directory is shown as ``~`` and the directories between it and
the last component are reduced to their first character, so
``~/projects/fws-kitty`` becomes ``~/p/fws-kitty``. When max_length is
positive and the result is wider, the middle directories are replaced by
an ellipsis, keeping the last component, which is the most informative
part. Widths are measured in terminal cells.
"""
if not path:
return ''
home = os.path.normpath(home or os.path.expanduser('~'))
p = os.path.normpath(path)
if home and (p == home or p.startswith(home + os.sep)):
prefix, rest = '~', p[len(home) :]
elif p.startswith(os.sep):
prefix, rest = os.sep, p
else:
prefix, rest = '', p
components = [c for c in rest.split(os.sep) if c]
if not components:
return prefix or os.sep
def join(parts: Sequence[str]) -> str:
if prefix == os.sep:
return os.sep + os.sep.join(parts)
if prefix == '~':
return '~' + (os.sep + os.sep.join(parts) if parts else '')
return os.sep.join(parts)
ans = join([c[0] for c in components[:-1]] + [components[-1]])
if max_length > 0 and wcswidth(ans) > max_length:
last = components[-1]
marker = prefix + os.sep + '…' if prefix else '…'
for candidate in (marker + os.sep + last, '…' + os.sep + last if prefix else last):
if wcswidth(candidate) <= max_length:
return candidate
# Even the last component alone is too wide, keep its end as that is
# the part that distinguishes it from its siblings.
available = max_length - wcswidth(marker) - 1
if available > 0:
return marker + os.sep + truncate_line(last, available)
return truncate_line(ans, max_length)
return ans
def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int, max_title_length: int = 0) -> None:
title = apply_title_template(draw_data, tab, index, max_title_length)
# Close buttons live in horizontal tab bars, where there is a spare cell at
# the start of each tab. Vertical tabs are already crowded and their titles
# wrap, so they keep closing with the middle mouse button.
show_close = tab.tab_id > 0 and draw_data.tab_bar_edge in ('top', 'bottom') and (max_title_length <= 0 or max_title_length >= 3)
title_width = max(1, max_title_length - 2) if show_close and max_title_length > 0 else max_title_length
title = apply_title_template(draw_data, tab, index, title_width)
if draw_data.max_tab_title_lines > 1 and draw_data.wrap_width:
title = wrap_title(title, draw_data.wrap_width)
if '\n' in title:
@@ -511,9 +586,14 @@ def draw_title(draw_data: DrawData, screen: Screen, tab: TabBarData, index: int,
# Mark the truncation, since the caller's ellipsis logic only fires
# when the final line reaches the full width of the tab.
del lines[limit:]
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or max_title_length)
lines[-1] = truncate_line(lines[-1], draw_data.wrap_width or title_width)
title = '\n'.join(lines)
before_draw = screen.cursor.x
if show_close:
if close_button_cells is not None:
close_button_cells[(before_draw, screen.cursor.y)] = tab.tab_id
close_button_cells[(before_draw + 1, screen.cursor.y)] = tab.tab_id
screen.draw('× ')
draw_attributed_string(title, screen)
if draw_data.max_tab_title_length > 0:
x_limit = before_draw + draw_data.max_tab_title_length
@@ -811,6 +891,7 @@ class TabBar:
self.data_buffer_size = 0
self.blank_rects: tuple[Border, ...] = ()
self.tab_extents: Sequence[TabExtent] = ()
self.close_button_cells: dict[tuple[int, int], int] = {}
self.window_drop_insert_before: int | None = None
self.tab_drop_insert_before: int | None = None
self.laid_out_once = False
@@ -996,6 +1077,7 @@ class TabBar:
self.blank_rects = tuple(blank_rects)
def layout(self) -> None:
self.close_button_cells = {}
central, tab_bar, vw, vh, cell_width, cell_height = viewport_for_window(self.os_window_id)
if self.is_vertical:
if tab_bar.width < cell_width or tab_bar.height < cell_height:
@@ -1149,11 +1231,15 @@ class TabBar:
s.erase_in_line(2, False)
cr: list[TabExtent] = []
ed.for_layout = False
global close_button_cells
close_button_cells = {}
for i, t in enumerate(data):
try:
draw_tab(i, t, cr, max_tab_lengths[i])
except StopIteration:
break
self.close_button_cells = close_button_cells
close_button_cells = None
self.tab_extents = cr
s.erase_in_line(0, False) # Ensure no long titles bleed after the last tab
self.align()
@@ -1164,6 +1250,7 @@ class TabBar:
s = self.screen
self.last_laid_out_tabs = data
self.tab_extents = ()
self.close_button_cells = {}
s.cursor.x = s.cursor.y = 0
s.erase_in_display(2, False)
if not data:
@@ -1312,6 +1399,17 @@ class TabBar:
return te.tab_id
return 0
def close_tab_id_at(self, x: int, y: int) -> int:
"The id of the tab whose close button is at the specified pixel, or zero."
if not self.laid_out_once or not self.close_button_cells:
return 0
g = self.window_geometry
if not (g.left <= x < g.right and g.top <= y < g.bottom):
return 0
x = (x - g.left) // self.cell_width
y = (y - g.top) // self.cell_height
return self.close_button_cells.get((x, y), 0)
def drag_axis_coordinate(self, x: int, y: int) -> int:
return y if self.is_vertical else x
+10
View File
@@ -2093,9 +2093,19 @@ class TabManager: # {{{
self.recent_tab_bar_mouse_events.clear()
return
if button == GLFW_MOUSE_BUTTON_LEFT:
close_tab_id = self.tab_bar.close_tab_id_at(int(x), int(y))
if action == GLFW_PRESS:
if close_tab_id:
return # clicking the close button must not start a drag
set_tab_being_dragged(tab.id, False, x, y)
return
if close_tab_id:
if self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT) == 1:
set_tab_being_dragged()
self.recent_tab_bar_mouse_events.clear()
if (tab_to_close := self.tab_for_id(close_tab_id)) is not None:
get_boss().close_tab(tab_to_close)
return
match self.recent_tab_bar_mouse_events.click_count(GLFW_MOUSE_BUTTON_LEFT):
case 2:
self.set_active_tab(tab)
+2
View File
@@ -2056,6 +2056,8 @@ class Window:
self.last_cmd_exit_status = int(exit_status)
except Exception:
self.last_cmd_exit_status = 0
if (tab := self.tabref()) is not None:
tab.mark_tab_bar_dirty()
end_time = monotonic()
last_cmd_output_duration = end_time - self.last_cmd_output_start_time
self.last_cmd_output_start_time = 0.0
+90 -9
View File
@@ -1,11 +1,27 @@
#!/usr/bin/env python
# License: GPL v3 Copyright: 2026, Kovid Goyal <kovid at kovidgoyal.net>
import os
from types import SimpleNamespace
from unittest.mock import patch
from kitty.fast_data_types import LEFT_EDGE, Color, Region, Screen
from kitty.options.utils import tab_title_wrap
from kitty.tab_bar import CellRange, DrawData, ExtraData, TabBar, TabBarData, TabExtent, WindowDropTarget, as_rgb, powerline_symbols, truncate_line, wrap_title
from kitty.tab_bar import (
CellRange,
DrawData,
ExtraData,
TabBar,
TabBarData,
TabExtent,
WindowDropTarget,
abbreviate_path,
as_rgb,
exit_status_indicator,
powerline_symbols,
truncate_line,
wrap_title,
)
from kitty.utils import color_as_int
from .base import BaseTest
@@ -392,6 +408,47 @@ class TestTabBar(BaseTest):
# empty line still gets ellipsis
self.ae(truncate_line('', 4), '…')
def test_abbreviate_path(self) -> None:
self.ae(abbreviate_path(''), '')
self.ae(abbreviate_path('/home/user/projects/fws-kitty', '/home/user'), '~/p/fws-kitty')
# the home directory itself has no component to abbreviate
self.ae(abbreviate_path('/home/user', '/home/user'), '~')
self.ae(abbreviate_path('/home/user/', '/home/user'), '~')
# a trailing slash does not add an empty component
self.ae(abbreviate_path('/usr/local/bin/'), '/u/l/bin')
self.ae(abbreviate_path('/'), '/')
self.ae(abbreviate_path('some/relative/dir'), 's/r/dir')
# the last component is never abbreviated, it is the most informative
self.ae(abbreviate_path('/home/user/a/very-long-project', '/home/user'), '~/a/very-long-project')
# when the result is too wide, middle directories are elided rather
# than cutting off the end of the title
self.ae(abbreviate_path('/home/user/one/two/three/project', '/home/user', 14), '~/…/project')
# when even that is too wide, the last component is truncated too
self.ae(abbreviate_path('/home/user/a/very-long-final-dir', '/home/user', 12), '~/…/very-lo…')
# widths are measured in terminal cells, so wide characters count double
self.ae(abbreviate_path('/日本語/東京'), '/日/東京')
def test_exit_status_indicator(self) -> None:
self.ae(exit_status_indicator(0), '')
self.ae(exit_status_indicator(1), '✘ 1 ')
self.ae(exit_status_indicator(130), '✘ 130 ')
def test_tab_title_indicators(self) -> None:
home = os.path.expanduser('~')
fake_tab = SimpleNamespace(
active_window=SimpleNamespace(last_cmd_exit_status=127),
get_cwd_of_active_window=lambda oldest=False: os.path.join(home, 'projects', 'fws-kitty'),
)
boss = SimpleNamespace(tab_for_id=lambda tab_id: fake_tab, mappings=SimpleNamespace(current_keyboard_mode_name=''))
line = self.horizontal_tab_bar_line(
['ignored'],
60,
boss=boss,
tab_bar_style='separator',
tab_title_template='{last_exit_code}:{exit_status_symbol}{tab.active_wd_abbreviated}',
)
self.assertIn('127:✘ 127 ~/p/fws-kitty', line)
def test_tab_title_wrap_option(self) -> None:
for off in ('no', 'No', 'n', 'false', 'none', '0'):
self.ae(tab_title_wrap(off), 0)
@@ -601,7 +658,7 @@ class TestTabBar(BaseTest):
[f' t0 {separator}', f'abcdefghijk{separator}', f'x {separator}'],
)
def horizontal_tab_bar_line(self, titles: list[str], columns: int, **opts: object) -> str:
def horizontal_tab_bar(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> TabBar:
self.set_options({'tab_title_template': '{title}', **opts})
central = region(0, 0, columns * 10, 180)
tab_bar = region(0, 180, columns * 10, 200)
@@ -610,24 +667,48 @@ class TestTabBar(BaseTest):
patch('kitty.tab_bar.viewport_for_window', return_value=(central, tab_bar, columns * 10, 200, 10, 20)),
patch('kitty.tab_bar.set_tab_bar_render_data'),
patch('kitty.tab_bar.update_tab_bar_edge_colors', return_value=None),
patch('kitty.tab_bar.get_boss', return_value=DummyBoss()),
patch('kitty.tab_bar.get_boss', return_value=boss if boss is not None else DummyBoss()),
):
tb = TabBar(1)
tb.layout()
tb.update(tuple(TabBarData(title=t, tab_id=i + 1, is_active=i == 0) for i, t in enumerate(titles)))
return str(tb.screen.line(0)).rstrip()
return tb
def horizontal_tab_bar_line(self, titles: list[str], columns: int, boss: object | None = None, **opts: object) -> str:
return str(self.horizontal_tab_bar(titles, columns, boss, **opts).screen.line(0)).rstrip()
def test_horizontal_tab_bar_close_buttons(self) -> None:
tb = self.horizontal_tab_bar(['one', 'two'], 40, tab_bar_style='separator')
line = str(tb.screen.line(0))
self.ae(line.count('×'), 2)
# each close button is two cells wide, at the start of its tab
self.ae(set(tb.close_button_cells.values()), {1, 2})
for (cell_x, row), tab_id in tb.close_button_cells.items():
px = tb.window_geometry.left + cell_x * tb.cell_width + 1
py = tb.window_geometry.top + row * tb.cell_height + 1
self.ae(tb.close_tab_id_at(px, py), tab_id)
# clicking the title itself does not close the tab
for te in tb.tab_extents:
px = tb.window_geometry.left + te.x.end * tb.cell_width
py = tb.window_geometry.top + 1
self.ae(tb.close_tab_id_at(px, py), 0)
self.ae(tb.close_tab_id_at(0, 0), 0)
# vertical tab bars keep closing with the middle mouse button
self.ae(self.vertical_tab_bar().close_button_cells, {})
def test_horizontal_tab_bar_uses_free_space(self) -> None:
line = self.horizontal_tab_bar_line
# space not needed by short tabs goes to the long ones, instead of
# being left unused at the end of the tab bar
long_title = 'abcdefghijklmn'
# two extra cells per tab are needed for its close button
for style, columns, titles in (
('fade', 25, ['1', long_title]),
('fade', 35, ['1'] * 2 + [long_title]),
('separator', 60, ['1'] * 8 + [long_title] * 2),
('powerline', 80, ['1'] * 5 + [long_title] * 3),
('slant', 126, ['1'] * 9 + [long_title] * 4),
('fade', 29, ['1', long_title]),
('fade', 41, ['1'] * 2 + [long_title]),
('separator', 80, ['1'] * 8 + [long_title] * 2),
('powerline', 96, ['1'] * 5 + [long_title] * 3),
('slant', 152, ['1'] * 9 + [long_title] * 4),
):
text = line(titles, columns, tab_bar_style=style)
self.ae(text.count(long_title), titles.count(long_title), (style, text))