forked from pixmeo/osirix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBrowserController+Sources.m
1409 lines (1191 loc) · 56.5 KB
/
BrowserController+Sources.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 "BrowserController+Sources.h"
#import "BrowserController+Sources+Copy.h"
#import "DataNodeIdentifier.h"
#import "PrettyCell.h"
#import "DicomDatabase.h"
#import "RemoteDicomDatabase.h"
#import "NSManagedObject+N2.h"
#import "DicomImage.h"
#import "MutableArrayCategory.h"
#import "NSImage+N2.h"
#import "NSUserDefaultsController+N2.h"
#import "N2Debug.h"
#import "NSThread+N2.h"
#import "N2Operators.h"
#import "ThreadModalForWindowController.h"
#import "BonjourPublisher.h"
#import "DicomFile.h"
#import "ThreadsManager.h"
#import "NSDictionary+N2.h"
#import "NSFileManager+N2.h"
#import "DCMNetServiceDelegate.h"
#import "AppController.h"
#import <netinet/in.h>
#import <arpa/inet.h>
#import "DicomDatabase+Scan.h"
#import "DCMPix.h"
#import "NSHost+N2.h"
#import "DefaultsOsiriX.h"
#import "NSString+N2.h"
/*
#include <IOKit/IOKitLib.h>
#include <IOKit/IOMessage.h>
#include <IOKit/IOCFPlugIn.h>
#include <IOKit/usb/IOUSBLib.h>
*/
@interface BrowserSourcesHelper : NSObject<NSNetServiceBrowserDelegate, NSNetServiceDelegate>/*<NSTableViewDelegate,NSTableViewDataSource>*/
{
BrowserController* _browser;
NSNetServiceBrowser* _nsbOsirix;
NSNetServiceBrowser* _nsbDicom;
NSMutableArray* _bonjourSources, *_bonjourServices;
BOOL dontListenToSourcesChanges;
}
-(id)initWithBrowser:(BrowserController*)browser;
-(void)_analyzeVolumeAtPath:(NSString*)path;
@end
@interface DefaultLocalDatabaseNodeIdentifier : LocalDatabaseNodeIdentifier
+(DefaultLocalDatabaseNodeIdentifier*)identifier;
@end
/*@interface BonjourDataNodeIdentifier : DataNodeIdentifier
{
NSNetService* _service;
}
@property(retain) NSNetService* service;
-(NSInteger)port;
@end*/
@interface MountedDatabaseNodeIdentifier : LocalDatabaseNodeIdentifier
{
NSString* _devicePath;
DicomDatabase* _database;
NSInteger _mountType;
NSThread* _scanThread;
NSButton* _unmountButton;
}
enum {
MountTypeGeneric = 0,
MountTypeIPod = 1
};
@property(retain) NSString* devicePath;
@property NSInteger mountType;
+(id)mountedDatabaseNodeIdentifierWithPath:(NSString*)devicePath description:(NSString*)description dictionary:(NSDictionary*)dictionary type:(NSInteger)type;
-(void)willUnmount;
@end
@interface UnavaliableDataNodeException : NSException
@end
@implementation BrowserController (Sources)
-(void)removePathFromSources:(NSString*) path
{
MountedDatabaseNodeIdentifier* mbs = nil;
for (MountedDatabaseNodeIdentifier* ibs in self.sources.arrangedObjects)
if ([ibs isKindOfClass:[MountedDatabaseNodeIdentifier class]] && [ibs.devicePath isEqualToString:path])
{
mbs = ibs;
break;
}
if (mbs)
{
if ([[self sourceIdentifierForDatabase:self.database] isEqualToDataNodeIdentifier:mbs])
[self performSelector: @selector(setDatabase:) withObject: DicomDatabase.defaultDatabase afterDelay: 0.01]; //This will guarantee that this will not happen in middle of a drag & drop, for example
[mbs retain];
[self.sources removeObject:mbs];
[mbs willUnmount];
[mbs performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
-(void)awakeSources
{
[_sourcesArrayController setSortDescriptors:[NSArray arrayWithObjects: [[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES] autorelease], NULL]];
[_sourcesArrayController setAutomaticallyRearrangesObjects:YES];
[_sourcesArrayController addObject:[DefaultLocalDatabaseNodeIdentifier identifier]];
[_sourcesArrayController setSelectsInsertedObjects:NO];
_sourcesHelper = [[BrowserSourcesHelper alloc] initWithBrowser:self];
[_sourcesTableView setDataSource:_sourcesHelper];
[_sourcesTableView setDelegate:_sourcesHelper];
PrettyCell* cell = [[[PrettyCell alloc] init] autorelease];
[[_sourcesTableView tableColumnWithIdentifier:@"Source"] setDataCell:cell];
[_sourcesTableView registerForDraggedTypes:[NSArray arrayWithObject:O2AlbumDragType]];
[_sourcesTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:0] byExtendingSelection:NO];
}
-(void)deallocSources
{
[_sourcesHelper release]; _sourcesHelper = nil;
}
-(NSInteger)sourcesCount
{
return [[_sourcesArrayController arrangedObjects] count];
}
-(DataNodeIdentifier*)sourceIdentifierAtRow:(int)row
{
return ([_sourcesArrayController.arrangedObjects count] > row)? [_sourcesArrayController.arrangedObjects objectAtIndex:row] : nil;
}
-(int)rowForSourceIdentifier:(DataNodeIdentifier*)source
{
for (NSInteger i = 0; i < [[_sourcesArrayController arrangedObjects] count]; ++i)
if ([[_sourcesArrayController.arrangedObjects objectAtIndex:i] isEqualToDataNodeIdentifier:source])
return i;
return -1;
}
-(DataNodeIdentifier*)sourceIdentifierForDatabase:(DicomDatabase*)database // TODO: move this to -[DicomDatabase dataNodeIdentifier]
{
if (database == [DicomDatabase defaultDatabase])
return [DefaultLocalDatabaseNodeIdentifier identifier];
if (database.isLocal)
return [LocalDatabaseNodeIdentifier localDatabaseNodeIdentifierWithPath:database.baseDirPath];
else
return [RemoteDatabaseNodeIdentifier remoteDatabaseNodeIdentifierWithLocation:[(RemoteDicomDatabase*)database address] port:[(RemoteDicomDatabase*)database port] description:nil dictionary:nil];
}
-(int)rowForDatabase:(DicomDatabase*)database
{
return [self rowForSourceIdentifier:[self sourceIdentifierForDatabase:database]];
}
-(void)selectSourceForDatabase:(DicomDatabase*)database
{
NSInteger row = [self rowForDatabase:database];
if (row >= 0)
[_sourcesTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
else NSLog(@"Warning: couldn't find database in sources (%@)", database);
}
-(void)selectCurrentDatabaseSource
{
if (!_database)
{
[_sourcesTableView selectRowIndexes:[NSIndexSet indexSet] byExtendingSelection:NO];
return;
}
NSInteger i = [self rowForDatabase:_database];
if (i == -1 && _database != [DicomDatabase defaultDatabase])
{
NSDictionary* source = [NSDictionary dictionaryWithObjectsAndKeys: [_database.baseDirPath stringByDeletingLastPathComponent], @"Path", [_database.baseDirPath.stringByDeletingLastPathComponent.lastPathComponent stringByAppendingString: NSLocalizedString( @" DB", @"DB = DataBase")], @"Description", nil];
[[NSUserDefaults standardUserDefaults] setObject:[[[NSUserDefaults standardUserDefaults] objectForKey:@"localDatabasePaths"] arrayByAddingObject:source] forKey:@"localDatabasePaths"];
i = [self rowForDatabase:_database];
}
if (i != [_sourcesTableView selectedRow])
[_sourcesTableView selectRowIndexes:[NSIndexSet indexSetWithIndex:i] byExtendingSelection:NO];
}
-(void)setDatabaseOnMainThread: (DicomDatabase*) db
{
[self performSelector: @selector( setDatabase:) withObject: db afterDelay: 0.01]; //This will guarantee that this will not happen in middle of a drag & drop, for example
}
-(void)setDatabaseThread:(NSArray*)io
{
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
@try
{
NSString* type = [io objectAtIndex:0];
DicomDatabase* db = nil;
if ([type isEqualToString:@"Local"])
{
NSString* path = [io objectAtIndex:1];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSString* message = NSLocalizedString(@"The selected database's data was not found on your computer.", nil);
if ([path hasPrefix:@"/Volumes/"])
message = [message stringByAppendingFormat:@" %@", NSLocalizedString(@"If it is stored on an external drive? If so, please make sure the device in connected and on.", nil)];
[NSException raise:NSGenericException format:@"%@", message];
}
NSString* name = io.count > 2? [io objectAtIndex:2] : nil;
db = [DicomDatabase databaseAtPath:path name:name];
}
if ([type isEqualToString:@"Remote"])
{
NSString* address = [io objectAtIndex:1];
NSInteger port = [[io objectAtIndex:2] intValue];
NSString* name = io.count > 3? [io objectAtIndex:3] : nil;
db = [RemoteDicomDatabase databaseForLocation:address port:port name:name update:YES];
}
[self performSelectorOnMainThread:@selector( setDatabaseOnMainThread:) withObject:db waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
[NSThread sleepForTimeInterval: 1];
} @catch (NSException* e)
{
[self performSelectorOnMainThread:@selector(selectCurrentDatabaseSource) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
if (![e.description isEqualToString:@"Cancelled."])
{
N2LogExceptionWithStackTrace(e);
[self performSelectorOnMainThread:@selector(_complain:) withObject:[NSArray arrayWithObjects: [NSNumber numberWithFloat:0.1], NSLocalizedString(@"Error", nil), e.description, NULL] waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
}
} @finally
{
[pool release];
}
}
-(void)_complain:(NSArray*)why { // if 1st obj in array is a number then execute this after the delay specified by that number, with the rest of the array
if ([[why objectAtIndex:0] isKindOfClass:[NSNumber class]])
[self performSelector:@selector(_complain:) withObject:[why subarrayWithRange:NSMakeRange(1, (long)why.count-1)] afterDelay:[[why objectAtIndex:0] floatValue]];
else
NSBeginAlertSheet([why objectAtIndex:0], nil, nil, nil, self.window, NSApp, @selector(endSheet:), nil, nil, @"%@", [why objectAtIndex:1]);
}
-(NSThread*)initiateSetDatabaseAtPath:(NSString*)path name:(NSString*)name
{
NSArray* io = [NSMutableArray arrayWithObjects: @"Local", path, name, nil];
NSThread* thread = [[[NSThread alloc] initWithTarget:self selector:@selector(setDatabaseThread:) object:io] autorelease];
thread.name = NSLocalizedString(@"Loading OsiriX database...", nil);
thread.supportsCancel = YES;
thread.status = NSLocalizedString(@"Reading data...", nil);
[thread startModalForWindow:self.window];
[thread start];
return thread;
}
-(NSThread*)initiateSetRemoteDatabaseWithAddress:(NSString*)address port:(NSInteger)port name:(NSString*)name
{
NSArray* io = [NSMutableArray arrayWithObjects: @"Remote", address, [NSNumber numberWithInteger:port], name, nil];
NSThread* thread = [[NSThread alloc] initWithTarget:self selector:@selector(setDatabaseThread:) object:io];
thread.name = NSLocalizedString(@"Loading remote OsiriX database...", nil);
thread.supportsCancel = YES;
[thread startModalForWindow:self.window];
[thread start];
return [thread autorelease];
}
- (void) setDatabaseWithModalWindow: (DicomDatabase*) db
{
NSThread* thread = [NSThread currentThread];
thread.name = NSLocalizedString(@"Opening database...", nil);
thread.status = NSLocalizedString(@"Opening database...", nil);
thread.supportsCancel = YES;
ThreadModalForWindowController* tmc = [thread startModalForWindow:self.window];
[self setDatabase: db];
[tmc invalidate];
}
-(void)setDatabaseFromSourceIdentifier:(DataNodeIdentifier*)dni
{
if ([dni isEqualToDataNodeIdentifier:[self sourceIdentifierForDatabase:_database]])
return;
@try
{
DicomDatabase* db = [dni database];
if (db)
[self performSelector: @selector( setDatabaseWithModalWindow:) withObject: db afterDelay: 0.01]; //This will guarantee that this will not happen in middle of a drag & drop, for example
else if ([dni isKindOfClass:[LocalDatabaseNodeIdentifier class]])
[self initiateSetDatabaseAtPath:dni.location name:dni.description];
else if ([dni isKindOfClass:[RemoteDatabaseNodeIdentifier class]])
{
NSString* host = nil; NSInteger port = -1;
[RemoteDatabaseNodeIdentifier location:dni.location port:dni.port toAddress:&host port:&port];
if( host && port != -1)
[self initiateSetRemoteDatabaseWithAddress:host port:port name:dni.description];
}
else
{
[UnavaliableDataNodeException raise:NSGenericException format:@"%@", NSLocalizedString(@"This is a DICOM destination node: you cannot browse its content. You can only drag & drop studies on them.", nil)];
}
} @catch (UnavaliableDataNodeException* e)
{
NSBeginAlertSheet(NSLocalizedString(@"Sources", nil), nil, nil, nil, self.window, NSApp, @selector(endSheet:), nil, nil, @"%@", [e reason]);
[self selectCurrentDatabaseSource];
}
}
-(void)redrawSources
{
if( [NSThread isMainThread])
[_sourcesTableView setNeedsDisplay:YES];
else
[self performSelectorOnMainThread: @selector( redrawSources) withObject: nil waitUntilDone: NO];
}
-(int)findDBPath:(NSString*)path dbFolder:(NSString*)DBFolderLocation { // __deprecated
NSInteger i = [self rowForSourceIdentifier:[LocalDatabaseNodeIdentifier localDatabaseNodeIdentifierWithPath:path]];
if (i < 0) i = [self rowForSourceIdentifier:[LocalDatabaseNodeIdentifier localDatabaseNodeIdentifierWithPath:DBFolderLocation]];
return i;
}
@end
@implementation BrowserSourcesHelper
static void* const LocalBrowserSourcesContext = @"LocalBrowserSourcesContext";
static void* const RemoteBrowserSourcesContext = @"RemoteBrowserSourcesContext";
static void* const DicomBrowserSourcesContext = @"DicomBrowserSourcesContext";
static void* const SearchBonjourNodesContext = @"SearchBonjourNodesContext";
static void* const SearchDicomNodesContext = @"SearchDicomNodesContext";
-(id)initWithBrowser:(BrowserController*)browser
{
if ((self = [super init]))
{
_browser = browser;
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:@"localDatabasePaths" options:NSKeyValueObservingOptionInitial context:LocalBrowserSourcesContext];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:@"OSIRIXSERVERS" options:NSKeyValueObservingOptionInitial context:RemoteBrowserSourcesContext];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:@"SERVERS" options:NSKeyValueObservingOptionInitial context:DicomBrowserSourcesContext];
_bonjourSources = [[NSMutableArray alloc] init];
_bonjourServices = [[NSMutableArray alloc] init];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:@"searchDICOMBonjour" options:NSKeyValueObservingOptionInitial context:SearchDicomNodesContext];
[[NSUserDefaultsController sharedUserDefaultsController] addObserver:self forValuesKey:@"DoNotSearchForBonjourServices" options:NSKeyValueObservingOptionInitial context:SearchBonjourNodesContext];
_nsbOsirix = [[NSNetServiceBrowser alloc] init];
[_nsbOsirix setDelegate:self];
[_nsbOsirix searchForServicesOfType:@"_osirixdb._tcp." inDomain:@""];
_nsbDicom = [[NSNetServiceBrowser alloc] init];
[_nsbDicom setDelegate:self];
[_nsbDicom searchForServicesOfType:@"_dicom._tcp." inDomain:@""];
// mounted devices
[[[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];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(_observeVolumeWillUnmountNotification:) name:NSWorkspaceWillUnmountNotification object:nil];
if( [[NSUserDefaults standardUserDefaults] integerForKey: @"MOUNT"] != 2)
{
for (NSString* path in [[NSWorkspace sharedWorkspace] mountedRemovableMedia])
[self _analyzeVolumeAtPath:path];
}
}
return self;
}
-(void)dealloc
{
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceDidMountNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceDidUnmountNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceWillUnmountNotification object:nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] removeObserver:self name:NSWorkspaceDidRenameVolumeNotification object:nil];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:@"DoNotSearchForBonjourServices"];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:@"searchDICOMBonjour"];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:@"SERVERS"];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:@"OSIRIXSERVERS"];
[[NSUserDefaultsController sharedUserDefaultsController] removeObserver:self forValuesKey:@"localDatabasePaths"];
[_nsbDicom release]; _nsbDicom = nil;
[_nsbOsirix release]; _nsbOsirix = nil;
[_bonjourSources release];
[_bonjourServices release];
// [[[NSUserDefaults standardUserDefaults] objectForKey:@"localDatabasePaths"] removeObserver:self forValuesKey:@"values"];
_browser = nil;
[super dealloc];
}
-(void)_observeValueForKeyPathOfObjectChangeContext:(NSArray*)args {
[self observeValueForKeyPath:[args objectAtIndex:0] ofObject:[args objectAtIndex:1] change:[args objectAtIndex:2] context:[[args objectAtIndex:3] pointerValue]];
}
+ (BOOL)host:(NSHost*)h1 isEqualToHost:(NSHost*)h2 {
#define MAC_CONCURRENT_ISEQUALTOHOST 10
static dispatch_semaphore_t sid = 0;
if (!sid)
sid = dispatch_semaphore_create(MAC_CONCURRENT_ISEQUALTOHOST);
if (dispatch_semaphore_wait(sid, DISPATCH_TIME_FOREVER) == 0)
@try {
if (h1.address && h2.address && [h1.address isEqualToString:h2.address])
return YES;
if (h1.name && h2.name && [h1.name isEqualToString:h2.name])
return YES;
// return [h1 isEqualToHost:h2];
} @catch (...) {
@throw;
} @finally {
dispatch_semaphore_signal(sid);
}
return NO;
}
-(void)observeValueForKeyPath:(NSString*)keyPath ofObject:(id)object change:(NSDictionary*)change context:(void*)context
{
if (![NSThread isMainThread])
{
[self performSelectorOnMainThread:@selector(_observeValueForKeyPathOfObjectChangeContext:) withObject:[NSArray arrayWithObjects: keyPath, object, change, [NSValue valueWithPointer:context], nil] waitUntilDone:NO modes:[NSArray arrayWithObject:NSDefaultRunLoopMode]];
return;
}
// NSKeyValueChange changeKind = [[change valueForKey:NSKeyValueChangeKindKey] unsignedIntegerValue];
dontListenToSourcesChanges = YES;
id previousNode = [_browser sourceIdentifierForDatabase:_browser.database];
@try
{
if (context == LocalBrowserSourcesContext)
{
NSArray* a = [[NSUserDefaults standardUserDefaults] objectForKey:@"localDatabasePaths"];
// remove old items
for (DataNodeIdentifier* dni in [[_browser.sources.content copy] autorelease])
{
if ([dni isKindOfClass:[LocalDatabaseNodeIdentifier class]] && dni.entered) // is a local database and is flagged as "entered"
if (![[a valueForKey:@"Path"] containsObject:dni.location]) { // is no longer in the entered list
dni.entered = NO; // mark it as not entered
if (!dni.detected)
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
}
// add new items
for (NSDictionary* d in a)
{
NSString* dpath = [d valueForKey:@"Path"];
if ([[DicomDatabase baseDirPathForPath:dpath] isEqualToString:DicomDatabase.defaultDatabase.baseDirPath]) // is already listed as "default database"
continue;
DataNodeIdentifier* dni;
NSUInteger i = [[_browser.sources.content valueForKey:@"location"] indexOfObject:dpath];
if (i == NSNotFound) {
dni = [LocalDatabaseNodeIdentifier localDatabaseNodeIdentifierWithPath:dpath description:[d objectForKey:@"Description"] dictionary:d];
dni.entered = YES;
[_browser.sources addObject:dni];
} else {
dni = [_browser.sources.content objectAtIndex:i];
dni.entered = YES;
dni.description = [d objectForKey:@"Description"];
dni.dictionary = d;
}
}
}
if (context == RemoteBrowserSourcesContext)
{
NSHost* currentHost = [DefaultsOsiriX currentHost];
NSArray* a = [[NSUserDefaults standardUserDefaults] objectForKey:@"OSIRIXSERVERS"];
// remove old items
for (DataNodeIdentifier* dni in [[_browser.sources.content copy] autorelease])
{
if ([dni isKindOfClass:[RemoteDatabaseNodeIdentifier class]] && dni.entered) // is a remote database and is flagged as "entered"
if (![[a valueForKey:@"Address"] containsObject:dni.location]) // is no longer in the entered list
{
dni.entered = NO; // mark it as not entered
if (!dni.detected)
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
}
// add new items
// NSOperationQueue* queue = [[[NSOperationQueue alloc] init] autorelease];
for (NSDictionary* d in a)
{
[NSThread performBlockInBackground:^{
// we're now in a background thread
NSString* dadd = [d valueForKey:@"Address"];
if ([[self class] host:[NSHost hostWithAddressOrName:dadd] isEqualToHost:currentHost]) // don't list self
return;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// we're now back in the main thread
DataNodeIdentifier* dni;
NSUInteger i = [[_browser.sources.content valueForKey:@"location"] indexOfObject:dadd];
if (i == NSNotFound) {
dni = [RemoteDatabaseNodeIdentifier remoteDatabaseNodeIdentifierWithLocation:dadd port:[[d valueForKey:@"Port"] intValue] description:[d objectForKey:@"Description"] dictionary:d];
dni.entered = YES;
[_browser.sources addObject:dni];
} else {
dni = [_browser.sources.content objectAtIndex:i];
dni.entered = YES;
dni.description = [d objectForKey:@"Description"];
dni.dictionary = d;
}
}];
}];
}
}
if (context == DicomBrowserSourcesContext)
{
NSHost* currentHost = [DefaultsOsiriX currentHost];
NSArray* a = [[NSUserDefaults standardUserDefaults] objectForKey:@"SERVERS"];
NSMutableDictionary* aa = [NSMutableDictionary dictionary];
for (NSDictionary* ai in a)
{
if( [[ai objectForKey: @"Activated"] boolValue] && [[ai objectForKey: @"Send"] boolValue])
{
NSString *uniqueKey =[NSString stringWithFormat:@"%@%d%@", [ai objectForKey:@"Address"],[[ai objectForKey:@"Port"] unsignedIntValue],[ai objectForKey:@"AETitle"]];
[aa setObject:ai forKey:uniqueKey];
}
}
// remove old items
for (DataNodeIdentifier* dni in [[_browser.sources.content copy] autorelease])
{
if ([dni isKindOfClass:[DicomNodeIdentifier class]] && dni.entered) // is a dicom node and is flagged as "entered"
if (![[aa allKeys] containsObject:dni.location]) { // is no longer in the entered list
dni.entered = NO; // mark it as not entered
if (!dni.detected)
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
}
// add new items
for (NSString* aak in aa)
{
// [NSThread performBlockInBackground:^{
// // we're now in a background thread
// NSString* aet = nil;
// if ([[self class] host:[DicomNodeIdentifier location:aak toHost:NULL port:NULL aet:&aet] isEqualToHost:currentHost] && [aet isEqualToString:[[NSUserDefaults standardUserDefaults] stringForKey:@"AETITLE"]]) // don't list self
// return;
// [[NSOperationQueue mainQueue] addOperationWithBlock:^{
// we're now back in the main thread
DataNodeIdentifier* dni;
NSUInteger i = [[_browser.sources.content valueForKey:@"location"] indexOfObject:aak];
if (i == NSNotFound)
{
NSDictionary *k = [aa objectForKey:aak];
dni = [DicomNodeIdentifier dicomNodeIdentifierWithLocation: [k objectForKey:@"Address"] port:[[k objectForKey:@"Port"] intValue] aetitle:[k objectForKey:@"AETitle"] description:[k objectForKey:@"Description"] dictionary:[aa objectForKey:aak]];
dni.entered = YES;
[_browser.sources addObject:dni];
} else {
dni = [_browser.sources.content objectAtIndex:i];
dni.entered = YES;
dni.dictionary = [aa objectForKey:aak];
dni.description = [dni.dictionary objectForKey:@"Description"];
}
// }];
// }];
}
}
if (context == SearchBonjourNodesContext)
@synchronized (_bonjourSources) {
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"DoNotSearchForBonjourServices"]) // add remote databases detected with bonjour
{ // remove remote databases detected with bonjour
for (DataNodeIdentifier* dni in _bonjourSources)
if ([dni isKindOfClass:[RemoteDatabaseNodeIdentifier class]] && dni.detected) {
dni.detected = NO;
if (!dni.entered && [_browser.sources.content containsObject:dni])
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
} else
{ // add remote databases detected with bonjour
for (DataNodeIdentifier* dni in _bonjourSources)
if ([dni isKindOfClass:[RemoteDatabaseNodeIdentifier class]] && !dni.detected && dni.location) {
dni.detected = YES;
if (![_browser.sources.content containsObject:dni])
[_browser.sources addObject:dni];
}
}
}
if (context == SearchDicomNodesContext)
@synchronized (_bonjourSources) {
if (![[NSUserDefaults standardUserDefaults] boolForKey:@"searchDICOMBonjour"])
{ // remove dicom nodes detected with bonjour
for (DataNodeIdentifier* dni in _bonjourSources)
if ([dni isKindOfClass:[DicomNodeIdentifier class]] && dni.detected) {
dni.detected = NO;
if (!dni.entered && [_browser.sources.content containsObject:dni])
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
} else
{ // add dicom nodes detected with bonjour
for (DataNodeIdentifier* dni in _bonjourSources)
if ([dni isKindOfClass:[DicomNodeIdentifier class]] && !dni.detected && dni.location) {
dni.detected = YES;
if (![_browser.sources.content containsObject:dni])
[_browser.sources addObject:dni];
}
}
}
}
@catch (NSException *exception) {
N2LogExceptionWithStackTrace( exception);
}
dontListenToSourcesChanges = NO;
if( [_browser rowForSourceIdentifier: previousNode] == -1)
[_browser performSelector: @selector(setDatabase:) withObject: DicomDatabase.defaultDatabase afterDelay: 0.01]; //This will guarantee that this will not happen in middle of a drag & drop, for example
else
[_browser selectSourceForDatabase: _browser.database];
}
-(void)netServiceDidResolveAddress:(NSNetService*)service
{
@try
{
[service retain];
[service stop]; //Technical Q&A QA1297
DataNodeIdentifier* source0 = nil;
@synchronized (_bonjourSources)
{
if( [_bonjourServices indexOfObject: service] != NSNotFound)
source0 = [_bonjourSources objectAtIndex: [_bonjourServices indexOfObject: service]];
else
NSLog( @"***** unknown didResolve Service");
}
if (!source0)
return;
@try
{
NSDictionary* dict = nil;
if (![service.domain isEqualToString:@"_osirixdb._tcp."])
dict = [BonjourPublisher dictionaryFromXTRecordData:service.TXTRecordData];
else dict = [DCMNetServiceDelegate DICOMNodeInfoFromTXTRecordData:service.TXTRecordData];
if ([[dict objectForKey:@"UID"] isEqualToString:[AppController UID]])
{
@synchronized (_bonjourSources)
{
NSLog( @"Remove Service: %@", service);
if( [_bonjourServices indexOfObject: service] != NSNotFound)
{
[_bonjourSources removeObjectAtIndex: [_bonjourServices indexOfObject: service]];
[_bonjourServices removeObject: service];
}
else
NSLog( @"***** unknown didResolve Service");
}
return; // it's me
}
}
@catch (NSException *exception) {
N2LogException( exception);
return;
}
@try {
// we're now back in the main thread
NSMutableArray* addresses = [NSMutableArray array];
// Prefer IP4
for (NSData* address in service.addresses)
{
struct sockaddr* sockAddr = (struct sockaddr*)address.bytes;
if (sockAddr->sa_family == AF_INET)
{
struct sockaddr_in* sockAddrIn = (struct sockaddr_in*)sockAddr;
char *str = inet_ntoa(sockAddrIn->sin_addr);
if( str)
{
NSString* host = [NSString stringWithUTF8String:str];
NSInteger port = ntohs(sockAddrIn->sin_port);
[addresses addObject:[NSArray arrayWithObjects: host, [NSNumber numberWithInteger:port], NULL]];
}
}
}
// And search IPv6
for (NSData* address in service.addresses)
{
struct sockaddr* sockAddr = (struct sockaddr*)address.bytes;
if (sockAddr->sa_family == AF_INET6)
{
struct sockaddr_in6* sockAddrIn6 = (struct sockaddr_in6*)sockAddr;
char buffer[INET6_ADDRSTRLEN];
if( inet_ntop(AF_INET6, &sockAddrIn6->sin6_addr, buffer, INET6_ADDRSTRLEN))
{
NSString* host = [NSString stringWithUTF8String:buffer];
NSInteger port = ntohs(sockAddrIn6->sin6_port);
[addresses addObject:[NSArray arrayWithObjects: host, [NSNumber numberWithInteger:port], NULL]];
}
}
}
DataNodeIdentifier* source = source0;
for (NSArray* address in addresses)
{
if (!source.location && address.count >= 2)
{
if ([source isKindOfClass:[RemoteDatabaseNodeIdentifier class]] || [source isKindOfClass:[DicomNodeIdentifier class]])
{
source.location = [address objectAtIndex:0];
source.port = [[address objectAtIndex:1] integerValue];
}
if( [source isKindOfClass:[DicomNodeIdentifier class]])
source.aetitle = source.description;
}
}
NSUInteger i = [_browser.sources.content indexOfObject:source];
if (i != NSNotFound) // Already known
@synchronized (_bonjourSources)
{
if( [_bonjourServices indexOfObject: service] != NSNotFound)
[_bonjourSources replaceObjectAtIndex: [_bonjourServices indexOfObject: service] withObject: (source = [_browser.sources.content objectAtIndex:i])];
else
NSLog( @"***** unknown didResolve Service");
}
if ([source isKindOfClass:[RemoteDatabaseNodeIdentifier class]])
source.dictionary = [BonjourPublisher dictionaryFromXTRecordData:service.TXTRecordData];
else
source.dictionary = [DCMNetServiceDelegate DICOMNodeInfoFromTXTRecordData:service.TXTRecordData];
if (source.location)
{
if (([source isKindOfClass:[RemoteDatabaseNodeIdentifier class]] && ![[NSUserDefaults standardUserDefaults] boolForKey:@"DoNotSearchForBonjourServices"]) ||
([source isKindOfClass:[DicomNodeIdentifier class]] && [[NSUserDefaults standardUserDefaults] boolForKey:@"searchDICOMBonjour"])) {
source.detected = YES;
if (![_browser.sources.content containsObject:source])
[_browser.sources addObject:source];
}
}
}
@catch (NSException *exception) {
N2LogException( exception);
}
}
@catch ( NSException *exception) {
N2LogException( exception);
}
@finally {
[service release];
}
}
-(void)netService:(NSNetService*)service didNotResolve:(NSDictionary*)errorDict
{
[service stop];
NSNetService* bsk = nil;
@synchronized (_bonjourSources) {
for (NSNetService* ibsk in _bonjourServices) {
if ([ibsk isEqual: service]) {
bsk = ibsk;
break;
}
}
if (!bsk)
return;
NSLog( @"Remove Service: %@", bsk);
[_bonjourSources removeObjectAtIndex: [_bonjourServices indexOfObject: bsk]];
[_bonjourServices removeObject: bsk];
}
}
-(void)netServiceBrowser:(NSNetServiceBrowser*)nsb didFindService:(NSNetService*)service moreComing:(BOOL)moreComing
{
//NSLog(@"Bonjour service found: %@", service);
DataNodeIdentifier* source;
if (nsb == _nsbOsirix)
source = [RemoteDatabaseNodeIdentifier remoteDatabaseNodeIdentifierWithLocation:nil port:0 description:service.name dictionary:nil];
else
source = [DicomNodeIdentifier dicomNodeIdentifierWithLocation:nil port:0 aetitle:@"" description:service.name dictionary:nil];
// source.discovered = YES;
// source.service = service;
@synchronized (_bonjourSources) {
[_bonjourServices addObject: service];
[_bonjourSources addObject: source];
}
NSLog( @"Find Service: %@", service);
// resolve the address and port for this NSNetService
[service setDelegate:self];
[service resolveWithTimeout:30];
}
-(void)netServiceBrowser:(NSNetServiceBrowser*)nsb didRemoveService:(NSNetService*)service moreComing:(BOOL)moreComing
{
NSLog(@"Bonjour service gone: %@", service);
DataNodeIdentifier* dni;
NSNetService *bsk = nil;
@synchronized (_bonjourSources) {
for (NSNetService* ibsk in _bonjourServices) {
if ([ibsk isEqual: service]) {
bsk = ibsk;
break;
}
}
if (!bsk)
return;
dni = [_bonjourSources objectAtIndex: [_bonjourServices indexOfObject: bsk]];
if (([dni isKindOfClass:[RemoteDatabaseNodeIdentifier class]] && ![[NSUserDefaults standardUserDefaults] boolForKey:@"DoNotSearchForBonjourServices"]) ||
([dni isKindOfClass:[DicomNodeIdentifier class]] && [[NSUserDefaults standardUserDefaults] boolForKey:@"searchDICOMBonjour"])) {
dni.detected = NO;
if (!dni.entered && [_browser.sources.content containsObject:dni])
{
[dni retain];
[_browser.sources removeObject:dni]; // not entered, not detected.. remove it
[dni performSelector: @selector( autorelease) withObject: nil afterDelay: 60];
}
}
// if the disappearing node is active, select the default DB
if ([[_browser sourceIdentifierForDatabase:_browser.database] isEqualToDataNodeIdentifier:dni])
{
[_browser performSelector: @selector(setDatabase:) withObject: DicomDatabase.defaultDatabase afterDelay: 0.01]; //This will guarantee that this will not happen in middle of a drag & drop, for example
}
NSLog( @"Remove Service: %@", bsk);
[_bonjourSources removeObjectAtIndex: [_bonjourServices indexOfObject: bsk]];
[_bonjourServices removeObject: bsk];
}
}
-(void)_analyzeVolumeAtPath:(NSString*)path
{
BOOL used = NO;
for (DataNodeIdentifier* ibs in _browser.sources.arrangedObjects)
if ([ibs isKindOfClass:[LocalDatabaseNodeIdentifier class]] && [ibs.location hasPrefix:path])
{
return; // device is somehow already listed as a source
}
NSLog( @"--- start diskutil");
NSTask* task = [[NSTask alloc] init];
[task setLaunchPath:@"/usr/sbin/diskutil"];
[task setArguments:[NSArray arrayWithObjects: @"info", @"-plist", path, NULL]];
[task setStandardError:[NSPipe pipe]];
[task setStandardOutput:[task standardError]];
[task launch];
while( [task isRunning]) [NSThread sleepForTimeInterval: 0.01];
NSLog( @"--- end diskutil");
NSData* output = [[[[[task standardError] fileHandleForReading] readDataToEndOfFile] retain] autorelease];
[task release];
NSDictionary* result = [NSPropertyListSerialization propertyListFromData:output mutabilityOption:NSPropertyListImmutable format:0 errorDescription:NULL];
if ([[result objectForKey:@"OpticalMediaType"] length]) // is CD/DVD or other optical media
@try {
[_browser.sources addObject:[MountedDatabaseNodeIdentifier mountedDatabaseNodeIdentifierWithPath:path description:path.lastPathComponent dictionary:nil type:MountTypeGeneric]];
} @catch (NSException* e) {
N2LogExceptionWithStackTrace(e);
}
else if ([[result objectForKey:@"MediaType"] isEqualToString:@"iPod"])
@try {
[_browser.sources addObject:[MountedDatabaseNodeIdentifier mountedDatabaseNodeIdentifierWithPath:path description:path.lastPathComponent dictionary:nil type:MountTypeIPod]];
} @catch (NSException* e) {
N2LogExceptionWithStackTrace(e);
}
else // Is there a DICOMDIR at root?
{
if( [[NSFileManager defaultManager] fileExistsAtPath: [path stringByAppendingPathComponent: @"DICOMDIR"]])
{
@try {
[_browser.sources addObject:[MountedDatabaseNodeIdentifier mountedDatabaseNodeIdentifierWithPath:path description:path.lastPathComponent dictionary:nil type:MountTypeGeneric]];
} @catch (NSException* e) {
N2LogExceptionWithStackTrace(e);
}
}
else if( [[NSFileManager defaultManager] fileExistsAtPath: [path stringByAppendingPathComponent: OsirixDataDirName]])
{
@try {
[_browser.sources addObject:[MountedDatabaseNodeIdentifier mountedDatabaseNodeIdentifierWithPath:path description:path.lastPathComponent dictionary:nil type:MountTypeGeneric]];
} @catch (NSException* e) {
N2LogExceptionWithStackTrace(e);
}
}
}
/* OSStatus err;
kern_return_t kr;
FSRef ref;
err = FSPathMakeRef((const UInt8*)[path fileSystemRepresentation], &ref, nil);
if (err != noErr) return;
FSCatalogInfo catInfo;
err = FSGetCatalogInfo(&ref, kFSCatInfoVolume, &catInfo, nil, nil, nil);
if (err != noErr) return;
GetVolParmsInfoBuffer gvpib;
HParamBlockRec hpbr;
hpbr.ioParam.ioNamePtr = NULL;
hpbr.ioParam.ioVRefNum = catInfo.volume;
hpbr.ioParam.ioBuffer = (Ptr)&gvpib;
hpbr.ioParam.ioReqCount = sizeof(gvpib);
err = PBHGetVolParmsSync(&hpbr);
if (err != noErr) return;
NSString* bsdName = [NSString stringWithCString:(char*)gvpib.vMDeviceID];
NSLog(@"we are mounting %@ ||| %@", path, bsdName);
CFDictionaryRef matchingDict = IOBSDNameMatching(kIOMasterPortDefault, 0, (const char*)gvpib.vMDeviceID);
io_iterator_t ioIterator = nil;
kr = IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDict, &ioIterator);
if (kr != kIOReturnSuccess) return;
io_service_t ioService;
while (ioService = IOIteratorNext(ioIterator)) {
CFTypeRef data = IORegistryEntrySearchCFProperty(ioService, kIOServicePlane, CFSTR("BSD Name"), kCFAllocatorDefault, kIORegistryIterateRecursively);
NSLog(@"\t%@", data);
io_name_t ioName;
IORegistryEntryGetName(ioService, ioName);
NSLog(@"\t\t%s", ioName);
CFRelease(data);
IOObjectRelease(ioService);