-
Notifications
You must be signed in to change notification settings - Fork 2
/
AppDelegate.swift
435 lines (368 loc) · 13.9 KB
/
AppDelegate.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
//
// AppDelegate.swift
// shbar2
//
// Created by Rich Infante on 2/14/19.
// Copyright © 2019 Rich Infante. All rights reserved.
//
import Cocoa
import Foundation
/// Wrapper for process
class Script : Codable {
/// Absolute path to binary
var bin: String
/// Arguments to binary
var args: [String]
/// Environment variables
var env: [String:String]
/// Intialize a new script
init (bin: String, args:[String], env: [String:String]) {
self.bin = bin
self.args = args
self.env = env
}
/// Execute script in background, collecting output
func execute(launched: ((Process)->())? = nil, completed: ((Int32, String)->())?) {
DispatchQueue.global(qos: .background).async { [weak self] in
guard let `self` = self else { return }
let pipe = Pipe()
let task = Process()
task.currentDirectoryPath = "/"
task.environment = self.env
task.launchPath = self.bin
task.arguments = self.args
task.standardOutput = pipe
task.launch()
DispatchQueue.main.sync {
launched?(task)
}
task.waitUntilExit()
let status = task.terminationStatus
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
print("Child process exited with code \(status)")
DispatchQueue.main.sync {
completed?(status, output)
}
}
}
}
enum ItemConfigMode : String, Codable {
case RefreshingItem
case JobStatus
case ApplicationQuit
}
enum JobStatus : String {
case Stopped
case Exited
case Running
}
class ItemConfig : Codable {
var mode: ItemConfigMode? = .RefreshingItem
var title: String?
var titleScript: Script?
var titleRefreshInterval: TimeInterval?
var actionScript: Script?
var shortcutKey: String?
var jobScript: Script?
var reloadJob: Bool?
var autostartJob: Bool?
var menuItem: NSMenuItem?
var refreshTimer: Timer?
var jobStatusItem: NSMenuItem?
var jobExitStatus: Int32?
var currentJob: Process?
var isPaused : Bool = false
var startMenuItem: NSMenuItem?
var stopMenuItem: NSMenuItem?
var restartMenuItem: NSMenuItem?
var suspendMenuItem: NSMenuItem?
var resumeMenuItem: NSMenuItem?
private enum CodingKeys: String, CodingKey {
case mode
case title
case titleScript
case titleRefreshInterval
case actionScript
case shortcutKey
case jobScript
case reloadJob
case autostartJob
}
init(
mode: ItemConfigMode? = .RefreshingItem,
title: String? = nil,
titleScript: Script? = nil,
titleRefreshInterval: TimeInterval? = nil,
actionScript: Script? = nil,
jobScript: Script? = nil,
reloadJob: Bool? = false,
autostartJob: Bool? = false,
shortcutKey: String? = nil
) {
self.mode = mode
self.title = title
self.titleScript = titleScript
self.titleRefreshInterval = titleRefreshInterval
self.actionScript = actionScript
self.shortcutKey = shortcutKey
self.jobScript = jobScript
self.reloadJob = reloadJob
self.autostartJob = autostartJob
}
@objc func suspendJob() {
if let process = self.currentJob {
process.suspend()
self.isPaused = true
if let title = self.title {
self.updateTitle(title: title)
}
}
}
@objc func resumeJob() {
if let process = self.currentJob {
process.resume()
self.isPaused = false
if let title = self.title {
self.updateTitle(title: title)
}
}
}
@objc func startJob() {
self.currentJob?.terminate()
if let script = self.jobScript {
script.execute (launched: {
process in
self.currentJob = process
if let title = self.title {
self.updateTitle(title: title)
}
}, completed: {
status, result in
if let title = self.title {
self.updateTitle(title: title)
}
if let reloadJob = self.reloadJob, reloadJob {
self.startJob()
}
})
}
}
@objc func stopJob() {
self.reloadJob = false
self.currentJob?.terminate()
}
func updateTitle(title: String) {
if self.mode == .JobStatus {
var color = NSColor.gray
// Update job's status label
if let currentJob = self.currentJob {
if self.isPaused {
color = NSColor.blue
} else if currentJob.isRunning {
color = NSColor.green
} else if currentJob.terminationStatus != 0 {
color = NSColor.red
}
if self.isPaused {
// self.startMenuItem?.isHidden = true
// self.stopMenuItem?.isHidden = false
// self.restartMenuItem?.isHidden = false
// self.suspendMenuItem?.isHidden = true
// self.resumeMenuItem?.isHidden = false
self.jobStatusItem?.title = "suspended - pid:\(currentJob.processIdentifier)"
} else if currentJob.isRunning {
// self.startMenuItem?.isHidden = true
// self.stopMenuItem?.isHidden = false
// self.restartMenuItem?.isHidden = false
// self.suspendMenuItem?.isHidden = false
// self.resumeMenuItem?.isHidden = true
self.jobStatusItem?.title = "running - pid:\(currentJob.processIdentifier)"
} else {
// self.startMenuItem?.isHidden = false
// self.stopMenuItem?.isHidden = true
// self.restartMenuItem?.isHidden = true
// self.suspendMenuItem?.isHidden = true
// self.resumeMenuItem?.isHidden = false
self.jobStatusItem?.title = "exited: \(currentJob.terminationStatus)"
}
}
let mutableAttributedString = NSMutableAttributedString(string: "●", attributes: [
NSAttributedString.Key.foregroundColor: color
])
mutableAttributedString.append(NSAttributedString(string: " " + title))
menuItem?.attributedTitle = mutableAttributedString
} else {
menuItem?.title = title
}
}
func createMenuItem(_ appDeletate: AppDelegate) -> NSMenuItem {
let menuItem = NSMenuItem()
if self.mode == .JobStatus {
let subMenu = NSMenu()
let statusItem = NSMenuItem(title: "stopped", action: nil, keyEquivalent: "")
self.jobStatusItem = statusItem
let startItem = NSMenuItem(title: "start", action: nil, keyEquivalent: "")
startItem.action = #selector(ItemConfig.startJob)
startItem.target = self
let stopItem = NSMenuItem(title: "stop", action: nil, keyEquivalent: "")
stopItem.action = #selector(ItemConfig.stopJob)
stopItem.target = self
let restartItem = NSMenuItem(title: "restart", action: nil, keyEquivalent: "")
restartItem.action = #selector(ItemConfig.startJob)
restartItem.target = self
let suspendItem = NSMenuItem(title: "suspend", action: nil, keyEquivalent: "")
suspendItem.action = #selector(ItemConfig.suspendJob)
suspendItem.target = self
let resumeItem = NSMenuItem(title: "resume", action: nil, keyEquivalent: "")
resumeItem.action = #selector(ItemConfig.resumeJob)
resumeItem.target = self
subMenu.addItem(statusItem)
subMenu.addItem(startItem)
subMenu.addItem(stopItem)
subMenu.addItem(restartItem)
subMenu.addItem(suspendItem)
subMenu.addItem(resumeItem)
self.startMenuItem = startItem
self.stopMenuItem = stopItem
self.restartMenuItem = restartItem
self.suspendMenuItem = suspendItem
self.resumeMenuItem = resumeItem
menuItem.submenu = subMenu
// Start the job if needed
if let autoStart = self.autostartJob, autoStart {
self.startJob()
}
} else if self.mode == .ApplicationQuit {
menuItem.target = appDeletate
menuItem.action = #selector(AppDelegate.terminateMenuBarApp(_:))
} else if self.mode == .RefreshingItem {
// Set up scripting
if self.actionScript != nil {
menuItem.target = self
menuItem.action = #selector(ItemConfig.dispatchAction)
}
}
// Shortcut key
if let shortcutKey = self.shortcutKey {
menuItem.keyEquivalent = shortcutKey
menuItem.keyEquivalentModifierMask = .command
}
// Associate the menu item to the model
self.menuItem = menuItem
self.initializeTitle()
return menuItem
}
/// Dispatch background script action
@objc func dispatchAction() {
if let script = self.actionScript {
script.execute {
_, result in
print("Result: \(result)")
}
}
}
/// Initialize title bar
func initializeTitle() {
// 1. Set initial title.
if let title = self.title {
self.updateTitle(title: title)
}
// 2. Dispatch script for other title.
if let titleScript = self.titleScript {
titleScript.execute { [weak self] _, result in
self?.menuItem?.title = result
}
// While we're executing the title script,
// Also set up a timer if we need it.
if let titleRefreshInterval = self.titleRefreshInterval {
self.refreshTimer = Timer.scheduledTimer(withTimeInterval: titleRefreshInterval, repeats: true, block: {
timer in
// In the future, execute the title updates
titleScript.execute { [weak self] _, result in
// Update in background.
self?.menuItem?.title = result
// Invalidate if self is no longer available (gc)
if self == nil {
timer.invalidate()
}
}
})
}
}
}
}
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var menuItems : [ItemConfig] = [
ItemConfig(
title: "IP Address",
titleScript: Script(
bin: "/bin/sh",
args: ["-c", "echo IP: $(curl https://api.ipify.org)"],
env: [
"PATH": "/usr/bin:/usr/local/bin:/sbin:/bin"
]),
titleRefreshInterval: 120
),
ItemConfig(
title: "Setup Help",
actionScript: Script(
bin: "/bin/sh",
args: ["-c", "open https://github.com/richinfante/shbar"],
env: [
"PATH": "/usr/bin:/usr/local/bin:/sbin:/bin"
])
),
ItemConfig(
mode: .ApplicationQuit,
title: "Quit",
shortcutKey: "q"
)
]
let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
var userHomeDirectoryPath : String {
let pw = getpwuid(getuid())
let home = pw?.pointee.pw_dir
let homePath = FileManager.default.string(withFileSystemRepresentation: home!, length: Int(strlen(home)))
return homePath
}
func applicationDidFinishLaunching(_ aNotification: Notification) {
let json = try? Data(contentsOf: URL(fileURLWithPath: "\(userHomeDirectoryPath)/.config/shbar/shbar.json"))
if let json = json {
let decoder = JSONDecoder()
let decodedItems = try? decoder.decode([ItemConfig].self, from: json)
if let decodedItems = decodedItems {
print("Loaded from File!")
menuItems = decodedItems
}
} else {
print("No config file present!")
}
let jsonEncoder = JSONEncoder()
jsonEncoder.outputFormatting = .prettyPrinted
let data = try? jsonEncoder.encode(menuItems)
print(String(data: data!, encoding: .utf8)!)
// Insert code here to initialize your application
let menu = NSMenu(title: "shbar")
menu.items = []
for item in menuItems {
// Add to actual menu
menu.items.append(item.createMenuItem(self))
}
// Set main title
statusItem.button!.title = "shbar"
statusItem.menu = menu
print("launched.")
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
@objc func terminateMenuBarApp(_ sender: NSMenuItem?) {
// Terminate jobs
for item in menuItems {
item.currentJob?.terminate()
}
NSApplication.shared.terminate(self)
}
}