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