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