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