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