In -[DebuggerController debuggerConnected] clear out the source viewer.
[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 // Do not cache the file between debugger executions.
190 sourceViewer.file = nil;
191 }
192
193 /**
194 * Called once the debugger disconnects.
195 */
196 - (void)debuggerDisconnected
197 {
198 // Invalidate the marked line so we don't look like we're still running.
199 sourceViewer.markedLine = -1;
200 [sourceViewer setNeedsDisplay:YES];
201 }
202
203 /**
204 * Forwards the message to run script execution to the connection
205 */
206 - (IBAction)run:(id)sender
207 {
208 [connection run];
209 }
210
211 - (IBAction)attachedToggled:(id)sender
212 {
213 connection.autoAttach = [sender state] == NSOnState;
214 }
215
216 /**
217 * Forwards the message to "step in" to the connection
218 */
219 - (IBAction)stepIn:(id)sender
220 {
221 if ([[variablesTreeController selectedObjects] count] > 0)
222 selectedVariable = [[variablesTreeController selectedObjects] objectAtIndex:0];
223
224 [connection stepIn];
225 }
226
227 /**
228 * Forwards the message to "step out" to the connection
229 */
230 - (IBAction)stepOut:(id)sender
231 {
232 if ([[variablesTreeController selectedObjects] count] > 0)
233 selectedVariable = [[variablesTreeController selectedObjects] objectAtIndex:0];
234
235 [connection stepOut];
236 }
237
238 /**
239 * Forwards the message to "step over" to the connection
240 */
241 - (IBAction)stepOver:(id)sender
242 {
243 if ([[variablesTreeController selectedObjects] count] > 0)
244 selectedVariable = [[variablesTreeController selectedObjects] objectAtIndex:0];
245
246 [connection stepOver];
247 }
248
249 /**
250 * Forwards the detach/"stop" message to the back end.
251 */
252 - (IBAction)stop:(id)sender
253 {
254 [connection stop];
255 }
256
257 /**
258 * NSTableView delegate method that informs the controller that the stack selection did change and that
259 * we should update the source viewer
260 */
261 - (void)tableViewSelectionDidChange:(NSNotification*)notif
262 {
263 // TODO: This is very, very hacky because it's nondeterministic. The issue
264 // is that calling |-[NSOutlineView expandItem:]| while the table is still
265 // doing its redraw will translate to a no-op. Instead, we need to restructure
266 // this controller so that when everything has been laid out we call
267 // |-expandVariables|; but NSOutlineView doesn't have a |-didFinishDoingCrap:|
268 // method. The other issue is that we need to call this method from
269 // selectionDidChange but ONLY when it was the result of a user-initiated
270 // action and not the stack viewer updating causing a selection change.
271 // If it happens in the latter, then we run into the same issue that causes
272 // this to no-op.
273 [self performSelector:@selector(expandVariables) withObject:nil afterDelay:0.05];
274 }
275
276 /**
277 * Called whenver an item is expanded. This allows us to determine if we need to fetch deeper
278 */
279 - (void)outlineViewItemDidExpand:(NSNotification*)notif
280 {
281 NSTreeNode* node = [[notif userInfo] objectForKey:@"NSObject"];
282 [expandedVariables addObject:[[node representedObject] fullName]];
283
284 [connection loadVariableNode:[node representedObject]
285 forStackFrame:[[stackArrayController selectedObjects] lastObject]];
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 @end