braid-tui 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,44 @@
1
+ """单行状态栏:把模型、上下文、费用、计划、权限与后台任务压进一行。
2
+
3
+ 宽终端完整显示,窄终端按可见宽度截断并加省略号;始终补齐到视口宽,保证
4
+ 差分渲染时该行内容稳定。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from braid_tui.layout import pad_to_width, truncate_to_width
10
+ from braid_tui.renderer import Component
11
+
12
+ __all__ = ["StatusBar"]
13
+
14
+
15
+ class StatusBar(Component):
16
+ """恒定一行的状态栏。"""
17
+
18
+ def __init__(self, text: str = "") -> None:
19
+ self._text = text
20
+ self._cache_key: tuple[str, int] | None = None
21
+ self._cached_lines: list[str] = []
22
+
23
+ @property
24
+ def text(self) -> str:
25
+ return self._text
26
+
27
+ def set_text(self, text: str) -> None:
28
+ if text != self._text:
29
+ self._text = text
30
+ self._cache_key = None
31
+
32
+ def invalidate(self) -> None:
33
+ self._cache_key = None
34
+
35
+ def render(self, width: int) -> list[str]:
36
+ width = max(1, width)
37
+ key = (self._text, width)
38
+ if self._cache_key == key:
39
+ return self._cached_lines
40
+ shown = truncate_to_width(self._text, width, ellipsis="…")
41
+ lines = [pad_to_width(shown, width)]
42
+ self._cache_key = key
43
+ self._cached_lines = lines
44
+ return lines
@@ -0,0 +1,77 @@
1
+ """多行文本组件。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ from braid_tui.layout import TAB_WIDTH, pad_to_width, wrap_text
6
+
7
+ __all__ = ["Text"]
8
+
9
+
10
+ class Text:
11
+ """显示多行文本:词法换行 + 内边距 + 补齐到视口宽。
12
+
13
+ - 空白文本渲染为空数组(不占行);
14
+ - ``padding_x`` 在窄终端自动收缩(内容与边距放不下时先保内容);
15
+ - 换行只做词法换行(CJK 字符间可断、拉丁词整词),补齐是调用方的职责;
16
+ - 每行行尾补空格到 ``width``。
17
+
18
+ 渲染缓存按 ``(text, width)`` 失效:流式场景反复 ``set_text`` 时,
19
+ 未变化的帧直接命中缓存,差分渲染不再付换行成本。
20
+ """
21
+
22
+ def __init__(
23
+ self,
24
+ text: str = "",
25
+ *,
26
+ padding_x: int = 1,
27
+ padding_y: int = 1,
28
+ ) -> None:
29
+ self._text = text
30
+ self._padding_x = padding_x
31
+ self._padding_y = padding_y
32
+ self._cache_key: tuple[str, int] | None = None
33
+ self._cached_lines: list[str] = []
34
+
35
+ def set_text(self, text: str) -> None:
36
+ if text == self._text:
37
+ return
38
+ self._text = text
39
+ self._cache_key = None
40
+
41
+ @property
42
+ def text(self) -> str:
43
+ return self._text
44
+
45
+ def set_padding_x(self, padding_x: int) -> None:
46
+ self._padding_x = padding_x
47
+ self.invalidate()
48
+
49
+ def invalidate(self) -> None:
50
+ self._cache_key = None
51
+
52
+ def render(self, width: int) -> list[str]:
53
+ key = (self._text, width)
54
+ if self._cache_key == key:
55
+ return self._cached_lines
56
+ lines = self._render_uncached(width)
57
+ self._cache_key = key
58
+ self._cached_lines = lines
59
+ return lines
60
+
61
+ def _render_uncached(self, width: int) -> list[str]:
62
+ if not self._text.strip():
63
+ return []
64
+ normalized = self._text.replace("\t", " " * TAB_WIDTH)
65
+ # 边距自动收缩:内容至少留 1 列。
66
+ padding_x = min(self._padding_x, max(0, (width - 1) // 2))
67
+ content_width = max(1, width - padding_x * 2)
68
+ wrapped = wrap_text(normalized, content_width)
69
+
70
+ content_lines: list[str] = []
71
+ for line in wrapped:
72
+ with_margins = " " * padding_x + line + " " * padding_x
73
+ content_lines.append(pad_to_width(with_margins, width))
74
+ empty_line = " " * width
75
+ top = [empty_line] * self._padding_y
76
+ bottom = [empty_line] * self._padding_y
77
+ return top + content_lines + bottom
braid_tui/layout.py ADDED
@@ -0,0 +1,454 @@
1
+ """宽度计算与文本布局。
2
+
3
+ 实现约束:
4
+
5
+ 1. 宽度按 **codepoint** 计算:组合附标
6
+ (Mn/Me)与格式字符(Cf,含 ZWJ、变体选择子)宽度 0;遇到 ZWJ 把后续
7
+ base 吞进同一个 emoji 序列(序列整体仍 2 列)。
8
+ 2. SGR 跟踪器只跟踪基本属性
9
+ (颜色 / 粗体 / 斜体 / 下划线 / 反色 / 暗色 / 删除线),OSC 8 超链接
10
+ 不跨行保留。
11
+ 3. 换行处行尾统一补 ``\\x1b[0m`` 全量重置,
12
+ 新行行首重开全部活跃 SGR。代价是彩色背景的换行处会出现一条基色缝隙。
13
+
14
+ 终端坐标约定:列从 0 数起;``\\x1b[nG`` 是 1 起的,使用方自行 +1。
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import unicodedata
20
+ from typing import Final
21
+
22
+ ESC: Final[str] = "\x1b"
23
+ BEL: Final[str] = "\x07"
24
+ #: tab 的显示宽度。
25
+ TAB_WIDTH: Final[int] = 3
26
+ #: 行尾全量重置:SGR 重置 + OSC 8 关闭。
27
+ SEGMENT_RESET: Final[str] = "\x1b[0m\x1b]8;;\x07"
28
+
29
+ _ZWJ: Final[str] = "\u200d"
30
+
31
+
32
+ def ansi_code_length(text: str, pos: int) -> int:
33
+ """返回 ``text[pos:]`` 起始的 ANSI/OSC/APC 序列长度,无序列返回 0。
34
+
35
+ - CSI:``ESC [`` … 以 ``m/G/K/H/J`` 结束;
36
+ - OSC:``ESC ]`` … 以 BEL 或 ``ESC \\`` 结束;
37
+ - APC:``ESC _`` … 以 BEL 或 ``ESC \\`` 结束(光标标记 ``_pi:c`` 用它)。
38
+
39
+ CSI 按 final byte(0x40–0x7E,
40
+ 含 ``m``、``K``、``G``、``h``、``l`` 等)结束。未知形态返回 0,
41
+ 让调用方把它当普通字符处理(宽度计算防御性兜底)。
42
+ """
43
+ if pos >= len(text) or text[pos] != ESC:
44
+ return 0
45
+ if pos + 1 >= len(text):
46
+ return 0
47
+ kind = text[pos + 1]
48
+ if kind == "[":
49
+ for j in range(pos + 2, len(text)):
50
+ code = ord(text[j])
51
+ if 0x40 <= code <= 0x7E: # final byte:参数/中间字节都小于 0x40
52
+ return j + 1 - pos
53
+ return 0
54
+ if kind in ("]", "_"):
55
+ j = pos + 2
56
+ while j < len(text):
57
+ code = text[j]
58
+ if code == BEL:
59
+ return j + 1 - pos
60
+ if code == ESC and j + 1 < len(text) and text[j + 1] == "\\":
61
+ return j + 2 - pos
62
+ j += 1
63
+ return 0
64
+ return 0
65
+
66
+
67
+ def strip_ansi(text: str) -> str:
68
+ """剥离所有 ANSI/OSC/APC 序列,只留可见文本。"""
69
+ if ESC not in text:
70
+ return text
71
+ result: list[str] = []
72
+ i = 0
73
+ while i < len(text):
74
+ length = ansi_code_length(text, i)
75
+ if length > 0:
76
+ i += length
77
+ continue
78
+ result.append(text[i])
79
+ i += 1
80
+ return "".join(result)
81
+
82
+
83
+ def char_width(ch: str) -> int:
84
+ """单个 codepoint 的终端列宽(不感知 ANSI,ANSI 由 :func:`visible_width` 剥离)。
85
+
86
+ 公开给组件(Input 的水平滚动需要按单字符宽度找边界)。
87
+ """
88
+ cp = ord(ch)
89
+ if ch == "\t":
90
+ return TAB_WIDTH
91
+ if cp == 0 or cp < 0x20 or cp == 0x7F:
92
+ return 0 # 控制字符
93
+ category = unicodedata.category(ch)
94
+ if category in ("Mn", "Me", "Cf"):
95
+ return 0 # 组合附标与格式字符(ZWJ、变体选择子、词连接符)
96
+ if category == "Cs":
97
+ return 0 # 孤立代理项(防御,正常 str 不会出现)
98
+ # 区域指示符(旗帜的一半)终端普遍按 2 列渲染。
99
+ if 0x1F1E6 <= cp <= 0x1F1FF:
100
+ return 2
101
+ if unicodedata.east_asian_width(ch) in ("W", "F"):
102
+ return 2
103
+ # Emoji 与象形区块(无 East_Asian_Width=F/W 标注时终端也按 2 列)。
104
+ if 0x1F000 <= cp <= 0x1FAFF or 0x2600 <= cp <= 0x27BF or 0x2B50 <= cp <= 0x2B55:
105
+ return 2
106
+ return 1
107
+
108
+
109
+ def visible_width(text: str) -> int:
110
+ """字符串的终端可见列宽:ANSI 序列 0 列、宽字符 2 列、组合附标 0 列。
111
+
112
+ 快路径:纯可打印 ASCII(含 ANSI 序列与 tab)
113
+ 直接按字符数累计,不查 Unicode 表。
114
+ """
115
+ width = 0
116
+ i = 0
117
+ while i < len(text):
118
+ if text[i] == ESC:
119
+ length = ansi_code_length(text, i)
120
+ if length == 0:
121
+ i += 1
122
+ continue
123
+ i += length
124
+ continue
125
+ ch = text[i]
126
+ w = char_width(ch)
127
+ width += w
128
+ i += 1
129
+ # ZWJ emoji 序列(👨‍👩‍👧):ZWJ 宽 0,后续 base 与零宽成分整块吞掉,
130
+ # 序列总宽度保持首个 emoji 的 2 列(终端把整族渲染为一个 2 列字形)。
131
+ if ch == _ZWJ and width >= 2:
132
+ while i < len(text):
133
+ nxt = text[i]
134
+ if nxt == _ZWJ or unicodedata.category(nxt) in ("Mn", "Me", "Cf"):
135
+ i += 1
136
+ continue
137
+ if char_width(nxt) == 2:
138
+ i += 1
139
+ continue
140
+ break
141
+ return width
142
+
143
+
144
+ def _iter_cells(text: str) -> list[str]:
145
+ """把文本切成"可见单元"(codepoint),保留原顺序;ANSI 序列保持为整段。"""
146
+ cells: list[str] = []
147
+ i = 0
148
+ while i < len(text):
149
+ length = ansi_code_length(text, i)
150
+ if length > 0:
151
+ cells.append(text[i : i + length])
152
+ i += length
153
+ continue
154
+ cells.append(text[i])
155
+ i += 1
156
+ return cells
157
+
158
+
159
+ class _SgrTracker:
160
+ """跟踪行内活跃的 SGR 属性,供换行时在下一行行首重开。"""
161
+
162
+ _attrs: Final[tuple[str, ...]] = (
163
+ "1",
164
+ "2",
165
+ "3",
166
+ "4",
167
+ "7",
168
+ "9", # bold/dim/italic/underline/inverse/strike
169
+ )
170
+
171
+ def __init__(self) -> None:
172
+ self._active: list[str] = []
173
+
174
+ def process(self, code: str) -> None:
175
+ if not (code.startswith(f"{ESC}[") and code.endswith("m")):
176
+ return
177
+ params = code[2:-1]
178
+ if params in ("", "0"):
179
+ self._active.clear()
180
+ return
181
+ parts = params.split(";")
182
+ i = 0
183
+ while i < len(parts):
184
+ token = parts[i]
185
+ if token in ("38", "48"):
186
+ # 38;5;N 或 38;2;R;G;B —— 颜色整体作为一个活跃码。
187
+ if i + 1 < len(parts) and parts[i + 1] == "5" and i + 2 < len(parts):
188
+ self._active.append(";".join(parts[i : i + 3]))
189
+ i += 3
190
+ continue
191
+ if i + 1 < len(parts) and parts[i + 1] == "2" and i + 4 < len(parts):
192
+ self._active.append(";".join(parts[i : i + 5]))
193
+ i += 5
194
+ continue
195
+ i += 1
196
+ continue
197
+ if token in self._attrs:
198
+ self._active.append(token)
199
+ elif token in ("22", "23", "24", "27", "29"):
200
+ off = {"22": ("1", "2"), "23": ("3",), "24": ("4",), "27": ("7",), "29": ("9",)}
201
+ self._active = [a for a in self._active if a not in off[token]]
202
+ elif token == "39" or token == "49":
203
+ self._active = [a for a in self._active if not a.startswith(token[0])]
204
+ elif (
205
+ token[:1] in ("3", "9")
206
+ and token[1].isdigit()
207
+ and len(token) == 2
208
+ and 30 <= int(token) <= 97
209
+ ) or (
210
+ token[:1] in ("4", "1")
211
+ and token[1].isdigit()
212
+ and len(token) == 3
213
+ and 100 <= int(token) <= 107
214
+ ):
215
+ self._active.append(token)
216
+ i += 1
217
+
218
+ def active_codes(self) -> str:
219
+ """当前活跃 SGR 的重开序列(无活跃属性时为空串)。"""
220
+ if not self._active:
221
+ return ""
222
+ return f"{ESC}[{' ;'.join(sorted(set(self._active))).replace(' ', '')}m"
223
+
224
+ def reset_prefix(self) -> str:
225
+ """换行处的行尾重置(全量 reset,见模块 docstring 的取舍说明)。"""
226
+ return "\x1b[0m" if self._active else ""
227
+
228
+
229
+ def _tokenize(text: str) -> list[str]:
230
+ """词法 token 化:ANSI 附着到后续可见字符;CJK 字符独立成 token;空格归并。
231
+
232
+ 换行可以在 CJK 字符之间、空格与词的
233
+ 边界发生,但不能把拉丁词拆开(超长词另走硬断行)。
234
+ """
235
+ tokens: list[str] = []
236
+ pending_ansi = ""
237
+ current = ""
238
+ current_kind: str | None = None
239
+
240
+ def flush() -> None:
241
+ nonlocal current, current_kind
242
+ if current:
243
+ tokens.append(current)
244
+ current = ""
245
+ current_kind = None
246
+
247
+ for cell in _iter_cells(text):
248
+ if cell.startswith(ESC):
249
+ pending_ansi += cell
250
+ continue
251
+ ch = cell
252
+ kind: str | None
253
+ if unicodedata.east_asian_width(ch) in ("W", "F") or char_width(ch) == 2:
254
+ flush()
255
+ tokens.append(pending_ansi + ch)
256
+ pending_ansi = ""
257
+ continue
258
+ kind = "space" if ch == " " else "word"
259
+ if current and current_kind != kind:
260
+ flush()
261
+ if pending_ansi:
262
+ current += pending_ansi
263
+ pending_ansi = ""
264
+ current_kind = kind
265
+ current += ch
266
+ if pending_ansi:
267
+ if current:
268
+ current += pending_ansi
269
+ elif tokens:
270
+ tokens[-1] += pending_ansi
271
+ else:
272
+ current = pending_ansi
273
+ flush()
274
+ return tokens
275
+
276
+
277
+ def _break_long_token(token: str, width: int) -> list[str]:
278
+ """超过 ``width`` 的 token 按可见单元硬断行。"""
279
+ lines: list[str] = []
280
+ current = ""
281
+ current_width = 0
282
+ for cell in _iter_cells(token):
283
+ if cell.startswith(ESC):
284
+ current += cell
285
+ continue
286
+ w = char_width(cell)
287
+ if current_width + w > width and current_width > 0:
288
+ lines.append(current)
289
+ current = ""
290
+ current_width = 0
291
+ current += cell
292
+ current_width += w
293
+ if current:
294
+ lines.append(current)
295
+ return lines if lines else [""]
296
+
297
+
298
+ def wrap_text(text: str, width: int) -> list[str]:
299
+ """词法换行:每行可见宽度 ≤ ``width``,行不补空格(调用方按需 pad)。
300
+
301
+ - 先按 ``\\n`` / ``\\r\\n`` 切段,段内再做词法换行;
302
+ - 活跃 SGR 跨行保留:断行处行尾补重置、新行行首重开;
303
+ - 拉丁词整词移动,放不下时硬断;CJK 字符之间允许任意断行;
304
+ - 行尾的空格 token 在断行时丢弃(不把空格带到下一行行首)。
305
+
306
+ ``width <= 0`` 时按 1 处理(防御,调用方负责给正宽度)。
307
+ """
308
+ if width <= 0:
309
+ width = 1
310
+ if not text:
311
+ return [""]
312
+
313
+ result: list[str] = []
314
+ for segment in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
315
+ tracker = _SgrTracker()
316
+ prefix = tracker.active_codes()
317
+ wrapped = _wrap_single_line(prefix + segment, width, tracker)
318
+ result.extend(wrapped)
319
+ return result if result else [""]
320
+
321
+
322
+ def _wrap_single_line(line: str, width: int, tracker: _SgrTracker) -> list[str]:
323
+ if not line:
324
+ return [""]
325
+ if visible_width(line) <= width:
326
+ return [line.rstrip() or ""]
327
+
328
+ wrapped: list[str] = []
329
+ current = ""
330
+ current_width = 0
331
+
332
+ for token in _tokenize(line):
333
+ token_width = visible_width(token)
334
+ is_space = not strip_ansi(token).strip()
335
+
336
+ if token_width > width and not is_space:
337
+ if current:
338
+ wrapped.append(current + tracker.reset_prefix())
339
+ current = ""
340
+ current_width = 0
341
+ broken = _break_long_token(tracker.active_codes() + token, width)
342
+ wrapped.extend(broken[:-1])
343
+ current = broken[-1]
344
+ current_width = visible_width(current)
345
+ _absorb_sgr(token, tracker)
346
+ continue
347
+
348
+ if current_width + token_width > width and current_width > 0:
349
+ wrapped.append(current.rstrip() + tracker.reset_prefix())
350
+ if is_space:
351
+ current = tracker.active_codes()
352
+ current_width = 0
353
+ else:
354
+ current = tracker.active_codes() + token
355
+ current_width = token_width
356
+ _absorb_sgr(token, tracker)
357
+ continue
358
+
359
+ current += token
360
+ current_width += token_width
361
+ _absorb_sgr(token, tracker)
362
+
363
+ if current:
364
+ wrapped.append(current.rstrip() or "")
365
+ return wrapped if wrapped else [""]
366
+
367
+
368
+ def _absorb_sgr(token: str, tracker: _SgrTracker) -> None:
369
+ i = token.find(ESC)
370
+ while i != -1:
371
+ length = ansi_code_length(token, i)
372
+ if length > 0:
373
+ tracker.process(token[i : i + length])
374
+ i += length
375
+ else:
376
+ i += 1
377
+ i = token.find(ESC, i)
378
+
379
+
380
+ def truncate_to_width(text: str, max_width: int, ellipsis: str = "...") -> str:
381
+ """按可见宽度截断,超出时以 ``ellipsis`` 收尾。
382
+
383
+ ANSI 序列不占宽度:截断点之前的 ANSI 原样保留,之后丢弃。
384
+ 不会把结果补齐到 ``max_width``(补齐用 :func:`pad_to_width`)。
385
+ """
386
+ if max_width <= 0:
387
+ return ""
388
+ if visible_width(text) <= max_width:
389
+ return text
390
+ ellipsis_width = visible_width(ellipsis)
391
+ if ellipsis_width >= max_width:
392
+ ellipsis = ellipsis[:max_width] if visible_width(ellipsis[:max_width]) <= max_width else ""
393
+ ellipsis_width = visible_width(ellipsis)
394
+ budget = max_width - ellipsis_width
395
+
396
+ result: list[str] = []
397
+ kept = 0
398
+ i = 0
399
+ while i < len(text) and kept < budget:
400
+ if text[i] == ESC:
401
+ length = ansi_code_length(text, i)
402
+ if length == 0:
403
+ i += 1
404
+ continue
405
+ result.append(text[i : i + length])
406
+ i += length
407
+ continue
408
+ w = char_width(text[i])
409
+ if kept + w > budget:
410
+ break
411
+ result.append(text[i])
412
+ kept += w
413
+ i += 1
414
+ return "".join(result) + SEGMENT_RESET + ellipsis
415
+
416
+
417
+ def pad_to_width(line: str, width: int) -> str:
418
+ """把行补齐到恰好 ``width`` 可见列(不足补空格,超出不裁剪)。"""
419
+ missing = width - visible_width(line)
420
+ if missing <= 0:
421
+ return line
422
+ return line + " " * missing
423
+
424
+
425
+ def slice_by_column(line: str, start_col: int, length: int) -> str:
426
+ """按可见列区间 ``[start_col, start_col+length)`` 取子串。
427
+
428
+ ANSI 序列零宽:区间之前的 ANSI 丢弃(调用方需要前置样式时自行拼接);
429
+ 跨越右边界的宽字符整块不取(避免把 2 列字符切一半产生错位)。
430
+ """
431
+ if length <= 0:
432
+ return ""
433
+ end_col = start_col + length
434
+ result: list[str] = []
435
+ col = 0
436
+ i = 0
437
+ while i < len(line):
438
+ if line[i] == ESC:
439
+ length_seq = ansi_code_length(line, i)
440
+ if length_seq == 0:
441
+ i += 1
442
+ continue
443
+ if start_col <= col < end_col:
444
+ result.append(line[i : i + length_seq])
445
+ i += length_seq
446
+ continue
447
+ w = char_width(line[i])
448
+ if col >= start_col and col + w <= end_col:
449
+ result.append(line[i])
450
+ col += w
451
+ if col >= end_col:
452
+ break
453
+ i += 1
454
+ return "".join(result)