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