Skip to content

Commit e958f38

Browse files
committed
Hide floating widget if not in floating widget mode
1 parent fbba065 commit e958f38

1 file changed

Lines changed: 43 additions & 2 deletions

File tree

Core/Sources/SuggestionWidget/SuggestionWidgetController.swift

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,23 @@ import AppKit
33
import AXNotificationStream
44
import Environment
55
import SwiftUI
6+
import XPCShared
67

78
@MainActor
89
public final class SuggestionWidgetController {
10+
class UserDefaultsObserver: NSObject {
11+
var onChange: (() -> Void)?
12+
13+
override func observeValue(
14+
forKeyPath keyPath: String?,
15+
of object: Any?,
16+
change: [NSKeyValueChangeKey: Any]?,
17+
context: UnsafeMutableRawPointer?
18+
) {
19+
onChange?()
20+
}
21+
}
22+
923
private lazy var widgetWindow = {
1024
let it = NSWindow(
1125
contentRect: .zero,
@@ -50,6 +64,7 @@ public final class SuggestionWidgetController {
5064
let widgetViewModel = WidgetViewModel()
5165
let suggestionPanelViewModel = SuggestionPanelViewModel()
5266

67+
private var userDefaultsObserver = UserDefaultsObserver()
5368
private var windowChangeObservationTask: Task<Void, Error>?
5469
private var activeApplicationMonitorTask: Task<Void, Error>?
5570
private var xcode: NSRunningApplication?
@@ -81,6 +96,19 @@ public final class SuggestionWidgetController {
8196
}
8297
}
8398
}
99+
100+
Task { @MainActor in
101+
userDefaultsObserver.onChange = { [weak self] in
102+
guard let self else { return }
103+
self.updateWindowLocation()
104+
}
105+
UserDefaults.shared.addObserver(
106+
userDefaultsObserver,
107+
forKeyPath: SettingsKey.suggestionPresentationMode,
108+
options: .new,
109+
context: nil
110+
)
111+
}
84112
}
85113

86114
public func suggestCode(
@@ -164,6 +192,20 @@ public final class SuggestionWidgetController {
164192
/// - note: It's possible to get the scroll view's postion by getting position on the focus
165193
/// element.
166194
private func updateWindowLocation() {
195+
func hide() {
196+
panelWindow.alphaValue = 0
197+
widgetWindow.alphaValue = 0
198+
}
199+
200+
guard PresentationMode(
201+
rawValue: UserDefaults.shared
202+
.integer(forKey: SettingsKey.suggestionPresentationMode)
203+
) == .floatingWidget
204+
else {
205+
hide()
206+
return
207+
}
208+
167209
if let xcode {
168210
let application = AXUIElementCreateApplication(xcode.processIdentifier)
169211
if let focusElement: AXUIElement = try? application
@@ -212,7 +254,6 @@ public final class SuggestionWidgetController {
212254
}
213255
}
214256

215-
panelWindow.alphaValue = 0
216-
widgetWindow.alphaValue = 0
257+
hide()
217258
}
218259
}

0 commit comments

Comments
 (0)