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