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