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