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