-
Notifications
You must be signed in to change notification settings - Fork 218
/
AppController.m
3944 lines (3246 loc) · 142 KB
/
AppController.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 - GPL
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 "SystemConfiguration/SCDynamicStoreCopySpecific.h"
#include <CoreFoundation/CoreFoundation.h>
#include <ApplicationServices/ApplicationServices.h>
#import "ToolbarPanel.h"
#import "AppController.h"
#import "PreferencePaneController.h"
#import "BrowserController.h"
#import "BrowserControllerDCMTKCategory.h"
#import "ViewerController.h"
#import "XMLController.h"
#import "SplashScreen.h"
#import "NSFont_OpenGL.h"
#import "Survey.h"
#import "DicomFile.h"
#import "HTTPServer.h"
#import <OsiriX/DCM.h>
#import "PluginManager.h"
#import "DCMTKQueryRetrieveSCP.h"
#import "BLAuthentication.h"
#import "AppControllerDCMTKCategory.h"
#import "DefaultsOsiriX.h"
#import "OrthogonalMPRViewer.h"
#import "OrthogonalMPRPETCTViewer.h"
#import "NavigatorView.h"
#import "WindowLayoutManager.h"
#import "QueryController.h"
#import "NSSplitViewSave.h"
#import "altivecFunctions.h"
#ifndef OSIRIX_LIGHT
#import <ILCrashReporter/ILCrashReporter.h>
#endif
#import "PluginManagerController.h"
#import "OSIWindowController.h"
#import "Notifications.h"
#import "WaitRendering.h"
#define BUILTIN_DCMTK YES
ToolbarPanelController *toolbarPanel[10] = {nil, nil, nil, nil, nil, nil, nil, nil, nil, nil};
static NSMenu *mainMenuCLUTMenu = nil, *mainMenuWLWWMenu = nil, *mainMenuConvMenu = nil, *mainOpacityMenu = nil;
static NSDictionary *previousWLWWKeys = nil, *previousCLUTKeys = nil, *previousConvKeys = nil, *previousOpacityKeys = nil;
static BOOL checkForPreferencesUpdate = YES;
static PluginManager *pluginManager = nil;
static unsigned char *LUT12toRGB = nil;
static BOOL canDisplay12Bit = NO;
static NSInvocation *fill12BitBufferInvocation = nil;
NSThread *mainThread = nil;
BOOL NEEDTOREBUILD = NO;
BOOL COMPLETEREBUILD = NO;
BOOL USETOOLBARPANEL = NO;
short Altivec = 1, UseOpenJpeg = 1;
AppController *appController = nil;
DCMTKQueryRetrieveSCP *dcmtkQRSCP = nil;
NSString *checkSN64String = nil;
NSNetService *checkSN64Service = nil;
NSRecursiveLock *PapyrusLock = nil, *STORESCP = nil; // Papyrus is NOT thread-safe
NSMutableArray *accumulateAnimationsArray = nil;
BOOL accumulateAnimations = NO;
extern int delayedTileWindows;
extern NSString* getMacAddress( void);
enum {kSuccess = 0,
kCouldNotFindRequestedProcess = -1,
kInvalidArgumentsError = -2,
kErrorGettingSizeOfBufferRequired = -3,
kUnableToAllocateMemoryForBuffer = -4,
kPIDBufferOverrunError = -5};
#include <sys/sysctl.h>
#include <netdb.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#ifdef OSIRIX_LIGHT
void exitOsiriX(void)
{
[NSException raise: @"JPEG error exception raised" format: @"JPEG error exception raised - See Console.app for error message"];
}
#endif
static char *GetPrivateIP()
{
struct hostent *h;
static char hostname[100];
gethostname(hostname, 99);
if( (h=gethostbyname(hostname)) == NULL)
{
NSLog( @"**** Cannot GetPrivateIP -> return nil");
return nil;
}
return (char*) inet_ntoa(*((struct in_addr *)h->h_addr));
}
int GetAllPIDsForProcessName(const char* ProcessName,
pid_t ArrayOfReturnedPIDs[],
const unsigned int NumberOfPossiblePIDsInArray,
unsigned int* NumberOfMatchesFound,
int* SysctlError)
{
// --- Defining local variables for this function and initializing all to zero --- //
int mib[6] = {0,0,0,0,0,0}; //used for sysctl call.
int SuccessfullyGotProcessInformation;
size_t sizeOfBufferRequired = 0; //set to zero to start with.
int error = 0;
long NumberOfRunningProcesses = 0;
unsigned int Counter = 0;
struct kinfo_proc* BSDProcessInformationStructure = NULL;
pid_t CurrentExaminedProcessPID = 0;
char* CurrentExaminedProcessName = NULL;
// --- Checking input arguments for validity --- //
if (ProcessName == NULL) //need valid process name
{
return(kInvalidArgumentsError);
}
if (ArrayOfReturnedPIDs == NULL) //need an actual array
{
return(kInvalidArgumentsError);
}
if (NumberOfPossiblePIDsInArray <= 0)
{
//length of the array must be larger than zero.
return(kInvalidArgumentsError);
}
if (NumberOfMatchesFound == NULL) //need an integer for return.
{
return(kInvalidArgumentsError);
}
//--- Setting return values to known values --- //
//initalizing PID array so all values are zero
memset(ArrayOfReturnedPIDs, 0, NumberOfPossiblePIDsInArray * sizeof(pid_t));
*NumberOfMatchesFound = 0; //no matches found yet
if (SysctlError != NULL) //only set sysctlError if it is present
{
*SysctlError = 0;
}
//--- Getting list of process information for all processes --- //
/* Setting up the mib (Management Information Base) which is an array of integers where each
* integer specifies how the data will be gathered. Here we are setting the MIB
* block to lookup the information on all the BSD processes on the system. Also note that
* every regular application has a recognized BSD process accociated with it. We pass
* CTL_KERN, KERN_PROC, KERN_PROC_ALL to sysctl as the MIB to get back a BSD structure with
* all BSD process information for all processes in it (including BSD process names)
*/
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_ALL;
/* Here we have a loop set up where we keep calling sysctl until we finally get an unrecoverable error
* (and we return) or we finally get a succesful result. Note with how dynamic the process list can
* be you can expect to have a failure here and there since the process list can change between
* getting the size of buffer required and the actually filling that buffer.
*/
SuccessfullyGotProcessInformation = FALSE;
while (SuccessfullyGotProcessInformation == FALSE)
{
/* Now that we have the MIB for looking up process information we will pass it to sysctl to get the
* information we want on BSD processes. However, before we do this we must know the size of the buffer to
* allocate to accomidate the return value. We can get the size of the data to allocate also using the
* sysctl command. In this case we call sysctl with the proper arguments but specify no return buffer
* specified (null buffer). This is a special case which causes sysctl to return the size of buffer required.
*
* First Argument: The MIB which is really just an array of integers. Each integer is a constant
* representing what information to gather from the system. Check out the man page to know what
* constants sysctl will work with. Here of course we pass our MIB block which was passed to us.
* Second Argument: The number of constants in the MIB (array of integers). In this case there are three.
* Third Argument: The output buffer where the return value from sysctl will be stored. In this case
* we don't want anything return yet since we don't yet know the size of buffer needed. Thus we will
* pass null for the buffer to begin with.
* Forth Argument: The size of the output buffer required. Since the buffer itself is null we can just
* get the buffer size needed back from this call.
* Fifth Argument: The new value we want the system data to have. Here we don't want to set any system
* information we only want to gather it. Thus, we pass null as the buffer so sysctl knows that
* we have no desire to set the value.
* Sixth Argument: The length of the buffer containing new information (argument five). In this case
* argument five was null since we didn't want to set the system value. Thus, the size of the buffer
* is zero or NULL.
* Return Value: a return value indicating success or failure. Actually, sysctl will either return
* zero on no error and -1 on error. The errno UNIX variable will be set on error.
*/
error = sysctl(mib, 3, NULL, &sizeOfBufferRequired, NULL, 0);
/* If an error occurred then return the accociated error. The error itself actually is stored in the UNIX
* errno variable. We can access the errno value using the errno global variable. We will return the
* errno value as the sysctlError return value from this function.
*/
if (error != 0)
{
if (SysctlError != NULL)
{
*SysctlError = errno; //we only set this variable if the pre-allocated variable is given
}
return(kErrorGettingSizeOfBufferRequired);
}
/* Now we successful obtained the size of the buffer required for the sysctl call. This is stored in the
* SizeOfBufferRequired variable. We will malloc a buffer of that size to hold the sysctl result.
*/
BSDProcessInformationStructure = (struct kinfo_proc*) malloc(sizeOfBufferRequired);
if (BSDProcessInformationStructure == NULL)
{
if (SysctlError != NULL)
{
*SysctlError = ENOMEM; //we only set this variable if the pre-allocated variable is given
}
return(kUnableToAllocateMemoryForBuffer); //unrecoverable error (no memory available) so give up
}
/* Now we have the buffer of the correct size to hold the result we can now call sysctl
* and get the process information.
*
* First Argument: The MIB for gathering information on running BSD processes. The MIB is really
* just an array of integers. Each integer is a constant representing what information to
* gather from the system. Check out the man page to know what constants sysctl will work with.
* Second Argument: The number of constants in the MIB (array of integers). In this case there are three.
* Third Argument: The output buffer where the return value from sysctl will be stored. This is the buffer
* which we allocated specifically for this purpose.
* Forth Argument: The size of the output buffer (argument three). In this case its the size of the
* buffer we already allocated.
* Fifth Argument: The buffer containing the value to set the system value to. In this case we don't
* want to set any system information we only want to gather it. Thus, we pass null as the buffer
* so sysctl knows that we have no desire to set the value.
* Sixth Argument: The length of the buffer containing new information (argument five). In this case
* argument five was null since we didn't want to set the system value. Thus, the size of the buffer
* is zero or NULL.
* Return Value: a return value indicating success or failure. Actually, sysctl will either return
* zero on no error and -1 on error. The errno UNIX variable will be set on error.
*/
error = sysctl(mib, 3, BSDProcessInformationStructure, &sizeOfBufferRequired, NULL, 0);
//Here we successfully got the process information. Thus set the variable to end this sysctl calling loop
if (error == 0)
{
SuccessfullyGotProcessInformation = TRUE;
}
else
{
/* failed getting process information we will try again next time around the loop. Note this is caused
* by the fact the process list changed between getting the size of the buffer and actually filling
* the buffer (something which will happen from time to time since the process list is dynamic).
* Anyways, the attempted sysctl call failed. We will now begin again by freeing up the allocated
* buffer and starting again at the beginning of the loop.
*/
free(BSDProcessInformationStructure);
}
}//end while loop
// --- Going through process list looking for processes with matching names --- //
/* Now that we have the BSD structure describing the running processes we will parse it for the desired
* process name. First we will the number of running processes. We can determine
* the number of processes running because there is a kinfo_proc structure for each process.
*/
NumberOfRunningProcesses = sizeOfBufferRequired / sizeof(struct kinfo_proc);
/* Now we will go through each process description checking to see if the process name matches that
* passed to us. The BSDProcessInformationStructure has an array of kinfo_procs. Each kinfo_proc has
* an extern_proc accociated with it in the kp_proc attribute. Each extern_proc (kp_proc) has the process name
* of the process accociated with it in the p_comm attribute and the PID of that process in the p_pid attibute.
* We test the process name by compairing the process name passed to us with the value in the p_comm value.
* Note we limit the compairison to MAXCOMLEN which is the maximum length of a BSD process name which is used
* by the system.
*/
for (Counter = 0 ; Counter < NumberOfRunningProcesses ; Counter++)
{
//Getting PID of process we are examining
CurrentExaminedProcessPID = BSDProcessInformationStructure[Counter].kp_proc.p_pid;
//Getting name of process we are examining
CurrentExaminedProcessName = BSDProcessInformationStructure[Counter].kp_proc.p_comm;
if ((CurrentExaminedProcessPID > 0) //Valid PID
&& ((strncmp(CurrentExaminedProcessName, ProcessName, MAXCOMLEN) == 0))) //name matches
{
// --- Got a match add it to the array if possible --- //
if ((*NumberOfMatchesFound + 1) > NumberOfPossiblePIDsInArray)
{
//if we overran the array buffer passed we release the allocated buffer give an error.
free(BSDProcessInformationStructure);
return(kPIDBufferOverrunError);
}
//adding the value to the array.
ArrayOfReturnedPIDs[*NumberOfMatchesFound] = CurrentExaminedProcessPID;
//incrementing our number of matches found.
*NumberOfMatchesFound = *NumberOfMatchesFound + 1;
}
}//end looking through process list
free(BSDProcessInformationStructure); //done with allocated buffer so release.
if (*NumberOfMatchesFound == 0)
{
//didn't find any matches return error.
return(kCouldNotFindRequestedProcess);
}
else
{
//found matches return success.
return(kSuccess);
}
}
NSString * documentsDirectoryFor( int mode, NSString *url)
{
char s[ 4096];
FSRef ref;
NSString *path = nil;
switch( mode)
{
case 0:
if( FSFindFolder (kOnAppropriateDisk, kDocumentsFolderType, kCreateFolder, &ref) == noErr )
{
BOOL isDir = YES;
FSRefMakePath(&ref, (UInt8 *)s, sizeof(s));
path = [[NSString stringWithUTF8String:s] stringByAppendingPathComponent:@"/OsiriX Data"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir] && isDir)
[[NSFileManager defaultManager] createDirectoryAtPath:path attributes:nil];
}
break;
case 1:
{
BOOL isDir = YES;
path = [url stringByAppendingPathComponent:@"/OsiriX Data"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:&isDir]) [[NSFileManager defaultManager] createDirectoryAtPath:path attributes:nil];
}
break;
}
NSString *dir = nil;
dir = [path stringByAppendingPathComponent:@"/REPORTS/"];
if ([[NSFileManager defaultManager] fileExistsAtPath: dir] == NO)
[[NSFileManager defaultManager] createDirectoryAtPath: dir attributes:nil];
dir = [path stringByAppendingPathComponent:@"/ROIs/"];
if ([[NSFileManager defaultManager] fileExistsAtPath: dir] == NO)
[[NSFileManager defaultManager] createDirectoryAtPath: dir attributes:nil];
if( path == 0L)
NSLog( @"**** documentsDirectoryFor is NIL");
return path;
}
NSString * documentsDirectory()
{
NSString *path = nil;
@try
{
path = documentsDirectoryFor( [[NSUserDefaults standardUserDefaults] integerForKey: @"DATABASELOCATION"], [[NSUserDefaults standardUserDefaults] stringForKey: @"DATABASELOCATIONURL"]);
if( [[NSFileManager defaultManager] fileExistsAtPath:path] == NO || path == 0L) // STILL NOT AVAILABLE??
{ // Use the default folder.. and reset this strange URL..
[[NSUserDefaults standardUserDefaults] setInteger: 0 forKey: @"DATABASELOCATION"];
[[NSUserDefaults standardUserDefaults] setInteger: 0 forKey: @"DEFAULT_DATABASELOCATION"];
return documentsDirectoryFor( [[NSUserDefaults standardUserDefaults] integerForKey: @"DATABASELOCATION"], [[NSUserDefaults standardUserDefaults] stringForKey: @"DATABASELOCATIONURL"]);
}
}
@catch (NSException *e)
{
NSLog( @"**** exception documentsDirectory: %@", e);
}
return path;
}
static volatile BOOL converting = NO;
NSString* filenameWithDate( NSString *inputfile)
{
NSDictionary *fattrs = [[NSFileManager defaultManager] fileAttributesAtPath:inputfile traverseLink:YES];
NSDate *createDate;
NSNumber *fileSize;
createDate = [fattrs objectForKey:NSFileModificationDate];
fileSize = [fattrs objectForKey:NSFileSize];
if( createDate == nil) createDate = [NSDate date];
return [[[[inputfile lastPathComponent] stringByDeletingPathExtension] stringByAppendingFormat:@"%@-%d-%@", [createDate descriptionWithCalendarFormat:@"%Y-%m-%d-%H-%M-%S" timeZone:nil locale:nil], [fileSize intValue], [[inputfile stringByDeletingLastPathComponent]lastPathComponent]] stringByAppendingString:@".dcm"];
}
NSString* convertDICOM( NSString *inputfile)
{
NSString *outputfile = [documentsDirectory() stringByAppendingFormat:@"/TEMP.noindex/%@", filenameWithDate( inputfile)];
if ([[NSFileManager defaultManager] fileExistsAtPath:outputfile])
return outputfile;
converting = YES;
NSLog(@"convertDICOM - FAILED to use current DICOM File Parser : %@", inputfile);
[[BrowserController currentBrowser] decompressDICOMList: [NSArray arrayWithObject: inputfile] to: [outputfile stringByDeletingLastPathComponent]];
return outputfile;
}
//NSString* convertDICOM( NSString *inputfile)
//{
// NSString *tempString, *outputfile = [documentsDirectory() stringByAppendingFormat:@"/TEMP.noindex/%@", filenameWithDate( inputfile)];
// NSMutableArray *theArguments = [NSMutableArray array];
// long i = 0;
//
// while( converting)
// {
// [NSThread sleepForTimeInterval:0.002];
// }
//
// NSLog(inputfile);
// if ([[NSFileManager defaultManager] fileExistsAtPath:outputfile])
// {
// //[[NSFileManager defaultManager] removeFileAtPath:outputfile handler: nil];
// //NSLog(@"Already converted...");
// return outputfile;
// }
//
// converting = YES;
// NSLog(@"IN");
// NSTask *convertTask = [[NSTask alloc] init];
//
//// [convertTask setEnvironment:[NSDictionary dictionaryWithObject:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/dicom.dic"] forKey:@"DCMDICTPATH"]];
//// [convertTask setLaunchPath:[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"/dcmdjpeg"]];
//
// [convertTask setEnvironment:[NSDictionary dictionaryWithObject:[[[NSBundle bundleForClass:[AppController class]] resourcePath] stringByAppendingPathComponent:@"/dicom.dic"] forKey:@"DCMDICTPATH"]];
// [convertTask setLaunchPath:[[[NSBundle bundleForClass:[AppController class]] resourcePath] stringByAppendingPathComponent:@"/dcmdjpeg"]];
//
// [theArguments addObject:inputfile];
// [theArguments addObject:outputfile];
//
// [convertTask setArguments:theArguments];
//
// NS_DURING
// // launch traceroute
// [convertTask launch];
// //[convertTask waitUntilExit];
//
// while( [convertTask isRunning] == YES)
// {
// // NSLog(@"CONVERSION WORK");
// [NSThread sleepForTimeInterval:0.002];
// }
//
// [convertTask interrupt];
// [convertTask release];
//
// NSLog(@"OUT");
//
// converting = NO;
//
// NS_HANDLER
// NSLog( [localException name]);
// converting = NO;
// NS_ENDHANDLER
//
// return outputfile ;
//}
int dictSort(id num1, id num2, void *context)
{
return [[num1 objectForKey:@"AETitle"] caseInsensitiveCompare: [num2 objectForKey:@"AETitle"]];
}
#define kHasAltiVecMask ( 1 << gestaltPowerPCHasVectorInstructions ) // used in looking for a g4
short HasAltiVec ( )
{
Boolean hasAltiVec = 0;
OSErr err;
SInt32 ppcFeatures;
err = Gestalt ( gestaltPowerPCProcessorFeatures, &ppcFeatures );
if ( err == noErr)
{
if ( ( ppcFeatures & kHasAltiVecMask) != 0 )
{
hasAltiVec = 1;
NSLog(@"AltiVEC is available");
}
}
return hasAltiVec;
}
//———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
BOOL hasMacOSXSnowLeopard()
{
OSErr err;
SInt32 osVersion;
err = Gestalt ( gestaltSystemVersion, &osVersion );
if ( err == noErr)
{
if ( osVersion < 0x1060UL )
{
return NO;
}
}
return YES;
}
BOOL hasMacOSXLeopard()
{
OSErr err;
SInt32 osVersion;
err = Gestalt ( gestaltSystemVersion, &osVersion );
if ( err == noErr)
{
if ( osVersion < 0x1050UL )
{
return NO;
}
}
return YES;
}
BOOL hasMacOSXTiger()
{
OSErr err;
SInt32 osVersion;
err = Gestalt ( gestaltSystemVersion, &osVersion );
if ( err == noErr)
{
if ( osVersion < 0x1040UL )
{
return NO;
}
}
return YES;
}
SInt32 osVersion()
{
OSErr err;
SInt32 osVersion;
err = Gestalt ( gestaltSystemVersion, &osVersion );
if ( err == noErr)
{
return osVersion;
}
return 0;
}
//———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
NSRect screenFrame()
{
int i = 0;
float height = 0.0;
float width = 0.0;
float singleWidth = 0.0;
int screenCount = [[NSScreen screens] count];
NSRect frame;
NSRect screenRect;
switch ([[NSUserDefaults standardUserDefaults] integerForKey: @"MULTIPLESCREENS"])
{
case 0: // use main screen only
screenRect = [[[NSScreen screens] objectAtIndex:0] visibleFrame];
break;
case 1: // use second screen only
if (screenCount == 2)
{
screenRect = [[[NSScreen screens] objectAtIndex: 1] visibleFrame];
}
else if ( screenCount > 2)
{
//multiple monitors. Need to span at least two monitors for viewing if they are the same size.
height = [[[NSScreen screens] objectAtIndex:1] frame].size.height;
singleWidth = width = [[[NSScreen screens] objectAtIndex:1] frame].size.width;
for (i = 2; i < screenCount; i ++)
{
frame = [[[NSScreen screens] objectAtIndex:i] frame];
if (frame.size.height == height && frame.size.width == singleWidth)
width =+ frame.size.width;
}
screenRect = NSMakeRect([[[NSScreen screens] objectAtIndex:1] frame].origin.x,
[[[NSScreen screens] objectAtIndex:1] frame].origin.y,
width,
height);
}
else //only one screen
{
screenRect = [[[NSScreen screens] objectAtIndex:0] visibleFrame];
}
break;
case 2: // use all screens
height = [[[NSScreen screens] objectAtIndex:0] frame].size.height;
singleWidth = width = [[[NSScreen screens] objectAtIndex:0] frame].size.width;
for (i = 1; i < screenCount; i ++)
{
frame = [[[NSScreen screens] objectAtIndex:i] frame];
if (frame.size.height == height && frame.size.width == singleWidth)
width =+ frame.size.width;
}
screenRect = NSMakeRect([[[NSScreen screens] objectAtIndex:0] frame].origin.x,
[[[NSScreen screens] objectAtIndex:0] frame].origin.y,
width,
height);
//screenRect = [[[NSScreen screens] objectAtIndex:0] visibleFrame];
break;
}
return screenRect;
}
//———————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————
static NSDate *lastWarningDate = nil;
@implementation AppController
@synthesize checkAllWindowsAreVisibleIsOff, filtersMenu;
- (void) pause
{
[[[BrowserController currentBrowser] checkIncomingLock] lock];
sleep( 2);
[[[BrowserController currentBrowser] checkIncomingLock] unlock];
}
// Plugins installation
- (void) installPlugins: (NSArray*) pluginsArray
{
NSMutableString *pluginNames = [NSMutableString string];
NSMutableString *replacingPlugins = [NSMutableString string];
NSString *replacing = NSLocalizedString(@" will be replaced by ", @"");
NSString *strVersion = NSLocalizedString(@" version ", @"");
NSMutableDictionary *active = [NSMutableDictionary dictionary];
NSMutableDictionary *availabilities = [NSMutableDictionary dictionary];
for(NSString *path in pluginsArray)
{
[pluginNames appendFormat:@"%@, ", [[path lastPathComponent] stringByDeletingPathExtension]];
NSString *pluginBundleName = [[path lastPathComponent] stringByDeletingPathExtension];
NSURL *bundleURL = [NSURL fileURLWithPath:[PluginManager pathResolved:path]];
CFDictionaryRef bundleInfoDict = CFBundleCopyInfoDictionaryInDirectory((CFURLRef)bundleURL);
CFStringRef versionString = nil;
if(bundleInfoDict != NULL)
versionString = CFDictionaryGetValue(bundleInfoDict, CFSTR("CFBundleVersion"));
NSString *pluginBundleVersion = nil;
if(versionString != NULL)
pluginBundleVersion = (NSString*)versionString;
else
pluginBundleVersion = @"";
NSArray *pluginsDictArray = [PluginManager pluginsList];
for(NSDictionary *plug in pluginsDictArray)
{
if([pluginBundleName isEqualToString:[plug objectForKey:@"name"]])
{
[replacingPlugins appendString:[plug objectForKey:@"name"]];
[replacingPlugins appendString:strVersion];
[replacingPlugins appendString:[plug objectForKey:@"version"]];
[replacingPlugins appendString:replacing];
[replacingPlugins appendString:pluginBundleName];
[replacingPlugins appendString:strVersion];
[replacingPlugins appendString:pluginBundleVersion];
[replacingPlugins appendString:@"\n\n"];
[availabilities setObject:[plug objectForKey:@"availability"] forKey:path];
[active setObject:[plug objectForKey:@"active"] forKey:path];
}
}
if( bundleInfoDict)
CFRelease( bundleInfoDict);
}
pluginNames = [NSMutableString stringWithString:[pluginNames substringToIndex:[pluginNames length]-2]];
if([replacingPlugins length]) replacingPlugins = [NSMutableString stringWithString:[replacingPlugins substringToIndex:[replacingPlugins length]-2]];
NSString *msg;
NSString *areYouSure = NSLocalizedString(@"Are you sure you want to install", @"");
if([pluginsArray count]==1)
msg = [NSString stringWithFormat:NSLocalizedString(@"%@ the plugin named : %@ ?", @""), areYouSure, pluginNames];
else
msg = [NSString stringWithFormat:NSLocalizedString(@"%@ the following plugins : %@ ?", @""), areYouSure, pluginNames];
if([replacingPlugins length])
msg = [NSString stringWithFormat:@"%@\n\n%@", msg, replacingPlugins];
NSInteger res = NSRunAlertPanel(NSLocalizedString(@"Plugins Installation", @""), msg, NSLocalizedString(@"OK", @""), NSLocalizedString(@"Cancel", @""), nil);
if(res)
{
// move the plugin package into the plugins (active) directory
NSString *destinationDirectory;
NSString *destinationPath;
NSArray *pluginManagerAvailabilities = [PluginManager availabilities];
for(NSString *path in pluginsArray)
{
NSString *availability = [availabilities objectForKey:path];
BOOL isActive = [[active objectForKey:path] boolValue];
if(!availability)
isActive = YES;
if([availability isEqualToString:[pluginManagerAvailabilities objectAtIndex:0]])
{
if(isActive)
destinationDirectory = [PluginManager userActivePluginsDirectoryPath];
else
destinationDirectory = [PluginManager userInactivePluginsDirectoryPath];
}
else if([availability isEqualToString:[pluginManagerAvailabilities objectAtIndex:1]])
{
if(isActive)
destinationDirectory = [PluginManager systemActivePluginsDirectoryPath];
else
destinationDirectory = [PluginManager systemInactivePluginsDirectoryPath];
}
else if([availability isEqualToString:[pluginManagerAvailabilities objectAtIndex:2]])
{
if(isActive)
destinationDirectory = [PluginManager appActivePluginsDirectoryPath];
else
destinationDirectory = [PluginManager appInactivePluginsDirectoryPath];
}
else
{
if(isActive)
destinationDirectory = [PluginManager userActivePluginsDirectoryPath];
else
destinationDirectory = [PluginManager userInactivePluginsDirectoryPath];
}
destinationPath = [destinationDirectory stringByAppendingPathComponent:[path lastPathComponent]];
// delete the plugin if it already exists.
NSString *pathToDelete = nil;
if([[NSFileManager defaultManager] fileExistsAtPath:destinationPath]) // .osirixplugin extension
pathToDelete = destinationPath;
else
{
NSString *pathWithOldExt = [[destinationPath stringByDeletingPathExtension] stringByAppendingPathExtension:@"plugin"];
if([[NSFileManager defaultManager] fileExistsAtPath:pathWithOldExt]) // the plugin already exists but with the old extension ".plugin"
pathToDelete = pathWithOldExt;
}
BOOL move = YES;
if(pathToDelete)
{
// first, try with NSFileManager
if( [[NSFileManager defaultManager] removeFileAtPath: pathToDelete handler: nil] == NO) // Please leave this line! ANR
{
NSMutableArray *args = [NSMutableArray array];
[args addObject:@"-r"];
[args addObject:pathToDelete];
[[BLAuthentication sharedInstance] executeCommand:@"/bin/rm" withArgs:args];
}
[[NSFileManager defaultManager] removeFileAtPath: pathToDelete handler: nil]; // Please leave this line! ANR
if( [[NSFileManager defaultManager] fileExistsAtPath: pathToDelete])
{
NSRunAlertPanel( NSLocalizedString( @"Plugins Installation", nil), NSLocalizedString( @"Failed to remove previous version of the plugin.", nil), NSLocalizedString( @"OK", nil), nil, nil);
move = NO;
}
}
// move the new plugin to the plugin folder
if( move)
[PluginManager movePluginFromPath:path toPath:destinationPath];
}
[PluginManager discoverPlugins];
[PluginManager setMenus: filtersMenu :roisMenu :othersMenu :dbMenu];
#ifndef OSIRIX_LIGHT
// refresh the plugin manager window (if open)
NSArray *winList = [NSApp windows];
for(NSWindow *window in winList)
{
if( [[window windowController] isKindOfClass:[PluginManagerController class]])
[[window windowController] refreshPluginList];
}
#endif
NSRunInformationalAlertPanel(NSLocalizedString(@"Plugin Update Completed", @""), NSLocalizedString(@"All your plugins are now up to date. Restart OsiriX to use the new or updated plugins.", @""), NSLocalizedString(@"OK", @""), nil, nil);
}
}
+ (void) createNoIndexDirectoryIfNecessary:(NSString*) path
{
BOOL newFolder = NO;
if( ![[NSFileManager defaultManager] fileExistsAtPath: path] && [[NSFileManager defaultManager] fileExistsAtPath: [path stringByDeletingPathExtension]])
{
[[NSFileManager defaultManager] movePath:[path stringByDeletingPathExtension] toPath:path handler: nil];
newFolder = YES;
}
if( ![[NSFileManager defaultManager] fileExistsAtPath: path])
{
if( [[NSFileManager defaultManager] createDirectoryAtPath: path withIntermediateDirectories: NO attributes: nil error: nil] == NO)
NSLog( @"******* failed to create directory: %@", path);
newFolder = YES;
}
if( [[NSFileManager defaultManager] fileExistsAtPath: [path stringByDeletingPathExtension]])
[[NSFileManager defaultManager] removeFileAtPath: [path stringByDeletingPathExtension] handler: nil];
if( newFolder)
{
NSDictionary *d = [[NSFileManager defaultManager] attributesOfItemAtPath:path error: nil];
if( d && [[d objectForKey: NSFileExtensionHidden] boolValue] == NO)
{
NSMutableDictionary *m = [NSMutableDictionary dictionaryWithDictionary: d];
[m setObject: [NSNumber numberWithBool: YES] forKey:NSFileExtensionHidden];
[[NSFileManager defaultManager] changeFileAttributes: m atPath: path];
}
}
}
+ (void) pause
{
[[AppController sharedAppController] performSelectorOnMainThread: @selector( pause) withObject: nil waitUntilDone: NO];
}
+ (NSThread*) mainThread
{
return mainThread;
}
+ (void) resetToolbars
{
int numberOfScreens = [[NSScreen screens] count] + 1; //Just in case, we connect a second monitor when using OsiriX.
for( int i = 0; i < numberOfScreens; i++)
{
if( toolbarPanel[ i]) [toolbarPanel[ i] release];
}
for( int i = 0; i < numberOfScreens; i++)
toolbarPanel[ i] = [[ToolbarPanelController alloc] initForScreen: i];
for( int i = 0; i < numberOfScreens; i++)
[toolbarPanel[ i] fixSize];
}
+ (void) resizeWindowWithAnimation:(NSWindow*) window newSize: (NSRect) newWindowFrame
{
if( [[NSUserDefaults standardUserDefaults] boolForKey:@"NSWindowsSetFrameAnimate"])
{
@try
{
NSDictionary *windowResize = [NSDictionary dictionaryWithObjectsAndKeys:
window, NSViewAnimationTargetKey,
[NSValue valueWithRect: newWindowFrame],
NSViewAnimationEndFrameKey,
nil];
if( accumulateAnimations)
{
if( accumulateAnimationsArray == nil) accumulateAnimationsArray = [[NSMutableArray array] retain];
[accumulateAnimationsArray addObject: windowResize];
}
else
{
[OSIWindowController setDontEnterWindowDidChangeScreen: YES];
NSViewAnimation * animation = [[[NSViewAnimation alloc] initWithViewAnimations: [NSArray arrayWithObjects: windowResize, nil]] autorelease];
[animation setAnimationBlockingMode: NSAnimationBlocking];
[animation setDuration: 0.15];
[animation startAnimation];
[OSIWindowController setDontEnterWindowDidChangeScreen: NO];
}
}
@catch( NSException *e)
{
NSLog( @"resizeWindowWithAnimation exception: %@", e);
}
}
else
{
[window setFrame: newWindowFrame display: YES];
}
}
+ (void) displayImportantNotice:(id) sender
{
int saved = [[NSUserDefaults standardUserDefaults] integerForKey: @"lastWarningDay"];
if( saved == 0)
{
if( lastWarningDate == nil || [lastWarningDate timeIntervalSinceNow] < -60*60*16)
{
int result = NSRunCriticalAlertPanel( NSLocalizedString( @"Important Notice", nil), NSLocalizedString( @"This version of OsiriX, being a free open-source software (FOSS), is not certified as a commercial medical device (FDA or CE-1) for primary diagnosis.\r\rPlease check with local compliance office for possible limitations in its clinical use.\r\rFor a FDA / CE-1 certified version, please check our partners web page:\r\rhttp://www.osirix-viewer.com/Partners.html\r", nil), NSLocalizedString( @"I agree", nil), NSLocalizedString( @"Quit", nil), NSLocalizedString( @"Partners", nil));
if( result == NSAlertOtherReturn)
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:@"http://www.osirix-viewer.com/Partners.html"]];
}
else if( result != NSAlertDefaultReturn)
[[AppController sharedAppController] terminate: self];
else
[[NSUserDefaults standardUserDefaults] setInteger: [[NSCalendarDate date] dayOfYear] forKey: @"lastWarningDay"];
}
[lastWarningDate release];
lastWarningDate = [[NSDate date] retain];
}
}
- (NSString *)computerName
{
return [(id)SCDynamicStoreCopyComputerName(NULL, NULL) autorelease];
}
- (NSString*) privateIP
{
NSString *ip = nil;
char *c = GetPrivateIP();
if( c)
ip = [NSString stringWithCString: c];
if( ip == nil || [ip length] == 0)
ip = [self computerName];
return ip;
}
- (IBAction)cancelModal:(id)sender
{