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