This repository has been archived by the owner on Mar 5, 2022. It is now read-only.
/
MWMATLABWindowController.m
584 lines (432 loc) · 16.3 KB
/
MWMATLABWindowController.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
#import "MWorksCocoa/MWCocoaEvent.h"
#import "MWorksCocoa/MWClientServerBase.h"
#import "MWorksCocoa/NSString+MWorksCocoaAdditions.h"
#import "MWorksCore/GenericData.h"
#import "MWorksCore/VariableProperties.h"
#import "MWMATLABWindowController.h"
#import "MWVarEntry.h"
@interface MWMATLABWindowController(Private)
- (void)codecArrived:(MWCocoaEvent *)codec;
- (void)updateClientCallbacks:(NSArray *)names_of_variables_to_register;
- (void)MATLABExecutionLoop:(id)obj;
- (void)serviceEvent:(MWCocoaEvent *)event;
- (void)reset;
- (void)updateCurrentSelectedVariables:(id)arg;
@end
#define MATLAB_WINDOW_CALLBACK_KEY @"MWorksMATLABWindow callback key"
#define MATLAB_EXECUTABLE_PATH @"MATLAB client window - MATLAB executable path"
#define MATLAB_M_FILE @"MATLAB client window - MATLAB .m file"
#define SYNC_EVENT_NAME @"MATLAB client window - sync event name"
#define SELECTED_VAR_NAMES @"MATLAB client window - selected variables"
#define COLLECTING_DATA @"MATLAB client window - running"
#define PROCESSING_DATA @"MATLAB client window - processing"
#define MW_SCROLL_TO_BOTTOM @"MATLAB client window - scroll to bottom on output"
@implementation MWMATLABWindowController
- (id) init {
self = [super init];
if (self != nil) {
matlabLock = [[NSLock alloc] init];
eventList = [[NSMutableArray alloc] init];
executionList = [[NSMutableArray alloc] init];
default_selected_variables = [[NSArray alloc] init];
collectingEvents = NO;
savedCodec = new Datum();
}
return self;
}
- (void)finalize {
delete savedCodec;
[executionList release];
[eventList release];
[matlabLock release];
[default_selected_variables release];
[super finalize];
}
- (void)dealloc {
delete savedCodec;
[executionList release];
[eventList release];
[matlabLock release];
[default_selected_variables release];
[super dealloc];
}
- (NSString *)matlabFileName {return [matlab_file_name lastPathComponent]; }
- (void)setMatlabFileName:(NSString *)new_matlab_file {
[matlab_file_name release];
matlab_file_name = [new_matlab_file copy];
[mi setMatlabFile:matlab_file_name];
}
- (void) setLogTextContent:(NSString *)new_content {
[logTextContent autorelease];
logTextContent = [new_content copy];
// set it in the UI
[[[logTextView textStorage] mutableString] setString:logTextContent];
};
@synthesize logTextContent;
@synthesize delegate;
- (void)setDelegate:(id)new_delegate {
if(![new_delegate respondsToSelector:@selector(unregisterCallbacksWithKey:)] ||
![new_delegate respondsToSelector:@selector(variableNames)] ||
![new_delegate respondsToSelector:@selector(registerEventCallbackWithReceiver:
selector:
callbackKey:
onMainThread:)] ||
![new_delegate respondsToSelector:@selector(registerEventCallbackWithReceiver:
selector:
callbackKey:
forVariableCode:
onMainThread:)] ||
![new_delegate respondsToSelector:@selector(codeForTag:)] ||
![new_delegate respondsToSelector:@selector(updateVariableWithTag:
withData:)]) {
[NSException raise:NSInternalInconsistencyException
format:@"Delegate doesn't respond to required methods for MWMATLABWindowController"];
}
delegate = new_delegate;
[delegate registerEventCallbackWithReceiver:self
selector:@selector(codecArrived:)
callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
forVariableCode:RESERVED_CODEC_CODE
onMainThread:YES];
}
- (void)awakeFromNib {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[self setProcessing:[defaults boolForKey:PROCESSING_DATA]];
[self setRunning:[defaults boolForKey:COLLECTING_DATA]];
NSString *matlabFile = [defaults objectForKey:MATLAB_M_FILE];
if(matlabFile != nil) {
[self setMatlabFileName:matlabFile];
}
if([defaults stringForKey:SYNC_EVENT_NAME]) {
self.syncEventName = [defaults stringForKey:SYNC_EVENT_NAME];
} else {
self.syncEventName = @"";
}
[NSThread detachNewThreadSelector:@selector(MATLABExecutionLoop:)
toTarget:self
withObject:nil];
[self setLogTextContent:@"Matlab output:\n"];
if ([defaults boolForKey:MW_SCROLL_TO_BOTTOM]) {
scrollToBottom = [defaults boolForKey:MW_SCROLL_TO_BOTTOM];
} else {
scrollToBottom = TRUE;
}
if (scrollToBottom == TRUE) {
[scrollToBottomButton setState:NSOnState];
} else {
[scrollToBottomButton setState:NSOffState];
}
}
// *******************************************************************
// * Interface builder methods
// *******************************************************************
- (IBAction)chooseMATLABFile:(id)sender {
[matlabLock lock];
NSOpenPanel * op = [NSOpenPanel openPanel];
[op setTitle:@"Select MATLAB .m file to open"];
[op setCanChooseDirectories:NO];
[op setCanChooseFiles:YES];
[op setAllowsMultipleSelection:NO];
[op setAllowedFileTypes:[NSArray arrayWithObject:@"m"]];
int bp = [op runModal];
if(bp == NSFileHandlingPanelOKButton) {
NSArray * fn = [op URLs];
NSEnumerator * fileEnum = [fn objectEnumerator];
NSURL * filename;
NSString *matlabFile;
while((filename = [fileEnum nextObject])) {
matlabFile = [filename path];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:matlabFile forKey:MATLAB_M_FILE];
[self setMatlabFileName:matlabFile];
}
[matlabLock unlock];
[self reset];
}
- (IBAction)primeMATLABEngine:(id)sender {
[matlabLock lock];
[mi startMATLABEngine];
[matlabLock unlock];
}
- (IBAction)resetAction:(id)sender {
[self reset];
}
/**********************************
* Accessors
**********************************/
- (NSString *)syncEventName { return sync_event_name; }
- (void)setSyncEventName:(NSString *)new_sync_event_name {
@synchronized(vl) {
[sync_event_name release];
sync_event_name = [new_sync_event_name copy];
[vl setSyncEventName:sync_event_name];
[[NSUserDefaults standardUserDefaults] setObject:sync_event_name forKey:SYNC_EVENT_NAME];
[self updateVariableFilter];
[vl reloadData];
}
[self reset];
}
- (int)processing { return processing; }
- (void)setProcessing:(int)new_processing {
[[NSUserDefaults standardUserDefaults] setBool:new_processing forKey:PROCESSING_DATA];
processing = new_processing;
}
- (int)running { return running; }
- (void)setRunning:(int)new_running {
[[NSUserDefaults standardUserDefaults] setBool:new_running forKey:COLLECTING_DATA];
running = new_running;
}
@synthesize numberToProcessString = number_to_process_string;
/*******************************************************************
* MWDataEventListenerProtocol Methods
*******************************************************************/
- (void)serviceEvent:(MWCocoaEvent *)event {
[matlabLock lock];
if(running == NSOnState) {
if([event code] == [[delegate codeForTag:sync_event_name] intValue]) {
Datum *syncData = [event data];
if(syncData->getInteger() > 0 && !collectingEvents) {
collectingEvents = YES;
[eventList removeAllObjects];
} else if(syncData->getInteger() == 0) {
if(collectingEvents) {
collectingEvents = NO;
[eventList addObject:event];
[executionList addObject:[NSArray arrayWithArray:eventList]];
[eventList removeAllObjects];
}
}
}
if(collectingEvents) {
[eventList addObject:event];
}
}
[matlabLock unlock];
}
// *******************************************************************
// * MWWindowController Methods
// *******************************************************************
- (NSString *)mWorksFrameAutosaveName {
return @"MWorksMATLABWindow";
}
#define MATLAB_DEBUG_OUTPUT_MAX_LENGTH 10000
- (IBAction)changeScrollToBottom:(id)sender {
if ([sender state] == NSOnState) {
[self doScrollToBottom];
scrollToBottom = TRUE;
} else {
scrollToBottom = FALSE;
}
[[NSUserDefaults standardUserDefaults] setBool:scrollToBottom forKey:MW_SCROLL_TO_BOTTOM];
//if ([sender state] == NSOffState) {
// do nothing
}
// *******************************************************************
// * Private Methods
// *******************************************************************
- (void) doScrollToBottomMain {
[logTextView scrollRangeToVisible:NSMakeRange([[logTextView textStorage] length], 0) ];
}
- (void) appendLogTextMain:(NSString *)logText {
//NSString *log = [logTextContent copy];
NSMutableString* tStr = [[self->logTextView textStorage] mutableString];
[tStr appendString:logText];
if ([tStr characterAtIndex:[tStr length]-1] != '\n') {
// append newline
[tStr appendString:@"\n"];
}
// Trim the beginning of the string if it is too long
if ([tStr length] > MATLAB_DEBUG_OUTPUT_MAX_LENGTH) {
NSRange deleteRange = NSMakeRange(0, ([tStr length] - MATLAB_DEBUG_OUTPUT_MAX_LENGTH));
[tStr deleteCharactersInRange:deleteRange];
}
[self->logTextView setNeedsDisplay:YES];
if (self->scrollToBottom) {
[self doScrollToBottom];
}
}
- (void)codecArrived:(MWCocoaEvent *)event {
[matlabLock lock];
Datum *new_codec = [event data];
if (*new_codec == *savedCodec) {
// Codec is unchanged. No need to reset anything.
[matlabLock unlock];
return;
}
// need to force it by capturing the pointer so it makes it a dictionary
delete savedCodec;
savedCodec = new Datum(*new_codec);
NSArray *current_selected_variables = [NSArray array];
[self performSelectorOnMainThread:@selector(updateDefaultSelectedVariables:)
withObject:nil
waitUntilDone:YES];
@synchronized(vl) {
[vl clear];
// determine max code number of codec
int max_key = -1;
for(int i=0; i< new_codec->getNElements(); ++i) {
max_key = MAX(new_codec->getScarabDatum()->data.dict->keys[i]->data.integer, max_key);
}
for(int i=0;i<=max_key;++i) {
Datum codec_entry(new_codec->getElement(Datum(M_INTEGER, i)));
if(!codec_entry.isUndefined()) {
NSString *variableName = [NSString stringWithCString:codec_entry.getElement("tagname").getString()
encoding:NSASCIIStringEncoding];
MWVarEntry *var = [[MWVarEntry alloc] initWithName:variableName];
// select previous variables
if(default_selected_variables != nil) {
NSEnumerator *enumerator = [default_selected_variables objectEnumerator];
NSString *selectedVariableName;
while(selectedVariableName = [enumerator nextObject]) {
if([selectedVariableName isEqualToString:variableName]) {
[var setSelected:YES];
}
}
}
[vl addVariable:[var autorelease]];
}
}
[vl setSyncEventName:[self syncEventName]];
current_selected_variables = [vl currentSelectedVariables];
[vl reloadData];
}
[matlabLock unlock];
[self updateClientCallbacks:current_selected_variables];
[self reset];
}
// must be run on main thread
- (void)updateDefaultSelectedVariables:(id)arg {
[default_selected_variables release];
default_selected_variables = [[NSArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:SELECTED_VAR_NAMES]];
}
- (void)updateClientCallbacks:(NSArray *)codes_to_register {
[delegate unregisterCallbacksWithKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]];
// register for codecs
[delegate registerEventCallbackWithReceiver:self
selector:@selector(codecArrived:)
callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
forVariableCode:RESERVED_CODEC_CODE
onMainThread:YES];
NSString *name;
NSEnumerator *enumerator = [codes_to_register objectEnumerator];
while(name = [enumerator nextObject]) {
NSNumber *event_code = [delegate codeForTag:name];
[delegate registerEventCallbackWithReceiver:self
selector:@selector(serviceEvent:)
callbackKey:[MATLAB_WINDOW_CALLBACK_KEY UTF8String]
forVariableCode:[event_code intValue]
onMainThread:YES];
}
}
- (void)MATLABExecutionLoop:(id)obj {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
do {
NSAutoreleasePool *pool2 = [[NSAutoreleasePool alloc] init];
[matlabLock lock];
self.numberToProcessString = [NSString stringWithFormat:@"Process %lu events", (unsigned long)[executionList count]];
[matlabLock unlock];
if(processing == NSOnState) {
NSArray *eventsToExecute = nil;
[matlabLock lock];
Datum codec(*savedCodec);
if([executionList count] > 0 && codec.isDictionary()) {
eventsToExecute = [[executionList objectAtIndex:0] retain];
[executionList removeObjectAtIndex:0];
}
[matlabLock unlock];
if(eventsToExecute != nil && codec.isDictionary()) {
mxArray *dataStruct = [mi createDataStruct:eventsToExecute
withCodec:&codec];
[mi runMatlabFile:dataStruct];
mxDestroyArray(dataStruct);
[eventsToExecute release];
}
}
usleep(5000); // sleep to surrender the processor
[pool2 release];
} while (1);
[pool release];
}
// this must be locked before being called
- (void)reset {
[matlabLock lock];
collectingEvents = NO;
// [delegate set:[[delegate codeForTag:[self syncEventName]] intValue] to:&sync_zero];
// [delegate setValue:[NSNumber numberWithInt:0] forKey:[@"variables." stringByAppendingString:self.syncEventName]];
NSArray *variable_names = [delegate variableNames];
NSEnumerator *var_name_enumerator = [variable_names objectEnumerator];
NSString *var_name = nil;
while(var_name = [var_name_enumerator nextObject]) {
if([var_name isEqualToString:self.syncEventName]) {
Datum data(0L);
[delegate updateVariableWithTag:self.syncEventName
withData:&data];
}
}
[mi resetRetval];
[executionList removeAllObjects];
[matlabLock unlock];
}
///////////////////////////////////////////////////////////////////////
// Delegate functions
///////////////////////////////////////////////////////////////////////
// this only gets called from the main thread
- (void)updateVariableFilter {
[matlabLock lock];
NSArray *selected_variables;
@synchronized(vl) {
selected_variables = [vl currentSelectedVariables];
}
if([selected_variables count] > 1) {
// don't update the defaults until there is some variables to update
[[NSUserDefaults standardUserDefaults] setObject:selected_variables forKey:SELECTED_VAR_NAMES];
}
[matlabLock unlock];
[self updateClientCallbacks:selected_variables];
}
- (void) appendLogText:(NSString *)logText {
[self performSelectorOnMainThread: @selector(appendLogTextMain:)
withObject: logText
waitUntilDone: NO];
}
-(void) doScrollToBottom {
[self performSelectorOnMainThread:@selector(doScrollToBottomMain)
withObject:nil
waitUntilDone:YES];
}
- (NSDictionary *)workspaceState {
NSMutableDictionary *workspaceState = [NSMutableDictionary dictionary];
if (running == NSOnState) {
if (matlab_file_name) {
[workspaceState setObject:matlab_file_name forKey:@"filePath"];
}
if (sync_event_name) {
[workspaceState setObject:sync_event_name forKey:@"syncEventName"];
}
@synchronized(vl) {
[workspaceState setObject:[vl currentSelectedVariables] forKey:@"selectedVariables"];
}
}
return workspaceState;
}
- (void)setWorkspaceState:(NSDictionary *)workspaceState {
NSString *newFilePath = [workspaceState objectForKey:@"filePath"];
if (newFilePath && [newFilePath isKindOfClass:[NSString class]]) {
newFilePath = [newFilePath mwk_absolutePath];
[[NSUserDefaults standardUserDefaults] setObject:newFilePath forKey:MATLAB_M_FILE];
[self setMatlabFileName:newFilePath];
}
NSString *newSyncEventName = [workspaceState objectForKey:@"syncEventName"];
if (newSyncEventName && [newSyncEventName isKindOfClass:[NSString class]]) {
[self setSyncEventName:newSyncEventName];
}
NSArray *newSelectedVariables = [workspaceState objectForKey:@"selectedVariables"];
if (newSelectedVariables &&
[newSelectedVariables isKindOfClass:[NSArray class]] &&
[newSelectedVariables count] > 0)
{
[[NSUserDefaults standardUserDefaults] setObject:newSelectedVariables forKey:SELECTED_VAR_NAMES];
}
}
@end