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