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