-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathModelPickerMenu.swift
More file actions
418 lines (366 loc) · 13.7 KB
/
ModelPickerMenu.swift
File metadata and controls
418 lines (366 loc) · 13.7 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
import AppKit
import HostAppActivator
import Persist
// MARK: - Search Field View for Menu
private class ModelSearchFieldView: NSView, NSSearchFieldDelegate {
let searchField = NSSearchField()
var onSearchTextChanged: ((String) -> Void)?
weak var parentMenu: NSMenu?
init(fontScale: Double, width: CGFloat) {
let height = 30 * fontScale
super.init(frame: NSRect(x: 0, y: 0, width: width, height: height + 8 * fontScale))
searchField.placeholderString = "Search models..."
searchField.font = NSFont.systemFont(ofSize: 12 * fontScale)
searchField.translatesAutoresizingMaskIntoConstraints = false
searchField.focusRingType = .none
searchField.delegate = self
addSubview(searchField)
NSLayoutConstraint.activate([
searchField.leadingAnchor.constraint(
equalTo: leadingAnchor, constant: 8 * fontScale
),
searchField.trailingAnchor.constraint(
equalTo: trailingAnchor, constant: -8 * fontScale
),
searchField.centerYAnchor.constraint(equalTo: centerYAnchor),
searchField.heightAnchor.constraint(equalToConstant: height),
])
}
@available(*, unavailable)
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func controlTextDidChange(_ obj: Notification) {
guard let field = obj.object as? NSSearchField else { return }
onSearchTextChanged?(field.stringValue)
}
/// Intercept Return / Enter in the search field to select the highlighted
/// menu item. NSMenu doesn't do this automatically for custom-view items.
func control(
_ control: NSControl,
textView _: NSTextView,
doCommandBy commandSelector: Selector
) -> Bool {
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
if let menu = parentMenu,
let highlightedItem = menu.highlightedItem,
let menuItemView = highlightedItem.view as? ModelPickerMenuItem
{
menuItemView.performSelect()
return true
}
}
return false
}
override func viewDidMoveToWindow() {
super.viewDidMoveToWindow()
if window != nil {
DispatchQueue.main.async { [weak self] in
self?.searchField.becomeFirstResponder()
}
}
}
}
// MARK: - Custom Menu (allows key events to reach search field)
private class ModelPickerNSMenu: NSMenu {
weak var searchField: NSSearchField?
override func performKeyEquivalent(with event: NSEvent) -> Bool {
guard event.type == .keyDown else {
return super.performKeyEquivalent(with: event)
}
// Return / Enter: NSMenu won't fire the action for items with custom
// views, so we find the currently highlighted ModelPickerMenuItem and
// invoke its selection callback directly.
let confirmKeyCodes: Set<UInt16> = [
36, // return
76, // enter (numpad)
]
if confirmKeyCodes.contains(event.keyCode) {
if let highlightedItem = highlightedItem,
let menuItemView = highlightedItem.view as? ModelPickerMenuItem
{
menuItemView.performSelect()
return true
}
return super.performKeyEquivalent(with: event)
}
// Forward printable character input and delete keys to the search
// field. Navigation keys (arrows, Escape, Space, Tab) fall through
// to super so NSMenu handles them normally.
if let searchField = searchField,
Self.shouldForwardToSearchField(event)
{
if let window = searchField.window {
window.makeFirstResponder(searchField)
searchField.currentEditor()?.keyDown(with: event)
return true
}
}
return super.performKeyEquivalent(with: event)
}
/// Returns `true` for key events that should be forwarded to the search
/// field: printable characters and delete/backspace. Returns `false` for
/// navigation and control keys so NSMenu can handle them.
private static func shouldForwardToSearchField(_ event: NSEvent) -> Bool {
// Always allow delete / forward-delete so the user can edit the query
let deleteKeyCodes: Set<UInt16> = [
51, // delete (backspace)
117, // forward delete
]
if deleteKeyCodes.contains(event.keyCode) {
return true
}
// Reject keys that NSMenu uses for navigation / activation
let navigationKeyCodes: Set<UInt16> = [
123, // left arrow
124, // right arrow
125, // down arrow
126, // up arrow
53, // escape
49, // space
48, // tab
]
if navigationKeyCodes.contains(event.keyCode) {
return false
}
// Don't forward Cmd-key shortcuts (Cmd+A, Cmd+C, etc.)
if event.modifierFlags.contains(.command) {
return false
}
// Forward if the key produces printable characters
if let chars = event.characters, !chars.isEmpty {
return true
}
return false
}
}
// MARK: - Model Picker Menu Builder
struct ModelPickerMenu {
let selectedModel: LLMModel?
let copilotModels: [LLMModel]
let byokModels: [LLMModel]
let isBYOKFFEnabled: Bool
let currentCache: ScopeCache
let fontScale: Double
private let detailPanel = ModelPickerDetailPanel.shared
func showMenu(relativeTo button: NSButton) {
let menu = createMenu(allCopilotModels: copilotModels, allBYOKModels: byokModels)
let buttonFrame = button.frame
let menuOrigin = NSPoint(x: buttonFrame.minX, y: buttonFrame.maxY)
menu.popUp(positioning: nil, at: menuOrigin, in: button.superview)
detailPanel.orderOut(nil)
}
private func createMenu(
allCopilotModels: [LLMModel],
allBYOKModels: [LLMModel]
) -> NSMenu {
let menu = ModelPickerNSMenu()
menu.autoenablesItems = false
let maxWidth = calculateMaxWidth(
copilotModels: allCopilotModels,
byokModels: allBYOKModels
)
// Search bar at top (sized to match content)
let searchItem = NSMenuItem()
let searchView = ModelSearchFieldView(fontScale: fontScale, width: maxWidth)
searchView.parentMenu = menu
searchItem.view = searchView
menu.addItem(searchItem)
menu.searchField = searchView.searchField
// Separator after search
menu.addItem(.separator())
// Build initial menu items
rebuildMenuItems(
menu: menu,
copilotModels: allCopilotModels,
byokModels: allBYOKModels,
maxWidth: maxWidth,
searchText: ""
)
// Handle search
searchView.onSearchTextChanged = { [weak menu] searchText in
guard let menu = menu else { return }
self.rebuildMenuItems(
menu: menu,
copilotModels: allCopilotModels,
byokModels: allBYOKModels,
maxWidth: maxWidth,
searchText: searchText
)
}
return menu
}
private func rebuildMenuItems(
menu: NSMenu,
copilotModels: [LLMModel],
byokModels: [LLMModel],
maxWidth: CGFloat,
searchText: String
) {
// Remove all items except the search bar and separator (first 2 items)
while menu.items.count > 2 {
menu.removeItem(at: menu.items.count - 1)
}
let query = searchText.lowercased().trimmingCharacters(in: .whitespaces)
let filteredCopilotModels: [LLMModel]
let filteredBYOKModels: [LLMModel]
if query.isEmpty {
filteredCopilotModels = copilotModels
filteredBYOKModels = byokModels
} else {
filteredCopilotModels = copilotModels.filter {
($0.displayName ?? $0.modelName).lowercased().contains(query)
|| $0.modelFamily.lowercased().contains(query)
}
filteredBYOKModels = byokModels.filter {
($0.displayName ?? $0.modelName).lowercased().contains(query)
|| $0.modelFamily.lowercased().contains(query)
|| ($0.providerName ?? "").lowercased().contains(query)
}
}
let premiumModels = filteredCopilotModels.filter { $0.isPremiumModel }
let standardModels = filteredCopilotModels.filter {
$0.isStandardModel && !$0.isAutoModel
}
let autoModel = filteredCopilotModels.first(where: { $0.isAutoModel })
// Auto model
if let autoModel = autoModel {
addModelItem(
to: menu, model: autoModel, maxWidth: maxWidth
)
}
// Standard models section
addSection(
to: menu, title: "Standard Models", models: standardModels,
maxWidth: maxWidth
)
// Premium models section
addSection(
to: menu, title: "Premium Models", models: premiumModels,
maxWidth: maxWidth
)
// BYOK models section
if isBYOKFFEnabled {
addSection(
to: menu, title: "Other Models", models: filteredBYOKModels,
maxWidth: maxWidth
)
if query.isEmpty {
menu.addItem(.separator())
let manageItem = NSMenuItem(
title: "Manage Models...",
action: #selector(ModelPickerMenuActions.manageModels),
keyEquivalent: ""
)
manageItem.target = ModelPickerMenuActions.shared
menu.addItem(manageItem)
}
}
if standardModels.isEmpty, premiumModels.isEmpty, autoModel == nil,
filteredBYOKModels.isEmpty
{
if query.isEmpty {
let addItem = NSMenuItem(
title: "Add Premium Models",
action: #selector(ModelPickerMenuActions.addPremiumModels),
keyEquivalent: ""
)
addItem.target = ModelPickerMenuActions.shared
menu.addItem(addItem)
} else {
let noResults = NSMenuItem(title: "No models found", action: nil, keyEquivalent: "")
noResults.isEnabled = false
menu.addItem(noResults)
}
}
}
private func addSection(
to menu: NSMenu,
title: String,
models: [LLMModel],
maxWidth: CGFloat
) {
guard !models.isEmpty else { return }
// Section header
menu.addItem(.separator())
let headerItem = NSMenuItem(title: title, action: nil, keyEquivalent: "")
headerItem.isEnabled = false
let headerFont = NSFont.systemFont(ofSize: 11 * fontScale, weight: .semibold)
headerItem.attributedTitle = NSAttributedString(
string: title,
attributes: [
.font: headerFont,
.foregroundColor: NSColor.secondaryLabelColor,
]
)
menu.addItem(headerItem)
for model in models {
addModelItem(to: menu, model: model, maxWidth: maxWidth)
}
}
private func addModelItem(
to menu: NSMenu,
model: LLMModel,
maxWidth: CGFloat
) {
let item = NSMenuItem()
let multiplierText = currentCache
.modelMultiplierCache[model.id.appending(model.providerName ?? "")]
?? ModelMenuItemFormatter.getMultiplierText(for: model)
let menuItemView = ModelPickerMenuItem(
model: model,
isSelected: selectedModel == model,
multiplierText: multiplierText,
fontScale: fontScale,
fixedWidth: maxWidth,
onSelect: {
AppState.shared.setSelectedModel(model)
menu.cancelTracking()
self.detailPanel.orderOut(nil)
},
onHover: { hoveredModel, itemRect in
self.detailPanel.show(
for: hoveredModel,
nearRect: itemRect,
fontScale: self.fontScale
)
},
onHoverExit: {
self.detailPanel.scheduleHide()
}
)
item.view = menuItemView
menu.addItem(item)
}
private func calculateMaxWidth(
copilotModels: [LLMModel],
byokModels: [LLMModel]
) -> CGFloat {
var maxWidth: CGFloat = 0
let allModels = isBYOKFFEnabled ? copilotModels + byokModels : copilotModels
for model in allModels {
let multiplierText = currentCache
.modelMultiplierCache[model.id.appending(model.providerName ?? "")]
?? ModelMenuItemFormatter.getMultiplierText(for: model)
let width = ModelPickerMenuItem.calculateItemWidth(
model: model,
multiplierText: multiplierText,
fontScale: fontScale
)
maxWidth = max(maxWidth, width)
}
return maxWidth
}
}
// MARK: - Menu Action Target
private class ModelPickerMenuActions: NSObject {
static let shared = ModelPickerMenuActions()
@objc func manageModels() {
try? launchHostAppBYOKSettings()
}
@objc func addPremiumModels() {
if let url = URL(string: "https://aka.ms/github-copilot-upgrade-plan") {
NSWorkspace.shared.open(url)
}
}
}