rvlib-shipkit 2.22.0 → 2.22.1

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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## 2.22.1
2
+
3
+ - **A screenshot is on the clipboard the instant it is shot.** The recorder writes the clipboard before any encode, its file, PNG and WebP made behind it; a paste that comes first waits for them, so a quick ⌘V never pastes the clipboard from before, whatever the format.
4
+
1
5
  ## 2.22.0
2
6
 
3
7
  - **A screen recorder replaces Snagit.** A menu bar app, built and run by shipkit, shoots videos and screenshots on global hotkeys. Each preset in `recorder.presets` (`repo.config.ts`) names its keys (one or several), what it shoots, the mic, the system sound, clicks, a countdown and what runs after: upload, a private or public link, the file, markdown, the editor, the Finder. `sk rec presets` lists them and every problem.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "2.22.0",
3
+ "version": "2.22.1",
4
4
  "funding": "https://github.com/sponsors/rvion",
5
5
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
6
6
  "license": "MIT",
@@ -1,7 +1,9 @@
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
5
7
  import AppKit
6
8
 
7
9
  enum ClipFormat: String, CaseIterable {
@@ -28,6 +30,91 @@ enum ClipFormat: String, CaseIterable {
28
30
  var cwebp: [String] { self == .webpLossless ? ["-lossless", "-z", "0"] : ["-q", "90", "-m", "2"] }
29
31
  }
30
32
 
33
+ /** one still's clipboard data, made off the main thread and handed to the clipboard as it asks: the image encoded or
34
+ * read, its file in the cache folder, its WebP; a WebP that fails falls back to the PNG, said */
35
+ final class ClipJob: NSObject, NSPasteboardItemDataProvider, @unchecked Sendable {
36
+ /** the jobs the clipboard still holds a promise of: kept alive until it lets go */
37
+ @MainActor static var live: [ClipJob] = []
38
+
39
+ let format: ClipFormat
40
+ private let ready = DispatchGroup()
41
+ private(set) var png = Data()
42
+ private(set) var file: URL?
43
+ private(set) var webp: Data?
44
+ /** why the chosen format could not be made; the PNG stands in */
45
+ private(set) var failure: String?
46
+
47
+ /** from the image itself (a capture), or from a PNG on the disk (a tray copy) */
48
+ init(image: CGImage? = nil, pngFile: URL? = nil, format: ClipFormat) {
49
+ self.format = format
50
+ super.init()
51
+ ready.enter()
52
+ DispatchQueue.global(qos: .userInitiated).async {
53
+ self.make(image, pngFile)
54
+ self.ready.leave()
55
+ }
56
+ }
57
+
58
+ private func make(_ image: CGImage?, _ pngFile: URL?) {
59
+ let f = DateFormatter()
60
+ f.dateFormat = "yyyyMMdd-HHmmss-SSS"
61
+ let base = Clip.dir.appendingPathComponent("screenshot-\(f.string(from: Date()))")
62
+ let at = base.appendingPathExtension("png")
63
+ do {
64
+ if let image {
65
+ let d = NSMutableData()
66
+ guard let dest = CGImageDestinationCreateWithData(d, "public.png" as CFString, 1, nil) else { throw Err("no PNG encoder") }
67
+ CGImageDestinationAddImage(dest, image, nil)
68
+ guard CGImageDestinationFinalize(dest) else { throw Err("the PNG did not encode") }
69
+ png = d as Data
70
+ } else if let pngFile {
71
+ png = try Data(contentsOf: pngFile)
72
+ }
73
+ try png.write(to: at)
74
+ file = at
75
+ Clip.prune()
76
+ } catch {
77
+ failure = "the clipboard's file: \(error.localizedDescription)"
78
+ return
79
+ }
80
+ guard format != .png else { return }
81
+ guard let bin = ["/opt/homebrew/bin/cwebp", "/usr/local/bin/cwebp"].first(where: { FileManager.default.isExecutableFile(atPath: $0) }) else {
82
+ failure = "\(format.label) needs cwebp (brew install webp): the clipboard has the PNG"
83
+ return
84
+ }
85
+ let out = base.appendingPathExtension("webp")
86
+ let r = Clip.runNow(bin, ["-quiet", "-mt"] + format.cwebp + [at.path, "-o", out.path])
87
+ guard r.code == 0, let d = try? Data(contentsOf: out) else {
88
+ failure = "cwebp: \(r.err.isEmpty ? "exit \(r.code)" : r.err); the clipboard has the PNG"
89
+ return
90
+ }
91
+ webp = d
92
+ file = out
93
+ }
94
+
95
+ /** waits for the data, then runs `done` on the main thread with what it says */
96
+ func whenReady(_ done: @escaping @MainActor (String, String?) -> Void) {
97
+ ready.notify(queue: .main) {
98
+ MainActor.assumeIsolated {
99
+ let size = ByteCountFormatter.string(fromByteCount: Int64(self.webp?.count ?? self.png.count), countStyle: .file)
100
+ done("on the clipboard as \(self.webp != nil ? self.format.label : "PNG") (\(size))", self.failure)
101
+ }
102
+ }
103
+ }
104
+
105
+ func pasteboard(_ pasteboard: NSPasteboard?, item: NSPasteboardItem, provideDataForType type: NSPasteboard.PasteboardType) {
106
+ // a paste that comes before the data waits for it: never the clipboard's older content
107
+ ready.wait()
108
+ if type == .fileURL, let file { item.setString(file.absoluteString, forType: .fileURL) }
109
+ else if type == .png { item.setData(png, forType: .png) }
110
+ else if type == Clip.WEBP_TYPE, let webp { item.setData(webp, forType: type) }
111
+ }
112
+
113
+ func pasteboardFinishedWithDataProvider(_ pasteboard: NSPasteboard) {
114
+ DispatchQueue.main.async { MainActor.assumeIsolated { ClipJob.live.removeAll { $0 === self } } }
115
+ }
116
+ }
117
+
31
118
  enum Clip {
32
119
  static let KEEP = 20
33
120
  static let WEBP_TYPE = NSPasteboard.PasteboardType("org.webmproject.webp")
@@ -38,41 +125,15 @@ enum Clip {
38
125
  return d
39
126
  }
40
127
 
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
- }
128
+ /** the job's item on the clipboard now, every type promised: the file, the PNG and, for a WebP format, the WebP */
129
+ @MainActor static func put(_ job: ClipJob) throws {
67
130
  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)
131
+ let types: [NSPasteboard.PasteboardType] = job.format == .png ? [.fileURL, .png] : [.fileURL, WEBP_TYPE, .png]
132
+ guard it.setDataProvider(job, forTypes: types) else { throw Err("the clipboard took no promise") }
71
133
  let pb = NSPasteboard.general
72
134
  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))"
135
+ if !pb.writeObjects([it]) { throw Err("the clipboard refused the still") }
136
+ ClipJob.live.append(job)
76
137
  }
77
138
 
78
139
  /** the newest KEEP stills and their WebP stay: a paste of an older clipboard still finds its file */
@@ -85,23 +146,17 @@ enum Clip {
85
146
  }
86
147
  }
87
148
 
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
- }
149
+ /** a tool run to its end on the calling thread: its exit code and what it said */
150
+ static func runNow(_ bin: String, _ args: [String]) -> (code: Int32, err: String) {
151
+ let p = Process()
152
+ p.executableURL = URL(fileURLWithPath: bin)
153
+ p.arguments = args
154
+ let e = Pipe()
155
+ p.standardError = e
156
+ p.standardOutput = FileHandle.nullDevice
157
+ do { try p.run() } catch { return (127, error.localizedDescription) }
158
+ let err = e.fileHandleForReading.readDataToEndOfFile()
159
+ p.waitUntilExit()
160
+ return (p.terminationStatus, String(decoding: err, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines))
106
161
  }
107
162
  }
@@ -258,7 +258,7 @@ final class RecentTray: NSObject {
258
258
  f = ["out.png", "raw.png"].map { "\(it.dir)/\($0)" }.first { FileManager.default.fileExists(atPath: $0) }
259
259
  }
260
260
  guard let f else { done(s, ok: false); return }
261
- let ok = (try? await Clip.put(try Clip.stage(URL(fileURLWithPath: f)), format)) != nil
261
+ let ok = (try? Clip.put(ClipJob(pngFile: URL(fileURLWithPath: f), format: format))) != nil
262
262
  done(s, ok: ok)
263
263
  }
264
264
  }
@@ -696,13 +696,14 @@ final class Recorder: NSObject, NSApplicationDelegate, SCStreamDelegate, SCRecor
696
696
 
697
697
  /** a screenshot written, on the clipboard when its preset copies it, and handed to sk */
698
698
  func keep(_ img: CGImage, _ a: Ask) async throws {
699
+ // the clipboard first, before any encode: a ⌘V right after the shot finds this still, never the one before
700
+ let clips = a.preset.after?.contains("copy-file") == true
701
+ if clips { clip(img) }
702
+ NSSound(named: "Grab")?.play()
699
703
  let url = tmpFile("png")
700
704
  guard let dest = CGImageDestinationCreateWithURL(url as CFURL, "public.png" as CFString, 1, nil) else { throw Err("could not write \(url.path)") }
701
705
  CGImageDestinationAddImage(dest, img, nil)
702
706
  guard CGImageDestinationFinalize(dest) else { throw Err("could not write \(url.path)") }
703
- NSSound(named: "Grab")?.play()
704
- let clips = a.preset.after?.contains("copy-file") == true
705
- if clips { clip(url) }
706
707
  await file(url, a, clipped: clips)
707
708
  }
708
709
 
@@ -756,16 +757,13 @@ final class Recorder: NSObject, NSApplicationDelegate, SCStreamDelegate, SCRecor
756
757
  try await keep(try crop(f, c.frame), a)
757
758
  }
758
759
 
759
- /** a still on the clipboard now, in the menu's format, while sk files the take; WebP failing falls back to PNG, said */
760
- func clip(_ png: URL) {
761
- let format = ClipFormat.current
762
- let staged: URL
763
- do { staged = try Clip.stage(png) } catch { fail("the clipboard: \(error.localizedDescription)"); return }
764
- Task { @MainActor in
765
- do { say("ok: \(try await Clip.put(staged, format))") } catch {
766
- let png = try? await Clip.put(staged, .png)
767
- fail(png.map { "\(error.localizedDescription); \($0) instead" } ?? "the clipboard: \(error.localizedDescription)")
768
- }
760
+ /** a still on the clipboard now, its data promised in the menu's format and made behind it; a WebP that fails
761
+ * leaves the PNG, said */
762
+ func clip(_ img: CGImage) {
763
+ let job = ClipJob(image: img, format: ClipFormat.current)
764
+ do { try Clip.put(job) } catch { fail("the clipboard: \(error.localizedDescription)"); return }
765
+ job.whenReady { [weak self] said, failure in
766
+ if let failure { self?.fail(failure) } else { say("ok: \(said)") }
769
767
  }
770
768
  }
771
769
 
@@ -842,12 +840,17 @@ if CommandLine.arguments.contains("--self-test") {
842
840
  }
843
841
 
844
842
  if let i = CommandLine.arguments.firstIndex(of: "--clip-test"), CommandLine.arguments.count > i + 2 {
845
- // the clipboard's smoke: `--clip-test <png> <png|webp-lossless|webp-hq>` puts a still on it as a capture does
843
+ // the clipboard's smoke: `--clip-test <png> <png|webp-lossless|webp-hq>` puts a still on it as a capture does,
844
+ // then stays 5 s to answer the promise (another process reads it meanwhile)
846
845
  let png = URL(fileURLWithPath: CommandLine.arguments[i + 1])
847
846
  let format = ClipFormat(rawValue: CommandLine.arguments[i + 2]) ?? .png
848
- Task { @MainActor in
849
- do { print(try await Clip.put(try Clip.stage(png), format)); exit(0) } catch { print("FAIL: \(error.localizedDescription)"); exit(1) }
847
+ MainActor.assumeIsolated {
848
+ let job = ClipJob(pngFile: png, format: format)
849
+ do { try Clip.put(job) } catch { print("FAIL: \(error.localizedDescription)"); exit(1) }
850
+ print("ok: on the clipboard, promised")
851
+ job.whenReady { said, failure in print(failure.map { "FAIL: \($0)" } ?? "ok: \(said)") }
850
852
  }
853
+ DispatchQueue.main.asyncAfter(deadline: .now() + 5) { exit(0) }
851
854
  RunLoop.main.run()
852
855
  }
853
856