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