forked from bettar/miele-lxiv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BurnerWindowController.m
1219 lines (946 loc) · 46.8 KB
/
BurnerWindowController.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
/*=========================================================================
Program: OsiriX
Copyright (c) OsiriX Team
All rights reserved.
Distributed under GNU - LGPL
See http://www.osirix-viewer.com/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#import "AppController.h"
#import "WaitRendering.h"
#import "BurnerWindowController.h"
#import "MutableArrayCategory.h"
#import <DiscRecordingUI/DRSetupPanel.h>
#import <DiscRecordingUI/DRBurnSetupPanel.h>
#import <DiscRecordingUI/DRBurnProgressPanel.h>
#import "BrowserController.h"
#import "DicomStudy.h"
#import "DicomImage.h"
#import "DicomStudy+Report.h"
#import "Anonymization.h"
#import "AnonymizationPanelController.h"
#import "AnonymizationViewController.h"
#import "ThreadsManager.h"
#import "NSThread+N2.h"
#import "NSFileManager+N2.h"
#import "N2Debug.h"
#import "NSImage+N2.h"
#import "DicomDir.h"
#import "DicomDatabase.h"
#import <DiskArbitration/DiskArbitration.h>
#import "DicomFile.h"
#import "DicomFileDCMTKCategory.h"
#import "DCMUIDs.h"
#import "DicomDatabase+DCMTK.h"
@implementation BurnerWindowController
@synthesize password, buttonsDisabled, selectedUSB;
- (void) createDMG:(NSString*) imagePath withSource:(NSString*) directoryPath
{
[[NSFileManager defaultManager] removeFileAtPath:imagePath handler:nil];
NSTask* makeImageTask = [[[NSTask alloc] init] autorelease];
[makeImageTask setLaunchPath: @"/bin/sh"];
imagePath = [imagePath stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""];
directoryPath = [directoryPath stringByReplacingOccurrencesOfString: @"\"" withString: @"\\\""];
NSString* cmdString = [NSString stringWithFormat: @"hdiutil create \"%@\" -srcfolder \"%@\"",
imagePath,
directoryPath];
NSArray *args = [NSArray arrayWithObjects: @"-c", cmdString, nil];
[makeImageTask setArguments:args];
[makeImageTask launch];
while( [makeImageTask isRunning])
[NSThread sleepForTimeInterval: 0.1];
//[aTask waitUntilExit]; // <- This is VERY DANGEROUS : the main runloop is continuing...
}
-(id) initWithFiles:(NSArray *)theFiles
{
if( self = [super initWithWindowNibName:@"BurnViewer"])
{
[[NSFileManager defaultManager] removeFileAtPath:[self folderToBurn] handler:nil];
files = [theFiles mutableCopy];
burning = NO;
[[self window] center];
NSLog( @"Burner allocated");
}
return self;
}
- (id)initWithFiles:(NSArray *)theFiles managedObjects:(NSArray *)managedObjects
{
if( self = [super initWithWindowNibName:@"BurnViewer"])
{
[[NSFileManager defaultManager] removeFileAtPath:[self folderToBurn] handler:nil];
files = [theFiles mutableCopy]; // file paths
dbObjectsID = [managedObjects mutableCopy];
originalDbObjectsID = [dbObjectsID mutableCopy];
[files removeDuplicatedStringsInSyncWithThisArray: dbObjectsID];
id managedObject;
id patient = nil;
_multiplePatients = NO;
for (managedObject in [[[BrowserController currentBrowser] database] objectsWithIDs: dbObjectsID])
{
NSString *newPatient = [managedObject valueForKeyPath:@"series.study.patientUID"];
if( patient == nil)
patient = newPatient;
else if( [patient compare: newPatient options: NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch] != NSOrderedSame)
{
_multiplePatients = YES;
break;
}
patient = newPatient;
}
burning = NO;
[[self window] center];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(_observeVolumeNotification:) name:NSWorkspaceDidMountNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(_observeVolumeNotification:) name:NSWorkspaceDidUnmountNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(_observeVolumeNotification:) name:NSWorkspaceDidRenameVolumeNotification object:nil];
NSLog( @"Burner allocated");
}
return self;
}
-(void)_observeVolumeNotification:(NSNotification*)notification
{
[self willChangeValueForKey: @"volumes"];
[self didChangeValueForKey:@"volumes"];
}
- (void)windowDidLoad
{
NSLog(@"BurnViewer did load");
[[self window] setDelegate:self];
[self setup:nil];
[compressionMode selectCellWithTag: [[NSUserDefaults standardUserDefaults] integerForKey: @"Compression Mode for Burning"]];
}
- (void)dealloc
{
windowWillClose = YES;
runBurnAnimation = NO;
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self];
[anonymizedFiles release];
[filesToBurn release];
[dbObjectsID release];
[originalDbObjectsID release];
[cdName release];
[password release];
[writeDMGPath release];
[writeVolumePath release];
[anonymizationTags release];
[files release];
NSLog(@"Burner dealloc");
[super dealloc];
}
//------------------------------------------------------------------------------------------------------------------------------------
#pragma mark•
- (NSArray *)filesToBurn
{
return filesToBurn;
}
- (void)setFilesToBurn:(NSArray *)theFiles
{
[filesToBurn release];
filesToBurn = [theFiles retain];
}
- (NSArray *)extractFileNames:(NSArray *)filenames
{
NSString *pname;
NSString *fname;
NSString *pathName;
BOOL isDir;
NSMutableArray *fileNames = [[[NSMutableArray alloc] init] autorelease];
//NSLog(@"Extract");
for (fname in filenames)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//NSLog(@"fname %@", fname);
NSFileManager *manager = [NSFileManager defaultManager];
if( [manager fileExistsAtPath:fname isDirectory:&isDir] && isDir)
{
NSDirectoryEnumerator *direnum = [manager enumeratorAtPath:fname];
//Loop Through directories
while (pname = [direnum nextObject])
{
pathName = [fname stringByAppendingPathComponent:pname]; //make pathanme
if( [manager fileExistsAtPath:pathName isDirectory:&isDir] && !isDir)
{ //check for directory
if( [DicomFile isDICOMFile: pathName])
[fileNames addObject:pathName];
}
} //while pname
} //if
else if( [DicomFile isDICOMFile: fname]) { //Pathname
[fileNames addObject:fname];
}
[pool release];
} //while
return fileNames;
}
//Actions
-(IBAction) burn: (id)sender
{
if( !(isExtracting || isSettingUpBurn || burning))
{
cancelled = NO;
[sizeField setStringValue: @""];
[cdName release];
cdName = [[nameField stringValue] retain];
if( [cdName length] <= 0)
{
[cdName release];
cdName = [@"UNTITLED" retain];
}
[[NSFileManager defaultManager] removeFileAtPath:[self folderToBurn] handler:nil];
[[NSFileManager defaultManager] removeFileAtPath:[NSString stringWithFormat:@"/tmp/burnAnonymized"] handler:nil];
[writeVolumePath release];
writeVolumePath = nil;
[writeDMGPath release];
writeDMGPath = nil;
[anonymizationTags release];
anonymizationTags = nil;
if( [[NSUserDefaults standardUserDefaults] boolForKey:@"anonymizedBeforeBurning"])
{
AnonymizationPanelController* panelController = [Anonymization showPanelForDefaultsKey:@"AnonymizationFields" modalForWindow:self.window modalDelegate:NULL didEndSelector:NULL representedObject:NULL];
if( panelController.end == AnonymizationPanelCancel)
return;
anonymizationTags = [panelController.anonymizationViewController.tagsValues retain];
}
else
{
[anonymizedFiles release];
anonymizedFiles = nil;
}
self.buttonsDisabled = YES;
@try
{
if( cdName != nil && [cdName length] > 0)
{
runBurnAnimation = YES;
if( [[NSUserDefaults standardUserDefaults] integerForKey: @"burnDestination"] == USBKey)
{
[writeVolumePath release];
writeVolumePath = nil;
if( selectedUSB != NSNotFound && selectedUSB < [self volumes].count)
writeVolumePath = [[[self volumes] objectAtIndex: selectedUSB] retain];
if( writeVolumePath == nil)
{
NSRunCriticalAlertPanel( NSLocalizedString( @"USB Writing", nil), NSLocalizedString( @"No destination selected.", nil), NSLocalizedString( @"OK", nil), nil, nil);
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
return;
}
NSInteger result = NSRunCriticalAlertPanel( NSLocalizedString( @"USB Writing", nil), NSLocalizedString( @"The ENTIRE content of the selected media (%@) will be deleted, before writing the new data. Do you confirm?", nil), NSLocalizedString( @"OK", nil), NSLocalizedString( @"Cancel", nil), nil, writeVolumePath, nil);
if( result != NSAlertDefaultReturn)
{
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
return;
}
[[BrowserController currentBrowser] removePathFromSources: writeVolumePath];
}
if( [[NSUserDefaults standardUserDefaults] integerForKey: @"burnDestination"] == DMGFile)
{
NSSavePanel *savePanel = [NSSavePanel savePanel];
[savePanel setCanSelectHiddenExtension:YES];
[savePanel setRequiredFileType:@"dmg"];
[savePanel setTitle:@"Save as DMG"];
if( [savePanel runModalForDirectory:nil file: cdName] == NSFileHandlingPanelOKButton)
{
[writeDMGPath release];
writeDMGPath = [[[savePanel URL] path] retain];
[[NSFileManager defaultManager] removeItemAtPath: writeDMGPath error: nil];
}
else
{
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
return;
}
}
self.password = @"";
if( [[NSUserDefaults standardUserDefaults] boolForKey: @"EncryptCD"])
{
int result = 0;
do
{
[NSApp beginSheet: passwordWindow
modalForWindow: self.window
modalDelegate: nil
didEndSelector: nil
contextInfo: nil];
result = [NSApp runModalForWindow: passwordWindow];
[passwordWindow makeFirstResponder: nil];
[NSApp endSheet: passwordWindow];
[passwordWindow orderOut: self];
}
while( [self.password length] < 8 && result == NSRunStoppedResponse);
if( result == NSRunStoppedResponse)
{
}
else
{
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
return;
}
}
NSThread* t = [[[NSThread alloc] initWithTarget:self selector:@selector(performBurn:) object: nil] autorelease];
t.name = NSLocalizedString( @"Burning...", nil);
[[ThreadsManager defaultManager] addThreadAndStart: t];
}
else
{
NSBeginAlertSheet( NSLocalizedString( @"Burn Warning", nil) , NSLocalizedString( @"OK", nil), nil, nil, nil, nil, nil, nil, nil, NSLocalizedString( @"Please add CD name", nil));
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
return;
}
}
@catch (NSException *exception)
{
NSLog( @"*** exception: %@", exception);
}
}
}
- (void)performBurn: (id) object
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
DicomDatabase *idatabase = [[[[BrowserController currentBrowser] database] independentDatabase] retain];
NSMutableArray *dbObjects = [[[idatabase objectsWithIDs: dbObjectsID] mutableCopy] autorelease];
NSMutableArray *originalDbObjects = [[[idatabase objectsWithIDs: originalDbObjectsID] mutableCopy] autorelease];
@try
{
isSettingUpBurn = YES;
if( anonymizationTags)
{
NSDictionary* anonOut = [Anonymization anonymizeFiles:files dicomImages: dbObjects toPath:@"/tmp/burnAnonymized" withTags: anonymizationTags];
[anonymizedFiles release];
anonymizedFiles = [[anonOut allValues] mutableCopy];
}
[self prepareCDContent: dbObjects :originalDbObjects];
isSettingUpBurn = NO;
int no = 0;
if( anonymizedFiles) no = [anonymizedFiles count];
else no = [files count];
burning = YES;
if( [[NSFileManager defaultManager] fileExistsAtPath: [self folderToBurn]] && cancelled == NO)
{
if( no)
{
switch( [[NSUserDefaults standardUserDefaults] integerForKey: @"burnDestination"])
{
case DMGFile:
[self createDMG: writeDMGPath withSource:[self folderToBurn]];
break;
case CDDVD:
[self performSelectorOnMainThread:@selector(burnCD:) withObject:nil waitUntilDone:NO];
return;
break;
case USBKey:
[self saveOnVolume];
break;
}
}
}
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
if( cancelled == NO)
{
// Finished ! Close the window....
[[NSSound soundNamed: @"Glass.aiff"] play];
[self.window performSelectorOnMainThread: @selector(performClose:) withObject: self waitUntilDone: NO];
}
}
@catch (NSException *exception)
{
NSLog( @"*** exception: %@", exception);
}
@finally
{
[pool release];
}
}
- (IBAction) setAnonymizedCheck: (id) sender
{
if( [anonymizedCheckButton state] == NSOnState)
{
if( [[nameField stringValue] isEqualToString: [self defaultTitle]])
{
NSDate *date = [NSDate date];
[self setCDTitle: [NSString stringWithFormat:@"Archive-%@", [date descriptionWithCalendarFormat:@"%Y%m%d" timeZone:nil locale:nil]]];
}
}
}
- (void)setCDTitle: (NSString *)title
{
if( title)
{
[cdName release];
//if( [title length] > 8)
// title = [title substringToIndex:8];
cdName = [[[title uppercaseString] filenameString] retain];
[nameField setStringValue: cdName];
}
}
-(IBAction)setCDName:(id)sender
{
NSString *name = [[nameField stringValue] uppercaseString];
[self setCDTitle:name];
}
-(NSString *)folderToBurn
{
return [NSString stringWithFormat:@"/tmp/%@",cdName];
}
-(NSArray*) volumes
{
NSArray *removeableMedia = [[NSWorkspace sharedWorkspace] mountedRemovableMedia];
NSMutableArray *array = [NSMutableArray array];
for( NSString *mediaPath in removeableMedia)
{
BOOL isWritable, isUnmountable, isRemovable;
NSString *description = nil, *type = nil;
[[NSWorkspace sharedWorkspace] getFileSystemInfoForPath: mediaPath isRemovable:&isRemovable isWritable:&isWritable isUnmountable:&isUnmountable description:&description type:&type];
if( isRemovable && isWritable && isUnmountable)
[array addObject: mediaPath];
}
return array;
}
- (void) saveOnVolume
{
NSLog( @"Erase volume : %@", writeVolumePath);
for( NSString *path in [[NSFileManager defaultManager] contentsOfDirectoryAtPath: writeVolumePath error: nil])
[[NSFileManager defaultManager] removeItemAtPath: [writeVolumePath stringByAppendingPathComponent: path] error: nil];
[[NSFileManager defaultManager] copyItemAtPath: [self folderToBurn] toPath: writeVolumePath byReplacingExisting: YES error: nil];
NSString *newName = cdName;
NSTask *t = [NSTask launchedTaskWithLaunchPath: @"/usr/sbin/diskutil" arguments: [NSArray arrayWithObjects: @"rename", writeVolumePath, newName, nil]];
while( [t isRunning])
[NSThread sleepForTimeInterval: 0.1];
//[aTask waitUntilExit]; // <- This is VERY DANGEROUS : the main runloop is continuing...
[NSThread sleepForTimeInterval: 1];
//Did we succeed? Basic MS-DOS FAT support only CAPITAL letters and maximum of 10 characters...
if( [[NSFileManager defaultManager] fileExistsAtPath: [[writeVolumePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: newName]] == NO)
{
if( newName.length > 10)
newName = [newName substringToIndex: 10];
NSTask *t = [NSTask launchedTaskWithLaunchPath: @"/usr/sbin/diskutil" arguments: [NSArray arrayWithObjects: @"rename", writeVolumePath, [newName uppercaseString], nil]];
while( [t isRunning])
[NSThread sleepForTimeInterval: 0.1];
//[t waitUntilExit]; // <- This is VERY DANGEROUS : the main runloop is continuing...
[NSThread sleepForTimeInterval: 1];
if( [[NSFileManager defaultManager] fileExistsAtPath: [[writeVolumePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: newName]] == NO)
{
newName = @"DICOM";
NSTask *t = [NSTask launchedTaskWithLaunchPath: @"/usr/sbin/diskutil" arguments: [NSArray arrayWithObjects: @"rename", writeVolumePath, newName, nil]];
while( [t isRunning])
[NSThread sleepForTimeInterval: 0.1];
//[aTask waitUntilExit]; // <- This is VERY DANGEROUS : the main runloop is continuing...
[NSThread sleepForTimeInterval: 1];
}
}
[[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: [[writeVolumePath stringByDeletingLastPathComponent] stringByAppendingPathComponent: newName]];
NSLog( @"Ejecting new DICOM Volume: %@", newName);
}
- (void)burnCD:(id)object
{
if( [NSThread isMainThread] == NO)
{
NSLog( @"******* THIS SHOULD BE ON THE MAIN THREAD: burnCD");
}
sizeInMb = [[self getSizeOfDirectory: [self folderToBurn]] intValue] / 1024;
DRTrack* track = [DRTrack trackForRootFolder: [DRFolder folderWithPath: [self folderToBurn]]];
if( track)
{
DRBurnSetupPanel *bsp = [DRBurnSetupPanel setupPanel];
[bsp setDelegate: self];
if( [bsp runSetupPanel] == NSOKButton)
{
DRBurnProgressPanel *bpp = [DRBurnProgressPanel progressPanel];
[bpp setDelegate: self];
[bpp beginProgressSheetForBurn:[bsp burnObject] layout:track modalForWindow: [self window]];
return;
}
}
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
}
//------------------------------------------------------------------------------------------------------------------------------------
#pragma mark•
- (BOOL) validateMenuItem:(id)sender
{
if( [sender action] == @selector(terminate:))
return (burning == NO); // No quitting while a burn is going on
return YES;
}
- (BOOL) setupPanel:(DRSetupPanel*)aPanel deviceContainsSuitableMedia:(DRDevice*)device promptString:(NSString**)prompt;
{
NSDictionary *status = [device status];
int freeSpace = [[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] longLongValue] * 2UL / 1024UL;
if( freeSpace > 0 && sizeInMb >= freeSpace)
{
*prompt = [NSString stringWithFormat: NSLocalizedString(@"The data to burn is larger than a media size (%d MB), you need a DVD to burn this amount of data (%d MB).", nil), freeSpace, sizeInMb];
cancelled = YES;
return NO;
}
else if( freeSpace > 0)
{
*prompt = [NSString stringWithFormat: NSLocalizedString(@"Data to burn: %d MB (Media size: %d MB), representing %2.2f %%.", nil), sizeInMb, freeSpace, (float) sizeInMb * 100. / (float) freeSpace];
}
return YES;
}
- (void) burnProgressPanelWillBegin:(NSNotification*)aNotification
{
burnAnimationIndex = 0;
runBurnAnimation = YES;
}
- (void) burnProgressPanelDidFinish:(NSNotification*)aNotification
{
}
- (BOOL) burnProgressPanel:(DRBurnProgressPanel*)theBurnPanel burnDidFinish:(DRBurn*)burn
{
NSDictionary* burnStatus = [burn status];
NSString* state = [burnStatus objectForKey:DRStatusStateKey];
BOOL succeed = NO;
if( [state isEqualToString:DRStatusStateFailed])
{
NSDictionary* errorStatus = [burnStatus objectForKey:DRErrorStatusKey];
NSString* errorString = [errorStatus objectForKey:DRErrorStatusErrorStringKey];
NSRunCriticalAlertPanel( NSLocalizedString( @"Burning failed", nil), @"%@", NSLocalizedString( @"OK", nil), nil, nil, errorString);
}
else
{
succeed = YES;
[sizeField setStringValue: NSLocalizedString( @"Burning is finished !", nil)];
}
self.buttonsDisabled = NO;
runBurnAnimation = NO;
burning = NO;
if( succeed)
[[self window] performSelector: @selector(performClose:) withObject: nil afterDelay: 1];
return YES;
}
- (void)windowWillClose:(NSNotification *)notification
{
[irisAnimationTimer invalidate];
[irisAnimationTimer release];
irisAnimationTimer = nil;
[burnAnimationTimer invalidate];
[burnAnimationTimer release];
burnAnimationTimer = nil;
windowWillClose = YES;
[[NSUserDefaults standardUserDefaults] setInteger: [compressionMode selectedTag] forKey:@"Compression Mode for Burning"];
NSLog(@"Burner windowWillClose");
[[self window] setDelegate: nil];
isExtracting = NO;
isSettingUpBurn = NO;
burning = NO;
runBurnAnimation = NO;
[self autorelease];
}
- (BOOL)windowShouldClose:(id)sender
{
NSLog(@"Burner windowShouldClose");
if( (isExtracting || isSettingUpBurn || burning))
return NO;
else
{
[[NSFileManager defaultManager] removeFileAtPath: [self folderToBurn] handler:nil];
[[NSFileManager defaultManager] removeFileAtPath: [NSString stringWithFormat:@"/tmp/burnAnonymized"] handler:nil];
[filesToBurn release];
filesToBurn = nil;
[files release];
files = nil;
[anonymizedFiles release];
anonymizedFiles = nil;
NSLog(@"Burner windowShouldClose YES");
return YES;
}
}
//------------------------------------------------------------------------------------------------------------------------------------
#pragma mark•
- (void)importFiles:(NSArray *)filenames{
}
- (NSString*) defaultTitle
{
NSString *title = nil;
if( [files count] > 0)
{
NSString *file = [files objectAtIndex:0];
title = [DicomFile getDicomField: @"PatientsName" forFile: file];
}
if( title == nil)
title = @"UNTITLED";
return [[title uppercaseString] filenameString];
}
- (void)setup:(id)sender
{
//NSLog(@"Set up burn");
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
runBurnAnimation = NO;
[burnButton setEnabled:NO];
isExtracting = YES;
[self performSelectorOnMainThread:@selector(estimateFolderSize:) withObject:nil waitUntilDone:YES];
isExtracting = NO;
irisAnimationTimer = [[NSTimer timerWithTimeInterval: 0.07 target: self selector: @selector(irisAnimation:) userInfo: NO repeats: YES] retain];
[[NSRunLoop currentRunLoop] addTimer: irisAnimationTimer forMode: NSModalPanelRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer: irisAnimationTimer forMode: NSDefaultRunLoopMode];
burnAnimationTimer = [[NSTimer timerWithTimeInterval: 0.07 target: self selector: @selector(burnAnimation:) userInfo: NO repeats: YES] retain];
[[NSRunLoop currentRunLoop] addTimer: burnAnimationTimer forMode: NSModalPanelRunLoopMode];
[[NSRunLoop currentRunLoop] addTimer: burnAnimationTimer forMode: NSDefaultRunLoopMode];
[burnButton setEnabled:YES];
NSString *title = nil;
if( _multiplePatients || [[NSUserDefaults standardUserDefaults] boolForKey:@"anonymizedBeforeBurning"])
{
NSDate *date = [NSDate date];
title = [NSString stringWithFormat:@"Archive-%@", [date descriptionWithCalendarFormat:@"%Y%m%d" timeZone:nil locale:nil]];
}
else title = [[self defaultTitle] uppercaseString];
[self setCDTitle: title];
[pool release];
}
//------------------------------------------------------------------------------------------------------------------------------------
#pragma mark•
/*+(void)image:(NSImage*)image writePGMToPath:(NSString*)ppmpath {
NSSize scaledDownSize = [image sizeByScalingDownProportionallyToSize:NSMakeSize(128,128)];
NSInteger width = scaledDownSize.width, height = scaledDownSize.height;
static CGColorSpaceRef grayColorSpace = nil;
if( !grayColorSpace) grayColorSpace = CGColorSpaceCreateDeviceGray();
CGContextRef cgContext = CGBitmapContextCreate(NULL, width, height, 8, width, grayColorSpace, 0);
uint8* data = CGBitmapContextGetData(cgContext);
NSGraphicsContext* nsContext = [NSGraphicsContext graphicsContextWithGraphicsPort:cgContext flipped:NO];
NSGraphicsContext* savedContext = [NSGraphicsContext currentContext];
[NSGraphicsContext setCurrentContext:nsContext];
[image drawInRect:NSMakeRect(0,0,width,height) fromRect:NSMakeRect(0,0,image.size.width,image.size.height) operation:NSCompositeCopy fraction:1];
[NSGraphicsContext setCurrentContext:savedContext];
NSMutableData* out = [NSMutableData data];
[out appendData:[[NSString stringWithFormat:@"P5\n%d %d\n255\n", width, height] dataUsingEncoding:NSUTF8StringEncoding]];
[out appendBytes:data length:width*height];
[[NSFileManager defaultManager] confirmDirectoryAtPath:[ppmpath stringByDeletingLastPathComponent]];
[out writeToFile:ppmpath atomically:YES];
CGContextRelease(cgContext);
}*/
- (void)addDICOMDIRUsingDCMTK_forFilesAtPaths:(NSArray*/*NSString*/)paths dicomImages:(NSArray*/*DicomImage*/)dimages
{
[DicomDir createDicomDirAtDir:[self folderToBurn]];
}
- (void) produceHtml:(NSString*) burnFolder dicomObjects: (NSMutableArray*) originalDbObjects
{
//We want to create html only for the images, not for PR, and hidden DICOM SR
NSMutableArray *images = [NSMutableArray arrayWithCapacity: [originalDbObjects count]];
for( id obj in originalDbObjects)
{
if( [DicomStudy displaySeriesWithSOPClassUID: [obj valueForKeyPath:@"series.seriesSOPClassUID"] andSeriesDescription: [obj valueForKeyPath:@"series.name"]])
[images addObject: obj];
}
[[BrowserController currentBrowser] exportQuicktimeInt: images :burnFolder :YES];
}
- (NSNumber*) getSizeOfDirectory: (NSString*) path
{
if( [[NSFileManager defaultManager] fileExistsAtPath: path] == NO) return [NSNumber numberWithLong: 0];
if( [[[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:NO]fileType]!=NSFileTypeSymbolicLink || [[[NSFileManager defaultManager] fileAttributesAtPath:path traverseLink:NO]fileType]!=NSFileTypeUnknown)
{
NSArray *args = nil;
NSPipe *fromPipe = nil;
NSFileHandle *fromDu = nil;
NSData *duOutput = nil;
NSString *size = nil;
NSArray *stringComponents = nil;
char aBuffer[ 300];
args = [NSArray arrayWithObjects:@"-ks",path,nil];
fromPipe =[NSPipe pipe];
fromDu = [fromPipe fileHandleForWriting];
NSTask *duTool = [[[NSTask alloc] init] autorelease];
[duTool setLaunchPath:@"/usr/bin/du"];
[duTool setStandardOutput:fromDu];
[duTool setArguments:args];
[duTool launch];
while( [duTool isRunning])
[NSThread sleepForTimeInterval: 0.1];
//[duTool waitUntilExit]; // <- This is VERY DANGEROUS : the main runloop is continuing...
duOutput = [[fromPipe fileHandleForReading] availableData];
[duOutput getBytes:aBuffer];
size = [NSString stringWithCString:aBuffer];
stringComponents = [size pathComponents];
size = [stringComponents objectAtIndex:0];
size = [size substringToIndex:[size length]-1];
return [NSNumber numberWithUnsignedLongLong:(unsigned long long)[size doubleValue]];
}
else return [NSNumber numberWithUnsignedLongLong:(unsigned long long)0];
}
- (IBAction) cancel:(id)sender
{
[NSApp abortModal];
}
- (IBAction) ok:(id)sender
{
[NSApp stopModal];
}
- (NSString*) cleanStringForFile: (NSString*) s
{
s = [s stringByReplacingOccurrencesOfString:@"/" withString:@"-"];
s = [s stringByReplacingOccurrencesOfString:@":" withString:@"-"];
return s;
}
- (void) prepareCDContent: (NSMutableArray*) dbObjects :(NSMutableArray*) originalDbObjects
{
NSThread* thread = [NSThread currentThread];
[finalSizeField performSelectorOnMainThread:@selector(setStringValue:) withObject:@"" waitUntilDone:YES];
@try
{
NSEnumerator *enumerator;
if( anonymizedFiles) enumerator = [anonymizedFiles objectEnumerator];
else enumerator = [files objectEnumerator];
NSString *file;
NSString *burnFolder = [self folderToBurn];
NSString *dicomdirPath = [NSString stringWithFormat:@"%@/DICOMDIR",burnFolder];
NSString *subFolder = [NSString stringWithFormat:@"%@/DICOM",burnFolder];
NSFileManager *manager = [NSFileManager defaultManager];
int i = 0;
//create burn Folder and dicomdir.
if( ![manager fileExistsAtPath:burnFolder])
[manager createDirectoryAtPath:burnFolder attributes:nil];
if( ![manager fileExistsAtPath:subFolder])
[manager createDirectoryAtPath:subFolder attributes:nil];
if( ![manager fileExistsAtPath:dicomdirPath])
[manager copyPath:[[NSBundle mainBundle] pathForResource:@"DICOMDIR" ofType:nil] toPath:dicomdirPath handler:nil];
NSMutableArray *newFiles = [NSMutableArray array];
NSMutableArray *compressedArray = [NSMutableArray array];
NSMutableArray *bigEndianFilesToConvert = [NSMutableArray array];
while((file = [enumerator nextObject]) && cancelled == NO)
{
@autoreleasepool {
NSString *newPath = [NSString stringWithFormat:@"%@/%05d", subFolder, i++];
[manager copyPath: file toPath: newPath handler:nil];
if( [DicomFile isDICOMFile: newPath])
{
if( [[DicomFile getDicomField: @"TransferSyntaxUID" forFile: newPath] isEqualToString: DCM_ExplicitVRBigEndian])
[bigEndianFilesToConvert addObject: newPath];
switch( [compressionMode selectedTag])
{
case 0:
break;
case 1:
[compressedArray addObject: newPath];
break;
case 2:
[compressedArray addObject: newPath];
break;
}
}
[newFiles addObject:newPath];
}
}
if( bigEndianFilesToConvert.count)
[DicomDatabase decompressDicomFilesAtPaths: bigEndianFilesToConvert];
if( [newFiles count] > 0 && cancelled == NO)
{
NSArray *copyCompressionSettings = nil;
NSArray *copyCompressionSettingsLowRes = nil;
if( [[NSUserDefaults standardUserDefaults] boolForKey: @"JPEGinsteadJPEG2000"] && [compressionMode selectedTag] == 1) // Temporarily switch the prefs... ugly....
{
copyCompressionSettings = [[NSUserDefaults standardUserDefaults] objectForKey: @"CompressionSettings"];
copyCompressionSettingsLowRes = [[NSUserDefaults standardUserDefaults] objectForKey: @"CompressionSettingsLowRes"];
[[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObject: [NSDictionary dictionaryWithObjectsAndKeys: NSLocalizedString( @"default", nil), @"modality", [NSNumber numberWithInt: compression_JPEG], @"compression", @"0", @"quality", nil]] forKey: @"CompressionSettings"];
[[NSUserDefaults standardUserDefaults] setObject: [NSArray arrayWithObject: [NSDictionary dictionaryWithObjectsAndKeys: NSLocalizedString( @"default", nil), @"modality", [NSNumber numberWithInt: compression_JPEG], @"compression", @"0", @"quality", nil]] forKey: @"CompressionSettingsLowRes"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
@try
{
switch( [compressionMode selectedTag])
{
case 1:
[[BrowserController currentBrowser] decompressArrayOfFiles: compressedArray work: [NSNumber numberWithChar: 'C']];
break;
case 2:
[[BrowserController currentBrowser] decompressArrayOfFiles: compressedArray work: [NSNumber numberWithChar: 'D']];
break;
}
}
@catch (NSException *e) {
NSLog(@"Exception while prepareCDContent compression: %@", e);
}
if( copyCompressionSettings && copyCompressionSettingsLowRes)
{
[[NSUserDefaults standardUserDefaults] setObject: copyCompressionSettings forKey:@"CompressionSettings"];
[[NSUserDefaults standardUserDefaults] setObject: copyCompressionSettingsLowRes forKey:@"CompressionSettingsLowRes"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
thread.name = NSLocalizedString( @"Burning...", nil);