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