Rewrite variable and property loading.
[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 /**
247 * NSTableView delegate method that informs the controller that the stack selection did change and that
248 * we should update the source viewer
249 */
250 - (void)tableViewSelectionDidChange:(NSNotification*)notif
251 {
252 [self updateSourceViewer];
253 // TODO: This is very, very hacky because it's nondeterministic. The issue
254 // is that calling |-[NSOutlineView expandItem:]| while the table is still
255 // doing its redraw will translate to a no-op. Instead, we need to restructure
256 // this controller so that when everything has been laid out we call
257 // |-expandVariables|; but NSOutlineView doesn't have a |-didFinishDoingCrap:|
258 // method. The other issue is that we need to call this method from
259 // selectionDidChange but ONLY when it was the result of a user-initiated
260 // action and not the stack viewer updating causing a selection change.
261 // If it happens in the latter, then we run into the same issue that causes
262 // this to no-op.
263 [self performSelector:@selector(expandVariables) withObject:nil afterDelay:0.05];
264 }
265
266 /**
267 * Called whenver an item is expanded. This allows us to determine if we need to fetch deeper
268 */
269 - (void)outlineViewItemDidExpand:(NSNotification*)notif
270 {
271 NSTreeNode* node = [[notif userInfo] objectForKey:@"NSObject"];
272 [expandedVariables addObject:[[node representedObject] fullName]];
273
274 [connection loadVariableNode:[node representedObject]
275 forStackFrame:[[stackArrayController selectedObjects] lastObject]];
276 }
277
278 /**
279 * Called when an item was collapsed. This allows us to remove it from the list of expanded items
280 */
281 - (void)outlineViewItemDidCollapse:(NSNotification*)notif
282 {
283 [expandedVariables removeObject:[[[[notif userInfo] objectForKey:@"NSObject"] representedObject] fullName]];
284 }
285
286 #pragma mark Private
287
288 /**
289 * Does the actual updating of the source viewer by reading in the file
290 */
291 - (void)updateSourceViewer
292 {
293 NSArray* selection = [stackArrayController selectedObjects];
294 if (!selection || [selection count] < 1)
295 return;
296 if ([selection count] > 1)
297 NSLog(@"INVALID SELECTION");
298 StackFrame* frame = [selection objectAtIndex:0];
299
300 if (!frame.loaded) {
301 [connection loadStackFrame:frame];
302 return;
303 }
304
305 // Get the filename.
306 NSString* filename = [[NSURL URLWithString:frame.filename] path];
307 if ([filename isEqualToString:@""])
308 return;
309
310 // Replace the source if necessary.
311 if (frame.source && ![sourceViewer.file isEqualToString:filename])
312 {
313 [sourceViewer setString:frame.source asFile:filename];
314
315 NSSet* breakpoints = [NSSet setWithArray:[[BreakpointManager sharedManager] breakpointsForFile:filename]];
316 [sourceViewer setMarkers:breakpoints];
317 }
318
319 [sourceViewer setMarkedLine:frame.lineNumber];
320 [sourceViewer scrollToLine:frame.lineNumber];
321
322 [[sourceViewer textView] display];
323 }
324
325 /**
326 * Expands the variables based on the stored set
327 */
328 - (void)expandVariables
329 {
330 NSString* selection = [selectedVariable fullName];
331
332 for (NSInteger i = 0; i < [variablesOutlineView numberOfRows]; i++) {
333 NSTreeNode* node = [variablesOutlineView itemAtRow:i];
334 NSString* fullName = [[node representedObject] fullName];
335
336 // see if it needs expanding
337 if ([expandedVariables containsObject:fullName])
338 [variablesOutlineView expandItem:node];
339
340 // select it if we had it selected before
341 if ([fullName isEqualToString:selection])
342 [variablesTreeController setSelectionIndexPath:[node indexPath]];
343 }
344 }
345
346 #pragma mark BSSourceView Delegate
347
348 /**
349 * The gutter was clicked, which indicates that a breakpoint needs to be changed
350 */
351 - (void)gutterClickedAtLine:(int)line forFile:(NSString*)file
352 {
353 BreakpointManager* mngr = [BreakpointManager sharedManager];
354
355 if ([mngr hasBreakpointAt:line inFile:file])
356 {
357 [mngr removeBreakpointAt:line inFile:file];
358 }
359 else
360 {
361 Breakpoint* bp = [[Breakpoint alloc] initWithLine:line inFile:file];
362 [mngr addBreakpoint:bp];
363 [bp release];
364 }
365
366 [sourceViewer setMarkers:[NSSet setWithArray:[mngr breakpointsForFile:file]]];
367 [sourceViewer setNeedsDisplay:YES];
368 }
369
370 #pragma mark GDBpConnectionDelegate
371
372 - (void)sourceUpdated:(StackFrame*)frame
373 {
374 [self updateSourceViewer];
375 }
376
377 @end