forked from bart-group/BART
/
NEPresentationController.m
643 lines (516 loc) · 19.2 KB
/
NEPresentationController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
//
// NEPresentationController.m
// BARTPresentation
//
// Created by Oliver Zscheyge on 4/6/10.
// Copyright 2010 MPI Cognitive and Human Brain Scienes Leipzig. All rights reserved.
//
//internal presentation stuff
#import "NEPresentationController.h"
#import "NEMediaText.h"
#import "NEStimEvent.h"
#import "NEPresentationLogger.h"
#import "NELogFormatter.h"
#import "NEViewManager.h"
#import "NEPresentationExternalConditionController.h"
//Feedback stuff
#import "NEFeedbackHeli.h"
#import "NEFeedbackThermo.h"
//config
#import "COExperimentContext.h"
/** The time interval for one update tick in milliseconds. */
#define TICK_TIME 1
/** The time interval for the update in seconds.*/
static const NSTimeInterval UPDATE_INTERVAL = TICK_TIME * 0.001;
/* Simple tuple class because Cocoa lacks one... */
@interface _NETuple : NSObject
{
id first;
id second;
}
@property (readonly) id first;
@property (readonly) id second;
-(id)initWithFirst:(id)fst
andSecond:(id)snd;
@end
@implementation _NETuple
@synthesize first;
@synthesize second;
-(id)initWithFirst:(id)fst
andSecond:(id)snd
{
if ((self = [super init])) {
first = [fst retain];
second = [snd retain];
}
return self;
}
-(void)dealloc
{
[first release];
[second release];
[super dealloc];
}
@end
/* END Tuple class. */
@interface NEPresentationController (PrivateMethods)
/**
* Entry point for mUpdateThread: creates an autorelease
* pool, continuously updates the timetable and views unti
* the presentation is over and finally cleans the thread.
*/
-(void)runUpdateThread;
/**
* Simulates one time tick (currently 20ms).
*/
-(void)tick;
/**
* Integrates all events from mChangedEvents into mTimetable
* (and removes those from mChangedEvents).
*/
-(void)updateTimetable;
/**
* Handles events starting at mTime (submits the media object
* to the PresentationView and adds to event to mEventsToEnd).
*/
-(void)handleStartingEvents;
/**
* Handles events ending at mTime (removing the media object
* from the PresentationView).
*/
-(void)handleEndingEvents;
/**
* Resets all time and trigger measuring variables to 0.
*/
-(void)resetTimeAndTriggerCount;
/**
* checks for the fullfillment of the external conditions
*/
-(NSDictionary*)checkForExternalConditionsForEvent:(NEStimEvent*)event;
/**
* starts the updateThread ,i.e. the real start of the presentation
*/
-(void)startPresentation;
-(void)doActionOnTimeTable:(NSDictionary*)action
withResultVariables:(NSDictionary*)resVariables
atEvent:(NEStimEvent*)currentEvent;
@end
@implementation NEPresentationController
@synthesize mTriggerCount;
@synthesize mLastTriggersTime;
@synthesize mExternalConditionController;
-(id)initWithView:(NEViewManager*)view
andTimetable:(NETimetable*)timetable
{
if ((self = [super init])) {
mViewManager = [view retain];
mTimetable = [timetable retain];
mEventsToEnd = [[NSMutableArray alloc] initWithCapacity:0];
mAddedEvents = [[NSMutableArray alloc] initWithCapacity:0];
mLockAddedEvents = [[NSLock alloc] init];
mChangedEvents = [[NSMutableArray alloc] initWithCapacity:0];
mLockChangedEvents = [[NSLock alloc] init];
mLogger = [NEPresentationLogger getInstance];
mUpdateThread = [[NSThread alloc] initWithTarget:self selector:@selector(runUpdateThread) object:nil];
mTR = (NSUInteger) [[[[COExperimentContext getInstance] systemConfig] getProp:@"$TR"] integerValue];
[self resetTimeAndTriggerCount];
[mViewManager setTimetable:mTimetable];
[mViewManager setController:self];
//register itself as an observer for the trigger messages from the sacnner
COExperimentContext *expContext = [COExperimentContext getInstance];
[expContext addOberserver:self forProtocol:@"BARTScannerTriggerProtocol"];
[expContext addOberserver:self forProtocol:@"BARTButtonPressProtocol"];
// TODO: hard-coded! get info from elsewhere!
// // Helicopter feedback.
// NSRect feedbackRect = NSMakeRect(200.0, 200.0, 400.0, 200.0);
// NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:@"0.0", @"minHeight",
// @"100.0", @"maxHeight",
// @"0.0", @"minFirerate",
// @"3.0", @"maxFirerate", nil];
// NEFeedbackObject* feedback = [[NEFeedbackHeli alloc] initWithFrame:feedbackRect
// andParameters:params];
// [mViewManager setFeedback:feedback];
// [feedback release];
// // Thermometer feedback.
// NSRect feedbackRect = NSMakeRect(350.0, 50.0, 100.0, 500.0);
// NSDictionary* params = [NSDictionary dictionaryWithObjectsAndKeys:@"0.0", @"minTemperature",
// @"50.0", @"maxTemperature", nil];
// NEFeedbackObject* feedback = [[NEFeedbackThermo alloc] initWithFrame:feedbackRect
// andParameters:params];
// [mViewManager setFeedback:feedback];
// [feedback release];
}
return self;
}
-(void)dealloc
{
[mViewManager release];
[mTimetable release];
[mEventsToEnd release];
[mChangedEvents release];
[mLockChangedEvents release];
[mAddedEvents release];
[mLockAddedEvents release];
[mUpdateThread release];
[super dealloc];
}
-(void)triggerArrived:(NSNotification*)aNotification
{
if (0 == [[aNotification object] unsignedLongValue])
{
[self startPresentation];
}
NSUInteger triggerCount = [self mTriggerCount] + 1;//tr
[mLogger logTrigger:triggerCount withTime:mTime];
[self setTriggerCount:triggerCount];
[self setLastTriggerTime:[NSDate timeIntervalSinceReferenceDate]];
}
-(void)buttonWasPressed:(NSNotification *)aNotification
{
// NSString *toLog = [NSString stringWithFormat:@"Button pressed: %u", [[aNotification object] unsignedCharValue]];
[mLogger logButtonPress:[[aNotification object] unsignedIntegerValue] atTrigger:mTriggerCount withTime:mTime];
//[mLogger log:toLog withTime:mTime];
}
-(void)requestAdditionOfEventWithTime:(NSUInteger)t
duration:(NSUInteger)dur
andMediaObjectID:(NSString*)mID
{
if (t < mTime) {
return;
}
NEMediaObject *mediaObj = [mTimetable getMediaObjectByID:mID];
NEStimEvent* event = [[NEStimEvent alloc] initWithTime:t
duration:dur
mediaObject:mediaObj];
if ([mUpdateThread isExecuting]) {
[mLockAddedEvents lock];
[mAddedEvents addObject:event];
[mLockAddedEvents unlock];
} else {
[mTimetable addEvent:event];
[mViewManager updateTimeline];
}
[event release];
return;
}
-(void)enqueueEvent:(NEStimEvent*)newEvent
asReplacementFor:(NEStimEvent*)oldEvent
{
if ([mUpdateThread isExecuting]) {
_NETuple* tuple = [[_NETuple alloc] initWithFirst:oldEvent andSecond:newEvent];
[mLockChangedEvents lock];
[mChangedEvents addObject:tuple];
[mLockChangedEvents unlock];
[tuple release];
} else {
[mTimetable replaceEvent:oldEvent
withEvent:newEvent];
}
}
-(NSUInteger)presentationDuration
{
return [mTimetable duration];
}
-(void)startListeningForTrigger
{
if (![mUpdateThread isExecuting]
&& ![mUpdateThread isCancelled]) {
[self resetTimeAndTriggerCount];
}
}
-(void)pausePresentation
{
if ([mUpdateThread isExecuting]) {
[mUpdateThread cancel];
[mViewManager pausePresentation];
}
}
-(void)stopPresentation
{
if ([mUpdateThread isExecuting]) {
[mUpdateThread cancel];
[mViewManager pausePresentation];
}
}
-(void)startPresentation
{
mLastTriggersTime = [NSDate timeIntervalSinceReferenceDate];
[mUpdateThread start];
}
-(void)continuePresentation
{
if ([mUpdateThread isFinished]) {
[mUpdateThread release];
mUpdateThread = [[NSThread alloc] initWithTarget:self selector:@selector(runUpdateThread) object:nil];
[mUpdateThread start];
[mViewManager continuePresentation];
}
}
-(void)resetPresentationToOriginal:(BOOL)toOriginalEvents
{
if ([mUpdateThread isExecuting] || [mUpdateThread isFinished]) {
[mUpdateThread cancel];
while (![mUpdateThread isFinished]) ; // Wait until run thread is finished.
}
[mUpdateThread release];
mUpdateThread = [[NSThread alloc] initWithTarget:self selector:@selector(runUpdateThread) object:nil];
[self resetTimeAndTriggerCount];
[mEventsToEnd removeAllObjects];
[mViewManager resetPresentation];
if (toOriginalEvents) {
[mTimetable resetTimetableToOriginalEvents];
} else {
[mTimetable resetTimetable];
}
/** BEGIN Test log output
*
* TODO: place elsewere and get tolerance from config!
*/
printf("### Log ###\n");
NSString *fName = @"BARTPresentationLogfile_";
NSString *log = [NSString stringWithFormat:@"/tmp/%@.log", fName];
//[[[COExperimentContext getInstance] logFilePath] stringByAppendingPathExtension:fName];
[mLogger printToFilePath:log];
[mLogger print];
printf("\n");
// printf("### Violations ###\n");
// for (NSString* violationMsg in [mLogger allMessagesViolatingTolerance:7]) {
// printf("%s\n", [violationMsg cStringUsingEncoding:NSUTF8StringEncoding]);
// }
// NSUInteger over100 = [[mLogger allMessagesViolatingTolerance:100] count] / 2;
// printf(">100: %ld\n", over100);
// NSUInteger over20 = [[mLogger allMessagesViolatingTolerance:20] count] / 2 - over100;
// printf(">20: %ld\n", over20);
// NSUInteger over7 = [[mLogger allMessagesViolatingTolerance:7] count] / 2 - (over20 + over100);
// printf(">7: %ld\n", over7);
[mLogger clear];
/** END Test log output. */
}
-(void)runUpdateThread
{
NSAutoreleasePool* autoreleasePool = [[NSAutoreleasePool alloc] init];
[mUpdateThread setThreadPriority:1.0];
while ([self mTriggerCount] == 0) {
// TODO: find suitable sleep interval!
}
do {
[self tick];
[NSThread sleepForTimeInterval:UPDATE_INTERVAL];
} while (![[NSThread currentThread] isCancelled]);
[autoreleasePool drain];
autoreleasePool = nil;
[NSThread exit];
}
-(void)tick
{
mCurrentTicksTime = [NSDate timeIntervalSinceReferenceDate];
NSUInteger timeDifference = (NSUInteger) ((mCurrentTicksTime - [self mLastTriggersTime]) * 1000.0);
if (mTime <= [mTimetable duration]) {
if (timeDifference < mTR - TICK_TIME) {
mTime = ([self mTriggerCount] - 1) * mTR + timeDifference;
}
//ask for conditions
NEStimEvent *event = [mTimetable previewNextEventAtTime:mTime];
//evaluate external condition
NSDictionary* externalCondition = [[self checkForExternalConditionsForEvent:event] retain];
if (nil != externalCondition)
{
BOOL isConditionFullfilled = YES;
for (NSString *s in [externalCondition objectForKey:@"conditionsArray"])
{
isConditionFullfilled = isConditionFullfilled && [s boolValue];
}
if (YES == isConditionFullfilled)
{
for (NSDictionary *action in [externalCondition objectForKey:@"actionsThen"])
{
[self doActionOnTimeTable:action
withResultVariables:[externalCondition objectForKey:@"resultVariables"]
atEvent:event];
}
}
else
{
for (NSDictionary *action in [externalCondition objectForKey:@"actionsElse"])
{
[self doActionOnTimeTable:action
withResultVariables:[externalCondition objectForKey:@"resultVariables"]
atEvent:event];
}
}
[externalCondition release];
}
[mViewManager setCurrentTime:mTime];
[self updateTimetable];
[self handleStartingEvents];
[self handleEndingEvents];
[mViewManager displayPresentationView];
} else {
[mUpdateThread cancel];
}
}
-(NSDictionary*)checkForExternalConditionsForEvent:(NEStimEvent *)event
{
if (NO == [[event mediaObject] isDependentFromConstraint])
{
return nil;
}
NSDictionary *dictReturn = nil;
dictReturn = [[mExternalConditionController checkConstraintForID:[[event mediaObject] getConstraintID]] retain];
if (nil != dictReturn)
{
return [dictReturn autorelease];
}
return nil;
}
-(void)doActionOnTimeTable:(NSDictionary*)action withResultVariables:(NSDictionary*)resVariables atEvent:(NEStimEvent*)currentEvent
{
NSString* fName = [action objectForKey:@"functionNameInternal"];
NSArray *attArray = [action objectForKey:@"attributesArray"];
NSString* toLog = [NSString stringWithFormat:@"Action: %@ with " , fName];
if (NSOrderedSame == [fName compare:@"replaceMediaObject"])
{
for (NSDictionary *att in attArray){
if ( NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"mediaObjectRef" options:NSCaseInsensitiveSearch])
{
NEMediaObject *mediaObj = [mTimetable getMediaObjectByID:[att objectForKey:@"attributeValue"]];
NEStimEvent *newEvent = [[NEStimEvent alloc] initWithTime:[currentEvent time]
duration:[currentEvent duration]
mediaObject:mediaObj];
[self enqueueEvent:newEvent asReplacementFor:currentEvent];
[newEvent release];
toLog = [toLog stringByAppendingFormat:@" %@", [mediaObj getID] ];
[mLogger log:toLog withTime:mTime];
return;
}
}
return;
}
if (NSOrderedSame == [fName compare:@"setMediaObjectParamter"])
{
NSString *paraName = nil;
float paraVal = 0.0;
for (NSDictionary *att in attArray){
if (NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"Name" options:NSCaseInsensitiveSearch])
{
paraName = [att objectForKey:@"attributeValue"];
}
else if (NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"systemVariableRef" options:NSCaseInsensitiveSearch])
{
NSString *key = [att objectForKey:@"attributeValue"];
paraVal = [[resVariables objectForKey:key] floatValue];
}
toLog = [toLog stringByAppendingFormat:@" parameter ",paraName];
toLog = [toLog stringByAppendingFormat:@"with value %.2f", paraVal];
}
[mLogger log:toLog withTime:mTime];
NEMediaObject *mo = [currentEvent mediaObject];
NSPoint p = NSMakePoint([mo position].x, [mo position].y);
if ( (nil != paraName) && (0 < [paraName rangeOfString:@"posX"].length) )
{
p.x = paraVal;
}
if ( (nil != paraName) && (0 < [paraName rangeOfString:@"posY"].length) )
{
p.y = paraVal;
}
[mo setPosition:p];
return;
}
if (NSOrderedSame == [fName compare:@"removeCurrentStimulusEvent"])
{
//TODO
return;
}
if (NSOrderedSame == [fName compare:@"insertNewStimulusEvent"])
{
NSUInteger duration = 0;
NSString *moRef = nil;
BOOL pushAllEvents = NO;
for (NSDictionary *att in attArray)
{
if (NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"mediaObjectRef" options:NSCaseInsensitiveSearch])
{
moRef = [att objectForKey:@"attributeValue"];
}
else if (NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"durationTime" options:NSCaseInsensitiveSearch])
{
duration = [[att objectForKey:@"attributeValue"] floatValue];
}
else if (NSOrderedSame == [[att objectForKey:@"attributeType"] compare:@"pushFlag" options:NSCaseInsensitiveSearch])
{
pushAllEvents = [[att objectForKey:@"attributeValue"] boolValue];
}
}
//TODO
//[self requestAdditionOfEventWithTime:[currentEvent time] duration:duration andMediaObjectID:moRef];
if (YES == pushAllEvents){
[mTimetable shiftOnsetForAllEventsToHappen:(NSUInteger)duration];
toLog = [toLog stringByAppendingFormat:@" %@ push %u ms", moRef, (NSUInteger)duration];
}
else{
toLog = [toLog stringByAppendingFormat:@" %@ no push", moRef];
}
[mLogger log:toLog withTime:mTime];
return;
}
return;
}
-(void)updateTimetable
{
// Add events.
[mLockAddedEvents lock];
for (NEStimEvent* event in mAddedEvents) {
[mTimetable addEvent:event];
}
[mAddedEvents removeAllObjects];
[mLockAddedEvents unlock];
// Replace events.
[mLockChangedEvents lock];
for (_NETuple* eventTuple in mChangedEvents) {
[mTimetable replaceEvent:[eventTuple first]
withEvent:[eventTuple second]];
}
[mChangedEvents removeAllObjects];
[mLockChangedEvents unlock];
// Remove events.
// TODO: implement removal of events.
}
-(void)handleStartingEvents
{
NEStimEvent* event = [mTimetable nextEventAtTime:mTime];
while (event) {
[mViewManager present:[event mediaObject]];
[NEStimEvent endTimeSortedInsertOf:event
inEventList:mEventsToEnd];
[mLogger logStartingEvent:event withTrigger:[self mTriggerCount] andTime:mTime];
event = [mTimetable nextEventAtTime:mTime];
}
}
-(void)handleEndingEvents
{
BOOL done = NO;
while ([mEventsToEnd count] > 0
&& !done) {
NEStimEvent* event = [mEventsToEnd objectAtIndex:0];
if (([event time] + [event duration]) <= mTime) {
[mViewManager stopPresentationOf:[event mediaObject]];
[mEventsToEnd removeObject:event];
[mLogger logEndingEvent:event withTrigger:[self mTriggerCount] andTime:mTime];
} else {
done = YES;
}
}
}
-(void)resetTimeAndTriggerCount
{
mTime = 0;
[self setTriggerCount:0];
//[mLogger printToFilePath:@"/tmp/MyLogFile.log"];
}
-(void)terminusFromScannerArrived:(NSNotification *)msg
{
NSLog(@"%@", msg);
[self resetPresentationToOriginal:NO];
}
@end