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