@clipen/clipen-cli 1.0.7 → 1.0.9

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.
Files changed (99) hide show
  1. package/README.md +16 -6
  2. package/apps/web/dist/assets/index-DPgSvXZ1.js +15 -0
  3. package/apps/web/dist/assets/index-DmPWV61v.css +1 -0
  4. package/apps/web/dist/index.html +2 -2
  5. package/bin/clipen.js +229 -68
  6. package/package.json +8 -2
  7. package/pyproject.toml +1 -1
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/qwen_worker.py +13 -4
  10. package/src/clipen/analysis/setup.py +2 -1
  11. package/src/clipen/analysis/setup_cli.py +58 -12
  12. package/src/clipen/bootstrap.py +499 -167
  13. package/src/clipen/cli.py +40 -15
  14. package/src/clipen/controller/app.py +120 -38
  15. package/src/clipen/controller/server.py +70 -27
  16. package/src/clipen/editing/agent_repository.py +8 -0
  17. package/src/clipen/editing/agent_tools.py +1 -1
  18. package/src/clipen/editing/caption_design.py +134 -0
  19. package/src/clipen/editing/change_report.py +17 -0
  20. package/src/clipen/editing/component_looks.py +3 -3
  21. package/src/clipen/editing/component_review.py +0 -38
  22. package/src/clipen/editing/coordinator.py +20 -0
  23. package/src/clipen/editing/evidence_jobs.py +3 -1
  24. package/src/clipen/editing/history_changes.py +56 -27
  25. package/src/clipen/editing/production_catalog.py +67 -13
  26. package/src/clipen/editing/production_media.py +13 -2
  27. package/src/clipen/editing/production_preview.py +11 -9
  28. package/src/clipen/editing/production_progress.py +48 -3
  29. package/src/clipen/editing/production_tools.py +11 -20
  30. package/src/clipen/editing/program_subtitles.py +5 -13
  31. package/src/clipen/editing/resolve_export.py +2 -183
  32. package/src/clipen/editing/skill_tools.py +142 -218
  33. package/src/clipen/editing/tool_receipts.py +2 -1
  34. package/src/clipen/editing/versions.py +55 -10
  35. package/src/clipen/editing/visual_preview.py +62 -0
  36. package/src/clipen/editing/workbench.py +21 -1
  37. package/src/clipen/i18n.py +155 -0
  38. package/src/clipen/locale_en.py +546 -0
  39. package/src/clipen/mcp_editing/__main__.py +8 -0
  40. package/src/clipen/media/storage.py +2 -2
  41. package/src/clipen/own_ffmpeg.py +113 -0
  42. package/src/clipen/projects/models.py +16 -1
  43. package/src/clipen/projects/picker.py +3 -1
  44. package/src/clipen/projects/storage.py +17 -1
  45. package/src/clipen/providers/claude_editing.py +3 -1
  46. package/src/clipen/providers/codex_editing.py +3 -1
  47. package/src/clipen/providers/editing_agent.py +42 -5
  48. package/src/clipen/providers/liveness.py +39 -0
  49. package/src/clipen/rendering/custom_components.py +216 -25
  50. package/src/clipen/rendering/custom_render.py +90 -54
  51. package/src/clipen/rendering/fetched_fonts.py +127 -0
  52. package/src/clipen/rendering/production_effects.py +24 -2
  53. package/src/clipen/rendering/program_components.py +18 -240
  54. package/src/clipen/rendering/renderer.py +23 -17
  55. package/src/clipen/rendering/titles.py +29 -12
  56. package/src/clipen/skills/builtin/SKILL.md +3 -3
  57. package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
  58. package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
  59. package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
  60. package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
  61. package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
  62. package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
  63. package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
  64. package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
  65. package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
  66. package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
  67. package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
  68. package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
  69. package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
  70. package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
  71. package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
  72. package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
  73. package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
  74. package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
  75. package/src/clipen/skills/builtin/display.en.json +89 -0
  76. package/src/clipen/skills/builtin/references/captions.md +12 -0
  77. package/src/clipen/skills/builtin/references/graphics.md +6 -6
  78. package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +9 -4
  79. package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +10 -5
  80. package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +9 -4
  81. package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +10 -6
  82. package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +10 -6
  83. package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +9 -7
  84. package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +10 -5
  85. package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +10 -5
  86. package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +10 -7
  87. package/src/clipen/skills/catalog.py +22 -8
  88. package/src/clipen/skills/package.py +1 -10
  89. package/src/clipen/terminal.py +344 -0
  90. package/src/clipen/workspace.py +97 -28
  91. package/apps/web/dist/assets/index-C3Zw0WaM.js +0 -14
  92. package/apps/web/dist/assets/index-CaxEZKLc.css +0 -1
  93. package/src/clipen/editing/resolve_titles.py +0 -291
  94. package/src/clipen/rendering/program_creator.py +0 -804
  95. package/src/clipen/rendering/program_identities.py +0 -350
  96. package/src/clipen/rendering/program_motion.py +0 -186
  97. package/src/clipen/rendering/program_studio.py +0 -227
  98. package/src/clipen/rendering/program_styles.py +0 -321
  99. package/src/clipen/skills/builtin/components.json +0 -133
@@ -28,7 +28,6 @@ _CORE_PATHS = (
28
28
  "SKILL.md",
29
29
  "manifest.json",
30
30
  "presets.json",
31
- "components.json",
32
31
  "visual_styles.json",
33
32
  "font_styles.json",
34
33
  "font_sources.json",
@@ -57,7 +56,6 @@ def _core():
57
56
  """The production core and the design library every skill shares."""
58
57
  root = _root()
59
58
  resources = {name: root.joinpath(name).read_text(encoding="utf-8") for name in _CORE_PATHS}
60
- components = json.loads(resources["components.json"])
61
59
  styles = json.loads(resources["visual_styles.json"])
62
60
  fonts = json.loads(resources["font_styles.json"])
63
61
  templates = json.loads(resources["templates.json"])
@@ -82,7 +80,6 @@ def _core():
82
80
  "resources": resources,
83
81
  "assets": assets,
84
82
  "samples": samples,
85
- "components": components,
86
83
  "visual_styles": styles,
87
84
  "font_styles": fonts,
88
85
  "presets": json.loads(resources["presets.json"]),
@@ -178,7 +175,6 @@ def compose(chain, *, core=None, binding=None, assets=None, source="builtin"):
178
175
  "visual_styles": core["visual_styles"],
179
176
  "font_styles": core["font_styles"],
180
177
  "presets": core["presets"],
181
- "components": core["components"],
182
178
  # Only the travel genre offers the template gallery in the UI.
183
179
  "templates": core["templates"] if selected["skill_id"] == BUILTIN_SKILL else [],
184
180
  "selected_visual_style_id": binding.get("visual_style_id", "variety"),
@@ -186,9 +182,6 @@ def compose(chain, *, core=None, binding=None, assets=None, source="builtin"):
186
182
  }
187
183
  if "template" in selected:
188
184
  skill["template"] = deepcopy(selected["template"])
189
- if "components" in binding:
190
- allowed = set(binding["components"])
191
- skill["components"] = [c for c in skill["components"] if c["component_id"] in allowed]
192
185
  if "default_duration_seconds" in binding:
193
186
  skill["default_duration_seconds"] = binding["default_duration_seconds"]
194
187
  skill["content_hash"] = _digest(
@@ -213,7 +206,6 @@ def design_library(core=None):
213
206
  return {
214
207
  "visual_styles": tuple(s["visual_style_id"] for s in core["visual_styles"]),
215
208
  "font_styles": tuple(s["font_style_id"] for s in core["font_styles"]),
216
- "components": tuple(c["component_id"] for c in core["components"]),
217
209
  }
218
210
 
219
211
 
@@ -304,9 +296,31 @@ def _public(skill):
304
296
  }
305
297
 
306
298
 
299
+ def _english(skill):
300
+ """The built-in skill and templates as an English reader sees them; their frozen content is unchanged."""
301
+ display = json.loads(_root().joinpath("display.en.json").read_text(encoding="utf-8"))
302
+ # A template's own skill is named after its template.
303
+ template = display["templates"].get(skill["skill_id"].removeprefix("clipen-"), {})
304
+ names = display["skills"].get(skill["skill_id"]) or {
305
+ k: template[k] for k in ("name", "description") if k in template
306
+ }
307
+ if names:
308
+ skill.update(names)
309
+ for template in skill["templates"]:
310
+ template.update(display["templates"].get(template["template_id"], {}))
311
+ for reference in template.get("references", []):
312
+ for key in ("title", "takeaway"):
313
+ reference[key] = display["references"].get(reference.get(key), reference.get(key))
314
+ return skill
315
+
316
+
307
317
  def list_skills():
318
+ from clipen.i18n import english
319
+
308
320
  core, skills = builtin_skills()
309
321
  listed = [_public(compose([entry], core=core)) for entry in skills.values()]
322
+ if english():
323
+ listed = [_english(skill) if skill["source"] == "builtin" else skill for skill in listed]
310
324
  library = skill_library()
311
325
  for item in library.list():
312
326
  if item["state"] == "ready":
@@ -35,7 +35,7 @@ PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
35
35
  # Finder and editor droppings that are neither content nor worth reporting.
36
36
  _QUIET = frozenset({".DS_Store", "Thumbs.db"})
37
37
  CLIPEN_KEYS = frozenset(
38
- {"skill_id", "version", "extends", "visual_style_id", "font_style_id", "components", "default_duration_seconds"}
38
+ {"skill_id", "version", "extends", "visual_style_id", "font_style_id", "default_duration_seconds"}
39
39
  )
40
40
 
41
41
 
@@ -238,15 +238,6 @@ def _binding(raw: str | None, design: dict[str, object] | None) -> dict[str, obj
238
238
  for key, catalog in (("visual_style_id", "visual_styles"), ("font_style_id", "font_styles")):
239
239
  if key in value and value[key] not in design.get(catalog, ()):
240
240
  raise invalid(f"clipen.json 的 {key}「{value[key]}」不是 Clipen 內建的選項。")
241
- if "components" in value:
242
- components = value["components"]
243
- if (
244
- not isinstance(components, list)
245
- or not components
246
- or len(set(components)) != len(components)
247
- or any(c not in design.get("components", ()) for c in components)
248
- ):
249
- raise invalid("clipen.json 的 components 必須是不重複的內建元件名稱清單。")
250
241
  if "default_duration_seconds" in value:
251
242
  duration = value["default_duration_seconds"]
252
243
  if isinstance(duration, bool) or not isinstance(duration, int) or not 30 <= duration <= 1200:
@@ -0,0 +1,344 @@
1
+ """Clipen's terminal look, shared by the installer and the running app.
2
+
3
+ Standard library only: the installer draws with it before any dependency exists. It uses the same
4
+ frame, symbols and colours as the npx launcher (@clack/prompts), so setup and launch read as one
5
+ product. Output that is not a terminal (a log, a pipe, a test) gets the same frame without colour or
6
+ animation.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import re
13
+ import shutil
14
+ import sys
15
+ import threading
16
+ import time
17
+ import unicodedata
18
+ from contextlib import contextmanager
19
+ from typing import Iterator, Sequence, TextIO
20
+
21
+ from clipen.i18n import tr
22
+
23
+ try:
24
+ import termios
25
+ import tty
26
+ except ImportError: # Windows has no POSIX terminal control; prompts fall back to a typed answer.
27
+ termios = tty = None
28
+
29
+ _ANSI = re.compile(r"\033\[[0-9;?]*[A-Za-z]|\033\]8;;.*?\033\\")
30
+ _FRAMES = "◒◐◓◑"
31
+ _LOGO = (
32
+ " ██████╗██╗ ██╗██████╗ ███████╗███╗ ██╗",
33
+ "██╔════╝██║ ██║██╔══██╗██╔════╝████╗ ██║",
34
+ "██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║",
35
+ "██║ ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║",
36
+ "╚██████╗███████╗██║██║ ███████╗██║ ╚████║",
37
+ " ╚═════╝╚══════╝╚═╝╚═╝ ╚══════╝╚═╝ ╚═══╝",
38
+ )
39
+ # The brand gold from the README badges, warming to amber down the logo.
40
+ _LOGO_COLOURS = ((246, 211, 122), (240, 198, 100), (233, 180, 76), (226, 160, 62), (218, 140, 52), (208, 120, 44))
41
+ _BRAND = (233, 180, 76)
42
+ # The npx launcher sets this when it has drawn the logo and opened the frame the installer continues.
43
+ FRAME_OPEN = "CLIPEN_FRAME_OPEN"
44
+
45
+
46
+ def display_width(text: str) -> int:
47
+ """Columns the text takes in a terminal: CJK characters take two, colour codes none."""
48
+ width = 0
49
+ for character in _ANSI.sub("", text):
50
+ if unicodedata.combining(character):
51
+ continue
52
+ width += 2 if unicodedata.east_asian_width(character) in "WF" else 1
53
+ return width
54
+
55
+
56
+ def _clip(text: str, columns: int) -> str:
57
+ """Cut the text to the given columns, keeping colour codes whole."""
58
+ if display_width(text) <= columns:
59
+ return text
60
+ pieces: list[str] = []
61
+ used = 0
62
+ position = 0
63
+ while position < len(text):
64
+ code = _ANSI.match(text, position)
65
+ if code:
66
+ pieces.append(code.group())
67
+ position = code.end()
68
+ continue
69
+ character = text[position]
70
+ width = 2 if unicodedata.east_asian_width(character) in "WF" else 1
71
+ if used + width > columns - 1:
72
+ pieces.append("…\033[0m" if "\033[" in text else "…")
73
+ break
74
+ pieces.append(character)
75
+ used += width
76
+ position += 1
77
+ return "".join(pieces)
78
+
79
+
80
+ def _wrap(text: str, columns: int) -> list[str]:
81
+ """Break a plain line so each piece fits the columns."""
82
+ lines: list[str] = []
83
+ current = ""
84
+ for character in text:
85
+ if current and display_width(current + character) > columns:
86
+ lines.append(current)
87
+ current = character.lstrip() if character == " " else character
88
+ else:
89
+ current += character
90
+ return [*lines, current]
91
+
92
+
93
+ def _is_terminal(stream: TextIO) -> bool:
94
+ try:
95
+ return stream.isatty()
96
+ except (AttributeError, ValueError):
97
+ return False
98
+
99
+
100
+ class Terminal:
101
+ def __init__(self, stream: TextIO | None = None) -> None:
102
+ self.stream = stream if stream is not None else sys.stdout
103
+ self.live = _is_terminal(self.stream)
104
+ self.colour = bool(os.environ.get("FORCE_COLOR")) or (self.live and "NO_COLOR" not in os.environ)
105
+
106
+ # Colours ---------------------------------------------------------------------------------
107
+
108
+ def paint(self, code: str, text: str) -> str:
109
+ return f"\033[{code}m{text}\033[0m" if self.colour else text
110
+
111
+ def rgb(self, colour: tuple[int, int, int], text: str) -> str:
112
+ return self.paint("38;2;{};{};{}".format(*colour), text)
113
+
114
+ def brand(self, text: str) -> str:
115
+ return self.rgb(_BRAND, text)
116
+
117
+ def bold(self, text: str) -> str:
118
+ return self.paint("1", text)
119
+
120
+ def dim(self, text: str) -> str:
121
+ return self.paint("2", text)
122
+
123
+ def link(self, url: str) -> str:
124
+ """A URL the terminal can open with a click."""
125
+ shown = self.paint("4;36", url)
126
+ return f"\033]8;;{url}\033\\{shown}\033]8;;\033\\" if self.live else shown
127
+
128
+ def columns(self) -> int:
129
+ return shutil.get_terminal_size((80, 24)).columns if self.live else 100
130
+
131
+ # Output ----------------------------------------------------------------------------------
132
+
133
+ def write(self, line: str = "") -> None:
134
+ self.stream.write(f"{line}\n")
135
+ self.stream.flush()
136
+
137
+ def _bar(self) -> str:
138
+ return self.paint("90", "│")
139
+
140
+ def _item(self, symbol: str, message: str) -> None:
141
+ first, *rest = message.split("\n")
142
+ self.write(self._bar())
143
+ self.write(f"{symbol} {first}")
144
+ for line in rest:
145
+ self.write(f"{self._bar()} {line}")
146
+
147
+ def logo(self, subtitle: str = "") -> None:
148
+ """The CLIPEN wordmark, or a compact badge where it would not fit."""
149
+ if self.colour and self.columns() >= 50:
150
+ self.write()
151
+ for line, colour in zip(_LOGO, _LOGO_COLOURS):
152
+ self.write(f" {self.rgb(colour, line)}")
153
+ if subtitle:
154
+ self.write(f" {self.dim(subtitle)}")
155
+ self.write()
156
+ else:
157
+ self.write(f"Clipen {subtitle}".rstrip())
158
+
159
+ def intro(self, title: str) -> None:
160
+ self.write(f"{self.paint('90', '┌')} {self.paint('30;48;2;233;180;76', f' {title} ')}")
161
+
162
+ def outro(self, message: str) -> None:
163
+ self.write(self._bar())
164
+ self.write(f"{self.paint('90', '└')} {message}")
165
+ self.write()
166
+
167
+ def step(self, message: str) -> None:
168
+ self._item(self.paint("32", "◇"), message)
169
+
170
+ def info(self, message: str) -> None:
171
+ self._item(self.paint("34", "●"), message)
172
+
173
+ def warn(self, message: str) -> None:
174
+ self._item(self.paint("33", "▲"), message)
175
+
176
+ def error(self, message: str) -> None:
177
+ self._item(self.paint("31", "■"), message)
178
+
179
+ def note(self, title: str, lines: Sequence[str], footer: Sequence[str] = ()) -> None:
180
+ """A framed block: what is about to happen, before the person is asked.
181
+
182
+ Footer lines are plain fine print, wrapped to the terminal and dimmed.
183
+ """
184
+ limit = max(20, self.columns() - 6)
185
+ body = [piece for line in lines for piece in (_wrap(line, limit) if not _ANSI.search(line) else [line])]
186
+ if footer:
187
+ body += ([""] if body else []) + [self.dim(piece) for line in footer for piece in _wrap(line, limit)]
188
+ inner = max([display_width(line) for line in body] + [display_width(title) + 2])
189
+ grey = lambda text: self.paint("90", text) # noqa: E731
190
+ self.write(self._bar())
191
+ self.write(
192
+ f"{self.paint('32', '◇')} {self.bold(title)} {grey('─' * (inner + 1 - display_width(title)) + '╮')}"
193
+ )
194
+ self.write(grey("│") + " " * (inner + 4) + grey("│"))
195
+ for line in body:
196
+ self.write(f"{grey('│')} {line}{' ' * (inner - display_width(line))} {grey('│')}")
197
+ self.write(grey("│") + " " * (inner + 4) + grey("│"))
198
+ self.write(grey("├" + "─" * (inner + 4) + "╯"))
199
+
200
+ # Prompts ---------------------------------------------------------------------------------
201
+
202
+ def confirm(self, message: str, stdin: TextIO, *, default: bool = True) -> bool:
203
+ """Yes or no; arrow keys in a terminal, a typed y/n anywhere else."""
204
+ if self.live and termios is not None and _is_terminal(stdin):
205
+ try:
206
+ descriptor = stdin.fileno()
207
+ except (AttributeError, OSError, ValueError):
208
+ descriptor = None
209
+ if descriptor is not None:
210
+ return self._confirm_keys(message, descriptor, default)
211
+ hint = "[Y/n]" if default else "[y/N]"
212
+ self.write(self._bar())
213
+ self.stream.write(f"{self.paint('36', '◆')} {message} {self.dim(hint)} ")
214
+ self.stream.flush()
215
+ answer = stdin.readline().strip().lower()
216
+ if not self.live: # A terminal echoes the Enter; anywhere else the next item needs its own line.
217
+ self.write()
218
+ return answer in {"y", "yes"} or (default and answer == "")
219
+
220
+ def _confirm_keys(self, message: str, descriptor: int, value: bool) -> bool:
221
+ def choices() -> str:
222
+ yes = (
223
+ tr(f"{self.paint('32', '●')} 是", f"{self.paint('32', '●')} Yes")
224
+ if value
225
+ else tr(f"{self.dim('○ 是')}", f"{self.dim('○ Yes')}")
226
+ )
227
+ no = (
228
+ tr(f"{self.paint('32', '●')} 否", f"{self.paint('32', '●')} No")
229
+ if not value
230
+ else tr(f"{self.dim('○ 否')}", f"{self.dim('○ No')}")
231
+ )
232
+ return f"{yes} {self.dim('/')} {no}"
233
+
234
+ def draw(first: bool) -> None:
235
+ if not first:
236
+ self.stream.write("\r\033[2A\033[J")
237
+ self.stream.write(
238
+ f"{self.paint('36', '◆')} {message}\n{self.paint('36', '│')} {choices()}\n{self.paint('36', '└')}"
239
+ )
240
+ self.stream.flush()
241
+
242
+ saved = termios.tcgetattr(descriptor)
243
+ self.write(self._bar())
244
+ self.stream.write("\033[?25l")
245
+ submitted = False
246
+ try:
247
+ tty.setcbreak(descriptor)
248
+ draw(True)
249
+ while True:
250
+ key = os.read(descriptor, 8)
251
+ if key in (b"\r", b"\n"):
252
+ break
253
+ if key in (b"y", b"Y", b"n", b"N"):
254
+ value = key in (b"y", b"Y")
255
+ break
256
+ if key in (b"\x1b",):
257
+ value = False
258
+ break
259
+ if key in (b"\x1b[C", b"\x1b[D", b"\x1b[A", b"\x1b[B", b"\t", b" ", b"h", b"l", b"j", b"k"):
260
+ value = not value
261
+ draw(False)
262
+ submitted = True
263
+ finally:
264
+ termios.tcsetattr(descriptor, termios.TCSADRAIN, saved)
265
+ self.stream.write("\r\033[2A\033[J")
266
+ symbol = self.paint("32", "◇") if submitted else self.paint("31", "■")
267
+ answer = (
268
+ tr(("是" if value else "否"), ("Yes" if value else "No")) if submitted else tr("已取消", "Cancelled")
269
+ )
270
+ self.stream.write(f"{symbol} {message}\n{self._bar()} {self.dim(answer)}\n\033[?25h")
271
+ self.stream.flush()
272
+ return value
273
+
274
+ # Progress --------------------------------------------------------------------------------
275
+
276
+ @contextmanager
277
+ def spinner(self, message: str) -> Iterator[Spinner]:
278
+ """An animated line while work runs, closed with ◇ on success or ■ when it fails."""
279
+ spinner = Spinner(self, message)
280
+ self.write(self._bar())
281
+ spinner.start()
282
+ try:
283
+ yield spinner
284
+ except BaseException:
285
+ spinner.stop()
286
+ self.write(f"{self.paint('31', '■')} {spinner.current}")
287
+ raise
288
+ spinner.stop()
289
+ self.write(f"{self.paint('32', '◇')} {spinner.final or spinner.current}")
290
+
291
+ def progress_bar(self, percent: int, width: int = 24) -> str:
292
+ filled = max(0, min(width, percent * width // 100))
293
+ return self.brand("━" * filled) + self.paint("90", "─" * (width - filled))
294
+
295
+ def overwrite(self, line: str) -> None:
296
+ """Redraw the current line in place (a live terminal only)."""
297
+ self.stream.write("\r\033[K" + _clip(line, self.columns() - 1))
298
+ self.stream.flush()
299
+
300
+
301
+ class Spinner:
302
+ def __init__(self, terminal: Terminal, message: str) -> None:
303
+ self._terminal = terminal
304
+ self.current = message
305
+ self.final: str | None = None
306
+ self._started = time.monotonic()
307
+ self._stopped = threading.Event()
308
+ self._thread: threading.Thread | None = None
309
+
310
+ def update(self, message: str) -> None:
311
+ self.current = message
312
+
313
+ def done(self, message: str) -> None:
314
+ """What the line says once the work has finished."""
315
+ self.final = message
316
+
317
+ def start(self) -> None:
318
+ if not self._terminal.live:
319
+ return
320
+ self._terminal.stream.write("\033[?25l")
321
+ self._thread = threading.Thread(target=self._spin, name="clipen-spinner", daemon=True)
322
+ self._thread.start()
323
+
324
+ def stop(self) -> None:
325
+ self._stopped.set()
326
+ if self._thread is not None:
327
+ self._thread.join()
328
+ self._terminal.stream.write("\r\033[K\033[?25h")
329
+ self._terminal.stream.flush()
330
+
331
+ def _spin(self) -> None:
332
+ frame = 0
333
+ while True:
334
+ elapsed = int(time.monotonic() - self._started)
335
+ clock = (
336
+ tr(f"{elapsed // 60} 分 {elapsed % 60:02d} 秒", f"{elapsed // 60}m {elapsed % 60:02d}s")
337
+ if elapsed >= 60
338
+ else tr(f"{elapsed} 秒", f"{elapsed}s")
339
+ )
340
+ symbol = self._terminal.paint("35", _FRAMES[frame % len(_FRAMES)])
341
+ self._terminal.overwrite(f"{symbol} {self.current} {self._terminal.dim(clock)}")
342
+ frame += 1
343
+ if self._stopped.wait(0.08):
344
+ return
@@ -12,6 +12,8 @@ from dataclasses import dataclass
12
12
  from datetime import datetime, timezone
13
13
  from pathlib import Path
14
14
 
15
+ from clipen.i18n import tr
16
+
15
17
  from .filesystem import restrict_permissions
16
18
  from .projects.storage import PROJECT_SCHEMA_VERSION
17
19
 
@@ -72,9 +74,9 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
72
74
  try:
73
75
  root = current_directory.resolve(strict=True)
74
76
  except OSError as error:
75
- raise WorkspaceError("Clipen 無法讀取目前的工作目錄。") from error
77
+ raise WorkspaceError(tr("Clipen 無法讀取目前的工作目錄。", "Clipen cannot read the current folder.")) from error
76
78
  if not root.is_dir():
77
- raise WorkspaceError("目前路徑不是可用的資料夾。")
79
+ raise WorkspaceError(tr("目前路徑不是可用的資料夾。", "The current path is not a usable folder."))
78
80
 
79
81
  managed = root / ".clipen"
80
82
  created = not managed.exists()
@@ -83,32 +85,47 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
83
85
  except FileExistsError:
84
86
  pass
85
87
  except OSError as error:
86
- raise WorkspaceError("Clipen 無法在目前目錄建立工作區。") from error
88
+ raise WorkspaceError(
89
+ tr("Clipen 無法在目前目錄建立工作區。", "Clipen cannot set up a workspace in this folder.")
90
+ ) from error
87
91
  if managed.is_symlink() or not managed.is_dir():
88
- raise WorkspaceError("目前目錄中的 .clipen 不是安全的工作區資料夾。")
92
+ raise WorkspaceError(
93
+ tr("目前目錄中的 .clipen 不是安全的工作區資料夾。", "The .clipen here is not a safe workspace folder.")
94
+ )
89
95
  restrict_permissions(managed, 0o700)
90
96
 
91
97
  manifest = managed / "workspace.json"
92
98
  if manifest.exists():
93
99
  if manifest.is_symlink() or not manifest.is_file():
94
- raise WorkspaceError("Clipen 工作區識別檔不安全。")
100
+ raise WorkspaceError(tr("Clipen 工作區識別檔不安全。", "The Clipen workspace ID file is not safe."))
95
101
  try:
96
102
  value = json.loads(manifest.read_text(encoding="utf-8"))
97
103
  except (OSError, UnicodeError, json.JSONDecodeError) as error:
98
- raise WorkspaceError("Clipen 工作區識別檔已損壞。") from error
104
+ raise WorkspaceError(
105
+ tr("Clipen 工作區識別檔已損壞。", "The Clipen workspace ID file is damaged.")
106
+ ) from error
99
107
  if not isinstance(value, dict) or value.get("schema") != _WORKSPACE_SCHEMA:
100
- raise WorkspaceError("這個工作區需要其他版本的 Clipen。")
108
+ raise WorkspaceError(
109
+ tr("這個工作區需要其他版本的 Clipen。", "This workspace needs a different version of Clipen.")
110
+ )
101
111
  workspace_id = value.get("workspace_id")
102
112
  if not isinstance(workspace_id, str) or re.fullmatch(r"wsp_[0-9a-f]{32}", workspace_id) is None:
103
- raise WorkspaceError("Clipen 工作區識別檔已損壞。")
113
+ raise WorkspaceError(tr("Clipen 工作區識別檔已損壞。", "The Clipen workspace ID file is damaged."))
104
114
  created = False
105
115
  else:
106
116
  try:
107
117
  existing_entries = tuple(managed.iterdir())
108
118
  except OSError as error:
109
- raise WorkspaceError("Clipen 無法檢查目前目錄的工作區。") from error
119
+ raise WorkspaceError(
120
+ tr("Clipen 無法檢查目前目錄的工作區。", "Clipen cannot check the workspace in this folder.")
121
+ ) from error
110
122
  if existing_entries:
111
- raise WorkspaceError("目前目錄已有無法識別的 .clipen 資料,Clipen 沒有修改它。")
123
+ raise WorkspaceError(
124
+ tr(
125
+ "目前目錄已有無法識別的 .clipen 資料,Clipen 沒有修改它。",
126
+ "This folder has .clipen data Clipen does not recognise; it was left unchanged.",
127
+ )
128
+ )
112
129
  created = True
113
130
  workspace_id = "wsp_" + uuid.uuid4().hex
114
131
  _atomic_json(
@@ -123,7 +140,9 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
123
140
  projects = managed / "projects"
124
141
  projects.mkdir(mode=0o700, exist_ok=True)
125
142
  if projects.is_symlink() or not projects.is_dir():
126
- raise WorkspaceError("Clipen 工作區中的 projects 不安全。")
143
+ raise WorkspaceError(
144
+ tr("Clipen 工作區中的 projects 不安全。", "The projects folder in this workspace is not safe.")
145
+ )
127
146
  restrict_permissions(projects, 0o700)
128
147
 
129
148
  return WorkspacePaths(
@@ -136,46 +155,96 @@ def prepare_workspace(current_directory: Path) -> WorkspacePaths:
136
155
  )
137
156
 
138
157
 
158
+ def _read_project(database: Path) -> tuple:
159
+ """The integrity check, schema version and project id, read without changing the project.
160
+
161
+ Read-only first. A read-only connection cannot rebuild the WAL index SQLite keeps beside a
162
+ database, and on some disks (exFAT) a project Clipen closed normally then reads as a disk I/O
163
+ error; a query-only connection lets SQLite rebuild that index and leaves the data untouched."""
164
+ uri = database.resolve(strict=True).as_uri()
165
+ for mode in ("ro", "rw"):
166
+ connection = sqlite3.connect(f"{uri}?mode={mode}", uri=True, timeout=5)
167
+ try:
168
+ connection.execute("PRAGMA query_only = ON")
169
+ return (
170
+ connection.execute("PRAGMA quick_check").fetchone(),
171
+ connection.execute("PRAGMA user_version").fetchone(),
172
+ connection.execute("SELECT project_id FROM project LIMIT 1").fetchone(),
173
+ )
174
+ except sqlite3.OperationalError:
175
+ if mode == "rw":
176
+ raise
177
+ finally:
178
+ connection.close()
179
+ raise AssertionError("unreachable")
180
+
181
+
139
182
  def inspect_workspace_projects(workspace: WorkspacePaths) -> WorkspaceInspection:
140
183
  """Verify every managed project before the provider or Controller starts."""
141
184
 
142
185
  try:
143
186
  entries = tuple(workspace.projects_root.iterdir())
144
187
  except OSError as error:
145
- raise WorkspaceError("Clipen 無法檢查目前目錄的作品。") from error
188
+ raise WorkspaceError(
189
+ tr("Clipen 無法檢查目前目錄的作品。", "Clipen cannot check the projects in this folder.")
190
+ ) from error
146
191
 
147
192
  project_count = 0
148
193
  for entry in entries:
149
194
  if entry.name.startswith("prj_") and _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
150
- raise WorkspaceError(f"偵測到無法識別的作品資料夾:{entry.name}。Clipen 沒有修改它。")
195
+ raise WorkspaceError(
196
+ tr(
197
+ f"偵測到無法識別的作品資料夾:{entry.name}。Clipen 沒有修改它。",
198
+ f"Found a project folder Clipen does not recognise: {entry.name}. It was left unchanged.",
199
+ )
200
+ )
151
201
  if _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
152
202
  continue
153
203
  if entry.is_symlink() or not entry.is_dir() or os.path.ismount(entry):
154
- raise WorkspaceError(f"作品 {entry.name} 的資料夾不安全,Clipen 沒有修改它。")
204
+ raise WorkspaceError(
205
+ tr(
206
+ f"作品 {entry.name} 的資料夾不安全,Clipen 沒有修改它。",
207
+ f"The folder of project {entry.name} is not safe; it was left unchanged.",
208
+ )
209
+ )
155
210
  database = entry / "project.sqlite3"
156
211
  try:
157
212
  info = database.lstat()
158
213
  except OSError as error:
159
- raise WorkspaceError(f"作品 {entry.name} 缺少可讀取的資料庫。") from error
214
+ raise WorkspaceError(
215
+ tr(f"作品 {entry.name} 缺少可讀取的資料庫。", f"Project {entry.name} has no readable database.")
216
+ ) from error
160
217
  if not stat.S_ISREG(info.st_mode) or info.st_nlink != 1:
161
- raise WorkspaceError(f"作品 {entry.name} 的資料庫不安全,Clipen 沒有修改它。")
218
+ raise WorkspaceError(
219
+ tr(
220
+ f"作品 {entry.name} 的資料庫不安全,Clipen 沒有修改它。",
221
+ f"The database of project {entry.name} is not safe; it was left unchanged.",
222
+ )
223
+ )
162
224
 
163
225
  try:
164
- uri = f"{database.resolve(strict=True).as_uri()}?mode=ro"
165
- connection = sqlite3.connect(uri, uri=True, timeout=5)
166
- try:
167
- connection.execute("PRAGMA query_only = ON")
168
- check = connection.execute("PRAGMA quick_check").fetchone()
169
- version = connection.execute("PRAGMA user_version").fetchone()
170
- row = connection.execute("SELECT project_id FROM project LIMIT 1").fetchone()
171
- finally:
172
- connection.close()
226
+ check, version, row = _read_project(database)
173
227
  except (OSError, sqlite3.Error) as error:
174
- raise WorkspaceError(f"作品 {entry.name} 的資料庫已損壞或無法讀取。") from error
228
+ raise WorkspaceError(
229
+ tr(
230
+ f"作品 {entry.name} 的資料庫已損壞或無法讀取。",
231
+ f"The database of project {entry.name} is damaged or unreadable.",
232
+ )
233
+ ) from error
175
234
  if check is None or check[0] != "ok" or row is None or row[0] != entry.name:
176
- raise WorkspaceError(f"作品 {entry.name} 的資料內容不完整,Clipen 沒有修改它。")
235
+ raise WorkspaceError(
236
+ tr(
237
+ f"作品 {entry.name} 的資料內容不完整,Clipen 沒有修改它。",
238
+ f"Project {entry.name} is incomplete; it was left unchanged.",
239
+ )
240
+ )
177
241
  if version is None or not isinstance(version[0], int) or not 1 <= version[0] <= PROJECT_SCHEMA_VERSION:
178
- raise WorkspaceError(f"作品 {entry.name} 需要其他版本的 Clipen。")
242
+ raise WorkspaceError(
243
+ tr(
244
+ f"作品 {entry.name} 需要其他版本的 Clipen。",
245
+ f"Project {entry.name} needs a different version of Clipen.",
246
+ )
247
+ )
179
248
  project_count += 1
180
249
 
181
250
  return WorkspaceInspection(project_count)