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