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