-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDailyDataDocument.m
1544 lines (950 loc) · 44.2 KB
/
DailyDataDocument.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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// DailyDataDocument.m
// Bartender
//
// Created by Tom Houpt on 09/6/14.dailu
// Copyright 2009 Behavioral Cybernetics. All rights reserved.
//
#import "DailyDataDocument.h"
#import "BarExperiment.h"
#import "BarItem.h"
#import "BCDailyDataWebView.h"
#import "BCAlert.h"
#import "BarBalance.h"
#import "FadeOutText.h"
#define kMaxNumWeightTries 20 // number of times to try and get a stable weight for scanned item
// if balance is checked every 0.1 s, this means trying for 2 seconds
BOOL useSpeech = NO;
@implementation DailyDataDocument
// ***************************************************************************************
// ***************************************************************************************
// NSDocument methods....
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
-(NSString *)windowNibName {
// Override returning the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
return @"DailyData";
}
-(void)windowControllerDidLoadNib:(NSWindowController *) aController {
[super windowControllerDidLoadNib:aController];
// Add any code here that needs to be executed once the windowController has loaded the document's window.
// // assume we only have one controller and one window...
// NSWindow myWindow = [ [ [ self windowControllers ] objectAtIndex:0 ] window ];
//
// if (kDataOnly == currentStatus) {
//
// // HIDE the window if we only need the daily data...
//
// [myWindow orderOut:self];
//
// }
// else {
// [myWindow makeKeyAndOrderFront:self]
//
// }
lastWeight = -32000.0;
if (useSpeech) {
speech = [[NSSpeechSynthesizer alloc] init];
}
// register for notifications
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(updateWeightDisplay:)
name:kBarBalanceReadingDidChangeNotification
object:nil];
}
-(NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError{
// Insert code here to write your document to data of the specified type. If the given outError != NULL, ensure that you set *outError when returning nil.
// You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// For applications targeted for Panther or earlier systems, you should use the deprecated API -dataRepresentationOfType:. In this case you can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return nil;
}
-(BOOL)readFromData:(NSData *)data ofType:(NSString *)typeName error:(NSError **)outError {
// Insert code here to read your document from the given data of the specified type. If the given outError != NULL, ensure that you set *outError when returning NO.
// You can also choose to override -readFromFileWrapper:ofType:error: or -readFromURL:ofType:error: instead.
// For applications targeted for Panther or earlier systems, you should use the deprecated API -loadDataRepresentation:ofType. In this case you can also choose to override -readFromFile:ofType: or -loadFileWrapperRepresentation:ofType: instead.
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return YES;
}
- (void)printShowingPrintPanel:(BOOL)showPanels; {
// If you want users to be able to print a document, you must override printOperationWithSettings: error:, possibly providing a modified NSPrintInfo object.
// get page size from [self printInfo]
// NSRect paperRect = NSMakeRect(0,0,[[self printInfo] paperSize].width, [[self printInfo] paperSize].height);
// Obtain a custom view that will be printed
// NSView *printView = [[BCDailyDataWebView alloc] initWithDailyData:dailyData andTable:dailyTableView];
BCDailyDataWebView *myWebView = [[BCDailyDataWebView alloc] initWithDailyData:dailyData andTable:dailyTableView];
NSView *printView = [[[myWebView mainFrame] frameView] documentView];
// Construct the print operation and setup Print panel
// NSPrintOperation *printOp = [NSPrintOperation
// printOperationWithView:printView
// printInfo:[self printInfo]];
// don't pass NSDocument printInfo to printOp: printView will show up in printPanel preview but won't print
// maybe because printView is not associated with an actual NSDocument
NSPrintOperation *printOp = [NSPrintOperation printOperationWithView:printView];
while ([myWebView isLoading]) { [[NSRunLoop currentRunLoop] limitDateForMode:NSDefaultRunLoopMode];}
[printOp runOperation];
if (closeAfterPrinting) {
[self removeFromBartender];
}
// the rest of this is for modal print
//
// [printOp setShowsPrintPanel:showPanels];
//
// if (showPanels) {
// // Add accessory view, if needed
// }
//
//
//
// // Run operation, which shows the Print panel if showPanels was YES
//
// [self runModalPrintOperation:printOp
// delegate:self
// didRunSelector:@selector(documentDidRunModalPrintOperation:success:contextInfo:)
// contextInfo:NULL];
//
}
//
//- (void)documentDidRunModalPrintOperation:(NSDocument *)document success:(BOOL)success contextInfo:(void *)contextInfo; {
//
// if (closeAfterPrinting) {
// [self removeFromBartender];
// }
//
//}
// ***************************************************************************************
// ***************************************************************************************
// setters and getters
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
-(BarDocument *)bartender {return bartender;}
-(void)setBartender:(BarDocument *)bt { bartender = bt;}
-(BarExperiment *)theExperiment { return theExperiment; }
-(void)startWeighingInState:(int)weighingState WithTheExperiment: (BarExperiment *)newExpt; {
currentState = weighingState;
[self setTheExperiment:newExpt];
}
-(void)startEditingDailyDay:(NSInteger)dayIndex WithTheExperiment: (BarExperiment *)newExpt; {
currentState = kUserEditing;
editingDayIndex = dayIndex;
[self setTheExperiment:newExpt];
}
- (void)setTheExperiment:(BarExperiment *)newExpt {
// set the values in the new expt panel
// using the values in the given expt
theExperiment = newExpt;
// title window with expt code and "ON" or "OFF"
// gets set even if theExperiment == nil
[self updateWindowTitle];
if (nil == theExperiment ) {
return;
}
// now that we have an experiment,
// we can load the onWeights/phase from disk (if weighing off bottles)
// and set up all the columns for the items & other window elements in the experiment
// DAILY DATA
// 1. allocate daily data
// 2. bind experiment
// 3. load on weights or set current phase
// set up our dailyData object
if (nil == dailyData) { dailyData = [[DailyData alloc] init]; }
[dailyData setTheExperiment:theExperiment]; // initializes the weight arrays too
// set the weighing status appropriately...
if ([theExperiment waitingForOff]) {
[self setToOffWeights];
// setToOffWeights read in previous on weights
}
else if (currentState == kUserEditing){
[self setToUserEditing];
// setToOnWeights will set phase day appropriately
}
else {
[self setToOnWeights];
// setToOnWeights will set phase day appropriately
}
// populate WINDOW ELEMENTS
// 0. window title (updated above, even if theExperiment == nil)
// 1. tableview with on/off weights
// 2. experiment name label
// 3. comment field
// 4. onTimeLabel (if weighing off)
// 5. phase menu & phase label
// configure the window elements:
// set up the table fields in our window
[self setUpDailyTableViewColumns];
// set the name of the experiment in the exptNameLabel
[exptNameLabel setStringValue:[theExperiment codeName]];
// set the text of the comment view...
NSRange wholeRange = NSMakeRange(0,[[commentView textStorage] length]);
[[commentView textStorage] replaceCharactersInRange:wholeRange withString:[dailyData comment]];
// set the onTimeLabel
if (currentState == kWeighingOff) {
[onTimeLabel setStringValue:[dailyData onTimeString]];
}
else if (currentState == kUserEditing) {
[onTimeLabel setStringValue:[dailyData onTimeString]];
[offTimeLabel setStringValue:[dailyData offTimeString]];
}
// set up the expt phase menu...
NSMenu *phaseMenu = [phasePopup menu];
[theExperiment addPhaseNamesToMenu:phaseMenu];
// update the phase menu and label
[self updatePhaseMenuAndLabel];
}
-(void)setToOnWeights {
currentState = kWeighingOn;
[itemLabel setEnabled:YES];
[itemWeight setEnabled:YES];
// set the dailyData phase
// if we are weighing on, then we should set phase to the current phase of the experiment (and the currentPhaseDay + 1)
// set the phase to the current phase of the experiment
// get the last phase day recorded by the experiment
// assuming we are now weighing this day, increment phase day by 1
// note that if never collected data for this phase before, then dayOfPhaseOfName returns NSNotFound
NSInteger exptPhaseDay = [theExperiment dayOfPhaseOfName:[theExperiment currentPhaseName]];
if (nil != [theExperiment phaseWithName:[theExperiment currentPhaseName]]) {
if (-1 == exptPhaseDay) { exptPhaseDay = 0; }
else { exptPhaseDay += 1 ; }
}
else {
// if not a real phase (e.g. "<none>") then leave exptPhase day as NSNotFound
exptPhaseDay = -1;
}
// update the daily data to reflect a new weighing on...
if (nil != dailyData) {
[dailyData setCurrentState: kWeighingOn];
[dailyData setPhaseName:[theExperiment currentPhaseName]];
[dailyData setPhaseDayIndex:exptPhaseDay];
}
}
-(void)setToOffWeights {
currentState = kWeighingOff;
[itemLabel setEnabled:YES];
[itemWeight setEnabled:YES];
if (nil != dailyData) {
[dailyData setCurrentState: kWeighingOff];
//NOTE: LOAD ON WEIGHTS OF GIVEN EXPT NAME....
// IF NO ON WEIGHTS and we're weighing OFF, post error...
[dailyData readOnWeights];
// set the dailyData phase
// if we are weighing off, then we use the daily data phase and index loaded from the onweights file.
}
}
-(void)setToUserEditing; {
currentState = kUserEditing;
[itemLabel setStringValue:@"editing mode"];
[itemLabel setEnabled:NO];
[itemWeight setStringValue:@"na"];
[itemWeight setEnabled:NO];
if (nil != dailyData) {
dailyData = [theExperiment dailyDataForDay:(NSUInteger)editingDayIndex];
[dailyData setCurrentState: kUserEditing];
}
}
-(void)updateWindowTitle; {
// assume the window is run by the first NSWindowController in the array of window controllers
if ([self windowControllers]) {
NSString *windowTitle;
if (nil == theExperiment) {
if (kWeighingOn == currentState) {
windowTitle = @"Weighing ON";
}
else if (kWeighingOff == currentState) {
windowTitle = @"Weighing OFF";
}
else if (kUserEditing == currentState) {
windowTitle = @"Editing Daily Data";
}
else {
windowTitle = @"Daily Data";
}
} // no expt
else {
if (kWeighingOn == currentState) {
windowTitle = [NSString stringWithFormat:@"%@ -- weighing ON", [theExperiment codeName]];
}
else if (kWeighingOff == currentState) {
windowTitle = [NSString stringWithFormat:@"%@ -- weighing OFF", [theExperiment codeName]];
}
else if (kUserEditing == currentState) {
windowTitle = [NSString stringWithFormat:@"%@ -- Editing", [theExperiment codeName]];
}
else {
windowTitle = [theExperiment codeName];
}
} // expt specified
NSWindowController *myWindowController;
NSWindow *myWindow;
myWindowController = (NSWindowController *)[[self windowControllers] objectAtIndex:0];
myWindow = [myWindowController window];
if (myWindow) { [myWindow setTitle:windowTitle]; }
} // got window controllers
}
// ***************************************************************************************
// ***************************************************************************************
// override of NSDocument methods
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
-(void)saveDocument:(id)sender; {
NSLog(@"method: saveDocument");
[self save:sender];
}
//----------------------------------------------------------------------------------------
-(void)printDocument:(id)sender; {
NSLog(@"method: printDocument");
[self print:sender];
}
-(void)removeFromBartender; {
if (nil != bartender) { [bartender removeDailyDataDocument:self]; }
}
// ***************************************************************************************
// ***************************************************************************************
// interface methods to handle toolbar button presses.
//----------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------
-(IBAction)open:(id)sender {
}
-(IBAction)saveAndPrint:(id)sender {
// pressing the save and Print button triggers closing...
NSLog(@"method: saveAndPrint");
// NOTE -- need to be called if the window is closed, or if "Quit" is selected...
// disabled the close button, need to figure out quitting...
// 1. check if there are still unweighed items
// 2. give user option to continue weighing
// 3. if OK to close, then save and print the dailyData
// 4. call [self removeFromBartender] to let Bartender release the document, and call [NSDocument close]
if (nil == theExperiment) { // nothing to save or print
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Save & Print: No experiment specified ",
@"Scan an item to start weighing",
@"OK");
return;
}
// 1. check if there are still unweighed items
// 2. give user option to continue weighing
if ([dailyData numberOfUnweighedItems] != 0) {
// some items have not yet be weighed
// put up a dialog to confirm saving even though there are some unweighed items
NSString *infoText = [[NSString alloc] initWithFormat:@"%ld items have not yet been weighed. Are you sure you want to save without weighing the remaining items?",[dailyData numberOfUnweighedItems]];
NSInteger button = BCTwoButtonAlert(NSAlertStyleWarning,
@"Save and Print Incomplete Weights?",
infoText,
@"Save and Print",
@"Return to Weighing");
if (button == NSAlertSecondButtonReturn) {
// "Return to weighing" clicked, so go back to weighing without saving...
return;
}
// else (button == NSAlertFirstButtonReturn)
// "Save and Print" clicked so continue with save
} // check for unweighed items
// 3. if OK to close, then save and print the dailyData
[self save:self];
closeAfterPrinting = YES;
[self print:self];
// 4. documentDidRunModalPrintOperation will call [self release the document..] to let Bartender handle the closing, and release the document..
}
-(IBAction)save:(id)sender {
// save the weights into the Documents/Bartender/DailyData directory
// On weights are stored in a file called "[ExptCode].onweights"
// Off weights are stored in a file called "[ExptCode] year-month-day.weights", in which the date is the save date
// i.e. if bottles in Expt TH were weighed on June 4, 2010 and weighed off June 5, 2010,
// then the weights are stored in the file "Documents/Bartender/DailyData/TH 2010-6-5.weights"
// note that the format of both onweights and weights files are identical XML plists,
// just that off weights in the .onweights file are set to NaN
NSLog(@"DD Document method: save");
if (nil == theExperiment) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Save: No experiment specified ",
@"Scan an item to start weighing",
@"OK");
return;
}
// be sure to extract the comment
// retrieve the text of the comment view...
[dailyData setComment:[NSString stringWithString:[[commentView textStorage] mutableString]]];
[dailyData save];
// tell ourselves that we have saved all changes
[self updateChangeCount: NSChangeCleared];
}
-(IBAction)print:(id)sender {
NSLog(@"method: print");
if (nil == theExperiment) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Print: No experiment specified ",
@"Scan an item to start weighing",
@"OK");
return;
}
[self printShowingPrintPanel:YES];
}
-(IBAction)setExptPhase:(id)sender; {
// user has changed the phase...
NSString * newPhaseName = [[phasePopup selectedItem] title];
// check to make sure we changed phases?
[dailyData setPhaseName : newPhaseName];
if ([[dailyData phaseName] isEqualToString:@"<none>"]) {
[dailyData setPhaseDayIndex:-1];
}
else {
// get the last phase day recorded by the experiment
// assuming we are now weighing this day, increment phase day by 1
// note that if never collected data for this phase before, then dayOfPhaseOfName returns -1
NSInteger exptPhaseDay = [theExperiment dayOfPhaseOfName:[dailyData phaseName]];
if (-1 == exptPhaseDay) { exptPhaseDay = 0; }
// else { exptPhaseDay += 1; } // don't need this!
[dailyData setPhaseDayIndex:exptPhaseDay];
}
// set the popup & phase day label to the current phase...
[self updatePhaseMenuAndLabel];
}
-(void)updatePhaseMenuAndLabel; {
// set the popup & phase day label to the current phase...
[phasePopup selectItemWithTitle: [dailyData phaseName] ];
if ([dailyData phaseDayIndex] > 0) {
[phaseDayLabel setStringValue: [[NSString alloc] initWithFormat:@"Day %ld",[dailyData phaseDayIndex]+1]];
// zero-indexed, so present as +1
}
else {
[phaseDayLabel setStringValue: [[NSString alloc] initWithFormat:kNoDataCellText]];
}
}
-(IBAction)abort:(id)sender {
// end the weighing session without saving the data...
// close and deallocate the NSDocument window...
// put up a dialog to confirm the cancellation
NSLog(@"DailyDocument: abort");
// if we haven't been assigned an experiment, then we can cancel without checking
if (nil != theExperiment) {
NSInteger button = BCTwoButtonAlert( NSAlertStyleWarning,
@"Cancel weighing session?",
@"Canceled weights will not be saved and cannot be restored.",
@"Return to Weighing",
@"Abort without saving");
if (button == NSAlertFirstButtonReturn) {
// "Return to weighing" clicked, so don't cancel
return;
}
// "Abort without saving was clicked, so go ahead and close ourselves up
}
// tell oursevles that we have no changes to save because we canceled
[self updateChangeCount: NSChangeCleared];
//need to close and deallocate the NSDocument window...
// have the NSDocument method handle this for us.
NSLog(@"DailyDocument about to call close");
[self removeFromBartender];
NSLog(@"DailyDocument back from calling close");
}
-(IBAction)tare:(id)sender; {
// toolbar button to tare the balance
[[bartender balance] tare];
}
-(IBAction)carryOver:(id)sender; {
// toolbar button to carry over yesterdays off weights to todays on weights
if (kUserEditing == currentState) { return; }
if (kWeighingOff == currentState) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Carry Over Data: Currently weighing off",
@"Can only carry over data when weighing data on",
@"OK");
return;
}
if (nil == theExperiment) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Carry Over Data: No experiment specified ",
@"Scan an item to start weighing on",
@"OK");
return;
}
DailyData *yesterdaysData = [theExperiment dailyDataForDay: ([theExperiment numberOfDays] - 1)];
if (nil == yesterdaysData) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Can't Carry Over Data: No Prior Data",
@"There are no previously collected data to carry over to today's weights",
@"OK");
return;
}
NSUInteger itemIndex, ratIndex;
double onWeight, offWeight,deltaWeight;
NSUInteger numItems = [theExperiment numberOfItems];
NSUInteger numRats = [theExperiment numberOfSubjects];
for (itemIndex = 0; itemIndex < numItems; itemIndex++) {
for (ratIndex = 0; ratIndex < numRats; ratIndex++) {
if ([yesterdaysData getWeightsForRat:ratIndex andItem:itemIndex onWeight:&onWeight offWeight:&offWeight deltaWeight:&deltaWeight]) {
// set today's onweights to yesterday's offweights
[dailyData setOnWeightForRat:ratIndex andItem:itemIndex weight:offWeight];
}
} // next rat
} // next item
[dailyTableView reloadData];
}
// ***************************************************************************************
///--------------------------------------------------------------------------------------------------
// interface methods for acquiring barcode and weight
///--------------------------------------------------------------------------------------------------
-(IBAction)labelStringEntered:(id)sender {
NSUInteger ratIndex = 0, itemIndex = 0;
NSLog(@"Label String Entered");
// a string was entered into the itemLabelfield
// parse the string to get expt code, rat number, and item type
// then make a request for a weight from the balance...
// the labelString is itemLabel's text...
NSString *labelString = [itemLabel stringValue];
if (useSpeech) {
[speech startSpeakingString: labelString];
while ([speech isSpeaking]) {
}
}
if (nil == labelString || 0 == [labelString length]) {
// no label entered, so just clear and return
// clear the itemLabel
[itemLabel setStringValue:[NSString string]];
return;
}
// parse the labelString
// if this is the first item to be scanned,
// parseLabelString will try to match the experiment
// and setup the dailyData for that experiment
if (![self parseLabelString:labelString getRatIndex:&ratIndex getItemIndex:&itemIndex ]) {
// failed to parse, so just return
// clear the item label...
[itemLabel setStringValue:[NSString string]];
// tell the label string to fade out...
// [itemLabel setAnimatedStringValue:[NSString string]];
// [itemLabel setTextColor:[NSColor redColor]];
// [itemLabel setNeedsDisplay];
return;
}
// post a request to get the current weight on the scale
scannedLabelString = [labelString copy];
scannedRatIndex = ratIndex;
scannedItemIndex = itemIndex;
numWeightTries = 0;
needWeightForItem = YES;
}
-(void) processWeightForScannedItem; {
// check a number of times for weight, until weight is stable
// if it fails to be stable within X number of tries, then post an alert that weight is not stable
BOOL stable_weight_acquired = [[bartender balance] curr_weight_stable];
if ( ! stable_weight_acquired) {
numWeightTries++;
if (kMaxNumWeightTries == numWeightTries) {
// give up waiting for stable weight
// clear the item label...
[itemLabel setStringValue:[NSString string]];
scannedLabelString = nil;
needWeightForItem = NO;
BCOneButtonAlert( NSAlertStyleWarning,
@"Unstable Weight",
@"Balance could not read a stable weight. Please try item again.",
@"OK");
}
return;
}
// current weight is stable
currentWeight = [[bartender balance] curr_weight];
// make a sound to notify the user that the weight was successfully read from balance
NSBeep();
if (useSpeech) {
NSString *weight_utterance =[NSString stringWithFormat: @"%.2lf", currentWeight];
[speech startSpeakingString:weight_utterance];
}
// check for double entry or out of range weight
[self checkWeightForLabel:scannedLabelString atItemIndex:scannedItemIndex];
// set the appropriate weight
if ([dailyData currentState] == kWeighingOn) {
// currentWeight = 400 + (20 * itemIndex) + ratIndex;
[dailyData setOnWeightForRat:scannedRatIndex andItem:scannedItemIndex weight:currentWeight];
}
else if ([dailyData currentState] == kWeighingOff) {
// currentWeight = 400 + (20 * itemIndex) + ratIndex - (ratIndex * 2);
[dailyData setOffWeightForRat:scannedRatIndex andItem:scannedItemIndex weight:currentWeight];
}
// NOTE: scroll to the right row in the table and highlite it...
[self selectTableRowAtIndex:scannedRatIndex];
// update the screen table with the new data...
[dailyTableView reloadData];
lastWeight = currentWeight;
// set the last item label
[lastItemLabel setStringValue:[[NSString alloc] initWithFormat:@"%@ %@", scannedLabelString, [[bartender balance] curr_weight_text]] ];
// clear the item label...
[itemLabel setStringValue:[NSString string]];
// tell ourselves that a change has been made...
[self updateChangeCount: NSChangeDone];
// processing successful, so no longer waiting for a new weight
scannedLabelString = nil;
needWeightForItem = NO;
}
-(BOOL) parseLabelString:(NSString *)labelString getRatIndex:(NSUInteger *)ratIndex getItemIndex:(NSUInteger *)itemIndex {
//classic ProcessTag
NSLog(@"method: parseLabelString");
BarExperiment *matchExpt;
matchExpt = [bartender getExperimentFromLabel:labelString];
// perform some checks on the experiment that matches the labels
// 1. is this a known experiment?
// 2. do we need to assign this experiment to the window (i.e. this is first label to be scanned)
// 2a. is this experiment already open in another window?
// 2b. are we trying to weigh on an experiment that has already been weighed on?
// 2c. are we trying to weigh off an experment that has not been weighed on?
// 2d. assign the matching experiment to this window
// 3. does the experiment match the currently assigned experiment?
// classic MatchTag2Expt
// 1. is this a known experiment?
if (matchExpt == nil) {
BCOneButtonAlert( NSAlertStyleWarning,
@"Unknown Experiment",
@"Did not recognize the experiment code within the label. Either the experiment has not been created yet, or the label is incorrect, or the label was not scanned properly.",
@"OK");
return NO;
}
// 2. do we need to assign this experiment to the window (i.e. this is first label to be scanned)
if ([self theExperiment] == nil ) {
// then this is first label to be scanned...
// 2a. is this experiment already open in another window?
// NOTE: check if experiment already being weighed in another window...
// 2b. are we trying to weigh on an experiment that has already been weighed on?
// if weighing on, make sure there isn't already a ".onweights" file
// if there is an ".onweights" file, ask if you want to overwrite it
// if weighing off, make sure there IS a ".onweights" file
BOOL onWeightsFileExists = [matchExpt onWeightsFileExists];
if (kWeighingOn == currentState && onWeightsFileExists) {
// trying to weigh bottles ON, but ".onweights" file already exists
// so can't overwrite
BCOneButtonAlert(NSAlertStyleWarning,
@"Bottles already ON",
@"The bottles for this experiment have already been weighed ON",
@"OK");
return NO;
}
// 2c. are we trying to weigh off an experment that has not been weighed on?
if (kWeighingOff == currentState && !onWeightsFileExists) {
// trying to weigh bottles OFF, but ".onweights" file doesn't exist
BCOneButtonAlert(NSAlertStyleWarning,
@"Bottles can't be weighed OFF",
@"The bottles for this experiment have not been weighed ON, so they cannot be weighed OFF",
@"OK");