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