agent-command-tab 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. agent_command_tab/__init__.py +4 -0
  2. agent_command_tab/agent_adapters/__init__.py +48 -0
  3. agent_command_tab/agent_adapters/base.py +162 -0
  4. agent_command_tab/agent_adapters/claude_code.py +120 -0
  5. agent_command_tab/agent_adapters/codex.py +102 -0
  6. agent_command_tab/agent_adapters/generic.py +22 -0
  7. agent_command_tab/agent_process_tree.py +557 -0
  8. agent_command_tab/agent_session_pausing.py +254 -0
  9. agent_command_tab/app_controller.py +947 -0
  10. agent_command_tab/claude_code_transcript_records.py +75 -0
  11. agent_command_tab/command_line.py +187 -0
  12. agent_command_tab/context_window_usage.py +230 -0
  13. agent_command_tab/dashboard_core_api.py +57 -0
  14. agent_command_tab/docked_window_frames_store.py +60 -0
  15. agent_command_tab/global_shortcut_key_filter.py +167 -0
  16. agent_command_tab/hook_event_forwarder.py +116 -0
  17. agent_command_tab/hook_event_tracking.py +129 -0
  18. agent_command_tab/hook_states_store.py +60 -0
  19. agent_command_tab/hooks_installer.py +300 -0
  20. agent_command_tab/installed_copy_paths.py +41 -0
  21. agent_command_tab/iterm2_actions.py +325 -0
  22. agent_command_tab/iterm2_connection_thread.py +2299 -0
  23. agent_command_tab/iterm2_snapshot_builder.py +403 -0
  24. agent_command_tab/list_sorting.py +117 -0
  25. agent_command_tab/messages_between_agent_sessions.py +78 -0
  26. agent_command_tab/monitor_assignment.py +109 -0
  27. agent_command_tab/pause_records_store.py +61 -0
  28. agent_command_tab/screen_readings.py +108 -0
  29. agent_command_tab/session_preview_computation.py +228 -0
  30. agent_command_tab/session_status_computation.py +235 -0
  31. agent_command_tab/settings_store.py +292 -0
  32. agent_command_tab/snapshot_data_classes.py +145 -0
  33. agent_command_tab/start_with_iterm2.py +138 -0
  34. agent_command_tab/tab_order_computation.py +26 -0
  35. agent_command_tab/user_interface/__init__.py +1 -0
  36. agent_command_tab/user_interface/agent_session_outline_view.py +2120 -0
  37. agent_command_tab/user_interface/agent_tool_icons.py +124 -0
  38. agent_command_tab/user_interface/app_icon.py +75 -0
  39. agent_command_tab/user_interface/control_helpers.py +38 -0
  40. agent_command_tab/user_interface/list_window.py +116 -0
  41. agent_command_tab/user_interface/menu_bar_status_item.py +193 -0
  42. agent_command_tab/user_interface/named_colors.py +58 -0
  43. agent_command_tab/user_interface/pointing_hand_button.py +42 -0
  44. agent_command_tab/user_interface/popover_container.py +461 -0
  45. agent_command_tab/user_interface/row_text_rendering.py +342 -0
  46. agent_command_tab/user_interface/screen_layout.py +91 -0
  47. agent_command_tab/user_interface/settings_window.py +530 -0
  48. agent_command_tab/user_interface/sidebar_panel.py +486 -0
  49. agent_command_tab/user_interface/sidebar_placement.py +105 -0
  50. agent_command_tab/user_interface/talk_to_each_other_alert.py +130 -0
  51. agent_command_tab/window_list_ordering.py +44 -0
  52. agent_command_tab-0.1.0.dist-info/METADATA +85 -0
  53. agent_command_tab-0.1.0.dist-info/RECORD +57 -0
  54. agent_command_tab-0.1.0.dist-info/WHEEL +5 -0
  55. agent_command_tab-0.1.0.dist-info/entry_points.txt +2 -0
  56. agent_command_tab-0.1.0.dist-info/licenses/LICENSE +21 -0
  57. agent_command_tab-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,530 @@
1
+ """The settings window. Every change applies at once and is saved.
2
+
3
+ Settings are added here as the features that use them are built (see settings_store).
4
+ """
5
+
6
+ import collections
7
+ import threading
8
+
9
+ import objc
10
+ from AppKit import (NSApp, NSBackingStoreBuffered, NSBox, NSBoxCustom, NSBoxSeparator, NSButton,
11
+ NSColor, NSControlSizeMini, NSControlSizeSmall, NSFont, NSMakeRect, NSNoTitle, NSNormalWindowLevel,
12
+ NSPopUpButton, NSScreen, NSScrollView, NSSwitch, NSTextField, NSView, NSViewMinXMargin, NSViewWidthSizable,
13
+ NSWindow, NSWindowOcclusionStateVisible, NSWindowStyleMaskClosable,
14
+ NSWindowStyleMaskResizable, NSWindowStyleMaskTitled, NSWorkspace)
15
+ from Foundation import NSURL
16
+ from PyObjCTools import AppHelper
17
+
18
+ from agent_command_tab.settings_store import (LIST_COLUMNS, SMALLEST_WINDOW_SIZES, find_launch_command_problem,
19
+ is_valid_setting_value, replace_agent_tool_field)
20
+ from agent_command_tab.user_interface.agent_session_outline_view import COLUMN_TITLES
21
+ from agent_command_tab.user_interface.control_helpers import add_popup_choices, read_popup_choice, select_popup_choice
22
+ from agent_command_tab.user_interface.named_colors import make_light_and_dark_mode_color_maker
23
+ from agent_command_tab.user_interface.screen_layout import (WindowFrameSavingController,
24
+ place_window_at_saved_frame_or_center,
25
+ read_monitors_from_screens)
26
+ from agent_command_tab.user_interface.sidebar_placement import (describe_sidebar_placement_fallback,
27
+ find_outer_screen_edges)
28
+
29
+ WINDOW_WIDTH = SMALLEST_WINDOW_SIZES["settings_window_frame"][0] # the rows' layout width; the window only gets wider
30
+ # The look of macOS's System Settings (user request, 2026-10-28; a bold title and a line across over
31
+ # rows of right-aligned labels and controls 30 points apart before): each section's rows in a rounded
32
+ # box under its title, each row's label at the left and its control at the right, thin lines between rows.
33
+ SIDE_MARGIN = 20 # from the window's sides to the boxes
34
+ TOP_MARGIN = 16 # above the first section's title
35
+ SECTION_TITLE_HEIGHT = 18
36
+ GAP_BELOW_SECTION_TITLE = 6
37
+ GAP_BETWEEN_SECTIONS = 20 # from a box, or the note under it, to the next section's title
38
+ # Below the last box, down to the window's bottom edge (24 below the last control until 2026-10-28; it is 27 now).
39
+ ROOM_BELOW_THE_LAST_SECTION = 20
40
+ ROW_HEIGHT = 36
41
+ ROW_PADDING = 10 # from a box's sides to the labels and controls in it
42
+ INDENT_OF_A_ROW_THAT_CONTINUES_THE_ONE_ABOVE = 16 # a harness's command, under the harness's name
43
+ GAP_BEFORE_UNITS = 6 # between a control and its units ("points")
44
+ BOX_CORNER_RADIUS = 8
45
+ MINI_SWITCH_SIZE = (26, 15) # what a mini NSSwitch draws (checked on macOS 27)
46
+ NOTE_HEIGHT = 30 # the sidebar's placement note under its box: two lines of small text
47
+ LAUNCH_COMMAND_FIELD_WIDTH = 360 # a longer command scrolls inside the field (user requests, 2026-10-25; 200 until 2026-10-28)
48
+ # A box's fill and border: a little darker than the window in light mode, a little lighter in dark mode.
49
+ make_section_box_fill_color = make_light_and_dark_mode_color_maker(
50
+ lambda: NSColor.colorWithSRGBRed_green_blue_alpha_(0, 0, 0, 0.03), lambda: NSColor.colorWithSRGBRed_green_blue_alpha_(1, 1, 1, 0.04))
51
+ make_section_box_border_color = make_light_and_dark_mode_color_maker(
52
+ lambda: NSColor.colorWithSRGBRed_green_blue_alpha_(0, 0, 0, 0.08), lambda: NSColor.colorWithSRGBRed_green_blue_alpha_(1, 1, 1, 0.08))
53
+ # The titles of the choices in settings_store (SHOW_AS_CHOICES, GLOBAL_SHORTCUT_CHOICES,
54
+ # APPEARANCE_CHOICES, SIDEBAR_MODES, SIDEBAR_EDGES), and the columns of LIST_COLUMNS in the
55
+ # settings' order; setting_choice_titles_tests checks that each table names every choice.
56
+ SHOW_AS_TITLES = {"popup": "Popup", "sidebar": "Sidebar", "window": "Window"}
57
+ GLOBAL_SHORTCUT_TITLES = {"shift_command_tab": "Shift-Command-Tab", "command_fn_tab": "Command-Fn-Tab", "off": "Off"}
58
+ APPEARANCE_TITLES = {"auto": "Auto", "dark": "Dark", "light": "Light"} # in the user's order (user request, 2026-10-27)
59
+ # System Settings > Privacy & Security > Accessibility, which the global shortcut's key filter needs.
60
+ ACCESSIBILITY_SETTINGS_URL = "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility"
61
+ SIDEBAR_MODE_TITLES = {
62
+ "auto_hide": "Auto-hide",
63
+ "floating": "Always: Above other windows",
64
+ "docked": "Always: Resize iTerm2 windows",
65
+ }
66
+ SIDEBAR_EDGE_TITLES = {"right": "Right", "left": "Left"}
67
+ # The tab rows' information columns, in the order the user listed them (user request, 2026-10-19).
68
+ # Each is labeled with the title over its column in the list (COLUMN_TITLES; user request, 2026-10-28:
69
+ # "Time Since Last Status Change", "Tokens Used" and the like until then).
70
+ LIST_COLUMN_NAMES_IN_SETTINGS_ORDER = ["state", "state_duration", "context_tokens", "created_time", "existence_duration",
71
+ "memory_usage", "cpu_usage"]
72
+ # One row in a section's box: its label at the left, its control at the right, and the units after the
73
+ # control. A row that continues the one above it (a harness's command; the accessibility button under
74
+ # the shortcut) has no line above it, and its label is indented.
75
+ SettingsRow = collections.namedtuple("SettingsRow", ["label", "control", "units", "continues_the_row_above"],
76
+ defaults=[None, False])
77
+ # A titled section of the window (user request, 2026-10-19): its rows in a rounded box under its title,
78
+ # and, for the sidebar, a note in small text under the box, which takes no room while it is empty.
79
+ SettingsSection = collections.namedtuple("SettingsSection", ["title", "rows", "note_field"], defaults=[None])
80
+
81
+
82
+ class FlippedView(NSView):
83
+ """A view whose y grows downward, so rows laid out from its top stay at the top of a scroll view."""
84
+
85
+ def isFlipped(self):
86
+ return True
87
+
88
+
89
+ class SettingsWindowController(WindowFrameSavingController):
90
+ """Builds the settings window and reports each change to the owner's settings_changed(settings),
91
+ its moves and resizes to window_frame_changed("settings_window_frame", frame), and its closing
92
+ to settings_window_closed()."""
93
+
94
+ frame_setting_name = "settings_window_frame"
95
+
96
+ def initWithOwner_(self, owner):
97
+ self = objc.super(SettingsWindowController, self).init()
98
+ if self is None:
99
+ return None
100
+ self.owner = owner
101
+ self.settings = None
102
+ self.window = None
103
+ return self
104
+
105
+ @objc.python_method
106
+ def show(self, settings):
107
+ """Opens (or brings forward) the window showing these settings, at its last frame while
108
+ that is on a connected screen, else in the middle of the main screen, as tall as its rows."""
109
+ self.settings = dict(settings)
110
+ if self.window is not None:
111
+ self.window.close()
112
+ self.window = self.build_window()
113
+ place_window_at_saved_frame_or_center(self.window, settings["settings_window_frame"])
114
+ # The saved height can be from other sections, shown for another "Show as", or from older margins.
115
+ self.fit_window_height_to_rows()
116
+ NSApp.activateIgnoringOtherApps_(True)
117
+ self.window.makeKeyAndOrderFront_(None)
118
+
119
+ @objc.python_method
120
+ def is_open(self):
121
+ return self.window is not None and bool(self.window.isVisible())
122
+
123
+ @objc.python_method
124
+ def close_if_open(self):
125
+ """Closes the window as its close button does (windowWillClose_ saves a field being typed in)."""
126
+ if self.is_open():
127
+ self.window.close()
128
+
129
+ @objc.python_method
130
+ def set_window_level(self, window_level):
131
+ """Puts the window at this level (above an open dropdown), or back at the normal level for None."""
132
+ if self.window is not None:
133
+ self.window.setLevel_(window_level if window_level is not None else NSNormalWindowLevel)
134
+
135
+ def windowDidResize_(self, notification):
136
+ # A scroll view doesn't widen what it holds, so the rows follow the window's width here
137
+ # (the boxes, the lines between rows and the sidebar's placement note then widen, and the
138
+ # controls move with the boxes' right ends, through their autoresizing).
139
+ self.rows_view.setFrameSize_((self.window.contentView().contentSize().width, self.rows_view.frame().size.height))
140
+
141
+ def windowWillClose_(self, notification):
142
+ if notification.object() is self.window:
143
+ # However it closes: a launch command or width being typed is saved as its field stops editing.
144
+ self.window.makeFirstResponder_(None)
145
+ AppHelper.callAfter(self.owner.settings_window_closed) # once it is no longer visible
146
+
147
+ def windowDidChangeOcclusionState_(self, notification):
148
+ """Closes the window once no part of it shows: other windows cover it, or it is on another
149
+ desktop, or the screen is locked (user request, 2026-10-25). Each setting is saved as it
150
+ changes, and a field being typed in as the window closes (windowWillClose_)."""
151
+ window = notification.object()
152
+ if window is self.window and window.isVisible() and not window.occlusionState() & NSWindowOcclusionStateVisible:
153
+ window.close()
154
+
155
+ # ----- building -----
156
+
157
+ @objc.python_method
158
+ def build_window(self):
159
+ # A pop-up, as the keyboard shortcut's is (radio buttons until 2026-10-26, user request).
160
+ self.show_as_popup = self.make_popup(SHOW_AS_TITLES, self.settings["show_as"])
161
+ self.global_shortcut_popup = self.make_popup(GLOBAL_SHORTCUT_TITLES, self.settings["global_shortcut"])
162
+ self.global_shortcut_popup.setToolTip_("Shows AgentCommandTab, and hides it when pressed again.") # the user's wording, 2026-10-28
163
+ # Shown, in a row of its own under the shortcut, only while macOS refuses the shortcut's key filter.
164
+ self.accessibility_settings_button = NSButton.buttonWithTitle_target_action_(
165
+ "Needs Accessibility: Open System Settings…", self, "openAccessibilitySettingsClicked:")
166
+ self.accessibility_settings_button.setControlSize_(NSControlSizeSmall)
167
+ self.accessibility_settings_button.setFont_(NSFont.systemFontOfSize_(NSFont.smallSystemFontSize()))
168
+ self.accessibility_settings_button.sizeToFit()
169
+ self.accessibility_settings_button.setToolTip_( # the user's wording, 2026-10-28
170
+ "The shortcut sees key presses before the app switcher does, which needs Accessibility permissions. "
171
+ "Turn it on for the app that starts AgentCommandTab (iTerm2, when you start it from iTerm2), then click "
172
+ "the menu bar icon")
173
+ self.update_accessibility_settings_button()
174
+ self.appearance_popup = self.make_popup(APPEARANCE_TITLES, self.settings["appearance"])
175
+ # "The menu bar icon keeps the menu bar's own look" after it until 2026-10-28 (user request).
176
+ self.appearance_popup.setToolTip_("Auto follows the Light or Dark setting in System Settings > Appearance")
177
+ self.start_with_iterm2_switch = self.make_switch(self.settings["app_starts_with_iterm2"])
178
+ self.start_with_iterm2_switch.setToolTip_("Starts AgentCommandTab whenever iTerm2 starts, through a script in "
179
+ "iTerm2's AutoLaunch folder, so it has iTerm2's permissions")
180
+ self.sidebar_mode_popup = self.make_popup(SIDEBAR_MODE_TITLES, self.settings["sidebar_mode"])
181
+ self.edge_popup = self.make_popup(SIDEBAR_EDGE_TITLES, self.settings["sidebar_edge"])
182
+ self.sidebar_width_field = self.make_text_field(str(int(self.settings["sidebar_width"])), 80)
183
+ # Switches, as System Settings has, for the on/off settings (checkboxes until 2026-10-28, user request).
184
+ self.column_switches = {column_name: self.make_switch(column_name in self.settings["shown_columns"])
185
+ for column_name in LIST_COLUMN_NAMES_IN_SETTINGS_ORDER}
186
+ self.edge_note = NSTextField.wrappingLabelWithString_("")
187
+ self.edge_note.setFont_(NSFont.systemFontOfSize_(NSFont.smallSystemFontSize()))
188
+ self.edge_note.setTextColor_(NSColor.secondaryLabelColor())
189
+ # A General section first: "Show as", the keyboard shortcut with its accessibility button
190
+ # under it, then Appearance (user requests, 2026-10-25 to 2026-10-27; Appearance last, the
191
+ # user's choice over after "Show as"), then Start with iTerm2 (user request, 2026-10-28).
192
+ general_section = SettingsSection("General", [
193
+ SettingsRow("Show as", self.show_as_popup), SettingsRow("Keyboard shortcut", self.global_shortcut_popup),
194
+ SettingsRow(None, self.accessibility_settings_button, continues_the_row_above=True),
195
+ SettingsRow("Appearance", self.appearance_popup), SettingsRow("Start with iTerm2", self.start_with_iterm2_switch)])
196
+ self.list_window_always_on_top_switch = self.make_switch(self.settings["list_window_is_always_on_top"])
197
+ window_section = SettingsSection("Window", [SettingsRow("Always on top", self.list_window_always_on_top_switch)])
198
+ sidebar_section = SettingsSection("Sidebar", [
199
+ SettingsRow("Show", self.sidebar_mode_popup), SettingsRow("Window edge", self.edge_popup),
200
+ SettingsRow("Width", self.sidebar_width_field, "points")], self.edge_note)
201
+ # The columns in a section of their own, above Harnesses (user request, 2026-10-25).
202
+ # A title on two lines in the list (a "\n" between them) is on one here.
203
+ columns_section = SettingsSection("Columns", [SettingsRow(COLUMN_TITLES[column_name].replace("\n", " "), column_switch)
204
+ for column_name, column_switch in self.column_switches.items()])
205
+ # Each agent tool: whether it is used, and below that, indented, its launch command (user request, 2026-10-19).
206
+ self.include_switches = []
207
+ self.launch_command_fields = []
208
+ harness_rows = []
209
+ for agent_tool in self.settings["agent_tools"]:
210
+ include_switch = self.make_switch(agent_tool["is_included"])
211
+ self.include_switches.append(include_switch)
212
+ # Right-aligned, so the command fields start together (user request, 2026-10-25).
213
+ launch_command_field = self.make_text_field(agent_tool["launch_command"], LAUNCH_COMMAND_FIELD_WIDTH)
214
+ self.launch_command_fields.append(launch_command_field)
215
+ harness_rows += [SettingsRow(agent_tool["agent_tool_name"], include_switch),
216
+ SettingsRow("Command", launch_command_field, continues_the_row_above=True)]
217
+ # The Window section shows only while "Show as" is Window, and the Sidebar section only while
218
+ # it is Sidebar (user request, 2026-10-27); the sidebar shown for a few seconds from the menu
219
+ # bar icon's menu's "Show sidebar" still uses the Sidebar section's edge and width. Each
220
+ # section: (the "Show as" choice it shows for, or None for every choice, the section).
221
+ self.sections = [(None, general_section), ("window", window_section), ("sidebar", sidebar_section),
222
+ (None, columns_section), (None, SettingsSection("Harnesses", harness_rows))]
223
+ self.update_edge_choices()
224
+ self.show_placement_fallback_note(self.settings)
225
+
226
+ # Resizable, with the rows in a scroll view, so a window made shorter than its rows scrolls
227
+ # (user request, 2026-10-19). The rows' view is flipped: rows go from the top down.
228
+ rows_view = FlippedView.alloc().initWithFrame_(NSMakeRect(0, 0, WINDOW_WIDTH, 0))
229
+ self.rows_view = rows_view
230
+ self.lay_out_sections(self.settings["show_as"])
231
+ rows_height = rows_view.frame().size.height
232
+ scroll_view = NSScrollView.alloc().initWithFrame_(NSMakeRect(0, 0, WINDOW_WIDTH, rows_height))
233
+ scroll_view.setHasVerticalScroller_(True)
234
+ scroll_view.setAutohidesScrollers_(True)
235
+ scroll_view.setDrawsBackground_(False)
236
+ scroll_view.setDocumentView_(rows_view)
237
+ window = NSWindow.alloc().initWithContentRect_styleMask_backing_defer_(
238
+ NSMakeRect(0, 0, WINDOW_WIDTH, rows_height),
239
+ NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskResizable, NSBackingStoreBuffered, False)
240
+ window.setTitle_("AgentCommandTab Settings")
241
+ window.setReleasedWhenClosed_(False)
242
+ window.setContentView_(scroll_view)
243
+ window.setMinSize_(SMALLEST_WINDOW_SIZES["settings_window_frame"])
244
+ window.setDelegate_(self)
245
+ for launch_command_field in self.launch_command_fields:
246
+ self.check_launch_command(launch_command_field)
247
+ return window
248
+
249
+ @objc.python_method
250
+ def find_what_the_layout_depends_on(self, show_as):
251
+ """The things that change which rows are laid out: the "Show as" choice (which sections show),
252
+ whether the accessibility button shows, and whether the sidebar's note says something."""
253
+ return show_as, bool(self.accessibility_settings_button.isHidden()), not self.edge_note.stringValue()
254
+
255
+ @objc.python_method
256
+ def lay_out_sections(self, show_as):
257
+ """Lays out, from the top of rows_view, every section shown for this "Show as" choice, in
258
+ place of what is there, and makes rows_view as tall as they need."""
259
+ for subview in list(self.rows_view.subviews()):
260
+ subview.removeFromSuperview()
261
+ top = TOP_MARGIN
262
+ for shown_for_show_as, section in self.sections:
263
+ if shown_for_show_as in (None, show_as):
264
+ top = self.add_section(self.rows_view, section, top) + GAP_BETWEEN_SECTIONS
265
+ self.rows_view.setFrameSize_((self.rows_view.frame().size.width,
266
+ top - GAP_BETWEEN_SECTIONS + ROOM_BELOW_THE_LAST_SECTION))
267
+ self.layout_depended_on = self.find_what_the_layout_depends_on(show_as)
268
+
269
+ @objc.python_method
270
+ def lay_out_sections_again_if_needed(self, show_as):
271
+ """Lays the sections out again, and fits the window's height to them, once a section shows
272
+ or hides, or the accessibility button or the sidebar's note does."""
273
+ if self.find_what_the_layout_depends_on(show_as) == self.layout_depended_on:
274
+ return
275
+ # A width being typed is saved first, as when the window closes: its field would end
276
+ # editing, and save, as it is taken out during the layout.
277
+ self.window.makeFirstResponder_(None)
278
+ self.lay_out_sections(show_as)
279
+ self.window.recalculateKeyViewLoop() # Tab goes through the fields shown now (code review, 2026-10-27)
280
+ self.fit_window_height_to_rows()
281
+
282
+ @objc.python_method
283
+ def fit_window_height_to_rows(self):
284
+ """Makes the window as tall as its rows, keeping its top edge and its width, but no taller
285
+ than the room below its top on its screen, where the rows then scroll (user request,
286
+ 2026-10-27, over keeping the window's height)."""
287
+ frame = self.window.frame()
288
+ top = frame.origin.y + frame.size.height
289
+ height = self.window.frameRectForContentRect_(
290
+ NSMakeRect(0, 0, frame.size.width, self.rows_view.frame().size.height)).size.height
291
+ screen = self.window.screen() or NSScreen.mainScreen()
292
+ if screen is not None:
293
+ height = min(height, top - screen.visibleFrame().origin.y)
294
+ self.window.setFrame_display_(NSMakeRect(frame.origin.x, top - height, frame.size.width, height), True)
295
+
296
+ @objc.python_method
297
+ def add_section(self, rows_view, section, top):
298
+ """Adds a section at top (rows_view is flipped): its bold title, its rows in a rounded box
299
+ under it, and its note under the box while the note says something. A row whose control is
300
+ hidden (the accessibility button) takes no room. Returns the bottom of what it added."""
301
+ box_width = rows_view.frame().size.width - 2 * SIDE_MARGIN # a wider window's too
302
+ title_field = NSTextField.labelWithString_(section.title)
303
+ title_field.setFont_(NSFont.boldSystemFontOfSize_(NSFont.systemFontSize()))
304
+ title_field.setFrame_(NSMakeRect(SIDE_MARGIN, top, title_field.fittingSize().width, SECTION_TITLE_HEIGHT))
305
+ rows_view.addSubview_(title_field)
306
+ rows = [row for row in section.rows if not row.control.isHidden()]
307
+ box_top = top + SECTION_TITLE_HEIGHT + GAP_BELOW_SECTION_TITLE
308
+ box = NSBox.alloc().initWithFrame_(NSMakeRect(SIDE_MARGIN, box_top, box_width, ROW_HEIGHT * len(rows)))
309
+ box.setBoxType_(NSBoxCustom)
310
+ box.setTitlePosition_(NSNoTitle)
311
+ box.setCornerRadius_(BOX_CORNER_RADIUS)
312
+ box.setBorderWidth_(1)
313
+ box.setBorderColor_(make_section_box_border_color())
314
+ box.setFillColor_(make_section_box_fill_color())
315
+ box.setAutoresizingMask_(NSViewWidthSizable) # reaches the right margin of a wider window
316
+ rows_view.addSubview_(box)
317
+ for index, row in enumerate(rows):
318
+ row_top = box_top + ROW_HEIGHT * index
319
+ if index > 0 and not row.continues_the_row_above:
320
+ line = NSBox.alloc().initWithFrame_(NSMakeRect(SIDE_MARGIN + ROW_PADDING, row_top, box_width - 2 * ROW_PADDING, 1))
321
+ line.setBoxType_(NSBoxSeparator)
322
+ line.setAutoresizingMask_(NSViewWidthSizable)
323
+ rows_view.addSubview_(line)
324
+ self.add_row(rows_view, row, row_top, SIDE_MARGIN + box_width - ROW_PADDING)
325
+ bottom = box_top + ROW_HEIGHT * len(rows)
326
+ if section.note_field is not None and section.note_field.stringValue():
327
+ section.note_field.setFrame_(NSMakeRect(SIDE_MARGIN + ROW_PADDING, bottom + 4, box_width - 2 * ROW_PADDING, NOTE_HEIGHT))
328
+ section.note_field.setAutoresizingMask_(NSViewWidthSizable)
329
+ rows_view.addSubview_(section.note_field)
330
+ bottom += 4 + NOTE_HEIGHT
331
+ return bottom
332
+
333
+ @objc.python_method
334
+ def add_row(self, rows_view, row, top, right):
335
+ """Adds a row's label at the left of its box and its control, then its units, ending at
336
+ right, each centered in the row's height. The control and units stay at the box's right
337
+ end as the window widens."""
338
+ if row.units is not None:
339
+ units_field = NSTextField.labelWithString_(row.units)
340
+ units_size = units_field.fittingSize()
341
+ right -= units_size.width
342
+ units_field.setFrame_(NSMakeRect(right, top + round((ROW_HEIGHT - units_size.height) / 2), units_size.width,
343
+ units_size.height))
344
+ units_field.setAutoresizingMask_(NSViewMinXMargin)
345
+ rows_view.addSubview_(units_field)
346
+ right -= GAP_BEFORE_UNITS
347
+ # Placed by what it draws (its alignment rect), so pop-ups, switches and fields end at the same x
348
+ # though their frames have different margins around it. The margins are applied here, since
349
+ # frameForAlignmentRect_ puts a control's top margin at its bottom in a flipped view.
350
+ margins = row.control.alignmentRectInsets()
351
+ frame_size = row.control.frame().size
352
+ drawn_width = frame_size.width - margins.left - margins.right
353
+ drawn_top = top + round((ROW_HEIGHT - (frame_size.height - margins.top - margins.bottom)) / 2)
354
+ row.control.setFrameOrigin_((right - drawn_width - margins.left, drawn_top - margins.top))
355
+ row.control.setAutoresizingMask_(NSViewMinXMargin)
356
+ rows_view.addSubview_(row.control)
357
+ if row.label is not None:
358
+ label_field = NSTextField.labelWithString_(row.label)
359
+ label_size = label_field.fittingSize()
360
+ if isinstance(row.control, NSSwitch):
361
+ label_top = top + round((ROW_HEIGHT - label_size.height) / 2)
362
+ else: # on the same baseline as the control's text
363
+ label_top = drawn_top + row.control.firstBaselineOffsetFromTop() - label_field.firstBaselineOffsetFromTop()
364
+ indent = INDENT_OF_A_ROW_THAT_CONTINUES_THE_ONE_ABOVE if row.continues_the_row_above else 0
365
+ label_field.setFrame_(NSMakeRect(SIDE_MARGIN + ROW_PADDING + indent, label_top, *label_size))
366
+ rows_view.addSubview_(label_field)
367
+
368
+ @objc.python_method
369
+ def make_switch(self, is_on):
370
+ switch = NSSwitch.alloc().init()
371
+ switch.setControlSize_(NSControlSizeMini) # the size System Settings' switches have
372
+ # A switch reports the regular size whatever its control size, and draws a mini one in the
373
+ # middle of that, so its frame is made to fit what it draws: it then lines up at the right.
374
+ switch.setFrame_(switch.frameForAlignmentRect_(NSMakeRect(0, 0, *MINI_SWITCH_SIZE)))
375
+ switch.setState_(1 if is_on else 0)
376
+ switch.setTarget_(self)
377
+ switch.setAction_("controlChanged:")
378
+ return switch
379
+
380
+ @objc.python_method
381
+ def make_popup(self, titles_by_value, selected_value):
382
+ """Returns a pop-up of a setting's values, titled from titles_by_value, with selected_value chosen."""
383
+ popup = NSPopUpButton.alloc().initWithFrame_pullsDown_(NSMakeRect(0, 0, 240, 24), False)
384
+ add_popup_choices(popup, titles_by_value)
385
+ popup.sizeToFit() # only as wide as its longest item
386
+ select_popup_choice(popup, selected_value)
387
+ popup.setTarget_(self)
388
+ popup.setAction_("controlChanged:")
389
+ return popup
390
+
391
+ @objc.python_method
392
+ def make_text_field(self, text, width):
393
+ text_field = NSTextField.alloc().initWithFrame_(NSMakeRect(0, 0, width, 22))
394
+ text_field.setStringValue_(text)
395
+ text_field.setTarget_(self)
396
+ text_field.setAction_("controlChanged:")
397
+ text_field.cell().setSendsActionOnEndEditing_(True) # also when the field loses focus, not only on Return
398
+ text_field.cell().setScrollable_(True) # a text longer than the field scrolls on one line rather than wrapping
399
+ return text_field
400
+
401
+ # ----- reading the controls -----
402
+
403
+ @objc.python_method
404
+ def update_edge_choices(self):
405
+ """Enables only the outer edges of the menu-bar monitor, where the sidebar goes. When
406
+ neither of its edges is outer (it stands between two monitors), both stay enabled: the
407
+ saved side then picks the outer edge of the monitor nearest it (choose_sidebar_edge)."""
408
+ screens = read_monitors_from_screens()
409
+ outer_edges = ({edge for index, edge in find_outer_screen_edges([screen["frame"] for screen in screens]) if index == 0}
410
+ or {"right", "left"})
411
+ self.edge_popup.setAutoenablesItems_(False)
412
+ for menu_item in self.edge_popup.itemArray():
413
+ menu_item.setEnabled_(menu_item.representedObject() in outer_edges)
414
+ select_popup_choice(self.edge_popup, self.settings["sidebar_edge"]) # back to the saved edge once it is outer again
415
+ if read_popup_choice(self.edge_popup) not in outer_edges:
416
+ select_popup_choice(self.edge_popup, sorted(outer_edges)[-1]) # "right" if it is outer
417
+
418
+ @objc.python_method
419
+ def screen_layout_changed(self):
420
+ """Brings an open window's edge choices and placement note up to date after a monitor was
421
+ connected, disconnected or rearranged; does nothing before the window was first opened."""
422
+ if self.window is None:
423
+ return
424
+ self.update_edge_choices()
425
+ self.show_placement_fallback_note(self.settings)
426
+ self.lay_out_sections_again_if_needed(self.layout_depended_on[0]) # the note can appear or go
427
+
428
+ @objc.python_method
429
+ def show_placement_fallback_note(self, settings):
430
+ """Says where the sidebar is when it can't go where the settings ask."""
431
+ self.edge_note.setStringValue_(describe_sidebar_placement_fallback(settings["sidebar_edge"], read_monitors_from_screens()))
432
+
433
+ def controlChanged_(self, sender):
434
+ """Changes only the setting that sender controls, on top of the app's current settings, so
435
+ a saved edge that can't be used right now (it borders another monitor) and changes made
436
+ elsewhere (a width dragged at the sidebar's edge) are kept."""
437
+ new_settings = dict(self.owner.settings)
438
+ if sender is self.show_as_popup:
439
+ new_settings["show_as"] = read_popup_choice(sender)
440
+ elif sender is self.global_shortcut_popup:
441
+ new_settings["global_shortcut"] = read_popup_choice(sender)
442
+ elif sender is self.appearance_popup:
443
+ new_settings["appearance"] = read_popup_choice(sender)
444
+ elif sender is self.start_with_iterm2_switch:
445
+ new_settings["app_starts_with_iterm2"] = bool(sender.state())
446
+ elif sender is self.sidebar_mode_popup:
447
+ new_settings["sidebar_mode"] = read_popup_choice(sender)
448
+ elif sender is self.edge_popup:
449
+ new_settings["sidebar_edge"] = read_popup_choice(sender)
450
+ elif sender is self.sidebar_width_field:
451
+ self.read_number_field_into_settings(sender, "sidebar_width", new_settings)
452
+ elif sender is self.list_window_always_on_top_switch:
453
+ new_settings["list_window_is_always_on_top"] = bool(sender.state())
454
+ elif sender in self.column_switches.values():
455
+ new_settings["shown_columns"] = [column_name for column_name in LIST_COLUMNS
456
+ if self.column_switches[column_name].state()]
457
+ elif sender in self.launch_command_fields:
458
+ tool_index = self.launch_command_fields.index(sender)
459
+ launch_command = sender.stringValue().strip() or new_settings["agent_tools"][tool_index]["launch_command"]
460
+ sender.setStringValue_(launch_command)
461
+ new_settings["agent_tools"] = replace_agent_tool_field(new_settings["agent_tools"], tool_index, "launch_command",
462
+ launch_command)
463
+ self.check_launch_command(sender)
464
+ elif sender in self.include_switches:
465
+ new_settings["agent_tools"] = replace_agent_tool_field(
466
+ new_settings["agent_tools"], self.include_switches.index(sender), "is_included", bool(sender.state()))
467
+ self.owner.settings_changed(new_settings)
468
+
469
+ def openAccessibilitySettingsClicked_(self, sender):
470
+ NSWorkspace.sharedWorkspace().openURL_(NSURL.URLWithString_(ACCESSIBILITY_SETTINGS_URL))
471
+
472
+ @objc.python_method
473
+ def update_accessibility_settings_button(self):
474
+ """Shows the button that opens the Accessibility settings only while the owner's global
475
+ shortcut lacks that permission."""
476
+ self.accessibility_settings_button.setHidden_(not self.owner.global_shortcut_lacks_permission())
477
+
478
+ @objc.python_method
479
+ def check_launch_command(self, launch_command_field):
480
+ """Checks, off the main thread, that the field's command can be run, then gives the field
481
+ a red border and an explanation if it can't (asking the login shell can take a moment)."""
482
+ launch_command = launch_command_field.stringValue()
483
+
484
+ def check():
485
+ problem = find_launch_command_problem(launch_command)
486
+ AppHelper.callAfter(self.show_launch_command_problem, launch_command_field, launch_command, problem)
487
+ threading.Thread(target=check, name="launch-command-check", daemon=True).start()
488
+
489
+ @objc.python_method
490
+ def show_launch_command_problem(self, launch_command_field, checked_launch_command, problem):
491
+ if launch_command_field.stringValue() != checked_launch_command:
492
+ return # edited since; that edit's own check decides
493
+ launch_command_field.setWantsLayer_(True)
494
+ launch_command_field.layer().setBorderColor_(NSColor.systemRedColor().CGColor())
495
+ launch_command_field.layer().setBorderWidth_(2 if problem else 0)
496
+ launch_command_field.layer().setCornerRadius_(3)
497
+ launch_command_field.setToolTip_(problem or None)
498
+
499
+ @objc.python_method
500
+ def read_number_field_into_settings(self, text_field, setting_name, new_settings):
501
+ """Stores a whole number typed in text_field, or puts the current value back if it isn't valid."""
502
+ try:
503
+ value = int(text_field.stringValue())
504
+ except ValueError:
505
+ value = None
506
+ if is_valid_setting_value(setting_name, value):
507
+ new_settings[setting_name] = value
508
+ else:
509
+ text_field.setStringValue_(str(int(new_settings[setting_name])))
510
+
511
+ @objc.python_method
512
+ def reflect_settings(self, settings):
513
+ """Shows settings changed elsewhere (a width dragged at the sidebar's edge) in an open
514
+ window; does nothing before the window was first opened."""
515
+ if self.window is None:
516
+ self.settings = dict(settings)
517
+ return
518
+ # A width typed but not saved yet is kept (a click on a switch doesn't end its editing);
519
+ # the field saves it once its editing ends. A field that only has the focus, as the first
520
+ # text field does when the window opens, shows the new width.
521
+ width_editor = self.sidebar_width_field.currentEditor()
522
+ width_is_being_typed = width_editor is not None and width_editor.string() != str(int(self.settings["sidebar_width"]))
523
+ self.settings = dict(settings)
524
+ select_popup_choice(self.show_as_popup, settings["show_as"])
525
+ self.update_accessibility_settings_button() # after a shortcut change, or once the permission was given
526
+ self.list_window_always_on_top_switch.setState_(1 if settings["list_window_is_always_on_top"] else 0)
527
+ if not width_is_being_typed:
528
+ self.sidebar_width_field.setStringValue_(str(int(settings["sidebar_width"])))
529
+ self.show_placement_fallback_note(settings)
530
+ self.lay_out_sections_again_if_needed(settings["show_as"])