Oolite
Loading...
Searching...
No Matches
OODebugMonitor.m
Go to the documentation of this file.
1/*
2
3OODebugMonitor.m
4
5
6Oolite debug support
7
8Copyright (C) 2007-2013 Jens Ayton
9
10Permission is hereby granted, free of charge, to any person obtaining a copy
11of this software and associated documentation files (the "Software"), to deal
12in the Software without restriction, including without limitation the rights
13to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14copies of the Software, and to permit persons to whom the Software is
15furnished to do so, subject to the following conditions:
16
17The above copyright notice and this permission notice shall be included in all
18copies or substantial portions of the Software.
19
20THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26SOFTWARE.
27
28*/
29
30#ifdef OO_DEBUG_MONITOR_ENABLED
31
32#import "OODebugMonitor.h"
35#import "OOLoggingExtended.h"
36#import "ResourceManager.h"
37
38#import "OOJSConsole.h"
39#import "OOJSEngineTimeManagement.h"
40#import "OOJSScript.h"
41#import "OOJSSpecialFunctions.h"
42
44#import "OOConcreteTexture.h"
45#import "OODrawable.h"
46#import "OOTexture.h"
47
49
50@interface OODebugMonitor (Private) <OOJavaScriptEngineMonitor>
51
52- (void)setUpDebugConsoleScript;
53- (void)javaScriptEngineWillReset:(NSNotification*)notification;
54
55- (void)disconnectDebuggerWithMessage:(NSString*)message;
56
57- (NSDictionary*)mergedConfiguration;
58
59/* Convert a configuration dictionary to a standard form. In particular,
60 convert all colour specifiers to RGBA arrays with values in [0, 1], and
61 converts "show-console" values to booleans.
62*/
63- (NSMutableDictionary*)normalizeConfigDictionary:(NSDictionary*)dictionary;
64- (id)normalizeConfigValue:(id)value forKey:(NSString*)key;
65
66- (NSArray*)loadSourceFile:(NSString*)filePath;
67
68@end
69
70@implementation OODebugMonitor
71#if OOLITE_SDL
72NSString* NSApplicationWillTerminateNotification = @"ApplicationWillTerminate";
73#endif
74
75- (id)init
76{
77 NSUserDefaults* defaults = nil;
78 NSMutableDictionary* config = nil;
79
80 self = [super init];
81 if (self != nil) {
82 config = [[[ResourceManager dictionaryFromFilesNamed:@"debugConfig.plist"
83 inFolder:@"Config"
84 andMerge:YES] mutableCopy] autorelease];
85 _configFromOXPs = [[self normalizeConfigDictionary:config] copy];
86
87 defaults = [NSUserDefaults standardUserDefaults];
88 config = [self normalizeConfigDictionary:[defaults dictionaryForKey:@"debug-settings-override"]];
89 if (config == nil)
90 config = [NSMutableDictionary dictionary];
91 _configOverrides = [config retain];
92
93 _TCPIgnoresDroppedPackets = NO;
94
95 OOJavaScriptEngine* jsEng = [OOJavaScriptEngine sharedEngine];
96#if OOJSENGINE_MONITOR_SUPPORT
97 [jsEng setMonitor:self];
98#endif
99
100 [self setUpDebugConsoleScript];
101
102 [[NSNotificationCenter defaultCenter] addObserver:self
103 selector:@selector(applicationWillTerminate:)
104 name:NSApplicationWillTerminateNotification
105 object:nil];
106
107 [[NSNotificationCenter defaultCenter] addObserver:self
108 selector:@selector(javaScriptEngineWillReset:)
109 name:kOOJavaScriptEngineWillResetNotification
110 object:jsEng];
111
112 [[NSNotificationCenter defaultCenter] addObserver:self
113 selector:@selector(setUpDebugConsoleScript)
114 name:kOOJavaScriptEngineDidResetNotification
115 object:jsEng];
116 }
117
118 return self;
119}
120
121- (void)dealloc
122{
123 [self disconnectDebuggerWithMessage:@"Debug controller object destroyed while debugging in progress."];
124
125 [_configFromOXPs release];
126 [_configOverrides release];
127
128 [_fgColors release];
129 [_bgColors release];
130 [_sourceFiles release];
131
132#if OOJS_QUICKJS
133 if (JS_IsObject(_jsSelf)) {
134 JS_FreeValue(OOJSAcquireContext(), _jsSelf);
135 _jsSelf = JS_UNDEFINED;
136 }
137#else
138 if (_jsSelf != NULL) {
140 }
141#endif
142
143 [super dealloc];
144}
145
146+ (OODebugMonitor*)sharedDebugMonitor
147{
148 // NOTE: assumes single-threaded access. The debug monitor is not, on the whole, thread safe.
149 if (sSingleton == nil) {
150 sSingleton = [[self alloc] init];
151 }
152
153 return sSingleton;
154}
155
156- (BOOL)setDebugger:(id<OODebuggerInterface>)newDebugger
157{
158 NSString* error = nil;
159
160 if (newDebugger != _debugger) {
161 // Disconnect existing debugger, if any.
162 if (newDebugger != nil) {
163 [self disconnectDebuggerWithMessage:@"New debugger set."];
164 } else {
165 [self disconnectDebuggerWithMessage:@"Debugger disconnected programatically."];
166 }
167
168 // If a new debugger was specified, try to connect it.
169 if (newDebugger != nil) {
170 @try {
171 if ([newDebugger connectDebugMonitor:self errorMessage:&error]) {
172 [newDebugger debugMonitor:self
173 noteConfiguration:[self mergedConfiguration]];
174 _debugger = [newDebugger retain];
175 } else {
176 OOLog(@"debugMonitor.setDebugger.failed", @"Could not connect to debugger %@, because an error occurred: %@", newDebugger, error);
177 }
178 }
179 @catch (NSException* exception) {
180 OOLog(@"debugMonitor.setDebugger.failed", @"Could not connect to debugger %@, because an exception occurred: %@ -- %@", newDebugger, [exception name], [exception reason]);
181 }
182 }
183 }
184
185 return _debugger == newDebugger;
186}
187
188- (oneway void)performJSConsoleCommand:(in NSString*)command
189{
190 JSContext* context = OOJSAcquireContext();
191 OOJSVal commandVal = OOJSValueFromNativeObject(context, command);
193 [_script callMethod:OOJSID("consolePerformJSCommand") inContext:context withArguments:&commandVal count:1 result:NULL];
195 OOJSFreeValue(context, commandVal);
196 OOJSRelinquishContext(context);
197}
198
199- (void)appendJSConsoleLine:(id)string
200 colorKey:(NSString*)colorKey
201 emphasisRange:(NSRange)emphasisRange
202{
203 if (string == nil)
204 return;
206 @try {
207 [_debugger debugMonitor:self
208 jsConsoleOutput:string
209 colorKey:colorKey
210 emphasisRange:emphasisRange];
211 }
212 @catch (NSException* exception) {
213 OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to send JavaScript console text to debugger: %@ -- %@", [exception name], [exception reason]);
214 }
216}
217
218- (void)appendJSConsoleLine:(id)string
219 colorKey:(NSString*)colorKey
220{
221 [self appendJSConsoleLine:string
222 colorKey:colorKey
223 emphasisRange:NSMakeRange(0, 0)];
224}
225
226- (void)clearJSConsole
227{
229 @try {
230 [_debugger debugMonitorClearConsole:self];
231 }
232 @catch (NSException* exception) {
233 OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to clear JavaScript console: %@ -- %@", [exception name], [exception reason]);
234 }
236}
237
238- (void)showJSConsole
239{
241 @try {
242 [_debugger debugMonitorShowConsole:self];
243 }
244 @catch (NSException* exception) {
245 OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to show JavaScript console: %@ -- %@", [exception name], [exception reason]);
246 }
248}
249
250- (id)configurationValueForKey:(in NSString*)key
251{
252 return [self configurationValueForKey:key class:Nil defaultValue:nil];
253}
254
255- (id)configurationValueForKey:(NSString*)key class:(Class)class defaultValue:(id)value
256{
257 id result = nil;
258
259 if (class == Nil)
260 class = [NSObject class];
261
262 result = [_configOverrides objectForKey:key];
263 if (![result isKindOfClass:class] && result != [NSNull null])
264 result = [_configFromOXPs objectForKey:key];
265 if (![result isKindOfClass:class] && result != [NSNull null])
266 result = [[value retain] autorelease];
267 if (result == [NSNull null])
268 result = nil;
269
270 return result;
271}
272
273- (long long)configurationIntValueForKey:(NSString*)key defaultValue:(long long)value
274{
275 long long result;
276 id object = nil;
277
278 object = [self configurationValueForKey:key];
279 if ([object respondsToSelector:@selector(longLongValue)])
280 result = [object longLongValue];
281 else if ([object respondsToSelector:@selector(intValue)])
282 result = [object intValue];
283 else
284 result = value;
285
286 return result;
287}
288
289- (void)setConfigurationValue:(in id)value forKey:(in NSString*)key
290{
291 if (key == nil)
292 return;
293
294 value = [self normalizeConfigValue:value forKey:key];
295
296 if (value == nil) {
297 [_configOverrides removeObjectForKey:key];
298 } else {
299 if (_configOverrides == nil)
300 _configOverrides = [[NSMutableDictionary alloc] init];
301 [_configOverrides setObject:value forKey:key];
302 }
303
304 // Send changed value to debugger
305 if (value == nil) {
306 // Setting a nil value removes an override, and may reveal an underlying OXP-defined value
307 value = [self configurationValueForKey:key];
308 }
309 @try {
310 [_debugger debugMonitor:self
311 noteChangedConfigrationValue:value
312 forKey:key];
313 }
314 @catch (NSException* exception) {
315 OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to send configuration update to debugger: %@ -- %@", [exception name], [exception reason]);
316 }
317}
318
319- (NSArray*)configurationKeys
320{
321 NSMutableSet* result = nil;
322
323 result = [NSMutableSet setWithCapacity:[_configFromOXPs count] + [_configOverrides count]];
324 [result addObjectsFromArray:[_configFromOXPs allKeys]];
325 [result addObjectsFromArray:[_configOverrides allKeys]];
326
327 return [[result allObjects] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
328}
329
330- (BOOL)debuggerConnected
331{
332 return _debugger != nil;
333}
334
335- (void)writeMemStat:(NSString*)format, ...
336{
337 va_list args;
338 va_start(args, format);
339 NSString* message = [[NSString alloc] initWithFormat:format arguments:args];
340 va_end(args);
341
342 OOLog(@"debug.memStats", @"%@", message);
343 [self appendJSConsoleLine:message colorKey:@"command-result"];
344
345 [message release];
346}
347
348static NSString* SizeString(size_t size)
349{
350 enum {
351 kThreshold = 2 // 2 KiB, 2 MiB etc.
352 };
353
354 unsigned magnitude = 0;
355 NSString* suffix = @"";
356
357 if (size < kThreshold << 10) {
358 return [NSString stringWithFormat:@"%zu bytes", size];
359 }
360 if (size < kThreshold << 20) {
361 magnitude = 1;
362 suffix = @"KiB";
363 } else if (size < ((size_t)kThreshold << 30)) {
364 magnitude = 2;
365 suffix = @"MiB";
366 } else {
367 magnitude = 3;
368 suffix = @"GiB";
369 }
370
371 float unit = 1 << (magnitude * 10);
372 float sizef = (float)size / unit;
373 sizef = round(sizef * 100.0f) / 100.f;
374
375 return [NSString stringWithFormat:@"%.2f %@", sizef, suffix];
376}
377
378typedef struct
379{
380 NSMutableSet* entityTextures;
381 NSMutableSet* visibleEntityTextures;
382 NSMutableSet* seenEntities;
383 unsigned seenCount;
384 size_t totalEntityObjSize;
385 size_t totalDrawableSize;
386} EntityDumpState;
387
388- (void)dumpEntity:(id)entity withState:(EntityDumpState*)state parentVisible:(BOOL)parentVisible
389{
390 if ([state->seenEntities containsObject:entity] || entity == nil)
391 return;
392 [state->seenEntities addObject:entity];
393
394 state->seenCount++;
395
396 size_t entitySize = [entity oo_objectSize];
397 size_t drawableSize = 0;
398 if ([entity isKindOfClass:[OOEntityWithDrawable class]]) {
399 OODrawable* drawable = [entity drawable];
400 drawableSize = [drawable totalSize];
401 }
402
403 BOOL visible = parentVisible && [entity isVisible];
404
405 NSSet* textures = [entity allTextures];
406 if (textures != nil) {
407 [state->entityTextures unionSet:textures];
408 if (visible)
409 [state->visibleEntityTextures unionSet:textures];
410 }
411
412 NSString* extra = @"";
413 if (visible) {
414 extra = [extra stringByAppendingString:@", visible"];
415 }
416
417 if (drawableSize != 0) {
418 extra = [extra stringByAppendingFormat:@", drawable: %@", SizeString(drawableSize)];
419 }
420
421 [self writeMemStat:@"%@: %@%@", [entity shortDescription], SizeString(entitySize), extra];
422
423 state->totalEntityObjSize += entitySize;
424 state->totalDrawableSize += drawableSize;
425
426 OOLogIndent();
427 if ([entity isShip]) {
428 id subentity = nil;
429 foreach (subentity, [entity subEntityEnumerator]) {
430 [self dumpEntity:subentity withState:state parentVisible:visible];
431 }
432
433 if ([entity isPlayer]) {
434 NSUInteger i, count = [entity dialMaxMissiles];
435 for (i = 0; i < count; i++) {
436 subentity = [entity missileForPylon:i];
437 if (subentity != nil)
438 [self dumpEntity:subentity withState:state parentVisible:NO];
439 }
440 }
441 }
442 if ([entity isPlanet]) {
443#if NEW_PLANETS
444 // FIXME: dump atmosphere texture.
445#else
446 PlanetEntity* atmosphere = [entity atmosphere];
447 if (atmosphere != nil) {
448 [self dumpEntity:atmosphere withState:state parentVisible:visible];
449 }
450#endif
451 }
452 if ([entity isWormhole]) {
453 NSDictionary* shipInfo = nil;
454 foreach (shipInfo, [entity shipsInTransit]) {
455 ShipEntity* ship = [shipInfo objectForKey:@"ship"];
456 [self dumpEntity:ship withState:state parentVisible:NO];
457 }
458 }
459 OOLogOutdent();
460}
461
462- (void)dumpMemoryStatistics
463{
464 OOLog(@"debug.memStats", @"%@", @"Memory statistics:");
465 OOLogIndent();
466
467 // Get texture retain counts before the entity dumper starts messing with them.
468 NSSet* allTextures = [OOTexture allTextures];
469 NSMutableDictionary* textureRefCounts = [NSMutableDictionary dictionaryWithCapacity:[allTextures count]];
470
471 OOTexture* tex = nil;
472 foreach (tex, allTextures) {
473 // We subtract one because allTextures retains the textures.
474 [textureRefCounts setObject:[NSNumber numberWithUnsignedInteger:[tex retainCount] - 1] forKey:[NSValue valueWithNonretainedObject:tex]];
475 }
476
477 size_t totalSize = 0;
478
479 [self writeMemStat:@"Entitites:"];
480 OOLogIndent();
481
482 NSArray* entities = [UNIVERSE entityList];
483 EntityDumpState entityDumpState = {
484 .entityTextures = [NSMutableSet set],
485 .visibleEntityTextures = [NSMutableSet set],
486 .seenEntities = [NSMutableSet set]
487 };
488
489 id entity = nil;
490 foreach (entity, entities) {
491 [self dumpEntity:entity withState:&entityDumpState parentVisible:YES];
492 }
493 foreach (entity, [PLAYER scannedWormholes]) {
494 [self dumpEntity:entity withState:&entityDumpState parentVisible:YES];
495 }
496
497 OOLogOutdent();
498 [self writeMemStat:@"Total entity size (excluding %u entities not accounted for): %@ (%@ entity objects, %@ drawables)",
499 gLiveEntityCount - entityDumpState.seenCount,
500 SizeString(entityDumpState.totalEntityObjSize + entityDumpState.totalDrawableSize),
501 SizeString(entityDumpState.totalEntityObjSize),
502 SizeString(entityDumpState.totalDrawableSize)];
503 totalSize += entityDumpState.totalEntityObjSize + entityDumpState.totalDrawableSize;
504
505 /* Sort textures so that textures in the "recent cache" come first by age,
506 followed by others.
507 */
508 NSMutableArray* textures = [[[OOTexture cachedTexturesByAge] mutableCopy] autorelease];
509
510 foreach (tex, allTextures) {
511 if ([textures indexOfObject:tex] == NSNotFound) {
512 [textures addObject:tex];
513 }
514 }
515
516 size_t totalTextureObjSize = 0;
517 size_t totalTextureDataSize = 0;
518 size_t visibleTextureDataSize = 0;
519
520 [self writeMemStat:@"Textures:"];
521 OOLogIndent();
522
523 foreach (tex, textures) {
524 size_t objSize = [tex oo_objectSize];
525 size_t dataSize = [tex dataSize];
526
527#if OOTEXTURE_RELOADABLE
528 NSString* byteCountSuffix = @"";
529#else
530 NSString* byteCountSuffix = @" (* 2)";
531#endif
532
533 NSString* usage = @"";
534 if ([entityDumpState.visibleEntityTextures containsObject:tex]) {
535 visibleTextureDataSize += dataSize; // NOT doubled if !OOTEXTURE_RELOADABLE, because we're interested in what the GPU sees.
536 usage = @", visible";
537 } else if ([entityDumpState.entityTextures containsObject:tex]) {
538 usage = @", active";
539 }
540
541 unsigned refCount = [textureRefCounts oo_unsignedIntForKey:[NSValue valueWithNonretainedObject:tex]];
542
543 [self writeMemStat:@"%@: [%u refs%@] %@%@",
544 [tex name],
545 refCount,
546 usage,
547 SizeString(objSize + dataSize),
548 byteCountSuffix];
549
550 totalTextureDataSize += dataSize;
551 totalTextureObjSize += objSize;
552 }
553 totalSize += totalTextureObjSize + totalTextureDataSize;
554
555 OOLogOutdent();
556
557#if !OOTEXTURE_RELOADABLE
558 totalTextureDataSize *= 2;
559#endif
560 [self writeMemStat:@"Total texture size: %@ (%@ object overhead, %@ data, %@ visible texture data)",
561 SizeString(totalTextureObjSize + totalTextureDataSize),
562 SizeString(totalTextureObjSize),
563 SizeString(totalTextureDataSize),
564 SizeString(visibleTextureDataSize)];
565
566 totalSize += [self dumpJSMemoryStatistics];
567
568 [self writeMemStat:@"Total: %@", SizeString(totalSize)];
569
570 OOLogOutdent();
571}
572
573- (size_t)dumpJSMemoryStatistics
574{
575 JSContext* context = OOJSAcquireContext();
576
577 JSRuntime* runtime = JS_GetRuntime(context);
578#if OOJS_QUICKJS
579 /* QuickJS has no heap limit or collection count; report the allocated
580 size and the threshold for the next cycle collection instead.
581 */
582 JSMemoryUsage usage;
583 JS_ComputeMemoryUsage(runtime, &usage);
584 size_t jsSize = (size_t)usage.malloc_size;
585 size_t jsGCThreshold = JS_GetGCThreshold(runtime);
586
587 OOJSRelinquishContext(context);
588
589 [self writeMemStat:@"JavaScript heap: %@ (%lli objects, next collection at %@)", SizeString(jsSize), (long long)usage.obj_count, SizeString(jsGCThreshold)];
590#else
591 size_t jsSize = JS_GetGCParameter(runtime, JSGC_BYTES);
592 size_t jsMax = JS_GetGCParameter(runtime, JSGC_MAX_BYTES);
593 uint32_t jsGCCount = JS_GetGCParameter(runtime, JSGC_NUMBER);
594
595 OOJSRelinquishContext(context);
596
597 [self writeMemStat:@"JavaScript heap: %@ (limit %@, %u collections to date)", SizeString(jsSize), SizeString(jsMax), jsGCCount];
598#endif
599 return jsSize;
600}
601
602- (void)setTCPIgnoresDroppedPackets:(BOOL)flag
603{
604 if (_TCPIgnoresDroppedPackets != flag) {
605 OOLog(@"debugMonitor.TCPSettings", @"The TCP console will %@ TCP packets.",
606 (flag ? @"try to stay connected, ignoring dropped" : @"disconnect if an error affects"));
607 }
608 _TCPIgnoresDroppedPackets = flag;
609}
610
611- (BOOL)TCPIgnoresDroppedPackets
612{
613 return _TCPIgnoresDroppedPackets;
614}
615
616- (void)setUsingPlugInController:(BOOL)flag
617{
618 _usingPlugInController = flag;
619}
620
621- (BOOL)usingPlugInController
622{
623 return _usingPlugInController;
624}
625
626- (NSString*)sourceCodeForFile:(in NSString*)filePath line:(in unsigned)line
627{
628 id linesForFile = nil;
629
630 linesForFile = [_sourceFiles objectForKey:filePath];
631
632 if (linesForFile == nil) {
633 linesForFile = [self loadSourceFile:filePath];
634 if (linesForFile == nil)
635 linesForFile = [NSArray arrayWithObject:[NSString stringWithFormat:@"<Can't load file %@>", filePath]];
636
637 if (_sourceFiles == nil)
638 _sourceFiles = [[NSMutableDictionary alloc] init];
639 [_sourceFiles setObject:linesForFile forKey:filePath];
640 }
641
642 if ([linesForFile count] < line || line == 0)
643 return @"<line out of range!>";
644
645 return [linesForFile objectAtIndex:line - 1];
646}
647
648- (void)disconnectDebugger:(in id<OODebuggerInterface>)debugger
649 message:(in NSString*)message
650{
651 if (debugger == nil)
652 return;
653
654 if (debugger == _debugger) {
655 [self disconnectDebuggerWithMessage:message];
656 } else {
657 OOLog(@"debugMonitor.disconnect.ignored", @"Attempt to disconnect debugger %@, which is not current debugger; ignoring.", debugger);
658 }
659}
660
661#if OOLITE_SDL
662- (void)applicationWillTerminate
663{
664 [[NSNotificationCenter defaultCenter] postNotificationName:NSApplicationWillTerminateNotification object:nil];
665}
666#endif
667
668- (void)applicationWillTerminate:(NSNotification*)notification
669{
670 if (_configOverrides != nil) {
671 [[NSUserDefaults standardUserDefaults] setObject:_configOverrides forKey:@"debug-settings-override"];
672 }
673
674 [self disconnectDebuggerWithMessage:@"Oolite is terminating."];
675}
676
677@end
678
679@implementation OODebugMonitor (Private)
680
681- (void)setUpDebugConsoleScript
682{
683 JSContext* context = OOJSAcquireContext();
684 /* The path to the console script is saved in this here static variable
685 so that we can reload it when resetting into strict mode.
686 -- Ahruman 2011-02-06
687 */
688 static NSString* path = nil;
689
690 if (path == nil) {
691 path = [[ResourceManager pathForFileNamed:@"oolite-debug-console.js" inFolder:@"Scripts"] retain];
692 }
693 if (path != nil) {
694#if OOJS_QUICKJS
695 JSValue special = JSSpecialFunctionsObjectWrapper(context);
696 OOJSValue* specialWrapper = [OOJSValue valueWithJSValue:special inContext:context];
697 JS_FreeValue(context, special);
698#else
699 OOJSValue* specialWrapper = JSSpecialFunctionsObjectWrapper(context);
700#endif
701 NSDictionary* jsProps = [NSDictionary dictionaryWithObjectsAndKeys:
702 self, @"console",
703 specialWrapper, @"special",
704 nil];
705 _script = [[OOJSScript scriptWithPath:path properties:jsProps] retain];
706 }
707
708 // If no script, just make console visible globally as debugConsole.
709 if (_script == nil) {
710#if OOJS_QUICKJS
711 JS_DefinePropertyValueStr(context, [[OOJavaScriptEngine sharedEngine] globalObject], "debugConsole", [self oo_jsValueInContext:context], JS_PROP_ENUMERABLE);
712#else
713 JSObject* global = [[OOJavaScriptEngine sharedEngine] globalObject];
714 JS_DefineProperty(context, global, "debugConsole", [self oo_jsValueInContext:context], NULL, NULL, JSPROP_ENUMERATE);
715#endif
716 }
717
718 OOJSRelinquishContext(context);
719}
720
721- (void)javaScriptEngineWillReset:(NSNotification*)notification
722{
723 DESTROY(_script);
724#if OOJS_QUICKJS
725 if (JS_IsObject(_jsSelf)) {
726 JS_FreeValue(OOJSAcquireContext(), _jsSelf);
727 }
728 _jsSelf = JS_UNDEFINED;
729#else
730 _jsSelf = NULL;
731
733#endif
734}
735
736- (void)disconnectDebuggerWithMessage:(NSString*)message
737{
738 @try {
739 [_debugger disconnectDebugMonitor:self message:message];
740 }
741 @catch (NSException* exception) {
742 OOLog(@"debugMonitor.debuggerConnection.exception", @"Exception while attempting to disconnect debugger: %@ -- %@", [exception name], [exception reason]);
743 }
744
745 id debugger = _debugger;
746 _debugger = nil;
747 [debugger release];
748}
749
750- (NSDictionary*)mergedConfiguration
751{
752 NSMutableDictionary* result = nil;
753
754 result = [NSMutableDictionary dictionary];
755 if (_configFromOXPs != nil)
756 [result addEntriesFromDictionary:_configFromOXPs];
757 if (_configOverrides != nil)
758 [result addEntriesFromDictionary:_configOverrides];
759
760 return result;
761}
762
763- (NSArray*)loadSourceFile:(NSString*)filePath
764{
765 NSString* contents = nil;
766 NSArray* lines = nil;
767
768 if (filePath == nil)
769 return nil;
770
771 contents = [NSString stringWithContentsOfUnicodeFile:filePath];
772 if (contents == nil)
773 return nil;
774
775 /* Extract lines from file.
776FIXME: this works with CRLF and LF, but not CR.
777 */
778 lines = [contents componentsSeparatedByString:@"\n"];
779 return lines;
780}
781
782- (NSMutableDictionary*)normalizeConfigDictionary:(NSDictionary*)dictionary
783{
784 NSMutableDictionary* result = nil;
785 NSString* key = nil;
786 id value = nil;
787
788 result = [NSMutableDictionary dictionaryWithCapacity:[dictionary count]];
789 foreachkey(key, dictionary)
790 {
791 value = [dictionary objectForKey:key];
792 value = [self normalizeConfigValue:value forKey:key];
793
794 if (key != nil && value != nil)
795 [result setObject:value forKey:key];
796 }
797
798 return result;
799}
800
801- (id)normalizeConfigValue:(id)value forKey:(NSString*)key
802{
803 OOColor* color = nil;
804 BOOL boolValue;
805
806 if (value != nil) {
807 if ([key hasSuffix:@"-color"] || [key hasSuffix:@"-colour"]) {
808 color = [OOColor colorWithDescription:value];
809 value = [color normalizedArray];
810 } else if ([key hasPrefix:@"show-console"]) {
811 boolValue = OOBooleanFromObject(value, NO);
812 value = [NSNumber numberWithBool:boolValue];
813 }
814 }
815
816 return value;
817}
818
819#if OOJS_QUICKJS
820- (oneway void)jsEngine:(in byref OOJavaScriptEngine*)engine
821 context:(in JSContext*)context
822 problemOfSeverity:(in NSString*)severity
823 inFile:(in NSString*)filePath
824 line:(in unsigned)line
825 stackSkip:(in unsigned)stackSkip
826 showingLocation:(in BOOL)showLocation
827 withMessage:(in NSString*)message
828{
829 NSString* colorKey = nil;
830 NSString* prefix = nil;
831 NSString* sourceLine = nil;
832 NSString* scriptLine = nil;
833 NSMutableString* formattedMessage = nil;
834 NSRange emphasisRange;
835 NSString* showKey = nil;
836 BOOL isWarning = [severity isEqualToString:@"warning"];
837
838 if (_debugger == nil)
839 return;
840
841 // QuickJS reports errors as exceptions; there are no non-exception errors or strict mode warnings.
842 if (isWarning) {
843 colorKey = @"warning";
844 prefix = @"Warning";
845 } else {
846 colorKey = @"exception";
847 prefix = @"Exception";
848 }
849
850 // Prefix and subsequent colon should be bold:
851 emphasisRange = NSMakeRange(0, [prefix length] + 1);
852
853 formattedMessage = [NSMutableString stringWithFormat:@"%@: %@", prefix, message];
854
855 // Note that the "active script" isn't necessarily the one causing the
856 // error, since one script can call another's methods.
857
858 // avoid windows DEP exceptions!
859 OOJSScript* thisScript = [[OOJSScript currentlyRunningScript] weakRetain];
860 scriptLine = [[thisScript weakRefUnderlyingObject] displayName];
861 [thisScript release];
862
863 if (scriptLine != nil) {
864 [formattedMessage appendFormat:@"\n Active script: %@", scriptLine];
865 }
866
867 if (showLocation && stackSkip == 0 && [filePath length] != 0) {
868 // Append file name and line
869 [formattedMessage appendFormat:@"\n %@, line %u", [filePath lastPathComponent], line];
870
871 // Append source code
872 sourceLine = [self sourceCodeForFile:filePath line:line];
873 if (sourceLine != nil) {
874 [formattedMessage appendFormat:@":\n %@", sourceLine];
875 }
876 }
877
878 [self appendJSConsoleLine:formattedMessage
879 colorKey:colorKey
880 emphasisRange:emphasisRange];
881
882 if (isWarning)
883 showKey = @"show-console-on-warning";
884 else
885 showKey = @"show-console-on-error"; // if not a warning, it's a proper error.
886 if (OOBooleanFromObject([self configurationValueForKey:showKey], NO)) {
887 [self showJSConsole];
888 }
889}
890#else
891- (oneway void)jsEngine:(in byref OOJavaScriptEngine*)engine
892 context:(in JSContext*)context
893 error:(in JSErrorReport*)errorReport
894 stackSkip:(in unsigned)stackSkip
895 showingLocation:(in BOOL)showLocation
896 withMessage:(in NSString*)message
897{
898 NSString* colorKey = nil;
899 NSString* prefix = nil;
900 NSString* filePath = nil;
901 NSString* sourceLine = nil;
902 NSString* scriptLine = nil;
903 NSMutableString* formattedMessage = nil;
904 NSRange emphasisRange;
905 NSString* showKey = nil;
906
907 if (_debugger == nil)
908 return;
909
910 if (errorReport->flags & JSREPORT_WARNING) {
911 colorKey = @"warning";
912 prefix = @"Warning";
913 } else if (errorReport->flags & JSREPORT_EXCEPTION) {
914 colorKey = @"exception";
915 prefix = @"Exception";
916 } else {
917 colorKey = @"error";
918 prefix = @"Error";
919 }
920
921 if (errorReport->flags & JSREPORT_STRICT) {
922 prefix = [prefix stringByAppendingString:@" (strict mode)"];
923 }
924
925 // Prefix and subsequent colon should be bold:
926 emphasisRange = NSMakeRange(0, [prefix length] + 1);
927
928 formattedMessage = [NSMutableString stringWithFormat:@"%@: %@", prefix, message];
929
930 // Note that the "active script" isn't necessarily the one causing the
931 // error, since one script can call another's methods.
932
933 // avoid windows DEP exceptions!
934 OOJSScript* thisScript = [[OOJSScript currentlyRunningScript] weakRetain];
935 scriptLine = [[thisScript weakRefUnderlyingObject] displayName];
936 [thisScript release];
937
938 if (scriptLine != nil) {
939 [formattedMessage appendFormat:@"\n Active script: %@", scriptLine];
940 }
941
942 if (showLocation && stackSkip == 0) {
943 // Append file name and line
944 if (errorReport->filename != NULL)
945 filePath = [NSString stringWithUTF8String:errorReport->filename];
946 if ([filePath length] != 0) {
947 [formattedMessage appendFormat:@"\n %@, line %u", [filePath lastPathComponent], errorReport -> lineno];
948
949 // Append source code
950 sourceLine = [self sourceCodeForFile:filePath line:errorReport->lineno];
951 if (sourceLine != nil) {
952 [formattedMessage appendFormat:@":\n %@", sourceLine];
953 }
954 }
955 }
956
957 [self appendJSConsoleLine:formattedMessage
958 colorKey:colorKey
959 emphasisRange:emphasisRange];
960
961 if (errorReport->flags & JSREPORT_WARNING)
962 showKey = @"show-console-on-warning";
963 else
964 showKey = @"show-console-on-error"; // if not a warning, it's a proper error.
965 if (OOBooleanFromObject([self configurationValueForKey:showKey], NO)) {
966 [self showJSConsole];
967 }
968}
969
970#endif
971
972- (oneway void)jsEngine:(in byref OOJavaScriptEngine*)engine
973 context:(in JSContext*)context
974 logMessage:(in NSString*)message
975 ofClass:(in NSString*)messageClass
976{
977 [self appendJSConsoleLine:message colorKey:@"log"];
978 if (OOBooleanFromObject([self configurationValueForKey:@"show-console-on-log"], NO)) {
979 [self showJSConsole];
980 }
981}
982
983#if OOJS_QUICKJS
984- (JSValue)oo_jsValueInContext:(JSContext*)context
985{
986 if (!JS_IsObject(_jsSelf)) {
987 _jsSelf = DebugMonitorToJSConsole(context, self);
988 }
989 return JS_DupValue(context, _jsSelf);
990}
991#else
992- (jsval)oo_jsValueInContext:(JSContext*)context
993{
994 if (_jsSelf == NULL) {
995 _jsSelf = DebugMonitorToJSConsole(context, self);
996 if (_jsSelf != NULL) {
997 if (!OOJSAddGCObjectRoot(context, &_jsSelf, "debug console")) {
998 _jsSelf = NULL;
999 }
1000 }
1001 }
1002
1003 if (_jsSelf != NULL)
1004 return OBJECT_TO_JSVAL(_jsSelf);
1005 else
1006 return JSVAL_NULL;
1007}
1008#endif
1009
1010@end
1011
1012@implementation OODebugMonitor (Singleton)
1013
1014/* Canonical singleton boilerplate.
1015See Cocoa Fundamentals Guide: Creating a Singleton Instance.
1016See also +sharedDebugMonitor above.
1017
1018NOTE: assumes single-threaded access.
1019*/
1020
1021+ (id)allocWithZone:(NSZone*)inZone
1022{
1023 if (sSingleton == nil) {
1024 sSingleton = [super allocWithZone:inZone];
1025 return sSingleton;
1026 }
1027 return nil;
1028}
1029
1030- (id)copyWithZone:(NSZone*)inZone
1031{
1032 return self;
1033}
1034
1035- (id)retain
1036{
1037 return self;
1038}
1039
1040- (NSUInteger)retainCount
1041{
1042 return UINT_MAX;
1043}
1044
1045- (void)release
1046{
1047}
1048
1049- (id)autorelease
1050{
1051 return self;
1052}
1053
1054@end
1055
1056#endif /* OO_DEBUG_MONITOR_ENABLED */
BOOL OOBooleanFromObject(id object, BOOL defaultValue)
#define DESTROY(x)
#define foreachkey(VAR, DICT)
JSObject * DebugMonitorToJSConsole(JSContext *context, OODebugMonitor *monitor)
void OOJSConsoleDestroy(void)
#define OOJSStopTimeLimiter()
#define kOOJSLongTimeLimit
#define OOJSStartTimeLimiterWithTimeLimit(limit)
OOJSValue * JSSpecialFunctionsObjectWrapper(JSContext *context)
void OOJSPauseTimeLimiter(void)
jsval OOJSVal
#define OOJSFreeValue(context, value)
OOINLINE jsval OOJSValueFromNativeObject(JSContext *context, id object)
OOINLINE JSContext * OOJSAcquireContext(void)
#define OOJSAddGCObjectRoot(context, root, name)
OOINLINE void OOJSRelinquishContext(JSContext *context)
void OOJSResumeTimeLimiter(void)
void OOLogOutdent(void)
Definition OOLogging.m:354
#define OOLog(class, format,...)
Definition OOLogging.h:84
void OOLogIndent(void)
Definition OOLogging.m:345
static OONullTexture * sSingleton
return self
unsigned count
return nil
OOINLINE OOScalar magnitude(Vector vec) INLINE_CONST_FUNC
Definition OOVector.h:242
#define PlanetEntity
#define PLAYER
OOColor * colorWithDescription:(id description)
Definition OOColor.m:135
NSArray * normalizedArray()
Definition OOColor.m:465
id scriptWithPath:properties:(NSString *path,[properties] NSDictionary *properties)
Definition OOJSScript.m:89
OOJSScript * currentlyRunningScript()
Definition OOJSScript.m:101
id valueWithJSValue:inContext:(jsval value,[inContext] JSContext *context)
OOJavaScriptEngine * sharedEngine()
void removeGCObjectRoot:(JSObject **rootPtr)
NSString * pathForFileNamed:inFolder:(NSString *fileName,[inFolder] NSString *folderName)
NSDictionary * dictionaryFromFilesNamed:inFolder:andMerge:(NSString *fileName,[inFolder] NSString *folderName,[andMerge] BOOL mergeFiles)
voidpf void uLong size
Definition ioapi.h:126
typedef long(ZCALLBACK *tell_file_func) OF((voidpf opaque