-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathViewController.swift
523 lines (464 loc) · 18.3 KB
/
ViewController.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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//
// ViewController.swift
// Sky
// All rights reserved.
//
import Cocoa
import WebKit
class ViewController: NSViewController {
// https://gist.github.com/swillits/df648e87016772c7f7e5dbed2b345066
struct Keycode {
static let escape : UInt16 = 0x35
static let leftBracket : UInt16 = 0x21
static let rightBracket : UInt16 = 0x1E
static let k : UInt16 = 0x28
}
var webView: WKWebView!
var webKitDelegate: WebKitDelegate!
var muteWordsWkUserScript: WKUserScript?
var orderPostsWkUserScript: WKUserScript?
var hideHomeRepliesWkUserScript: WKUserScript?
var setZoomFactorWkUserScript: WKUserScript?
let userScriptsAtDocumentStart = [
"hook_fetch",
]
let userScriptsAtDocumentEnd = [
"hook_ctrl_tab",
"hook_history_state",
"hook_local_storage",
"hook_window_color_scheme",
"hook_window_open",
]
var observation: NSKeyValueObservation?
func checkAppearance() {
let bestMatch = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua])
let initSystemAppearanceValue = bestMatch == .darkAqua ? "dark" : "light"
NSLog("checkAppearance initSystemAppearanceValue = \(initSystemAppearanceValue)")
if self.webView != nil {
NSLog("checkAppearance setting local storage")
self.webView.evaluateJavaScript(
Scripts.localStorageSetItem(
key: LocalStorageKeys.initSystemAppearance,
value: initSystemAppearanceValue
)
)
}
}
override func loadView() {
AppDelegate.shared.mainViewController = self
checkAppearance()
observation = NSApp.observe(\.effectiveAppearance) { (app, _) in
app.effectiveAppearance.performAsCurrentDrawingAppearance {
self.checkAppearance()
}
}
webKitDelegate = WebKitDelegate()
let webConfiguration = WKWebViewConfiguration()
let userContentController = WKUserContentController()
let scriptMessageHandler = ScriptMessageHandler()
scriptMessageHandler.viewController = self
for name in scriptMessageHandler.nameFns.keys {
userContentController.add(scriptMessageHandler, name: name)
}
for userScript in userScriptsAtDocumentStart {
userContentController.addUserScript(
JsLoader.loadWKUserScript(
"Scripts/\(userScript)",
[:],
.atDocumentStart))
}
for userScript in userScriptsAtDocumentEnd {
userContentController.addUserScript(
JsLoader.loadWKUserScript(
"Scripts/\(userScript)",
[:],
.atDocumentEnd))
}
let bestMatch = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua])
let initSystemAppearanceValue = bestMatch == .darkAqua ? "dark" : "light"
let saveSystemAppearanceWkUserScript = JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.initSystemAppearance, "value": initSystemAppearanceValue]
)
NSLog("setting init system appearance to \(initSystemAppearanceValue)")
userContentController.addUserScript(saveSystemAppearanceWkUserScript)
let orderPosts = AppDelegate.shared.getUserDefaultsOrderPosts()
let orderPostsValue = orderPosts ? "yes" : "no"
orderPostsWkUserScript = JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.orderPosts, "value": orderPostsValue]
)
userContentController.addUserScript(orderPostsWkUserScript!)
let hideHomeReplies = AppDelegate.shared.getUserDefaultsHideHomeReplies()
let hideHomeRepliesValue = hideHomeReplies ? "yes" : "no"
hideHomeRepliesWkUserScript = JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.hideHomeReplies, "value": hideHomeRepliesValue]
)
userContentController.addUserScript(hideHomeRepliesWkUserScript!)
let zoomFactor = AppDelegate.shared.getZoomFactor()
setZoomFactorWkUserScript = JsLoader.loadWKUserScript(
"Scripts/set_zoom_factor",
["zoom_factor": "\(zoomFactor)"]
)
userContentController.addUserScript(setZoomFactorWkUserScript!)
webConfiguration.userContentController = userContentController
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = webKitDelegate
webView.uiDelegate = webKitDelegate
webView.addObserver(self, forKeyPath: "URL", options: .new, context: nil)
if #available(macOS 12.3, *) {
webView.configuration.preferences.isElementFullscreenEnabled = true
}
// defaults write jcsalterego.Sky webInspector -bool TRUE
if let webInspector = UserDefaults.standard.object(forKey: UserDefaultKeys.webInspector) as? Bool {
webView.configuration.preferences.setValue(webInspector, forKey: "developerExtrasEnabled")
}
view = webView
}
// Observe value
override func observeValue(
forKeyPath keyPath: String?,
of object: Any?,
change: [NSKeyValueChangeKey : Any]?,
context: UnsafeMutableRawPointer?
) {
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: SkyUrls.root)
let myRequest = URLRequest(url: url!)
webView.load(myRequest)
}
override func keyDown(with event: NSEvent) {
if (event.keyCode == Keycode.escape) {
self.webView.evaluateJavaScript(Scripts.escGoesBack())
} else if (
event.modifierFlags.contains(.command)
&& event.keyCode == Keycode.k
) {
actionLaunchJumpbar(nil)
}
}
@IBAction func actionViewHome(_ sender: Any?) {
let checkLoadNew = (webView.url!.absoluteString == SkyUrls.home)
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: checkLoadNew,
label: "Home",
index: 0,
url: SkyUrls.home
)
)
}
@IBAction func actionViewSearch(_ sender: Any?) {
if webView.url!.absoluteString == SkyUrls.search {
self.webView.evaluateJavaScript(Scripts.focusSearch())
} else {
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: false,
label: "Search",
index: 1,
url: SkyUrls.search
)
)
}
}
@IBAction func actionViewFeeds(_ sender: Any?) {
let checkLoadNew = (webView.url!.absoluteString == SkyUrls.feeds)
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: checkLoadNew,
label: "Feeds",
index: -1,
url: SkyUrls.feeds
)
)
}
@IBAction func actionViewLists(_ sender: Any?) {
let checkLoadNew = (webView.url!.absoluteString == SkyUrls.lists)
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: checkLoadNew,
label: "Lists",
index: -1,
url: SkyUrls.lists
)
)
}
@IBAction func actionViewNotifications(_ sender: Any?) {
let checkLoadNew = (webView.url!.absoluteString == SkyUrls.notifications)
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: checkLoadNew,
label: "Notifications",
index: 3,
url: SkyUrls.notifications
)
)
}
@IBAction func actionViewChat(_ sender: Any?) {
let checkLoadNew = (webView.url!.absoluteString == SkyUrls.messages)
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: checkLoadNew,
label: "Chat;Messages",
index: 2,
url: SkyUrls.messages
)
)
}
@IBAction func actionViewProfile(_ sender: Any?) {
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: false,
label: "Profile",
index: 4,
url: nil
)
)
}
@IBAction func actionViewModeration(_ sender: Any?) {
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: false,
label: "Moderation",
index: -1,
url: SkyUrls.moderation
)
)
}
@IBAction func actionViewSettings(_ sender: Any?) {
self.webView.evaluateJavaScript(
Scripts.navigateNavbar(
checkLoadNew: false,
label: "Settings",
index: -1,
url: SkyUrls.settings
)
)
}
@IBAction func actionRefresh(_ sender: Any?) {
AppDelegate.shared.clearNotifCounts()
let scriptsToRefresh = [
muteWordsWkUserScript,
setZoomFactorWkUserScript,
]
var newUserScripts: [WKUserScript] = []
let userContentController = webView.configuration.userContentController
for userScript in userContentController.userScripts {
if !scriptsToRefresh.contains(userScript) {
newUserScripts.append(userScript)
}
}
let bestMatch = NSApp.effectiveAppearance.bestMatch(from: [.darkAqua, .aqua])
let initSystemAppearanceValue = bestMatch == .darkAqua ? "dark" : "light"
let saveSystemAppearanceWkUserScript = JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.initSystemAppearance, "value": initSystemAppearanceValue]
)
NSLog("setting refresh system appearance to \(initSystemAppearanceValue)")
newUserScripts.append(
saveSystemAppearanceWkUserScript
)
let orderPosts = AppDelegate.shared.getUserDefaultsOrderPosts()
let orderPostsValue = orderPosts ? "yes" : "no"
newUserScripts.append(
JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.orderPosts, "value": orderPostsValue]
)
)
let hideHomeReplies = AppDelegate.shared.getUserDefaultsHideHomeReplies()
let hideHomeRepliesValue = hideHomeReplies ? "yes" : "no"
newUserScripts.append(
JsLoader.loadWKUserScript(
"Scripts/local_storage_set_item",
["key": LocalStorageKeys.hideHomeReplies, "value": hideHomeRepliesValue]
)
)
let zoomFactor = AppDelegate.shared.getZoomFactor()
newUserScripts.append(
JsLoader.loadWKUserScript(
"Scripts/set_zoom_factor",
["zoom_factor": "\(zoomFactor)"]
)
)
userContentController.removeAllUserScripts()
for userScript in newUserScripts {
userContentController.addUserScript(userScript)
}
webView.reload()
}
func goToFeed(_ atURLString: String) {
NSLog("urlString = \(atURLString)")
// at://did:plc:z72i7hdynmk6r22z27h6tvur/app.bsky.feed.generator/hot-classic
let words = atURLString
.replacingOccurrences(of: "at://", with: "")
.split(separator: "/")
if words.count == 3 {
let actor = words[0]
let collection = words[1]
let rkey = words[2]
if actor.starts(with: "did:")
&& collection == "app.bsky.feed.generator"
{
let url = getFeedURL(actor: "\(actor)", rkey: "\(rkey)")
let myRequest = URLRequest(url: url!)
webView.load(myRequest)
}
}
}
func getFeedURL(actor: String, rkey: String) -> URL? {
let urlString = "https://bsky.app/profile/\(actor)/feed/\(rkey)"
return URL(string: urlString)
}
@IBAction func actionOpenInBrowser(_ sender: Any?) {
let urlString = webView.url!.absoluteString
switch urlString {
case SkyUrls.home,
SkyUrls.notifications:
break
default:
NSWorkspace.shared.open(webView.url!)
}
}
@IBAction func actionCopyLink(_ sender: Any?) {
let pasteboard = NSPasteboard.general
let urlString = webView.url!.absoluteString
pasteboard.declareTypes([NSPasteboard.PasteboardType.string], owner: nil)
pasteboard.setString(urlString, forType: NSPasteboard.PasteboardType.string)
}
@IBAction func actionNewPost(_ sender: Any?) {
// Does nothing because 'n' is bound to New Post now
if !NSEvent.modifierFlags.contains(.command) {
self.webView.evaluateJavaScript(Scripts.clickByAriaLabel("New Post"))
}
}
@IBAction func actionNextTab(_ sender: Any?) {
self.webView.evaluateJavaScript(Scripts.navigateTab(direction: 1))
}
@IBAction func actionPrevTab(_ sender: Any?) {
self.webView.evaluateJavaScript(Scripts.navigateTab(direction: -1))
}
@IBAction func actionOrderPosts(_ sender: Any?) {
if let menuItem = sender as? NSMenuItem {
var orderPosts = menuItem.state == .on
orderPosts = !orderPosts
menuItem.state = orderPosts ? .on : .off
setOrderPosts(orderPosts)
AppDelegate.shared.setUserDefaultsOrderPosts(orderPosts)
}
}
func setOrderPosts(_ orderPosts: Bool) {
let orderPostsValue = orderPosts ? "yes" : "no"
self.webView.evaluateJavaScript(
Scripts.localStorageSetItem(
key: LocalStorageKeys.orderPosts,
value: orderPostsValue
)
)
}
@IBAction func actionHideHomeReplies(_ sender: Any?) {
if let menuItem = sender as? NSMenuItem {
var hideHomeReplies = menuItem.state == .on
hideHomeReplies = !hideHomeReplies
menuItem.state = hideHomeReplies ? .on : .off
setHideHomeReplies(hideHomeReplies)
AppDelegate.shared.setUserDefaultsHideHomeReplies(hideHomeReplies)
let alert = NSAlert()
alert.messageText = "Refresh Timeline?"
if hideHomeReplies {
alert.informativeText = "Refresh the timeline to hide replies?\nOr you can go to File > Refresh later on."
} else {
alert.informativeText = "Refresh the timeline to include replies?\nOr you can go to File > Refresh later on."
}
alert.addButton(withTitle: "Yes")
alert.addButton(withTitle: "No")
let action = alert.runModal()
if action == .alertFirstButtonReturn {
AppDelegate.shared.mainViewController?.actionRefresh(nil)
}
}
}
@IBAction func actionUseTranslationsWindow(_ sender: Any?) {
if let menuItem = sender as? NSMenuItem {
var useTranslationsWindow = menuItem.state == .on
useTranslationsWindow = !useTranslationsWindow
menuItem.state = useTranslationsWindow ? .on : .off
AppDelegate.shared.setUserDefaultsUseTranslationsWindow(useTranslationsWindow)
}
}
func setHideHomeReplies(_ hideHomeReplies: Bool) {
let hideHomeRepliesValue = hideHomeReplies ? "yes" : "no"
self.webView.evaluateJavaScript(
Scripts.localStorageSetItem(
key: LocalStorageKeys.hideHomeReplies,
value: hideHomeRepliesValue
)
)
}
@IBAction func actionLaunchJumpbar(_ sender: Any?) {
if let jumpbarWindowController = AppDelegate.shared.jumpbarWindowController {
NSApplication.shared.runModal(for: jumpbarWindowController.window!)
}
}
enum WindowColorScheme {
case dark
case light
}
func updateTitleBar(_ mode: WindowColorScheme, backgroundColor: String) {
if backgroundColor.starts(with:"rgb("),
let range = backgroundColor.range(of: #"\((.*?)\)"#, options: .regularExpression)
{
let result = backgroundColor[range]
let trimmedResult = result.trimmingCharacters(in: CharacterSet(charactersIn: "()"))
let rgb: [String.SubSequence] = trimmedResult.split(separator: ",")
if rgb.count == 3 {
let r = CGFloat(Int(rgb[0].trimmingCharacters(in:.whitespaces))!) / 255.0
let g = CGFloat(Int(rgb[1].trimmingCharacters(in:.whitespaces))!) / 255.0
let b = CGFloat(Int(rgb[2].trimmingCharacters(in:.whitespaces))!) / 255.0
self.webView.window!.backgroundColor = NSColor(
red: r,
green: g,
blue: b,
alpha: 1.0
)
}
}
if mode == .dark {
self.webView.window!.appearance = NSAppearance(named: .darkAqua)
} else {
self.webView.window!.appearance = NSAppearance(named: .aqua)
}
}
func adjustAndApplyZoomFactor(_ adjustValue: Int) {
let ZOOM_FACTORS = AppDelegate.ZOOM_FACTORS
var zoomFactor = AppDelegate.shared.getZoomFactor()
if adjustValue != 0, var pos = ZOOM_FACTORS.firstIndex(of: zoomFactor) {
pos += adjustValue
pos = max(0, pos)
pos = min(pos, ZOOM_FACTORS.count - 1)
zoomFactor = ZOOM_FACTORS[pos]
} else {
zoomFactor = 1.0
}
AppDelegate.shared.setZoomFactor(zoomFactor)
self.webView.evaluateJavaScript(
JsLoader.loadScriptContents(
"Scripts/set_zoom_factor",
["zoom_factor": "\(zoomFactor)"]
)
)
}
@IBAction func actionZoomIn(_ sender: Any?) {
adjustAndApplyZoomFactor(1)
}
@IBAction func actionZoomOut(_ sender: Any?) {
adjustAndApplyZoomFactor(-1)
}
@IBAction func actionActualSize(_ sender: Any?) {
adjustAndApplyZoomFactor(0)
}
}