Rewire Debugger.xib to properties rather than ivars.
[macgdbp.git] / Source / DebuggerController.m
1 /*
2 * MacGDBp
3 * Copyright (c) 2007 - 2011, Blue Static <http://www.bluestatic.org>
4 *
5 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU
6 * General Public License as published by the Free Software Foundation; either version 2 of the
7 * License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
10 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along with this program; if not,
14 * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
15 */
16
17 #import "DebuggerController.h"
18
19 #import "AppDelegate.h"
20 #import "BSSourceView.h"
21 #import "BreakpointController.h"
22 #import "BreakpointManager.h"
23 #import "DebuggerBackEnd.h"
24 #import "DebuggerModel.h"
25 #import "EvalController.h"
26 #import "PreferenceNames.h"
27 #import "NSXMLElementAdditions.h"
28 #import "StackFrame.h"
29
30 @interface DebuggerController (Private)
31 - (void)updateSourceViewer;
32 - (void)expandVariables;
33 @end
34
35 @implementation DebuggerController {
36 DebuggerModel* _model;
37
38 DebuggerBackEnd* _connection;
39
40 BreakpointController* _breakpointsController;
41 EvalController* _evalController;
42
43 NSMutableSet* _expandedVariables;
44 VariableNode* _selectedVariable;
45 }
46
47 /**
48 * Initializes the window controller and sets the connection using preference
49 * values
50 */
51 - (id)init
52 {
53 if (self = [super initWithWindowNibName:@"Debugger"])
54 {
55 NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
56
57 _model = [[DebuggerModel alloc] init];
58 [_model addObserver:self
59 forKeyPath:@"connected"
60 options:NSKeyValueObservingOptionNew
61 context:nil];
62
63 _connection = [[DebuggerBackEnd alloc] initWithPort:[defaults integerForKey:kPrefPort]
64 autoAttach:[defaults boolForKey:kPrefDebuggerAttached]];
65 _connection.model = _model;
66 _model.breakpointManager.connection = _connection;
67
68 [_model addObserver:self
69 forKeyPath:@"status"
70 options:NSKeyValueObservingOptionNew
71 context:nil];
72
73 _expandedVariables = [[NSMutableSet alloc] init];
74 [[self window] makeKeyAndOrderFront:nil];
75 [[self window] setDelegate:self];
76
77 if ([defaults boolForKey:kPrefInspectorWindowVisible])
78 [_inspector orderFront:self];
79 }
80 return self;
81 }
82
83 /**
84 * Dealloc
85 */
86 - (void)dealloc
87 {
88 [_connection release];
89 [_model release];
90 [_breakpointsController release];
91 [_evalController release];
92 [_expandedVariables release];
93
94 [_sourceViewer release];
95 [_inspector release];
96
97 [_attachedCheckbox release];
98 [_stackArrayController release];
99 [_variablesTreeController release];
100 [_variablesOutlineView release];
101
102 [_segmentControl release];
103 [_tabView release];
104
105 [super dealloc];
106 }
107
108 /**
109 * Before the display get's comfortable, set up the NSTextView to scroll horizontally
110 */
111 - (void)awakeFromNib
112 {
113 [[self window] setExcludedFromWindowsMenu:YES];
114 [[self window] setTitle:[NSString stringWithFormat:@"MacGDBp @ %d", [_connection port]]];
115 [_sourceViewer setDelegate:self];
116 [_stackArrayController setSortDescriptors:@[ [[[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES] autorelease] ]];
117 [_stackArrayController addObserver:self
118 forKeyPath:@"selectedObjects"
119 options:NSKeyValueObservingOptionNew
120 context:nil];
121 [_stackArrayController addObserver:self
122 forKeyPath:@"selection.source"
123 options:NSKeyValueObservingOptionNew
124 context:nil];
125 self.connection.autoAttach = [_attachedCheckbox state] == NSOnState;
126
127 // Load view controllers into the tab views.
128 _breakpointsController = [[BreakpointController alloc] initWithBreakpointManager:_model.breakpointManager
129 sourceView:_sourceViewer];
130 [[self.tabView tabViewItemAtIndex:1] setView:_breakpointsController.view];
131
132 _evalController = [[EvalController alloc] initWithBackEnd:_connection];
133 [[self.tabView tabViewItemAtIndex:2] setView:_evalController.view];
134
135 // When the segment control's selection changes, update the tab view.
136 [[_segmentControl cell] addObserver:self
137 forKeyPath:@"selectedSegment"
138 options:0
139 context:nil];
140 // When the segment control's superview changes, recalculate the spacer
141 // segment widths.
142 [[_segmentControl superview] addObserver:self
143 forKeyPath:@"frame"
144 options:0
145 context:nil];
146
147 NSUInteger selectedSegment =
148 [[[NSUserDefaults standardUserDefaults] valueForKey:kPrefSelectedDebuggerSegment] intValue];
149 [[_segmentControl cell] setSelectedSegment:selectedSegment];
150 [self updateSegmentControl];
151 }
152
153 /**
154 * Key-value observation routine.
155 */
156 - (void)observeValueForKeyPath:(NSString*)keyPath
157 ofObject:(id)object
158 change:(NSDictionary<NSString*,id>*)change
159 context:(void*)context {
160 if (object == _stackArrayController && [keyPath isEqualToString:@"selectedObjects"]) {
161 for (StackFrame* frame in _stackArrayController.selectedObjects)
162 [_connection loadStackFrame:frame];
163 } else if (object == _stackArrayController && [keyPath isEqualToString:@"selection.source"]) {
164 [self updateSourceViewer];
165 } else if (object == _model) {
166 if ([keyPath isEqualToString:@"connected"]) {
167 if ([change[NSKeyValueChangeNewKey] boolValue]) {
168 [self debuggerConnected];
169 } else {
170 [self debuggerDisconnected];
171 }
172 }
173 } else if (object == _segmentControl.cell) {
174 [[NSUserDefaults standardUserDefaults] setValue:@(_segmentControl.selectedSegment)
175 forKey:kPrefSelectedDebuggerSegment];
176 [_tabView selectTabViewItemAtIndex:_segmentControl.selectedSegment - 1];
177 } else if (object == _segmentControl.superview) {
178 [self updateSegmentControl];
179 } else {
180 [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
181 }
182 }
183
184 /**
185 * Validates the menu items for the "Debugger" menu
186 */
187 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem
188 {
189 SEL action = [anItem action];
190
191 if (action == @selector(stepOut:)) {
192 return _model.connected && _model.stackDepth > 1;
193 } else if (action == @selector(stepIn:) ||
194 action == @selector(stepOver:) ||
195 action == @selector(run:) ||
196 action == @selector(stop:)) {
197 return _model.connected;
198 }
199 return [[self window] validateUserInterfaceItem:anItem];
200 }
201
202 /**
203 * Shows the inspector window
204 */
205 - (IBAction)showInspectorWindow:(id)sender
206 {
207 if (![_inspector isVisible])
208 [_inspector makeKeyAndOrderFront:sender];
209 else
210 [_inspector orderOut:sender];
211 }
212
213 /**
214 * Runs the eval window sheet.
215 */
216 - (IBAction)showEvalWindow:(id)sender
217 {
218 [self.segmentControl setSelectedSegment:3];
219 }
220
221 /**
222 * Delegate function for GDBpConnection for when the debugger connects.
223 */
224 - (void)debuggerConnected
225 {
226 if (!self.connection.autoAttach)
227 return;
228 if ([[NSUserDefaults standardUserDefaults] boolForKey:kPrefBreakOnFirstLine])
229 [self stepIn:self];
230 // Do not cache the file between debugger executions.
231 _sourceViewer.file = nil;
232 }
233
234 /**
235 * Called once the debugger disconnects.
236 */
237 - (void)debuggerDisconnected
238 {
239 // Invalidate the marked line so we don't look like we're still running.
240 _sourceViewer.markedLine = -1;
241 [_sourceViewer setNeedsDisplay:YES];
242 }
243
244 /**
245 * Forwards the message to run script execution to the connection
246 */
247 - (IBAction)run:(id)sender
248 {
249 [_connection run];
250 }
251
252 - (IBAction)attachedToggled:(id)sender
253 {
254 _connection.autoAttach = [sender state] == NSOnState;
255 }
256
257 /**
258 * Forwards the message to "step in" to the connection
259 */
260 - (IBAction)stepIn:(id)sender
261 {
262 if ([[_variablesTreeController selectedObjects] count] > 0)
263 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
264
265 [_connection stepIn];
266 }
267
268 /**
269 * Forwards the message to "step out" to the connection
270 */
271 - (IBAction)stepOut:(id)sender
272 {
273 if ([[_variablesTreeController selectedObjects] count] > 0)
274 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
275
276 [_connection stepOut];
277 }
278
279 /**
280 * Forwards the message to "step over" to the connection
281 */
282 - (IBAction)stepOver:(id)sender
283 {
284 if ([[_variablesTreeController selectedObjects] count] > 0)
285 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
286
287 [_connection stepOver];
288 }
289
290 /**
291 * Forwards the detach/"stop" message to the back end.
292 */
293 - (IBAction)stop:(id)sender
294 {
295 [_connection stop];
296 }
297
298 /**
299 * NSTableView delegate method that informs the controller that the stack selection did change and that
300 * we should update the source viewer
301 */
302 - (void)tableViewSelectionDidChange:(NSNotification*)notif
303 {
304 // TODO: This is very, very hacky because it's nondeterministic. The issue
305 // is that calling |-[NSOutlineView expandItem:]| while the table is still
306 // doing its redraw will translate to a no-op. Instead, we need to restructure
307 // this controller so that when everything has been laid out we call
308 // |-expandVariables|; but NSOutlineView doesn't have a |-didFinishDoingCrap:|
309 // method. The other issue is that we need to call this method from
310 // selectionDidChange but ONLY when it was the result of a user-initiated
311 // action and not the stack viewer updating causing a selection change.
312 // If it happens in the latter, then we run into the same issue that causes
313 // this to no-op.
314 [self performSelector:@selector(expandVariables) withObject:nil afterDelay:0.05];
315 }
316
317 /**
318 * Called whenver an item is expanded. This allows us to determine if we need to fetch deeper
319 */
320 - (void)outlineViewItemDidExpand:(NSNotification*)notif
321 {
322 NSTreeNode* node = [[notif userInfo] objectForKey:@"NSObject"];
323 [_expandedVariables addObject:[[node representedObject] fullName]];
324
325 [_connection loadVariableNode:[node representedObject]
326 forStackFrame:[[_stackArrayController selectedObjects] lastObject]];
327 }
328
329 /**
330 * Called when an item was collapsed. This allows us to remove it from the list of expanded items
331 */
332 - (void)outlineViewItemDidCollapse:(NSNotification*)notif
333 {
334 [_expandedVariables removeObject:[[[[notif userInfo] objectForKey:@"NSObject"] representedObject] fullName]];
335 }
336
337 #pragma mark Private
338
339 /**
340 * Does the actual updating of the source viewer by reading in the file
341 */
342 - (void)updateSourceViewer
343 {
344 NSArray* selection = [_stackArrayController selectedObjects];
345 if (!selection || [selection count] < 1)
346 return;
347 if ([selection count] > 1)
348 NSLog(@"INVALID SELECTION");
349 StackFrame* frame = [selection objectAtIndex:0];
350
351 if (!frame.loaded) {
352 [_connection loadStackFrame:frame];
353 return;
354 }
355
356 // Get the filename.
357 NSString* filename = [[NSURL URLWithString:frame.filename] path];
358 if ([filename isEqualToString:@""])
359 return;
360
361 // Replace the source if necessary.
362 if (frame.source && ![_sourceViewer.file isEqualToString:filename])
363 {
364 [_sourceViewer setString:frame.source asFile:filename];
365
366 NSSet<NSNumber*>* breakpoints = [_model.breakpointManager breakpointsForFile:filename];
367 [_sourceViewer setMarkers:breakpoints];
368 }
369
370 [_sourceViewer setMarkedLine:frame.lineNumber];
371 [_sourceViewer scrollToLine:frame.lineNumber];
372
373 [[_sourceViewer textView] setNeedsDisplay:YES];
374 }
375
376 /**
377 * Expands the variables based on the stored set
378 */
379 - (void)expandVariables
380 {
381 NSString* selection = [_selectedVariable fullName];
382
383 for (NSInteger i = 0; i < [_variablesOutlineView numberOfRows]; i++) {
384 NSTreeNode* node = [_variablesOutlineView itemAtRow:i];
385 NSString* fullName = [[node representedObject] fullName];
386
387 // see if it needs expanding
388 if ([_expandedVariables containsObject:fullName])
389 [_variablesOutlineView expandItem:node];
390
391 // select it if we had it selected before
392 if ([fullName isEqualToString:selection])
393 [_variablesTreeController setSelectionIndexPath:[node indexPath]];
394 }
395 }
396
397 /**
398 * Sets the widths of the segmented control.
399 */
400 - (void)updateSegmentControl {
401 NSRect containerFrame = [[_segmentControl superview] frame];
402 CGFloat containerWidth = NSWidth(containerFrame);
403 CGFloat segmentSizes = 0;
404 for (NSInteger i = 1; i < [_segmentControl segmentCount] - 1; ++i) {
405 segmentSizes += [_segmentControl widthForSegment:i];
406 }
407 CGFloat spacerWidth = (containerWidth - segmentSizes) / 2;
408 [_segmentControl setWidth:spacerWidth forSegment:0];
409 [_segmentControl setWidth:spacerWidth forSegment:[_segmentControl segmentCount] - 1];
410
411 [_segmentControl setFrame:NSMakeRect(-1, NSHeight(containerFrame) - 27, containerWidth + 2, 30)];
412 }
413
414 #pragma mark BSSourceView Delegate
415
416 /**
417 * The gutter was clicked, which indicates that a breakpoint needs to be changed
418 */
419 - (void)gutterClickedAtLine:(int)line forFile:(NSString*)file
420 {
421 BreakpointManager* manager = _model.breakpointManager;
422 Breakpoint* breakpoint = [Breakpoint breakpointAtLine:line inFile:file];
423
424 if ([manager hasBreakpoint:breakpoint]) {
425 [manager removeBreakpoint:breakpoint];
426 } else {
427 [manager addBreakpoint:breakpoint];
428 }
429
430 [_sourceViewer setMarkers:[manager breakpointsForFile:file]];
431 }
432
433 @end