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