dsh-notify-tray 0.1.12 → 0.1.13

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.
@@ -1,283 +1,283 @@
1
- // macOS menu bar helper for dsh-notify-tray, run with `osascript -l JavaScript`.
2
- // No compiled binary: JXA's Objective-C bridge drives NSStatusItem directly, so
3
- // it works on any Mac (Apple Silicon or Intel) without Rosetta or Xcode.
4
- //
5
- // argv: <view.json path> <host pid>
6
- // The host rewrites view.json atomically; this script polls its mtime. Menu
7
- // clicks are written to stdout as one JSON line each: {"action":"<id>"}.
8
- //
9
- // The icon is the whale from lib/whale.js, shipped as bezier paths in
10
- // icon.json (next to view.json; one frame list per state, plus fps / loop)
11
- // and rasterized here into template images at 1x and 2x.
12
- // Template images take the menu bar's own colour (white on dark, black on
13
- // light), exactly like the system icons next to it, so no tinting happens:
14
- // the whale's state is told by its shape (spout / "!" / "×"), not its colour.
15
- ObjC.import('Cocoa')
16
- ObjC.import('stdlib')
17
- ObjC.import('signal')
18
-
19
- /** Icon size in points: the whale is wider than tall, so 22×16 sits like an 18 pt template icon. */
20
- var ICON_H = 17
21
- var ICON_W = 23
22
- /** Timer period: view.json is polled and animation frames advanced at this rate. */
23
- var TICK_SECONDS = 0.1
24
-
25
- function run(argv) {
26
- var viewPath = argv[0]
27
- var hostPid = Number(argv[1] || 0)
28
- var app = $.NSApplication.sharedApplication
29
- app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
30
-
31
- var item = $.NSStatusBar.systemStatusBar.statusItemWithLength(-1) // NSVariableStatusItemLength
32
- var stdout = $.NSFileHandle.fileHandleWithStandardOutput
33
- var fm = $.NSFileManager.defaultManager
34
- var lastStamp = ''
35
- var icon = null // icon.json: { box, bounds, frames: { state: [paths...] }, anim: { state: { fps, loop } } }
36
- var images = {} // "<state>:<frame>" -> NSImage
37
- var symbolCache = {}
38
- var current = { state: 'idle', frame: 0, frames: 1, fps: 1, loop: false, clock: 0 }
39
-
40
- function send(action) {
41
- var line = $(JSON.stringify({ action: action }) + '\n').dataUsingEncoding($.NSUTF8StringEncoding)
42
- stdout.writeData(line)
43
- }
44
-
45
- function warn(text) {
46
- $.NSFileHandle.fileHandleWithStandardError.writeData($(text + '\n').dataUsingEncoding($.NSUTF8StringEncoding))
47
- }
48
-
49
- function hostAlive() {
50
- if (!hostPid) return true
51
- // kill(pid, 0) succeeds while the host process exists.
52
- return $.kill(hostPid, 0) === 0
53
- }
54
-
55
- function readIcon() {
56
- var iconPath = viewPath.replace(/[^\/]+$/, 'icon.json')
57
- var text = $.NSString.stringWithContentsOfFileEncodingError(iconPath, $.NSUTF8StringEncoding, null)
58
- if (!text || text.isNil()) return null
59
- try { return JSON.parse(ObjC.unwrap(text)) } catch (e) { return null }
60
- }
61
-
62
- function readView() {
63
- var attrs = fm.attributesOfItemAtPathError(viewPath, null)
64
- if (!attrs || attrs.isNil()) return null
65
- var stamp = ObjC.unwrap(attrs.fileModificationDate.description) + ':' + ObjC.unwrap(attrs.fileSize)
66
- if (stamp === lastStamp) return null
67
- lastStamp = stamp
68
- var text = $.NSString.stringWithContentsOfFileEncodingError(viewPath, $.NSUTF8StringEncoding, null)
69
- if (!text || text.isNil()) return null
70
- try { return JSON.parse(ObjC.unwrap(text)) } catch (e) { return null }
71
- }
72
-
73
- // ---- whale rasterizer --------------------------------------------------------
74
-
75
- /** Build an NSBezierPath from lib/whale.js commands, fitted into w×h pixels and flipped to AppKit's y-up. */
76
- function bezier(paths, spec, w, h) {
77
- var path = $.NSBezierPath.bezierPath
78
- path.windingRule = $.NSNonZeroWindingRule
79
- var b = spec.bounds || { x: 0, y: 0, w: spec.box, h: spec.box }
80
- var s = Math.min(w / b.w, h / b.h)
81
- var ox = (w - b.w * s) / 2
82
- var oy = (h - b.h * s) / 2
83
- var P = function (x, y) { return $.NSMakePoint(ox + (x - b.x) * s, h - oy - (y - b.y) * s) }
84
- paths.forEach(function (sub) {
85
- sub.forEach(function (cmd) {
86
- if (cmd[0] === 'M') path.moveToPoint(P(cmd[1], cmd[2]))
87
- else if (cmd[0] === 'L') path.lineToPoint(P(cmd[1], cmd[2]))
88
- else if (cmd[0] === 'C') path.curveToPointControlPoint1ControlPoint2(P(cmd[5], cmd[6]), P(cmd[1], cmd[2]), P(cmd[3], cmd[4]))
89
- else if (cmd[0] === 'Z') path.closePath
90
- })
91
- })
92
- return path
93
- }
94
-
95
- /** One bitmap rep of the whale at `scale` (1 or 2), black on transparent. */
96
- function rep(paths, spec, scale) {
97
- var w = ICON_W * scale
98
- var h = ICON_H * scale
99
- var bitmap = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
100
- $(), w, h, 8, 4, true, false, $.NSCalibratedRGBColorSpace, 0, 0)
101
- $.NSGraphicsContext.saveGraphicsState
102
- $.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(bitmap))
103
- // Fresh bitmap memory is not guaranteed to be zeroed: clear it to transparent first.
104
- $.NSColor.clearColor.set
105
- $.NSRectFill($.NSMakeRect(0, 0, w, h))
106
- $.NSColor.blackColor.set
107
- bezier(paths, spec, w, h).fill
108
- $.NSGraphicsContext.restoreGraphicsState
109
- // Set the point size only after drawing (before, the context would scale
110
- // pixel coordinates by it): 36 px at 18 pt is the retina 2x rep.
111
- bitmap.size = $.NSMakeSize(ICON_W, ICON_H)
112
- return bitmap
113
- }
114
-
115
- function whaleImage(state, frame) {
116
- var key = state + ':' + frame
117
- if (images[key]) return images[key]
118
- var frames = (icon && icon.frames[state]) || (icon && icon.frames.idle)
119
- if (!frames) return null
120
- var paths = frames[frame % frames.length]
121
- var image = $.NSImage.alloc.initWithSize($.NSMakeSize(ICON_W, ICON_H))
122
- image.addRepresentation(rep(paths, icon, 1))
123
- image.addRepresentation(rep(paths, icon, 2))
124
- image.template = true // the menu bar colours it like every other icon
125
- images[key] = image
126
- return image
127
- }
128
-
129
- function symbolImage(name) {
130
- if (!name) return null
131
- if (symbolCache[name] !== undefined) return symbolCache[name]
132
- var image = null
133
- if ($.NSImage.imageWithSystemSymbolNameAccessibilityDescription) {
134
- var candidate = $.NSImage.imageWithSystemSymbolNameAccessibilityDescription(name, name)
135
- if (candidate && !candidate.isNil()) image = candidate
136
- }
137
- symbolCache[name] = image
138
- return image
139
- }
140
-
141
- function showFrame() {
142
- var image = whaleImage(current.state, current.frame)
143
- if (image) item.button.image = image
144
- }
145
-
146
- // ---- view -> status item -----------------------------------------------------------
147
-
148
- /** Row height / text inset of a native menu item, so info rows line up with the clickable ones. */
149
- var INFO_ROW_H = 22
150
- var INFO_INSET = 14
151
- /** Leading SF Symbol of an info row: size and gap to the text. */
152
- var INFO_ICON = 16
153
- var INFO_GAP = 6
154
-
155
- /** The user's accent colour (System Settings › Appearance), dark-mode aware; blue before 10.14. */
156
- function accentColor() {
157
- var accent = $.NSColor.controlAccentColor
158
- return accent && !accent.isNil() ? accent : $.NSColor.systemBlueColor
159
- }
160
-
161
- /**
162
- * Read-only rows (balance, usage, …) are disabled so they never highlight or
163
- * fire, but AppKit draws a disabled title at a very low alpha, which made
164
- * them hard to read. A disabled item with a custom view is still inert, yet
165
- * its view is drawn as-is: the text is a plain NSTextField in labelColor
166
- * (solid black in light mode, white in dark mode), so it reads as clearly as
167
- * the actionable items. What tells the two apart is the row's own SF Symbol
168
- * drawn in front of the text in the accent colour: clickable items carry no
169
- * icon, info rows always do.
170
- */
171
- function infoView(label, iconName) {
172
- var x = INFO_INSET
173
- var view = $.NSView.alloc.initWithFrame($.NSMakeRect(0, 0, 200, INFO_ROW_H))
174
- view.autoresizingMask = $.NSViewWidthSizable // the menu stretches it to its own width
175
- var image = symbolImage(iconName)
176
- if (image) {
177
- var iconView = $.NSImageView.alloc.initWithFrame($.NSMakeRect(x, (INFO_ROW_H - INFO_ICON) / 2, INFO_ICON, INFO_ICON))
178
- iconView.image = image
179
- iconView.imageScaling = $.NSImageScaleProportionallyUpOrDown
180
- iconView.contentTintColor = accentColor()
181
- view.addSubview(iconView)
182
- x += INFO_ICON + INFO_GAP
183
- }
184
- var field = $.NSTextField.alloc.initWithFrame($.NSMakeRect(x, 0, 200, INFO_ROW_H))
185
- field.bezeled = false
186
- field.drawsBackground = false
187
- field.editable = false
188
- field.selectable = false
189
- field.font = $.NSFont.menuFontOfSize(0)
190
- field.textColor = $.NSColor.labelColor
191
- field.stringValue = $(label)
192
- field.sizeToFit
193
- var size = field.frame.size
194
- field.frame = $.NSMakeRect(x, (INFO_ROW_H - size.height) / 2, size.width, size.height)
195
- field.autoresizingMask = $.NSViewWidthSizable
196
- view.addSubview(field)
197
- view.frame = $.NSMakeRect(0, 0, x + size.width + INFO_INSET, INFO_ROW_H)
198
- return view
199
- }
200
-
201
- function buildMenu(rows) {
202
- var menu = $.NSMenu.alloc.init
203
- menu.autoenablesItems = false
204
- rows.forEach(function (row) {
205
- if (row.separator) { menu.addItem($.NSMenuItem.separatorItem); return }
206
- var mi = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent($(row.label), 'menuClicked:', '')
207
- mi.target = target
208
- mi.representedObject = $(row.id || '')
209
- mi.enabled = row.enabled !== false
210
- var image = symbolImage(row.icon)
211
- if (image) mi.image = image
212
- var hasChildren = Boolean(row.children && row.children.length)
213
- if (!mi.enabled && !hasChildren) mi.view = infoView(row.label, row.icon)
214
- if (hasChildren) {
215
- mi.action = $()
216
- mi.enabled = true
217
- mi.submenu = buildMenu(row.children)
218
- }
219
- menu.addItem(mi)
220
- })
221
- return menu
222
- }
223
-
224
- function apply(view) {
225
- if (view.quit) { app.terminate(null); return } // the host is taking the icon down
226
- if (view.icon) { icon = view.icon; images = {} } // legacy: geometry inline
227
- if (!icon) icon = readIcon()
228
- var frames = (icon && icon.frames[view.state]) ? icon.frames[view.state].length : 1
229
- var anim = (icon && icon.anim && icon.anim[view.state]) || { fps: 1, loop: false }
230
- // Same state again (e.g. the menu changed while running): keep the animation where it is.
231
- if (view.state !== current.state) current = { state: view.state, frame: 0, frames: frames, fps: anim.fps, loop: anim.loop, clock: 0 }
232
- var button = item.button
233
- button.imagePosition = $.NSImageLeft
234
- showFrame()
235
- button.title = $(view.title ? ' ' + view.title : '')
236
- button.toolTip = $(view.tooltip)
237
- item.menu = buildMenu(view.menu)
238
- }
239
-
240
- ObjC.registerSubclass({
241
- name: 'DshTrayTarget',
242
- methods: {
243
- 'menuClicked:': {
244
- types: ['void', ['id']],
245
- implementation: function (sender) {
246
- var id = ObjC.unwrap(sender.representedObject)
247
- if (!id) return
248
- if (id === 'hide-tray') { send(id); app.terminate(null); return }
249
- send(id)
250
- },
251
- },
252
- 'tick:': {
253
- types: ['void', ['id']],
254
- implementation: function () {
255
- try {
256
- if (!hostAlive()) { app.terminate(null); return }
257
- var view = readView()
258
- if (view) apply(view)
259
- if (current.frames > 1 && (current.loop || current.frame < current.frames - 1)) {
260
- current.clock += TICK_SECONDS
261
- var step = 1 / Math.max(1, current.fps)
262
- if (current.clock >= step) {
263
- current.clock -= step
264
- current.frame = current.loop ? (current.frame + 1) % current.frames : Math.min(current.frames - 1, current.frame + 1)
265
- showFrame()
266
- }
267
- }
268
- } catch (e) {
269
- // ObjC callbacks swallow exceptions silently; surface them on stderr.
270
- warn('tray tick failed: ' + e)
271
- }
272
- },
273
- },
274
- },
275
- })
276
- var target = $.DshTrayTarget.alloc.init
277
-
278
- var first = readView()
279
- if (first) apply(first)
280
- else item.button.title = $(' …')
281
- $.NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(TICK_SECONDS, target, 'tick:', null, true)
282
- app.run
283
- }
1
+ // macOS menu bar helper for dsh-notify-tray, run with `osascript -l JavaScript`.
2
+ // No compiled binary: JXA's Objective-C bridge drives NSStatusItem directly, so
3
+ // it works on any Mac (Apple Silicon or Intel) without Rosetta or Xcode.
4
+ //
5
+ // argv: <view.json path> <host pid>
6
+ // The host rewrites view.json atomically; this script polls its mtime. Menu
7
+ // clicks are written to stdout as one JSON line each: {"action":"<id>"}.
8
+ //
9
+ // The icon is the whale from lib/whale.js, shipped as bezier paths in
10
+ // icon.json (next to view.json; one frame list per state, plus fps / loop)
11
+ // and rasterized here into template images at 1x and 2x.
12
+ // Template images take the menu bar's own colour (white on dark, black on
13
+ // light), exactly like the system icons next to it, so no tinting happens:
14
+ // the whale's state is told by its shape (spout / "!" / "×"), not its colour.
15
+ ObjC.import('Cocoa')
16
+ ObjC.import('stdlib')
17
+ ObjC.import('signal')
18
+
19
+ /** Icon size in points: the whale is wider than tall, so 22×16 sits like an 18 pt template icon. */
20
+ var ICON_H = 17
21
+ var ICON_W = 23
22
+ /** Timer period: view.json is polled and animation frames advanced at this rate. */
23
+ var TICK_SECONDS = 0.1
24
+
25
+ function run(argv) {
26
+ var viewPath = argv[0]
27
+ var hostPid = Number(argv[1] || 0)
28
+ var app = $.NSApplication.sharedApplication
29
+ app.setActivationPolicy($.NSApplicationActivationPolicyAccessory)
30
+
31
+ var item = $.NSStatusBar.systemStatusBar.statusItemWithLength(-1) // NSVariableStatusItemLength
32
+ var stdout = $.NSFileHandle.fileHandleWithStandardOutput
33
+ var fm = $.NSFileManager.defaultManager
34
+ var lastStamp = ''
35
+ var icon = null // icon.json: { box, bounds, frames: { state: [paths...] }, anim: { state: { fps, loop } } }
36
+ var images = {} // "<state>:<frame>" -> NSImage
37
+ var symbolCache = {}
38
+ var current = { state: 'idle', frame: 0, frames: 1, fps: 1, loop: false, clock: 0 }
39
+
40
+ function send(action) {
41
+ var line = $(JSON.stringify({ action: action }) + '\n').dataUsingEncoding($.NSUTF8StringEncoding)
42
+ stdout.writeData(line)
43
+ }
44
+
45
+ function warn(text) {
46
+ $.NSFileHandle.fileHandleWithStandardError.writeData($(text + '\n').dataUsingEncoding($.NSUTF8StringEncoding))
47
+ }
48
+
49
+ function hostAlive() {
50
+ if (!hostPid) return true
51
+ // kill(pid, 0) succeeds while the host process exists.
52
+ return $.kill(hostPid, 0) === 0
53
+ }
54
+
55
+ function readIcon() {
56
+ var iconPath = viewPath.replace(/[^\/]+$/, 'icon.json')
57
+ var text = $.NSString.stringWithContentsOfFileEncodingError(iconPath, $.NSUTF8StringEncoding, null)
58
+ if (!text || text.isNil()) return null
59
+ try { return JSON.parse(ObjC.unwrap(text)) } catch (e) { return null }
60
+ }
61
+
62
+ function readView() {
63
+ var attrs = fm.attributesOfItemAtPathError(viewPath, null)
64
+ if (!attrs || attrs.isNil()) return null
65
+ var stamp = ObjC.unwrap(attrs.fileModificationDate.description) + ':' + ObjC.unwrap(attrs.fileSize)
66
+ if (stamp === lastStamp) return null
67
+ lastStamp = stamp
68
+ var text = $.NSString.stringWithContentsOfFileEncodingError(viewPath, $.NSUTF8StringEncoding, null)
69
+ if (!text || text.isNil()) return null
70
+ try { return JSON.parse(ObjC.unwrap(text)) } catch (e) { return null }
71
+ }
72
+
73
+ // ---- whale rasterizer --------------------------------------------------------
74
+
75
+ /** Build an NSBezierPath from lib/whale.js commands, fitted into w×h pixels and flipped to AppKit's y-up. */
76
+ function bezier(paths, spec, w, h) {
77
+ var path = $.NSBezierPath.bezierPath
78
+ path.windingRule = $.NSNonZeroWindingRule
79
+ var b = spec.bounds || { x: 0, y: 0, w: spec.box, h: spec.box }
80
+ var s = Math.min(w / b.w, h / b.h)
81
+ var ox = (w - b.w * s) / 2
82
+ var oy = (h - b.h * s) / 2
83
+ var P = function (x, y) { return $.NSMakePoint(ox + (x - b.x) * s, h - oy - (y - b.y) * s) }
84
+ paths.forEach(function (sub) {
85
+ sub.forEach(function (cmd) {
86
+ if (cmd[0] === 'M') path.moveToPoint(P(cmd[1], cmd[2]))
87
+ else if (cmd[0] === 'L') path.lineToPoint(P(cmd[1], cmd[2]))
88
+ else if (cmd[0] === 'C') path.curveToPointControlPoint1ControlPoint2(P(cmd[5], cmd[6]), P(cmd[1], cmd[2]), P(cmd[3], cmd[4]))
89
+ else if (cmd[0] === 'Z') path.closePath
90
+ })
91
+ })
92
+ return path
93
+ }
94
+
95
+ /** One bitmap rep of the whale at `scale` (1 or 2), black on transparent. */
96
+ function rep(paths, spec, scale) {
97
+ var w = ICON_W * scale
98
+ var h = ICON_H * scale
99
+ var bitmap = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel(
100
+ $(), w, h, 8, 4, true, false, $.NSCalibratedRGBColorSpace, 0, 0)
101
+ $.NSGraphicsContext.saveGraphicsState
102
+ $.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(bitmap))
103
+ // Fresh bitmap memory is not guaranteed to be zeroed: clear it to transparent first.
104
+ $.NSColor.clearColor.set
105
+ $.NSRectFill($.NSMakeRect(0, 0, w, h))
106
+ $.NSColor.blackColor.set
107
+ bezier(paths, spec, w, h).fill
108
+ $.NSGraphicsContext.restoreGraphicsState
109
+ // Set the point size only after drawing (before, the context would scale
110
+ // pixel coordinates by it): 36 px at 18 pt is the retina 2x rep.
111
+ bitmap.size = $.NSMakeSize(ICON_W, ICON_H)
112
+ return bitmap
113
+ }
114
+
115
+ function whaleImage(state, frame) {
116
+ var key = state + ':' + frame
117
+ if (images[key]) return images[key]
118
+ var frames = (icon && icon.frames[state]) || (icon && icon.frames.idle)
119
+ if (!frames) return null
120
+ var paths = frames[frame % frames.length]
121
+ var image = $.NSImage.alloc.initWithSize($.NSMakeSize(ICON_W, ICON_H))
122
+ image.addRepresentation(rep(paths, icon, 1))
123
+ image.addRepresentation(rep(paths, icon, 2))
124
+ image.template = true // the menu bar colours it like every other icon
125
+ images[key] = image
126
+ return image
127
+ }
128
+
129
+ function symbolImage(name) {
130
+ if (!name) return null
131
+ if (symbolCache[name] !== undefined) return symbolCache[name]
132
+ var image = null
133
+ if ($.NSImage.imageWithSystemSymbolNameAccessibilityDescription) {
134
+ var candidate = $.NSImage.imageWithSystemSymbolNameAccessibilityDescription(name, name)
135
+ if (candidate && !candidate.isNil()) image = candidate
136
+ }
137
+ symbolCache[name] = image
138
+ return image
139
+ }
140
+
141
+ function showFrame() {
142
+ var image = whaleImage(current.state, current.frame)
143
+ if (image) item.button.image = image
144
+ }
145
+
146
+ // ---- view -> status item -----------------------------------------------------------
147
+
148
+ /** Row height / text inset of a native menu item, so info rows line up with the clickable ones. */
149
+ var INFO_ROW_H = 22
150
+ var INFO_INSET = 14
151
+ /** Leading SF Symbol of an info row: size and gap to the text. */
152
+ var INFO_ICON = 16
153
+ var INFO_GAP = 6
154
+
155
+ /** The user's accent colour (System Settings › Appearance), dark-mode aware; blue before 10.14. */
156
+ function accentColor() {
157
+ var accent = $.NSColor.controlAccentColor
158
+ return accent && !accent.isNil() ? accent : $.NSColor.systemBlueColor
159
+ }
160
+
161
+ /**
162
+ * Read-only rows (balance, usage, …) are disabled so they never highlight or
163
+ * fire, but AppKit draws a disabled title at a very low alpha, which made
164
+ * them hard to read. A disabled item with a custom view is still inert, yet
165
+ * its view is drawn as-is: the text is a plain NSTextField in labelColor
166
+ * (solid black in light mode, white in dark mode), so it reads as clearly as
167
+ * the actionable items. What tells the two apart is the row's own SF Symbol
168
+ * drawn in front of the text in the accent colour: clickable items carry no
169
+ * icon, info rows always do.
170
+ */
171
+ function infoView(label, iconName) {
172
+ var x = INFO_INSET
173
+ var view = $.NSView.alloc.initWithFrame($.NSMakeRect(0, 0, 200, INFO_ROW_H))
174
+ view.autoresizingMask = $.NSViewWidthSizable // the menu stretches it to its own width
175
+ var image = symbolImage(iconName)
176
+ if (image) {
177
+ var iconView = $.NSImageView.alloc.initWithFrame($.NSMakeRect(x, (INFO_ROW_H - INFO_ICON) / 2, INFO_ICON, INFO_ICON))
178
+ iconView.image = image
179
+ iconView.imageScaling = $.NSImageScaleProportionallyUpOrDown
180
+ iconView.contentTintColor = accentColor()
181
+ view.addSubview(iconView)
182
+ x += INFO_ICON + INFO_GAP
183
+ }
184
+ var field = $.NSTextField.alloc.initWithFrame($.NSMakeRect(x, 0, 200, INFO_ROW_H))
185
+ field.bezeled = false
186
+ field.drawsBackground = false
187
+ field.editable = false
188
+ field.selectable = false
189
+ field.font = $.NSFont.menuFontOfSize(0)
190
+ field.textColor = $.NSColor.labelColor
191
+ field.stringValue = $(label)
192
+ field.sizeToFit
193
+ var size = field.frame.size
194
+ field.frame = $.NSMakeRect(x, (INFO_ROW_H - size.height) / 2, size.width, size.height)
195
+ field.autoresizingMask = $.NSViewWidthSizable
196
+ view.addSubview(field)
197
+ view.frame = $.NSMakeRect(0, 0, x + size.width + INFO_INSET, INFO_ROW_H)
198
+ return view
199
+ }
200
+
201
+ function buildMenu(rows) {
202
+ var menu = $.NSMenu.alloc.init
203
+ menu.autoenablesItems = false
204
+ rows.forEach(function (row) {
205
+ if (row.separator) { menu.addItem($.NSMenuItem.separatorItem); return }
206
+ var mi = $.NSMenuItem.alloc.initWithTitleActionKeyEquivalent($(row.label), 'menuClicked:', '')
207
+ mi.target = target
208
+ mi.representedObject = $(row.id || '')
209
+ mi.enabled = row.enabled !== false
210
+ var image = symbolImage(row.icon)
211
+ if (image) mi.image = image
212
+ var hasChildren = Boolean(row.children && row.children.length)
213
+ if (!mi.enabled && !hasChildren) mi.view = infoView(row.label, row.icon)
214
+ if (hasChildren) {
215
+ mi.action = $()
216
+ mi.enabled = true
217
+ mi.submenu = buildMenu(row.children)
218
+ }
219
+ menu.addItem(mi)
220
+ })
221
+ return menu
222
+ }
223
+
224
+ function apply(view) {
225
+ if (view.quit) { app.terminate(null); return } // the host is taking the icon down
226
+ if (view.icon) { icon = view.icon; images = {} } // legacy: geometry inline
227
+ if (!icon) icon = readIcon()
228
+ var frames = (icon && icon.frames[view.state]) ? icon.frames[view.state].length : 1
229
+ var anim = (icon && icon.anim && icon.anim[view.state]) || { fps: 1, loop: false }
230
+ // Same state again (e.g. the menu changed while running): keep the animation where it is.
231
+ if (view.state !== current.state) current = { state: view.state, frame: 0, frames: frames, fps: anim.fps, loop: anim.loop, clock: 0 }
232
+ var button = item.button
233
+ button.imagePosition = $.NSImageLeft
234
+ showFrame()
235
+ button.title = $(view.title ? ' ' + view.title : '')
236
+ button.toolTip = $(view.tooltip)
237
+ item.menu = buildMenu(view.menu)
238
+ }
239
+
240
+ ObjC.registerSubclass({
241
+ name: 'DshTrayTarget',
242
+ methods: {
243
+ 'menuClicked:': {
244
+ types: ['void', ['id']],
245
+ implementation: function (sender) {
246
+ var id = ObjC.unwrap(sender.representedObject)
247
+ if (!id) return
248
+ if (id === 'hide-tray') { send(id); app.terminate(null); return }
249
+ send(id)
250
+ },
251
+ },
252
+ 'tick:': {
253
+ types: ['void', ['id']],
254
+ implementation: function () {
255
+ try {
256
+ if (!hostAlive()) { app.terminate(null); return }
257
+ var view = readView()
258
+ if (view) apply(view)
259
+ if (current.frames > 1 && (current.loop || current.frame < current.frames - 1)) {
260
+ current.clock += TICK_SECONDS
261
+ var step = 1 / Math.max(1, current.fps)
262
+ if (current.clock >= step) {
263
+ current.clock -= step
264
+ current.frame = current.loop ? (current.frame + 1) % current.frames : Math.min(current.frames - 1, current.frame + 1)
265
+ showFrame()
266
+ }
267
+ }
268
+ } catch (e) {
269
+ // ObjC callbacks swallow exceptions silently; surface them on stderr.
270
+ warn('tray tick failed: ' + e)
271
+ }
272
+ },
273
+ },
274
+ },
275
+ })
276
+ var target = $.DshTrayTarget.alloc.init
277
+
278
+ var first = readView()
279
+ if (first) apply(first)
280
+ else item.button.title = $(' …')
281
+ $.NSTimer.scheduledTimerWithTimeIntervalTargetSelectorUserInfoRepeats(TICK_SECONDS, target, 'tick:', null, true)
282
+ app.run
283
+ }
package/cordis.patch.yml CHANGED
@@ -1,6 +1,6 @@
1
- # dsh-notify-tray bundle patch: mount the host half (state tracking, ledger,
2
- # tray helper, system-notification fallback). The browser half is discovered
3
- # through package.json `dsh.client` + exports["./client"].
4
- - insert:
5
- - id: notify-tray
6
- name: 'dsh-notify-tray'
1
+ # dsh-notify-tray bundle patch: mount the host half (state tracking, ledger,
2
+ # tray helper, system-notification fallback). The browser half is discovered
3
+ # through package.json `dsh.client` + exports["./client"].
4
+ - insert:
5
+ - id: notify-tray
6
+ name: 'dsh-notify-tray'
@@ -0,0 +1,33 @@
1
+ // Windows launches this program for this plugin's notification protocol.
2
+ // The argument can only name a one-time ticket already issued by the plugin.
3
+ using System;
4
+ using System.Diagnostics;
5
+ using System.IO;
6
+ using System.Text.RegularExpressions;
7
+
8
+ internal static class ToastActivator {
9
+ private static readonly Regex Ticket = new Regex(
10
+ @"\Adsh-notify-tray://click/([0-9a-f]{32})/([0-9a-f]{32})\z",
11
+ RegexOptions.CultureInvariant);
12
+
13
+ [STAThread]
14
+ public static void Main(string[] args) {
15
+ if (args.Length != 1) return;
16
+ Match match = Ticket.Match(args[0]);
17
+ if (!match.Success) return;
18
+ string ticket = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
19
+ match.Groups[1].Value, match.Groups[2].Value);
20
+ try {
21
+ string[] record = File.ReadAllLines(ticket + ".pending");
22
+ if (record.Length != 2) return;
23
+ Uri target;
24
+ if (record[0] != "dsh://open" && (!Uri.TryCreate(record[0], UriKind.Absolute, out target) ||
25
+ (target.Scheme != "https" && target.Scheme != "http"))) return;
26
+ // Move first: duplicate activations lose the race, and a cold-started
27
+ // UI can read the click as soon as its first poll arrives.
28
+ File.Move(ticket + ".pending", ticket + ".clicked");
29
+ Process.Start(new ProcessStartInfo(record[0]) { UseShellExecute = true });
30
+ } catch (IOException) { /* expired or already consumed */ }
31
+ catch (System.ComponentModel.Win32Exception) { /* DSH can consume the click on its next poll */ }
32
+ }
33
+ }