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