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