rvlib-shipkit 2.22.0 → 2.23.0

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 (52) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/package.json +1 -1
  3. package/src/annex/annex.ts +3 -0
  4. package/src/annex/born.ts +464 -0
  5. package/src/annex/flush.ts +46 -0
  6. package/src/annex/offload.ts +171 -38
  7. package/src/annex/snapshots.ts +53 -0
  8. package/src/annex/tidy.ts +368 -0
  9. package/src/checks/SK041-annex-links.check.ts +4 -2
  10. package/src/checks/SK043-scratch-on-the-mac.check.ts +45 -0
  11. package/src/cli/cmd_Annex.ts +60 -9
  12. package/src/cli/cmd_Home.ts +28 -0
  13. package/src/cli/cmd_Rec.ts +17 -7
  14. package/src/cli/cmd_Review.ts +27 -3
  15. package/src/core/machine-db.ts +8 -0
  16. package/src/home/claude-temp.ts +139 -0
  17. package/src/home/daemon-jobs.ts +10 -3
  18. package/src/home/global-units.ts +3 -0
  19. package/src/home/machine-stores.ts +27 -3
  20. package/src/home/pm.ts +4 -1
  21. package/src/home/run-pm.ts +1 -0
  22. package/src/identities/identities.ts +92 -24
  23. package/src/media-store/daemon.ts +2 -2
  24. package/src/media-store/purge.ts +4 -0
  25. package/src/recordings/load.ts +3 -3
  26. package/src/recordings/model.ts +7 -0
  27. package/src/recordings/open.ts +12 -0
  28. package/src/recordings/presets.ts +12 -5
  29. package/src/recordings/recorder-app/Capture.swift +34 -5
  30. package/src/recordings/recorder-app/Clip.swift +218 -54
  31. package/src/recordings/recorder-app/Editor.swift +177 -7
  32. package/src/recordings/recorder-app/Hud.swift +189 -0
  33. package/src/recordings/recorder-app/Tray.swift +179 -36
  34. package/src/recordings/recorder-app/icon.svg +16 -0
  35. package/src/recordings/recorder-app/main.swift +363 -29
  36. package/src/recordings/recorder-app.ts +8 -4
  37. package/src/recordings/recorder.shipkit.ts +2 -1
  38. package/src/recordings/routes.ts +52 -6
  39. package/src/recordings/run-recorder.ts +2 -1
  40. package/src/recordings/share.ts +27 -0
  41. package/src/recordings/take.ts +36 -4
  42. package/src/recordings/view.ts +11 -0
  43. package/src/repo-config.ts +9 -1
  44. package/src/review/model.ts +33 -4
  45. package/src/serve/hub-app/hub.css +4 -0
  46. package/src/serve/hub-app/recordings-st.ts +135 -24
  47. package/src/serve/hub-app/recordings-view.tsx +293 -54
  48. package/src/serve/hub-app/recordings.css +77 -24
  49. package/src/shipkit-files.ts +5 -0
  50. package/src/social/drafts.ts +4 -3
  51. package/src/social/load.ts +7 -2
  52. package/src/social/publish/discord.ts +10 -3
@@ -15,6 +15,10 @@ export const KEEP_DAYS = 14
15
15
  /** under this much free disk the daemon purges, when the owner turned it on */
16
16
  export const FREE_MIN_BYTES = 40e9
17
17
 
18
+ /** the daemon's window for a disk with `free` bytes: 14 days, 3 under FREE_MIN_BYTES, 1 under half of it. A young,
19
+ * heavy repo fills the disk in days, and a row its kind pins stays whatever the window */
20
+ export const windowDays = (free: number): number => (free >= FREE_MIN_BYTES ? KEEP_DAYS : free >= FREE_MIN_BYTES / 2 ? 3 : 1)
21
+
18
22
  export interface Candidate {
19
23
  item: string
20
24
  name: string
@@ -6,7 +6,7 @@ import { basename } from 'node:path'
6
6
  import { UNASSIGNED } from './place.ts'
7
7
  import { mergePresets, type NamedPreset } from './presets.ts'
8
8
 
9
- export type RecorderState = { presets: NamedPreset[]; problems: string[]; repos: string[]; repo: string; home: string | null }
9
+ export type RecorderState = { presets: NamedPreset[]; trayKeys: string[]; problems: string[]; repos: string[]; repo: string; home: string | null }
10
10
 
11
11
 
12
12
  /** the house repos and every preset, read from their configs side by side */
@@ -30,8 +30,8 @@ export async function recorderState(cwd = process.cwd()): Promise<RecorderState>
30
30
  const others = repos.filter((r) => r !== house)
31
31
  const each = await Promise.all(others.map(read))
32
32
  const merged = mergePresets(own, others.map((root, i) => ({ root, recorder: each[i] })))
33
- const { presets } = merged
33
+ const { presets, trayKeys } = merged
34
34
  const problems = [...broken, ...merged.problems]
35
35
  const names = [UNASSIGNED, ...repos.map((r) => basename(r)).sort()]
36
- return { presets, problems, repos: names, repo: UNASSIGNED, home: house ? homeUrl() : null }
36
+ return { presets, trayKeys, problems, repos: names, repo: UNASSIGNED, home: house ? homeUrl() : null }
37
37
  }
@@ -32,8 +32,15 @@ export type RecMeta = {
32
32
  /** every Space key it had that its files no longer name (an export, a poster or a public copy replaced): a delete
33
33
  * takes them too, so a link copied before an export dies with the rest */
34
34
  former?: string[]
35
+ /** every save of its edit that changed something, oldest first (take.ts, versionsOf) */
36
+ versions?: RecVersion[]
35
37
  }
36
38
 
39
+ /** one save of an edit: its number, when, the text that made it, and what it rendered (none for the take whole) */
40
+ export type RecVersion = { n: number; at: string; text: string; sha?: string; size?: number }
41
+ /** the saves kept: the oldest go first */
42
+ export const VERSIONS_KEPT = 50
43
+
37
44
  export type Recording = RecMeta & { dir: string; root: string }
38
45
 
39
46
  export const META = 'meta.json'
@@ -26,6 +26,18 @@ export function recorderUrl(o: { preset?: string; spec?: RecPreset; repo?: strin
26
26
  return `${RECORDER_SCHEME}://record?${q.toString()}`
27
27
  }
28
28
 
29
+ /** the url that asks the app to copy a capture's file natively, confirmed and shown by its clipboard indicator:
30
+ * `png` and `webp-hq` a still as that image, `file` the file alone (a video). `keep`: where the still's WebP stays
31
+ * once made, so the next copy reads it instead of encoding again */
32
+ export function recorderCopyUrl(file: string, format: 'png' | 'webp-hq' | 'file', keep?: string): string {
33
+ return `${RECORDER_SCHEME}://copy?${new URLSearchParams({ file, format, ...(keep ? { keep } : {}) }).toString()}`
34
+ }
35
+
36
+ /** the same for a text (a link): `label` and `detail` are what the indicator says */
37
+ export function recorderCopyTextUrl(text: string, label: string, detail: string): string {
38
+ return `${RECORDER_SCHEME}://copy?${new URLSearchParams({ text, label, detail }).toString()}`
39
+ }
40
+
29
41
  /** a folder to the Trash through the Finder: it works across drives, and it can be put back */
30
42
  export async function trash(dir: string): Promise<void> {
31
43
  const p = Bun.spawn(['osascript', '-e', 'on run argv', '-e', 'tell application "Finder" to delete (POSIX file (item 1 of argv) as alias)', '-e', 'end run', dir], { stdout: 'ignore', stderr: 'pipe' })
@@ -44,12 +44,18 @@ export type RecorderConfig = {
44
44
  * used while the drive is mounted, else the Mac's disk takes the take, said loud */
45
45
  dir?: string
46
46
  presets?: Record<string, RecPreset>
47
+ /** the global hotkey (or several) that shows or hides the recent captures tray (house config only). Absent: shipkit's
48
+ * own when the house names no presets either, else none */
49
+ trayKey?: string | string[]
47
50
  }
48
51
 
52
+ /** the tray's hotkey when the house names neither presets nor a tray key */
53
+ export const BUILTIN_TRAY_KEY = 'alt+shift+t'
54
+
49
55
  /** what ships when the house names none: a video and a screenshot, each a window or an area, and a screenshot taken
50
56
  * on the screen as it was the instant its hotkey was pressed */
51
57
  export const BUILTIN_PRESETS: Record<string, RecPreset> = {
52
- video: { key: 'alt+shift+r', label: 'Video', shoot: 'select', mic: true, clicks: true, after: ['upload', 'copy-link'] },
58
+ video: { key: 'alt+shift+r', label: 'Video', shoot: 'select', mic: true, clicks: true, after: ['upload', 'copy-link', 'open-editor'] },
53
59
  still: { key: 'alt+shift+s', label: 'Screenshot', shoot: 'select', still: true, after: ['copy-file', 'upload', 'open-editor'] },
54
60
  instant: { key: 'alt+shift+i', label: 'Screenshot, frozen', shoot: 'freeze', still: true, after: ['copy-file', 'upload', 'open-editor'] },
55
61
  }
@@ -82,18 +88,19 @@ export function presetProblems(id: string, p: RecPreset): string[] {
82
88
 
83
89
  /** the presets of the menu: the house's (or the built-in ones), then each repo's own as `<repo>/<name>`; a hotkey
84
90
  * two presets claim is a problem */
85
- export function mergePresets(house: RecorderConfig | undefined, repos: { root: string; recorder: RecorderConfig | undefined }[]): { presets: NamedPreset[]; problems: string[] } {
91
+ export function mergePresets(house: RecorderConfig | undefined, repos: { root: string; recorder: RecorderConfig | undefined }[]): { presets: NamedPreset[]; trayKeys: string[]; problems: string[] } {
86
92
  const presets: NamedPreset[] = []
87
93
  const base = house?.presets ?? BUILTIN_PRESETS
88
94
  for (const [id, p] of Object.entries(base)) presets.push({ ...p, id, from: house?.presets ? 'house' : 'shipkit', keys: keysOf(p) })
89
95
  for (const r of repos) for (const [n, p] of Object.entries(r.recorder?.presets ?? {})) presets.push({ ...p, id: `${basename(r.root)}/${n}`, from: basename(r.root), keys: keysOf(p) })
90
- const problems = presets.flatMap((p) => presetProblems(p.id, p))
91
- const keys = new Map<string, string>()
96
+ const trayKeys = keysOf({ key: house?.trayKey ?? (house?.presets ? undefined : BUILTIN_TRAY_KEY) })
97
+ const problems = [...trayKeys.filter((k) => !KEY.test(k)).map((k) => `tray: key ${k}: modifiers (cmd, ctrl, alt, shift) then one key, like alt+shift+t`), ...presets.flatMap((p) => presetProblems(p.id, p))]
98
+ const keys = new Map<string, string>(trayKeys.map((k) => [k, 'the tray']))
92
99
  for (const p of presets)
93
100
  for (const k of p.keys) {
94
101
  const had = keys.get(k)
95
102
  if (had) problems.push(`${p.id}: key ${k} is already ${had}'s`)
96
103
  else keys.set(k, p.id)
97
104
  }
98
- return { presets, problems }
105
+ return { presets, trayKeys, problems }
99
106
  }
@@ -75,9 +75,31 @@ func axSetFrame(_ w: AXUIElement, _ frame: NSRect) {
75
75
 
76
76
  enum Grip { case move, n, s, e, w, ne, nw, se, sw }
77
77
 
78
+ /** the bar's mic and system sound as they were left for a preset: its next video starts with them again. The preset's
79
+ * own values hold only until the bar is touched once */
80
+ enum SoundChoice {
81
+ private static func key(_ what: String, _ preset: String) -> String { "barChoice.\(what).\(preset)" }
82
+
83
+ static func get(_ what: String, _ preset: String?, else preset0: Bool) -> Bool {
84
+ guard let preset, !preset.isEmpty, let v = UserDefaults.standard.object(forKey: key(what, preset)) as? Bool else { return preset0 }
85
+ return v
86
+ }
87
+
88
+ static func set(_ what: String, _ preset: String?, _ on: Bool) {
89
+ guard let preset, !preset.isEmpty else { return }
90
+ UserDefaults.standard.set(on, forKey: key(what, preset))
91
+ }
92
+
93
+ static func forget(_ preset: String) {
94
+ for w in ["mic", "sound"] { UserDefaults.standard.removeObject(forKey: key(w, preset)) }
95
+ }
96
+ }
97
+
78
98
  @MainActor
79
99
  final class Chooser {
80
100
  let video: Bool
101
+ /** the preset whose bar this is: a switch flipped is kept for its next video */
102
+ let remember: String?
81
103
  let windowsToo: Bool
82
104
  var mic: Bool
83
105
  var sound: Bool
@@ -97,8 +119,9 @@ final class Chooser {
97
119
  /** a frozen screenshot's screen and its image of that instant: the overlay covers that screen alone, over it */
98
120
  let frozen: (screen: NSScreen, image: CGImage)?
99
121
 
100
- init(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil) {
122
+ init(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil, remember: String? = nil) {
101
123
  self.video = video
124
+ self.remember = remember
102
125
  self.windowsToo = windowsToo
103
126
  self.mic = mic
104
127
  self.sound = sound
@@ -322,8 +345,14 @@ final class Chooser {
322
345
 
323
346
  @objc func recordClicked() { go() }
324
347
  @objc func cancelClicked() { cancel() }
325
- @objc func micClicked(_ b: NSButton) { mic = b.state == .on }
326
- @objc func soundClicked(_ b: NSButton) { sound = b.state == .on }
348
+ @objc func micClicked(_ b: NSButton) {
349
+ mic = b.state == .on
350
+ SoundChoice.set("mic", remember, mic)
351
+ }
352
+ @objc func soundClicked(_ b: NSButton) {
353
+ sound = b.state == .on
354
+ SoundChoice.set("sound", remember, sound)
355
+ }
327
356
  }
328
357
 
329
358
  /** a borderless window that still takes the keyboard */
@@ -409,9 +438,9 @@ final class ChooseView: NSView {
409
438
  }
410
439
 
411
440
  /** the person's choice: a window or an area, then (a video) adjusted and confirmed; nil when cancelled */
412
- @MainActor func choose(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil) async -> Picked? {
441
+ @MainActor func choose(video: Bool, windowsToo: Bool, mic: Bool, sound: Bool, frozen: (screen: NSScreen, image: CGImage)? = nil, remember: String? = nil) async -> Picked? {
413
442
  await withCheckedContinuation { k in
414
- let c = Chooser(video: video, windowsToo: windowsToo, mic: mic, sound: sound, frozen: frozen)
443
+ let c = Chooser(video: video, windowsToo: windowsToo, mic: mic, sound: sound, frozen: frozen, remember: remember)
415
444
  c.done = { p in
416
445
  k.resume(returning: p)
417
446
  _ = c
@@ -1,9 +1,33 @@
1
1
  // a still on the clipboard the moment it is shot (wiki tools/shipkit/recordings.md, The recorder): the app writes it
2
2
  // itself, before sk files the take, as one item that is a file and its image (a chat or a mail attaches the file, a
3
- // terminal pastes the image). Its format is the menu's choice; WebP is encoded by cwebp (Homebrew's webp), since
4
- // ImageIO writes no WebP. The file a paste reads lives in the app's own cache folder, the newest few kept
3
+ // terminal pastes the image). The item is written at once with its data PROMISED: the PNG, the file and the WebP are
4
+ // made behind it, and a paste that comes first waits for them, so a ⌘V right after the shot never pastes the clipboard
5
+ // before it. Its format is the menu's choice; WebP is encoded by cwebp (Homebrew's webp), since ImageIO writes no
6
+ // WebP. The file a paste reads lives in the app's own cache folder, the newest few kept. What the indicator says is
7
+ // read back from the clipboard, never assumed: the change count the write got, then the bytes the clipboard serves
5
8
  import AppKit
6
9
 
10
+ /** what the clipboard holds once a job's data is made, read back from it */
11
+ enum ClipCheck: Equatable {
12
+ /** served byte for byte in the chosen format */
13
+ case ready(format: String, size: String)
14
+ /** served, but as the PNG: the chosen format could not be made */
15
+ case fallback(why: String, size: String)
16
+ /** another copy (a newer still, another app) took the clipboard before the data was made */
17
+ case replaced
18
+ /** the clipboard still holds the item, yet serves other bytes than the still's */
19
+ case unreadable(String)
20
+
21
+ var line: String {
22
+ switch self {
23
+ case let .ready(f, n): "ok: confirmed on the clipboard as \(f) (\(n))"
24
+ case let .fallback(why, n): "WARN: \(why): the clipboard has the PNG (\(n))"
25
+ case .replaced: "note: another copy took the clipboard before this still's data was made"
26
+ case let .unreadable(why): "FAIL: \(why)"
27
+ }
28
+ }
29
+ }
30
+
7
31
  enum ClipFormat: String, CaseIterable {
8
32
  case png
9
33
  case webpLossless = "webp-lossless"
@@ -28,6 +52,107 @@ enum ClipFormat: String, CaseIterable {
28
52
  var cwebp: [String] { self == .webpLossless ? ["-lossless", "-z", "0"] : ["-q", "90", "-m", "2"] }
29
53
  }
30
54
 
55
+ /** one still's clipboard data, made off the main thread and handed to the clipboard as it asks: the image encoded or
56
+ * read, its file in the cache folder, its WebP; a WebP that fails falls back to the PNG, said */
57
+ final class ClipJob: NSObject, NSPasteboardItemDataProvider, @unchecked Sendable {
58
+ /** the jobs the clipboard still holds a promise of: kept alive until it lets go */
59
+ @MainActor static var live: [ClipJob] = []
60
+
61
+ let format: ClipFormat
62
+ private let ready = DispatchGroup()
63
+ private(set) var png = Data()
64
+ private(set) var file: URL?
65
+ private(set) var webp: Data?
66
+ /** why the chosen format could not be made; the PNG stands in, and ClipCheck says so */
67
+ private(set) var failure: String?
68
+ /** the clipboard it was written to and the change count that write got: the clipboard is still ours while it holds */
69
+ fileprivate(set) var board: NSPasteboard?
70
+ fileprivate(set) var count = -1
71
+
72
+ /** where this still's WebP is kept once made: read there when it is, so a second copy encodes nothing */
73
+ private let keep: URL?
74
+
75
+ /** from the image itself (a capture), or from a PNG on the disk (a tray copy) */
76
+ init(image: CGImage? = nil, pngFile: URL? = nil, format: ClipFormat, keep: URL? = nil) {
77
+ self.format = format
78
+ self.keep = format == .webpHigh ? keep : nil
79
+ super.init()
80
+ ready.enter()
81
+ DispatchQueue.global(qos: .userInitiated).async {
82
+ self.make(image, pngFile)
83
+ self.ready.leave()
84
+ }
85
+ }
86
+
87
+ private func make(_ image: CGImage?, _ pngFile: URL?) {
88
+ let f = DateFormatter()
89
+ f.dateFormat = "yyyyMMdd-HHmmss-SSS"
90
+ let base = Clip.dir.appendingPathComponent("screenshot-\(f.string(from: Date()))")
91
+ let at = base.appendingPathExtension("png")
92
+ do {
93
+ if let image {
94
+ let d = NSMutableData()
95
+ guard let dest = CGImageDestinationCreateWithData(d, "public.png" as CFString, 1, nil) else { throw Err("no PNG encoder") }
96
+ CGImageDestinationAddImage(dest, image, nil)
97
+ guard CGImageDestinationFinalize(dest) else { throw Err("the PNG did not encode") }
98
+ png = d as Data
99
+ } else if let pngFile {
100
+ png = try Data(contentsOf: pngFile)
101
+ }
102
+ try png.write(to: at)
103
+ file = at
104
+ Clip.prune()
105
+ } catch {
106
+ failure = "the clipboard's file: \(error.localizedDescription)"
107
+ return
108
+ }
109
+ guard format != .png else { return }
110
+ let out = base.appendingPathExtension("webp")
111
+ if let keep, let d = try? Data(contentsOf: keep), !d.isEmpty, (try? d.write(to: out)) != nil {
112
+ webp = d
113
+ file = out
114
+ return
115
+ }
116
+ guard let bin = ["/opt/homebrew/bin/cwebp", "/usr/local/bin/cwebp"].first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else {
117
+ failure = "\(format.label) needs cwebp (brew install webp)"
118
+ return
119
+ }
120
+ let r = Clip.runNow(bin, ["-quiet", "-mt"] + format.cwebp + [at.path, "-o", out.path])
121
+ guard r.code == 0, let d = try? Data(contentsOf: out) else {
122
+ failure = "cwebp: \(r.err.isEmpty ? "exit \(r.code)" : r.err)"
123
+ return
124
+ }
125
+ webp = d
126
+ file = out
127
+ if let keep { try? d.write(to: keep, options: .atomic) }
128
+ }
129
+
130
+ /** the WebP HQ this job made, written to `at` once it is made: a capture's own, kept beside it */
131
+ func keepWebp(at: URL) {
132
+ guard format == .webpHigh else { return }
133
+ ready.notify(queue: .global(qos: .utility)) {
134
+ if let d = self.webp { try? d.write(to: at, options: .atomic) }
135
+ }
136
+ }
137
+
138
+ /** waits for the data, then runs `done` on the main thread with what the clipboard serves now */
139
+ func whenReady(_ done: @escaping @MainActor (ClipCheck) -> Void) {
140
+ ready.notify(queue: .main) { MainActor.assumeIsolated { done(Clip.check(self)) } }
141
+ }
142
+
143
+ func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
144
+ // a paste that comes before the data waits for it: never the clipboard's older content
145
+ ready.wait()
146
+ if type == .fileURL, let file { item.setString(file.absoluteString, forType: .fileURL) }
147
+ else if type == .png { item.setData(png, forType: .png) }
148
+ else if type == Clip.WEBP_TYPE, let webp { item.setData(webp, forType: type) }
149
+ }
150
+
151
+ func pasteboardFinishedWithDataProvider(_ pasteboard: NSPasteboard) {
152
+ DispatchQueue.main.async { MainActor.assumeIsolated { ClipJob.live.removeAll { $0 === self } } }
153
+ }
154
+ }
155
+
31
156
  enum Clip {
32
157
  static let KEEP = 20
33
158
  static let WEBP_TYPE = NSPasteboard.PasteboardType("org.webmproject.webp")
@@ -38,41 +163,86 @@ enum Clip {
38
163
  return d
39
164
  }
40
165
 
41
- /** the still copied where the clipboard's file lives, at once: sk moves the take's own file when it files it */
42
- static func stage(_ png: URL) throws -> URL {
43
- let f = DateFormatter()
44
- f.dateFormat = "yyyyMMdd-HHmmss-SSS"
45
- let to = dir.appendingPathComponent("screenshot-\(f.string(from: Date())).png")
46
- try? FileManager.default.removeItem(at: to)
47
- try FileManager.default.copyItem(at: png, to: to)
48
- prune()
49
- return to
50
- }
51
-
52
- /** the staged still on the clipboard in `format`; what it says, or the reason it could not */
53
- @MainActor static func put(_ png: URL, _ format: ClipFormat) async throws -> String {
54
- let data = try Data(contentsOf: png)
55
- var file = png
56
- var webp: Data?
57
- if format != .png {
58
- guard let bin = ["/opt/homebrew/bin/cwebp", "/usr/local/bin/cwebp"].first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else {
59
- throw Err("\(format.label) needs cwebp: brew install webp")
60
- }
61
- let out = png.deletingPathExtension().appendingPathExtension("webp")
62
- let r = await run(bin, ["-quiet", "-mt"] + format.cwebp + [png.path, "-o", out.path])
63
- if r.code != 0 { throw Err("cwebp: \(r.err.isEmpty ? "exit \(r.code)" : r.err)") }
64
- webp = try Data(contentsOf: out)
65
- file = out
66
- }
166
+ /** the job's item on the clipboard now, every type promised: the file, the PNG and, for a WebP format, the WebP.
167
+ * Throws unless the clipboard reads back as this write: its change count, and every type promised */
168
+ @MainActor static func put(_ job: ClipJob, on pb: NSPasteboard = .general) throws {
67
169
  let it = NSPasteboardItem()
68
- it.setString(file.absoluteString, forType: .fileURL)
69
- if let webp { it.setData(webp, forType: WEBP_TYPE) }
70
- it.setData(data, forType: .png)
71
- let pb = NSPasteboard.general
72
- pb.clearContents()
73
- if !pb.writeObjects([it]) { throw Err("the clipboard refused \(file.lastPathComponent)") }
74
- let size = ByteCountFormatter.string(fromByteCount: Int64(webp?.count ?? data.count), countStyle: .file)
75
- return "on the clipboard as \(format.label) (\(size))"
170
+ let types: [NSPasteboard.PasteboardType] = job.format == .png ? [.fileURL, .png] : [.fileURL, WEBP_TYPE, .png]
171
+ guard it.setDataProvider(job, forTypes: types) else { throw Err("the clipboard took no promise") }
172
+ let n = pb.clearContents()
173
+ if !pb.writeObjects([it]) { throw Err("the clipboard refused the still") }
174
+ guard pb.changeCount == n, let has = pb.types, types.allSatisfy(has.contains) else { throw Err("the clipboard does not read back as the still just written") }
175
+ job.board = pb
176
+ job.count = n
177
+ ClipJob.live.append(job)
178
+ }
179
+
180
+ /** the clipboard read back once the job's data is made: still this write (its change count), then the bytes and
181
+ * the file it serves compared with the job's own */
182
+ @MainActor static func check(_ job: ClipJob) -> ClipCheck {
183
+ guard let pb = job.board, pb.changeCount == job.count else { return .replaced }
184
+ let want = job.webp ?? job.png
185
+ let type = job.webp != nil ? WEBP_TYPE : .png
186
+ guard !want.isEmpty else { return .unreadable(job.failure ?? "the still did not encode") }
187
+ guard pb.data(forType: type) == want else { return .unreadable("the clipboard serves other bytes than the still's \(job.webp != nil ? job.format.label : "PNG")") }
188
+ guard let f = job.file, pb.string(forType: .fileURL) == f.absoluteString else { return .unreadable(job.failure ?? "the clipboard's file is not the still's") }
189
+ let size = ByteCountFormatter.string(fromByteCount: Int64(want.count), countStyle: .file)
190
+ if let why = job.failure { return .fallback(why: why, size: size) }
191
+ return .ready(format: job.webp != nil ? job.format.label : "PNG", size: size)
192
+ }
193
+
194
+ /** the one way a still reaches the clipboard: written, confirmed, the indicator showing each step it read back.
195
+ * `onFail` hears a write or a read back that failed. False when the write did not land */
196
+ @MainActor @discardableResult static func copy(_ job: ClipJob, onFail: @escaping @MainActor (String) -> Void) -> Bool {
197
+ ClipHud.shared.begin(job)
198
+ do { try put(job) } catch {
199
+ ClipHud.shared.show(job, .failed(error.localizedDescription))
200
+ onFail("the clipboard: \(error.localizedDescription)")
201
+ return false
202
+ }
203
+ ClipHud.shared.show(job, .copied(job.format))
204
+ job.whenReady { r in
205
+ say(r.line)
206
+ ClipHud.shared.show(job, .checked(r))
207
+ if case let .unreadable(why) = r { onFail(why) }
208
+ }
209
+ return true
210
+ }
211
+
212
+ /** a file alone on the clipboard (a video), as Finder's Copy puts it: written, read back (this write's change count,
213
+ * this file's url), the indicator showing what it read. `onFail` hears a write or a read back that failed */
214
+ @MainActor static func copyFile(_ file: URL, on pb: NSPasteboard = .general, onFail: @escaping @MainActor (String) -> Void) {
215
+ let owner = NSObject()
216
+ ClipHud.shared.begin(owner)
217
+ let n = pb.clearContents()
218
+ let wrote = pb.writeObjects([file as NSURL])
219
+ let read = pb.string(forType: .fileURL).flatMap { URL(string: $0) }?.standardizedFileURL.path
220
+ guard wrote, pb.changeCount == n, read == file.standardizedFileURL.path else {
221
+ let why = "the clipboard does not read back as \(file.lastPathComponent)"
222
+ ClipHud.shared.show(owner, .failed(why))
223
+ onFail(why)
224
+ return
225
+ }
226
+ let bytes = (try? FileManager.default.attributesOfItem(atPath: file.path)[.size] as? Int) ?? 0
227
+ let r = ClipCheck.ready(format: "\(file.pathExtension.uppercased()) file", size: ByteCountFormatter.string(fromByteCount: Int64(bytes), countStyle: .file))
228
+ say(r.line)
229
+ ClipHud.shared.show(owner, .checked(r))
230
+ }
231
+
232
+ /** a text on the clipboard (a link), written and read back, the indicator saying `label` and `detail` */
233
+ @MainActor static func copyText(_ text: String, label: String, detail: String, on pb: NSPasteboard = .general, onFail: @escaping @MainActor (String) -> Void) {
234
+ let owner = NSObject()
235
+ ClipHud.shared.begin(owner)
236
+ let n = pb.clearContents()
237
+ guard pb.setString(text, forType: .string), pb.changeCount == n, pb.string(forType: .string) == text else {
238
+ let why = "the clipboard does not read back as the \(label.lowercased())"
239
+ ClipHud.shared.show(owner, .failed(why))
240
+ onFail(why)
241
+ return
242
+ }
243
+ let r = ClipCheck.ready(format: label, size: detail)
244
+ say(r.line)
245
+ ClipHud.shared.show(owner, .checked(r))
76
246
  }
77
247
 
78
248
  /** the newest KEEP stills and their WebP stay: a paste of an older clipboard still finds its file */
@@ -85,23 +255,17 @@ enum Clip {
85
255
  }
86
256
  }
87
257
 
88
- static func run(_ bin: String, _ args: [String]) async -> (code: Int32, err: String) {
89
- await withCheckedContinuation { k in
90
- DispatchQueue.global().async {
91
- let p = Process()
92
- p.executableURL = URL(fileURLWithPath: bin)
93
- p.arguments = args
94
- let e = Pipe()
95
- p.standardError = e
96
- p.standardOutput = FileHandle.nullDevice
97
- do { try p.run() } catch {
98
- k.resume(returning: (127, error.localizedDescription))
99
- return
100
- }
101
- let err = e.fileHandleForReading.readDataToEndOfFile()
102
- p.waitUntilExit()
103
- k.resume(returning: (p.terminationStatus, String(decoding: err, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)))
104
- }
105
- }
258
+ /** a tool run to its end on the calling thread: its exit code and what it said */
259
+ static func runNow(_ bin: String, _ args: [String]) -> (code: Int32, err: String) {
260
+ let p = Process()
261
+ p.executableURL = URL(fileURLWithPath: bin)
262
+ p.arguments = args
263
+ let e = Pipe()
264
+ p.standardError = e
265
+ p.standardOutput = FileHandle.nullDevice
266
+ do { try p.run() } catch { return (127, error.localizedDescription) }
267
+ let err = e.fileHandleForReading.readDataToEndOfFile()
268
+ p.waitUntilExit()
269
+ return (p.terminationStatus, String(decoding: err, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
106
270
  }
107
271
  }