Add support for function return breakpoints.
[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 // Exclude from the Windows menu because there is an explicit entry.
114 [[self window] setExcludedFromWindowsMenu:YES];
115
116 // Connect to XIB properties.
117 [_sourceViewer setDelegate:self];
118 [_stackArrayController setSortDescriptors:@[ [[[NSSortDescriptor alloc] initWithKey:@"index" ascending:YES] autorelease] ]];
119 [_stackArrayController addObserver:self
120 forKeyPath:@"selectedObjects"
121 options:NSKeyValueObservingOptionNew
122 context:nil];
123 [_stackArrayController addObserver:self
124 forKeyPath:@"selection.source"
125 options:NSKeyValueObservingOptionNew
126 context:nil];
127 self.connection.autoAttach = [_attachedCheckbox state] == NSOnState;
128
129 // Load view controllers into the tab views.
130 _breakpointsController = [[BreakpointController alloc] initWithBreakpointManager:_model.breakpointManager
131 sourceView:_sourceViewer];
132 [[self.tabView tabViewItemAtIndex:1] setView:_breakpointsController.view];
133
134 _evalController = [[EvalController alloc] initWithBackEnd:_connection];
135 [[self.tabView tabViewItemAtIndex:2] setView:_evalController.view];
136
137 // When the segment control's selection changes, update the tab view.
138 [[_segmentControl cell] addObserver:self
139 forKeyPath:@"selectedSegment"
140 options:0
141 context:nil];
142 // When the segment control's superview changes, recalculate the spacer
143 // segment widths.
144 [[_segmentControl superview] addObserver:self
145 forKeyPath:@"frame"
146 options:0
147 context:nil];
148
149 NSUInteger selectedSegment =
150 [[[NSUserDefaults standardUserDefaults] valueForKey:kPrefSelectedDebuggerSegment] intValue];
151 [[_segmentControl cell] setSelectedSegment:selectedSegment];
152 [self updateSegmentControl];
153 }
154
155 /**
156 * Key-value observation routine.
157 */
158 - (void)observeValueForKeyPath:(NSString*)keyPath
159 ofObject:(id)object
160 change:(NSDictionary<NSString*,id>*)change
161 context:(void*)context {
162 if (object == _stackArrayController && [keyPath isEqualToString:@"selectedObjects"]) {
163 for (StackFrame* frame in _stackArrayController.selectedObjects)
164 [_connection loadStackFrame:frame];
165 } else if (object == _stackArrayController && [keyPath isEqualToString:@"selection.source"]) {
166 [self updateSourceViewer];
167 } else if (object == _model) {
168 if ([keyPath isEqualToString:@"connected"]) {
169 if ([change[NSKeyValueChangeNewKey] boolValue]) {
170 [self debuggerConnected];
171 } else {
172 [self debuggerDisconnected];
173 }
174 }
175 } else if (object == _segmentControl.cell) {
176 [[NSUserDefaults standardUserDefaults] setValue:@(_segmentControl.selectedSegment)
177 forKey:kPrefSelectedDebuggerSegment];
178 [_tabView selectTabViewItemAtIndex:_segmentControl.selectedSegment - 1];
179 } else if (object == _segmentControl.superview) {
180 [self updateSegmentControl];
181 } else {
182 [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
183 }
184 }
185
186 /**
187 * Validates the menu items for the "Debugger" menu
188 */
189 - (BOOL)validateUserInterfaceItem:(id <NSValidatedUserInterfaceItem>)anItem
190 {
191 SEL action = [anItem action];
192
193 if (action == @selector(stepOut:)) {
194 return _model.connected && _model.stackDepth > 1;
195 } else if (action == @selector(stepIn:) ||
196 action == @selector(stepOver:) ||
197 action == @selector(run:) ||
198 action == @selector(stop:)) {
199 return _model.connected;
200 }
201 return [[self window] validateUserInterfaceItem:anItem];
202 }
203
204 /**
205 * Shows the inspector window
206 */
207 - (IBAction)showInspectorWindow:(id)sender
208 {
209 if (![_inspector isVisible])
210 [_inspector makeKeyAndOrderFront:sender];
211 else
212 [_inspector orderOut:sender];
213 }
214
215 /**
216 * Runs the eval window sheet.
217 */
218 - (IBAction)showEvalWindow:(id)sender
219 {
220 [self.segmentControl setSelectedSegment:3];
221 }
222
223 /**
224 * Delegate function for GDBpConnection for when the debugger connects.
225 */
226 - (void)debuggerConnected
227 {
228 if (!self.connection.autoAttach)
229 return;
230 if ([[NSUserDefaults standardUserDefaults] boolForKey:kPrefBreakOnFirstLine])
231 [self stepIn:self];
232 // Do not cache the file between debugger executions.
233 _sourceViewer.file = nil;
234 }
235
236 /**
237 * Called once the debugger disconnects.
238 */
239 - (void)debuggerDisconnected
240 {
241 // Invalidate the marked line so we don't look like we're still running.
242 _sourceViewer.markedLine = -1;
243 [_sourceViewer setNeedsDisplay:YES];
244 }
245
246 /**
247 * Forwards the message to run script execution to the connection
248 */
249 - (IBAction)run:(id)sender
250 {
251 [_connection run];
252 }
253
254 - (IBAction)attachedToggled:(id)sender
255 {
256 _connection.autoAttach = [sender state] == NSOnState;
257 }
258
259 /**
260 * Forwards the message to "step in" to the connection
261 */
262 - (IBAction)stepIn:(id)sender
263 {
264 if ([[_variablesTreeController selectedObjects] count] > 0)
265 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
266
267 [_connection stepIn];
268 }
269
270 /**
271 * Forwards the message to "step out" to the connection
272 */
273 - (IBAction)stepOut:(id)sender
274 {
275 if ([[_variablesTreeController selectedObjects] count] > 0)
276 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
277
278 [_connection stepOut];
279 }
280
281 /**
282 * Forwards the message to "step over" to the connection
283 */
284 - (IBAction)stepOver:(id)sender
285 {
286 if ([[_variablesTreeController selectedObjects] count] > 0)
287 _selectedVariable = [[_variablesTreeController selectedObjects] objectAtIndex:0];
288
289 [_connection stepOver];
290 }
291
292 /**
293 * Forwards the detach/"stop" message to the back end.
294 */
295 - (IBAction)stop:(id)sender
296 {
297 [_connection stop];
298 }
299
300 /**
301 * NSTableView delegate method that informs the controller that the stack selection did change and that
302 * we should update the source viewer
303 */
304 - (void)tableViewSelectionDidChange:(NSNotification*)notif
305 {
306 // TODO: This is very, very hacky because it's nondeterministic. The issue
307 // is that calling |-[NSOutlineView expandItem:]| while the table is still
308 // doing its redraw will translate to a no-op. Instead, we need to restructure
309 // this controller so that when everything has been laid out we call
310 // |-expandVariables|; but NSOutlineView doesn't have a |-didFinishDoingCrap:|
311 // method. The other issue is that we need to call this method from
312 // selectionDidChange but ONLY when it was the result of a user-initiated
313 // action and not the stack viewer updating causing a selection change.
314 // If it happens in the latter, then we run into the same issue that causes
315 // this to no-op.
316 [self performSelector:@selector(expandVariables) withObject:nil afterDelay:0.05];
317 }
318
319 /**
320 * Called whenver an item is expanded. This allows us to determine if we need to fetch deeper
321 */
322 - (void)outlineViewItemDidExpand:(NSNotification*)notif
323 {
324 NSTreeNode* node = [[notif userInfo] objectForKey:@"NSObject"];
325 [_expandedVariables addObject:[[node representedObject] fullName]];
326
327 [_connection loadVariableNode:[node representedObject]
328 forStackFrame:[[_stackArrayController selectedObjects] lastObject]];
329 }
330
331 /**
332 * Called when an item was collapsed. This allows us to remove it from the list of expanded items
333 */
334 - (void)outlineViewItemDidCollapse:(NSNotification*)notif
335 {
336 [_expandedVariables removeObject:[[[[notif userInfo] objectForKey:@"NSObject"] representedObject] fullName]];
337 }
338
339 #pragma mark Private
340
341 /**
342 * Does the actual updating of the source viewer by reading in the file
343 */
344 - (void)updateSourceViewer
345 {
346 NSArray* selection = [_stackArrayController selectedObjects];
347 if (!selection || [selection count] < 1)
348 return;
349 if ([selection count] > 1)
350 NSLog(@"INVALID SELECTION");
351 StackFrame* frame = [selection objectAtIndex:0];
352
353 if (!frame.loaded) {
354 [_connection loadStackFrame:frame];
355 return;
356 }
357
358 // Get the filename.
359 NSString* filename = [[NSURL URLWithString:frame.filename] path];
360 if ([filename isEqualToString:@""])
361 return;
362
363 // Replace the source if necessary.
364 if (frame.source && ![_sourceViewer.file isEqualToString:filename])
365 {
366 [_sourceViewer setString:frame.source asFile:filename];
367
368 NSSet<NSNumber*>* breakpoints = [_model.breakpointManager breakpointsForFile:filename];
369 [_sourceViewer setMarkers:breakpoints];
370 }
371
372 [_sourceViewer setMarkedLine:frame.lineNumber];
373 [_sourceViewer scrollToLine:frame.lineNumber];
374
375 [[_sourceViewer textView] setNeedsDisplay:YES];
376 }
377
378 /**
379 * Expands the variables based on the stored set
380 */
381 - (void)expandVariables
382 {
383 NSString* selection = [_selectedVariable fullName];
384
385 for (NSInteger i = 0; i < [_variablesOutlineView numberOfRows]; i++) {
386 NSTreeNode* node = [_variablesOutlineView itemAtRow:i];
387 NSString* fullName = [[node representedObject] fullName];
388
389 // see if it needs expanding
390 if ([_expandedVariables containsObject:fullName])
391 [_variablesOutlineView expandItem:node];
392
393 // select it if we had it selected before
394 if ([fullName isEqualToString:selection])
395 [_variablesTreeController setSelectionIndexPath:[node indexPath]];
396 }
397 }
398
399 /**
400 * Sets the widths of the segmented control.
401 */
402 - (void)updateSegmentControl {
403 NSRect containerFrame = [[_segmentControl superview] frame];
404 CGFloat containerWidth = NSWidth(containerFrame);
405 CGFloat segmentSizes = 0;
406 for (NSInteger i = 1; i < [_segmentControl segmentCount] - 1; ++i) {
407 segmentSizes += [_segmentControl widthForSegment:i];
408 }
409 CGFloat spacerWidth = (containerWidth - segmentSizes) / 2;
410 [_segmentControl setWidth:spacerWidth forSegment:0];
411 [_segmentControl setWidth:spacerWidth forSegment:[_segmentControl segmentCount] - 1];
412
413 [_segmentControl setFrame:NSMakeRect(-5, NSHeight(containerFrame) - 27, containerWidth + 10, 30)];
414 }
415
416 #pragma mark BSSourceView Delegate
417
418 /**
419 * The gutter was clicked, which indicates that a breakpoint needs to be changed
420 */
421 - (void)gutterClickedAtLine:(int)line forFile:(NSString*)file
422 {
423 BreakpointManager* manager = _model.breakpointManager;
424 Breakpoint* breakpoint = [Breakpoint breakpointAtLine:line inFile:file];
425
426 if ([manager hasBreakpoint:breakpoint]) {
427 [manager removeBreakpoint:breakpoint];
428 } else {
429 [manager addBreakpoint:breakpoint];
430 }
431
432 [_sourceViewer setMarkers:[manager breakpointsForFile:file]];
433 }
434
435 @end