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