forked from intitni/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWidgetFeature.swift
More file actions
690 lines (618 loc) · 30.3 KB
/
WidgetFeature.swift
File metadata and controls
690 lines (618 loc) · 30.3 KB
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
import ActiveApplicationMonitor
import AsyncAlgorithms
import AXNotificationStream
import ComposableArchitecture
import Environment
import Foundation
import Preferences
import SwiftUI
import XcodeInspector
public struct WidgetFeature: ReducerProtocol {
public struct WindowState: Equatable {
var alphaValue: Double = 0
var frame: CGRect = .zero
}
public struct Windows: Equatable {
public var widgetWindowState = WindowState()
public var chatWindowState = WindowState()
public var suggestionPanelWindowState = WindowState()
public var sharedPanelWindowState = WindowState()
public var tabWindowState = WindowState()
}
public struct State: Equatable {
var focusingDocumentURL: URL?
public var colorScheme: ColorScheme = .light
// MARK: Panels
public var panelState = PanelFeature.State()
// MARK: ChatPanel
public var chatPanelState = ChatPanelFeature.State()
// MARK: CircularWidget
public struct CircularWidgetState: Equatable {
var isProcessingCounters = [CircularWidgetFeature.IsProcessingCounter]()
var isProcessing: Bool = false
var animationProgress: Double = 0
}
public var circularWidgetState = CircularWidgetState()
var _circularWidgetState: CircularWidgetFeature.State {
get {
.init(
isProcessingCounters: circularWidgetState.isProcessingCounters,
isProcessing: circularWidgetState.isProcessing,
isDisplayingContent: {
if chatPanelState.isPanelDisplayed {
return true
}
if panelState.sharedPanelState.isPanelDisplayed,
!panelState.sharedPanelState.isEmpty
{
return true
}
if panelState.suggestionPanelState.isPanelDisplayed,
panelState.suggestionPanelState.content != nil
{
return true
}
return false
}(),
isContentEmpty: chatPanelState.chatTabGroup.tabInfo.isEmpty
&& panelState.sharedPanelState.isEmpty,
isChatPanelDetached: chatPanelState.chatPanelInASeparateWindow,
isChatOpen: chatPanelState.isPanelDisplayed,
animationProgress: circularWidgetState.animationProgress
)
}
set {
circularWidgetState = .init(
isProcessingCounters: newValue.isProcessingCounters,
isProcessing: newValue.isProcessing,
animationProgress: newValue.animationProgress
)
}
}
public init() {}
}
private enum CancelID {
case observeActiveApplicationChange
case observeCompletionPanelChange
case observeFullscreenChange
case observeWindowChange
case observeEditorChange
case observeUserDefaults
}
public enum Action: Equatable {
case startup
case observeActiveApplicationChange
case observeCompletionPanelChange
case observeFullscreenChange
case observeColorSchemeChange
case observePresentationModeChange
case observeWindowChange
case observeEditorChange
case updateActiveApplication
case updateColorScheme
case updateWindowLocation(animated: Bool)
case updateWindowOpacity
case updateFocusingDocumentURL
case panel(PanelFeature.Action)
case chatPanel(ChatPanelFeature.Action)
case circularWidget(CircularWidgetFeature.Action)
}
var windows: WidgetWindows {
suggestionWidgetControllerDependency.windows
}
@Dependency(\.suggestionWidgetUserDefaultsObservers) var userDefaultsObservers
@Dependency(\.suggestionWidgetControllerDependency) var suggestionWidgetControllerDependency
@Dependency(\.activeApplicationMonitor) var activeApplicationMonitor
@Dependency(\.xcodeInspector) var xcodeInspector
@Dependency(\.mainQueue) var mainQueue
public enum DebounceKey: Hashable {
case updateWindowOpacity
}
public init() {}
public var body: some ReducerProtocol<State, Action> {
Scope(state: \._circularWidgetState, action: /Action.circularWidget) {
CircularWidgetFeature()
}
Reduce { state, action in
switch action {
case .circularWidget(.detachChatPanelToggleClicked):
return .run { send in
await send(.chatPanel(.toggleChatPanelDetachedButtonClicked))
}
case .circularWidget(.widgetClicked):
let isDisplayingContent = state._circularWidgetState.isDisplayingContent
if isDisplayingContent {
state.panelState.sharedPanelState.isPanelDisplayed = false
state.panelState.suggestionPanelState.isPanelDisplayed = false
state.chatPanelState.isPanelDisplayed = false
} else {
state.panelState.sharedPanelState.isPanelDisplayed = true
state.panelState.suggestionPanelState.isPanelDisplayed = true
state.chatPanelState.isPanelDisplayed = true
}
return .run { _ in
guard isDisplayingContent else { return }
if let app = activeApplicationMonitor.previousApp, app.isXcode {
try await Task.sleep(nanoseconds: 200_000_000)
app.activate()
}
}
default: return .none
}
}
Scope(state: \.panelState, action: /Action.panel) {
PanelFeature()
}
Scope(state: \.chatPanelState, action: /Action.chatPanel) {
ChatPanelFeature()
}
Reduce { state, action in
switch action {
case .chatPanel(.presentChatPanel):
let isDetached = state.chatPanelState.chatPanelInASeparateWindow
return .run { send in
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
if isDetached {
Task { @MainActor in
windows.chatPanelWindow.alphaValue = 1
}
}
}
case .chatPanel(.toggleChatPanelDetachedButtonClicked):
let isDetached = state.chatPanelState.chatPanelInASeparateWindow
return .run { send in
await send(.updateWindowLocation(animated: !isDetached))
await send(.updateWindowOpacity)
}
default: return .none
}
}
Reduce { state, action in
switch action {
case .startup:
return .merge(
.run { send in await send(.observeActiveApplicationChange) },
.run { send in await send(.observeCompletionPanelChange) },
.run { send in await send(.observeFullscreenChange) },
.run { send in await send(.observeColorSchemeChange) },
.run { send in await send(.observePresentationModeChange) }
)
case .observeActiveApplicationChange:
return .run { send in
var previousApp: NSRunningApplication?
for await app in activeApplicationMonitor.createStream() {
try Task.checkCancellation()
if app != previousApp {
await send(.updateActiveApplication)
}
previousApp = app
}
}.cancellable(id: CancelID.observeActiveApplicationChange, cancelInFlight: true)
case .observeCompletionPanelChange:
return .run { send in
let stream = AsyncStream<Void> { continuation in
let cancellable = XcodeInspector.shared.$completionPanel.sink { newValue in
Task {
if newValue == nil {
// so that the buttons on the suggestion panel could be
// clicked
// before the completion panel updates the location of the
// suggestion panel
try await Task.sleep(nanoseconds: 400_000_000)
}
continuation.yield()
}
}
continuation.onTermination = { _ in
cancellable.cancel()
}
}
for await _ in stream {
try Task.checkCancellation()
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
}
}.cancellable(id: CancelID.observeCompletionPanelChange, cancelInFlight: true)
case .observeFullscreenChange:
return .run { _ in
let sequence = NSWorkspace.shared.notificationCenter
.notifications(named: NSWorkspace.activeSpaceDidChangeNotification)
for await _ in sequence {
try Task.checkCancellation()
guard let activeXcode = activeApplicationMonitor.activeXcode
else { continue }
guard await windows.fullscreenDetector.isOnActiveSpace else { continue }
let app = AXUIElementCreateApplication(activeXcode.processIdentifier)
if let _ = app.focusedWindow {
await windows.orderFront()
}
}
}.cancellable(id: CancelID.observeFullscreenChange, cancelInFlight: true)
case .observeColorSchemeChange:
return .run { send in
await send(.updateColorScheme)
let stream = AsyncStream<Void> { continuation in
userDefaultsObservers.colorSchemeChangeObserver.onChange = {
continuation.yield()
}
userDefaultsObservers.systemColorSchemeChangeObserver.onChange = {
continuation.yield()
}
continuation.onTermination = { _ in
userDefaultsObservers.colorSchemeChangeObserver.onChange = {}
userDefaultsObservers.systemColorSchemeChangeObserver.onChange = {}
}
}
for await _ in stream {
try Task.checkCancellation()
await send(.updateColorScheme)
}
}.cancellable(id: CancelID.observeUserDefaults, cancelInFlight: true)
case .observePresentationModeChange:
return .run { send in
await send(.updateColorScheme)
let stream = AsyncStream<Void> { continuation in
userDefaultsObservers.presentationModeChangeObserver.onChange = {
continuation.yield()
}
continuation.onTermination = { _ in
userDefaultsObservers.presentationModeChangeObserver.onChange = {}
}
}
for await _ in stream {
try Task.checkCancellation()
await send(.updateWindowLocation(animated: false))
}
}.cancellable(id: CancelID.observeUserDefaults, cancelInFlight: true)
case .observeWindowChange:
guard let app = activeApplicationMonitor.activeApplication else { return .none }
guard app.isXcode else { return .none }
let documentURL = state.focusingDocumentURL
return .run { [app] send in
await send(.observeEditorChange)
let notifications = AXNotificationStream(
app: app,
notificationNames:
kAXApplicationActivatedNotification,
kAXMovedNotification,
kAXResizedNotification,
kAXMainWindowChangedNotification,
kAXFocusedWindowChangedNotification,
kAXFocusedUIElementChangedNotification,
kAXWindowMovedNotification,
kAXWindowResizedNotification,
kAXWindowMiniaturizedNotification,
kAXWindowDeminiaturizedNotification
)
for await notification in notifications {
try Task.checkCancellation()
// Hide the widgets before switching to another window/editor
// so the transition looks better.
if [
kAXFocusedUIElementChangedNotification,
kAXFocusedWindowChangedNotification,
].contains(notification.name) {
let newDocumentURL = xcodeInspector.realtimeActiveDocumentURL
if documentURL != newDocumentURL {
await send(.panel(.removeDisplayedContent))
await hidePanelWindows()
}
await send(.updateFocusingDocumentURL)
}
// update widgets.
if [
kAXFocusedUIElementChangedNotification,
kAXApplicationActivatedNotification,
kAXMainWindowChangedNotification,
kAXFocusedWindowChangedNotification,
].contains(notification.name) {
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
await send(.observeEditorChange)
await send(.panel(.switchToAnotherEditorAndUpdateContent))
} else {
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
}
}
}.cancellable(id: CancelID.observeWindowChange, cancelInFlight: true)
case .observeEditorChange:
guard let app = activeApplicationMonitor.activeApplication else { return .none }
return .run { send in
let appElement = AXUIElementCreateApplication(app.processIdentifier)
if let focusedElement = appElement.focusedElement,
focusedElement.description == "Source Editor",
let scrollView = focusedElement.parent,
let scrollBar = scrollView.verticalScrollBar
{
let selectionRangeChange = AXNotificationStream(
app: app,
element: focusedElement,
notificationNames: kAXSelectedTextChangedNotification
)
let scroll = AXNotificationStream(
app: app,
element: scrollBar,
notificationNames: kAXValueChangedNotification
)
if #available(macOS 13.0, *) {
for await _ in merge(
selectionRangeChange.debounce(for: Duration.milliseconds(500)),
scroll
) {
guard activeApplicationMonitor.latestXcode != nil
else { return }
try Task.checkCancellation()
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
}
} else {
for await _ in merge(selectionRangeChange, scroll) {
guard activeApplicationMonitor.latestXcode != nil
else { return }
try Task.checkCancellation()
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
}
}
}
}.cancellable(id: CancelID.observeEditorChange, cancelInFlight: true)
case .updateActiveApplication:
if let app = activeApplicationMonitor.activeApplication, app.isXcode {
return .run { send in
await send(.panel(.switchToAnotherEditorAndUpdateContent))
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
await windows.orderFront()
await send(.observeWindowChange)
}
}
return .run { send in
await send(.updateWindowLocation(animated: false))
await send(.updateWindowOpacity)
}
case .updateColorScheme:
let widgetColorScheme = UserDefaults.shared.value(for: \.widgetColorScheme)
let systemColorScheme: ColorScheme = NSApp.effectiveAppearance.name == .darkAqua
? .dark
: .light
let scheme: ColorScheme = {
switch (widgetColorScheme, systemColorScheme) {
case (.system, .dark), (.dark, _):
return .dark
case (.system, .light), (.light, _):
return .light
case (.system, _):
return .light
}
}()
state.colorScheme = scheme
state.panelState.sharedPanelState.colorScheme = scheme
state.panelState.suggestionPanelState.colorScheme = scheme
state.chatPanelState.colorScheme = scheme
return .none
case .updateFocusingDocumentURL:
state.focusingDocumentURL = xcodeInspector.realtimeActiveDocumentURL
return .none
case let .updateWindowLocation(animated):
guard let widgetLocation = generateWidgetLocation() else { return .none }
state.panelState.sharedPanelState.alignTopToAnchor = widgetLocation
.defaultPanelLocation
.alignPanelTop
if let suggestionPanelLocation = widgetLocation.suggestionPanelLocation {
state.panelState.suggestionPanelState.isPanelOutOfFrame = false
state.panelState.suggestionPanelState
.alignTopToAnchor = suggestionPanelLocation
.alignPanelTop
} else {
state.panelState.suggestionPanelState.isPanelOutOfFrame = true
}
let isChatPanelDetached = state.chatPanelState.chatPanelInASeparateWindow
return .run { _ in
Task { @MainActor in
windows.widgetWindow.setFrame(
widgetLocation.widgetFrame,
display: false,
animate: animated
)
windows.tabWindow.setFrame(
widgetLocation.tabFrame,
display: false,
animate: animated
)
windows.sharedPanelWindow.setFrame(
widgetLocation.defaultPanelLocation.frame,
display: false,
animate: animated
)
if let suggestionPanelLocation = widgetLocation.suggestionPanelLocation {
windows.suggestionPanelWindow.setFrame(
suggestionPanelLocation.frame,
display: false,
animate: animated
)
}
if isChatPanelDetached {
if windows.chatPanelWindow.alphaValue == 0 {
windows.chatPanelWindow.setFrame(
widgetLocation.defaultPanelLocation.frame,
display: false,
animate: animated
)
}
} else {
windows.chatPanelWindow.setFrame(
widgetLocation.defaultPanelLocation.frame,
display: false,
animate: animated
)
}
}
}
case .updateWindowOpacity:
let isChatPanelDetached = state.chatPanelState.chatPanelInASeparateWindow
let hasChat = !state.chatPanelState.chatTabGroup.tabInfo.isEmpty
return .run { _ in
try await mainQueue.sleep(for: .seconds(0.2))
Task { @MainActor in
if let app = activeApplicationMonitor.activeApplication, app.isXcode {
let application = AXUIElementCreateApplication(app.processIdentifier)
/// We need this to hide the windows when Xcode is minimized.
let noFocus = application.focusedWindow == nil
windows.sharedPanelWindow.alphaValue = noFocus ? 0 : 1
windows.suggestionPanelWindow.alphaValue = noFocus ? 0 : 1
windows.widgetWindow.alphaValue = noFocus ? 0 : 1
windows.tabWindow.alphaValue = 0
if isChatPanelDetached {
windows.chatPanelWindow.alphaValue = hasChat ? 1 : 0
} else {
windows.chatPanelWindow.alphaValue = noFocus ? 0 : 1
}
} else if let app = activeApplicationMonitor.activeApplication,
app.bundleIdentifier == Bundle.main.bundleIdentifier
{
let noFocus = {
guard let xcode = xcodeInspector.latestActiveXcode
else { return true }
if let window = xcode.appElement.focusedWindow,
window.role == "AXWindow"
{
return false
}
return true
}()
windows.sharedPanelWindow.alphaValue = noFocus ? 0 : 1
windows.suggestionPanelWindow.alphaValue = noFocus ? 0 : 1
windows.widgetWindow.alphaValue = noFocus ? 0 : 1
windows.tabWindow.alphaValue = 0
if isChatPanelDetached {
windows.chatPanelWindow.alphaValue = hasChat ? 1 : 0
} else {
windows.chatPanelWindow.alphaValue = noFocus && !windows
.chatPanelWindow.isKeyWindow ? 0 : 1
}
} else {
windows.sharedPanelWindow.alphaValue = 0
windows.suggestionPanelWindow.alphaValue = 0
windows.widgetWindow.alphaValue = 0
windows.tabWindow.alphaValue = 0
if !isChatPanelDetached {
windows.chatPanelWindow.alphaValue = 0
}
}
}
}
.cancellable(id: DebounceKey.updateWindowOpacity, cancelInFlight: true)
case .circularWidget:
return .none
case .panel:
return .none
case .chatPanel:
return .none
}
}
}
@MainActor
func hidePanelWindows() {
windows.sharedPanelWindow.alphaValue = 0
windows.suggestionPanelWindow.alphaValue = 0
}
func generateWidgetLocation() -> WidgetLocation? {
if let application = xcodeInspector.latestActiveXcode?.appElement {
if let focusElement = xcodeInspector.focusedEditor?.element,
let parent = focusElement.parent,
let frame = parent.rect,
let screen = NSScreen.screens.first(where: { $0.frame.origin == .zero }),
let firstScreen = NSScreen.main
{
let positionMode = UserDefaults.shared
.value(for: \.suggestionWidgetPositionMode)
let suggestionMode = UserDefaults.shared
.value(for: \.suggestionPresentationMode)
switch positionMode {
case .fixedToBottom:
var result = UpdateLocationStrategy.FixedToBottom().framesForWindows(
editorFrame: frame,
mainScreen: screen,
activeScreen: firstScreen
)
switch suggestionMode {
case .nearbyTextCursor:
result.suggestionPanelLocation = UpdateLocationStrategy
.NearbyTextCursor()
.framesForSuggestionWindow(
editorFrame: frame, mainScreen: screen,
activeScreen: firstScreen,
editor: focusElement,
completionPanel: xcodeInspector.completionPanel
)
default:
break
}
return result
case .alignToTextCursor:
var result = UpdateLocationStrategy.AlignToTextCursor().framesForWindows(
editorFrame: frame,
mainScreen: screen,
activeScreen: firstScreen,
editor: focusElement
)
switch suggestionMode {
case .nearbyTextCursor:
result.suggestionPanelLocation = UpdateLocationStrategy
.NearbyTextCursor()
.framesForSuggestionWindow(
editorFrame: frame, mainScreen: screen,
activeScreen: firstScreen,
editor: focusElement,
completionPanel: xcodeInspector.completionPanel
)
default:
break
}
return result
}
} else if var window = application.focusedWindow,
var frame = application.focusedWindow?.rect,
!["menu bar", "menu bar item"].contains(window.description),
frame.size.height > 300,
let screen = NSScreen.screens.first(where: { $0.frame.origin == .zero }),
let firstScreen = NSScreen.main
{
if ["open_quickly"].contains(window.identifier)
|| ["alert"].contains(window.label)
{
// fallback to use workspace window
guard let workspaceWindow = application.windows
.first(where: { $0.identifier == "Xcode.WorkspaceWindow" }),
let rect = workspaceWindow.rect
else {
return WidgetLocation(
widgetFrame: .zero,
tabFrame: .zero,
defaultPanelLocation: .init(frame: .zero, alignPanelTop: false)
)
}
window = workspaceWindow
frame = rect
}
if ["Xcode.WorkspaceWindow"].contains(window.identifier) {
// extra padding to bottom so buttons won't be covered
frame.size.height -= 40
} else {
// move a bit away from the window so buttons won't be covered
frame.origin.x -= Style.widgetPadding + Style.widgetWidth / 2
frame.size.width += Style.widgetPadding * 2 + Style.widgetWidth
}
return UpdateLocationStrategy.FixedToBottom().framesForWindows(
editorFrame: frame,
mainScreen: screen,
activeScreen: firstScreen,
preferredInsideEditorMinWidth: 9_999_999_999 // never
)
}
}
return nil
}
}