-
Notifications
You must be signed in to change notification settings - Fork 3
/
listing17.html
executable file
·1421 lines (1235 loc) · 51.5 KB
/
listing17.html
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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<!-- BEGIN META TAG INFO -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<link rel="home" href="http://developer.apple.com/">
<link rel="find" href="http://developer.apple.com/search/">
<link rel="stylesheet" type="text/css" href="../../documentation/css/adcstyle.css" title="fonts">
<script language="JavaScript" src="../../documentation/js/adc.js" type="text/javascript"></script>
<!-- END META TAG INFO -->
<!-- BEGIN TITLE -->
<title>SourceView - /MyWindowController.m</title>
<!-- END TITLE -->
<script language="JavaScript">
function JumpToNewPage() {
window.location=document.scpopupmenu.gotop.value;
return true;
}
</script>
</head>
<!-- BEGIN BODY OPEN -->
<body>
<!--END BODY OPEN -->
<!-- START CENTER OPEN -->
<center>
<!-- END CENTER OPEN -->
<!-- BEGIN LOGO AND SEARCH -->
<!--#include virtual="/includes/adcnavbar"-->
<!-- END LOGO AND SEARCH -->
<!-- START BREADCRUMB -->
<div id="breadcrumb">
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr>
<td scope="row"><img width="340" height="10" src="images/1dot.gif" alt=""></td>
<td><img width="340" height="10" src="images/1dot.gif" alt=""></td>
</tr>
<tr valign="middle">
<td align="left" colspan="2">
<a href="http://developer.apple.com/">ADC Home</a> > <a href="../../referencelibrary/index.html">Reference Library</a> > <a href="../../samplecode/index.html">Sample Code</a> > <a href="../../samplecode/Cocoa/index.html">Cocoa</a> > <a href="../../samplecode/Cocoa/idxUserExperience-date.html">User Experience</a> > <A HREF="javascript:location.replace('index.html');">SourceView</A> >
</td>
</tr>
<tr>
<td colspan="2" scope="row"><img width="680" height="35" src="images/1dot.gif" alt=""></td>
</tr>
</table>
</div>
<!-- END BREADCRUMB -->
<!-- START MAIN CONTENT -->
<!-- START TITLE GRAPHIC AND INTRO-->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td><h1><div id="pagehead">SourceView</div></h1></td>
</tr>
</table>
<!-- END TITLE GRAPHIC AND INTRO -->
<!-- START WIDE COLUMN -->
<table width="680" border="0" cellpadding="0" cellspacing="0">
<tr align="left" valign="top">
<td id="scdetails">
<h2>/MyWindowController.m</h2>
<form name="scpopupmenu" onSubmit="return false;" method=post>
<p><strong>View Source Code:</strong>
<select name="gotop" onChange="JumpToNewPage();" style="width:340px"><option selected value="ingnore">Select File</option>
<option value="listing1.html">/AppDelegate.h</option>
<option value="listing2.html">/AppDelegate.m</option>
<option value="listing3.html">/BaseNode.h</option>
<option value="listing4.html">/BaseNode.m</option>
<option value="listing5.html">/ChildEditController.h</option>
<option value="listing6.html">/ChildEditController.m</option>
<option value="listing7.html">/ChildNode.h</option>
<option value="listing8.html">/ChildNode.m</option>
<option value="listing9.html">/FileViewController.h</option>
<option value="listing10.html">/FileViewController.m</option>
<option value="listing11.html">/IconViewController.h</option>
<option value="listing12.html">/IconViewController.m</option>
<option value="listing13.html">/ImageAndTextCell.h</option>
<option value="listing14.html">/ImageAndTextCell.m</option>
<option value="listing15.html">/main.m</option>
<option value="listing16.html">/MyWindowController.h</option>
<option value="listing17.html">/MyWindowController.m</option>
<option value="listing18.html">/NSArray_Extensions.h</option>
<option value="listing19.html">/NSArray_Extensions.m</option>
<option value="listing20.html">/SeparatorCell.h</option>
<option value="listing21.html">/SeparatorCell.m</option></select>
</p>
</form>
<p><strong><a href="SourceView.zip">Download Sample</a></strong> (“SourceView.zip”, 265.6K)<BR>
<strong><a href="SourceView.dmg">Download Sample</a></strong> (“SourceView.dmg”, 317.8K)</p>
<!--
<p><strong><a href="#">Download Sample</a></strong> (“filename.sit”, 500K)</p>
-->
</td>
</tr>
<tr>
<td scope="row"><img width="680" height="10" src="images/1dot.gif" alt=""><br>
<img height="1" width="680" src="images/1dot_919699.gif" alt=""><br>
<img width="680" height="20" src="images/1dot.gif" alt=""></td>
</tr>
<tr>
<td scope="row">
<!--googleon: index -->
<pre class="sourcecodebox">//
// File: MyWindowController.m
//
// Abstract: Source for MyWindowController class.
//
// Version: 1.0
//
// Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple")
// in consideration of your agreement to the following terms, and your use,
// installation, modification or redistribution of this Apple software
// constitutes acceptance of these terms. If you do not agree with these
// terms, please do not use, install, modify or redistribute this Apple
// software.
//
// In consideration of your agreement to abide by the following terms, and
// subject to these terms, Apple grants you a personal, non - exclusive
// license, under Apple's copyrights in this original Apple software ( the
// "Apple Software" ), to use, reproduce, modify and redistribute the Apple
// Software, with or without modifications, in source and / or binary forms;
// provided that if you redistribute the Apple Software in its entirety and
// without modifications, you must retain this notice and the following text
// and disclaimers in all such redistributions of the Apple Software. Neither
// the name, trademarks, service marks or logos of Apple Inc. may be used to
// endorse or promote products derived from the Apple Software without specific
// prior written permission from Apple. Except as expressly stated in this
// notice, no other rights or licenses, express or implied, are granted by
// Apple herein, including but not limited to any patent rights that may be
// infringed by your derivative works or by other works in which the Apple
// Software may be incorporated.
//
// The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO
// WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
// WARRANTIES OF NON - INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION
// ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
//
// IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
// CONSEQUENTIAL DAMAGES ( INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION ) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION
// AND / OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER
// UNDER THEORY OF CONTRACT, TORT ( INCLUDING NEGLIGENCE ), STRICT LIABILITY OR
// OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (C) 2007 Apple Inc. All Rights Reserved.
//
#import "MyWindowController.h"
#import "IconViewController.h"
#import "FileViewController.h"
#import "ChildEditController.h"
#import "ChildNode.h"
#import "ImageAndTextCell.h"
#import "SeparatorCell.h"
#define COLUMNID_NAME @"NameColumn" // the single column name in our outline view
#define INITIAL_INFODICT @"Outline" // name of the dictionary file to populate our outline view
#define ICONVIEW_NIB_NAME @"IconView" // nib name for the icon view
#define FILEVIEW_NIB_NAME @"FileView" // nib name for the file view
#define CHILDEDIT_NAME @"ChildEdit" // nib name for the child edit window controller
#define UNTITLED_NAME @"Untitled" // default name for added folders and leafs
#define HTTP_PREFIX @"http://"
// default folder titles
#define DEVICES_NAME @"DEVICES"
#define PLACES_NAME @"PLACES"
// keys in our disk-based dictionary representing our outline view's data
#define KEY_NAME @"name"
#define KEY_URL @"url"
#define KEY_SEPARATOR @"separator"
#define KEY_GROUP @"group"
#define KEY_FOLDER @"folder"
#define KEY_ENTRIES @"entries"
#define kMinOutlineViewSplit 120.0f
#define kNodesPBoardType @"myNodesPBoardType" // drag and drop pasteboard type
// -------------------------------------------------------------------------------
// TreeAdditionObj
//
// This object is used for passing data between the main and secondary thread
// which populates the outline view.
// -------------------------------------------------------------------------------
@interface TreeAdditionObj : NSObject
{
NSIndexPath *indexPath;
NSString *nodeURL;
NSString *nodeName;
BOOL selectItsParent;
}
@property (readonly) NSIndexPath *indexPath;
@property (readonly) NSString *nodeURL;
@property (readonly) NSString *nodeName;
@property (readonly) BOOL selectItsParent;
@end
@implementation TreeAdditionObj
@synthesize indexPath, nodeURL, nodeName, selectItsParent;
// -------------------------------------------------------------------------------
- (id)initWithURL:(NSString *)url withName:(NSString *)name selectItsParent:(BOOL)select
{
self = [super init];
nodeName = name;
nodeURL = url;
selectItsParent = select;
return self;
}
@end
@implementation MyWindowController
@synthesize dragNodesArray;
// -------------------------------------------------------------------------------
// initWithWindow:window:
// -------------------------------------------------------------------------------
-(id)initWithWindow:(NSWindow *)window
{
self = [super initWithWindow:window];
if (self)
{
contents = [[NSMutableArray alloc] init];
// cache the reused icon images
folderImage = [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kGenericFolderIcon)] retain];
[folderImage setSize:NSMakeSize(16,16)];
urlImage = [[[NSWorkspace sharedWorkspace] iconForFileType:NSFileTypeForHFSTypeCode(kGenericURLIcon)] retain];
[urlImage setSize:NSMakeSize(16,16)];
}
return self;
}
// -------------------------------------------------------------------------------
// dealloc:
// -------------------------------------------------------------------------------
- (void)dealloc
{
[folderImage release];
[urlImage release];
[iconViewController release];
[contents release];
[separatorCell release];
self.dragNodesArray = nil;
[super dealloc];
}
// -------------------------------------------------------------------------------
// awakeFromNib:
// -------------------------------------------------------------------------------
- (void)awakeFromNib
{
// load the icon view controller for later use
iconViewController = [[IconViewController alloc] initWithNibName:ICONVIEW_NIB_NAME bundle:nil];
// load the file view controller for later use
fileViewController = [[FileViewController alloc] initWithNibName:FILEVIEW_NIB_NAME bundle:nil];
// load the child edit view controller for later use
childEditController = [[ChildEditController alloc] initWithWindowNibName:CHILDEDIT_NAME];
[[self window] setAutorecalculatesContentBorderThickness:YES forEdge:NSMinYEdge];
[[self window] setContentBorderThickness:30 forEdge:NSMinYEdge];
// apply our custom ImageAndTextCell for rendering the first column's cells
NSTableColumn *tableColumn = [myOutlineView tableColumnWithIdentifier:COLUMNID_NAME];
ImageAndTextCell *imageAndTextCell = [[[ImageAndTextCell alloc] init] autorelease];
[imageAndTextCell setEditable:YES];
[tableColumn setDataCell:imageAndTextCell];
separatorCell = [[SeparatorCell alloc] init];
[separatorCell setEditable:NO];
// build our default tree on a separate thread,
// some portions are from disk which could get expensive depending on the size of the dictionary file:
[NSThread detachNewThreadSelector: @selector(populateOutlineContents:)
toTarget:self // we are the target
withObject:nil];
// add images to our add/remove buttons
NSImage *addImage = [NSImage imageNamed:NSImageNameAddTemplate];
[addFolderButton setImage:addImage];
NSImage *removeImage = [NSImage imageNamed:NSImageNameRemoveTemplate];
[removeButton setImage:removeImage];
// insert an empty menu item at the beginning of the drown down button's menu and add its image
NSImage *actionImage = [NSImage imageNamed:NSImageNameActionTemplate];
[actionImage setSize:NSMakeSize(10,10)];
NSMenuItem *menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
[[actionButton menu] insertItem:menuItem atIndex:0];
[menuItem setImage:actionImage];
[menuItem release];
// truncate to the middle if the url is too long to fit
[[urlField cell] setLineBreakMode:NSLineBreakByTruncatingMiddle];
// scroll to the top in case the outline contents is very long
[[[myOutlineView enclosingScrollView] verticalScroller] setFloatValue:0.0];
[[[myOutlineView enclosingScrollView] contentView] scrollToPoint:NSMakePoint(0,0)];
// make our outline view appear with gradient selection, and behave like the Finder, iTunes, etc.
[myOutlineView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleSourceList];
// drag and drop support
[myOutlineView registerForDraggedTypes:[NSArray arrayWithObjects:
kNodesPBoardType, // our internal drag type
NSURLPboardType, // single url from pasteboard
NSFilenamesPboardType, // from Safari or Finder
NSFilesPromisePboardType, // from Safari or Finder (multiple URLs)
nil]];
[webView setUIDelegate:self]; // be the webView's delegate to capture NSResponder calls
}
// -------------------------------------------------------------------------------
// setContents:newContents
// -------------------------------------------------------------------------------
- (void)setContents:(NSArray*)newContents
{
if (contents != newContents)
{
[contents release];
contents = [[NSMutableArray alloc] initWithArray:newContents];
}
}
// -------------------------------------------------------------------------------
// contents:
// -------------------------------------------------------------------------------
- (NSMutableArray *)contents
{
return contents;
}
// -------------------------------------------------------------------------------
// selectParentFromSelection:
//
// Take the currently selected node and select its parent.
// -------------------------------------------------------------------------------
- (void)selectParentFromSelection
{
if ([[treeController selectedNodes] count] > 0)
{
NSTreeNode* firstSelectedNode = [[treeController selectedNodes] objectAtIndex:0];
NSTreeNode* parentNode = [firstSelectedNode parentNode];
if (parentNode)
{
// select the parent
NSIndexPath* parentIndex = [parentNode indexPath];
[treeController setSelectionIndexPath:parentIndex];
}
else
{
// no parent exists (we are at the top of tree), so make no selection in our outline
NSArray* selectionIndexPaths = [treeController selectionIndexPaths];
[treeController removeSelectionIndexPaths:selectionIndexPaths];
}
}
}
// -------------------------------------------------------------------------------
// performAddFolder:treeAddition
// -------------------------------------------------------------------------------
-(void)performAddFolder:(TreeAdditionObj *)treeAddition
{
// NSTreeController inserts objects using NSIndexPath, so we need to calculate this
NSIndexPath *indexPath = nil;
// if there is no selection, we will add a new group to the end of the contents array
if ([[treeController selectedObjects] count] == 0)
{
// there's no selection so add the folder to the top-level and at the end
indexPath = [NSIndexPath indexPathWithIndex:[contents count]];
}
else
{
// get the index of the currently selected node, then add the number its children to the path -
// this will give us an index which will allow us to add a node to the end of the currently selected node's children array.
//
indexPath = [treeController selectionIndexPath];
if ([[[treeController selectedObjects] objectAtIndex:0] isLeaf])
{
// user is trying to add a folder on a selected child,
// so deselect child and select its parent for addition
[self selectParentFromSelection];
}
else
{
indexPath = [indexPath indexPathByAddingIndex:[[[[treeController selectedObjects] objectAtIndex:0] children] count]];
}
}
ChildNode *node = [[ChildNode alloc] init];
[node setNodeTitle:[treeAddition nodeName]];
// the user is adding a child node, tell the controller directly
[treeController insertObject:node atArrangedObjectIndexPath:indexPath];
[node release];
}
// -------------------------------------------------------------------------------
// addFolder:folderName:
// -------------------------------------------------------------------------------
- (void)addFolder:(NSString *)folderName
{
TreeAdditionObj *treeObjInfo = [[TreeAdditionObj alloc] initWithURL:nil withName:folderName selectItsParent:NO];
if (buildingOutlineView)
{
// add the folder to the tree controller, but on the main thread to avoid lock ups
[self performSelectorOnMainThread:@selector(performAddFolder:) withObject:treeObjInfo waitUntilDone:YES];
}
else
{
[self performAddFolder:treeObjInfo];
}
[treeObjInfo release];
}
// -------------------------------------------------------------------------------
// addFolderAction:sender:
// -------------------------------------------------------------------------------
- (IBAction)addFolderAction:(id)sender
{
[self addFolder:UNTITLED_NAME];
}
// -------------------------------------------------------------------------------
// performAddChild:treeAddition
// -------------------------------------------------------------------------------
-(void)performAddChild:(TreeAdditionObj *)treeAddition
{
if ([[treeController selectedObjects] count] > 0)
{
// we have a selection
if ([[[treeController selectedObjects] objectAtIndex:0] isLeaf])
{
// trying to add a child to a selected leaf node, so select its parent for add
[self selectParentFromSelection];
}
}
// find the selection to insert our node
NSIndexPath *indexPath;
if ([[treeController selectedObjects] count] > 0)
{
// we have a selection, insert at the end of the selection
indexPath = [treeController selectionIndexPath];
indexPath = [indexPath indexPathByAddingIndex:[[[[treeController selectedObjects] objectAtIndex:0] children] count]];
}
else
{
// no selection, just add the child to the end of the tree
indexPath = [NSIndexPath indexPathWithIndex:[contents count]];
}
// create a leaf node
ChildNode *node = [[ChildNode alloc] initLeaf];
[node setURL:[treeAddition nodeURL]];
if ([treeAddition nodeURL])
{
if ([[treeAddition nodeURL] length] > 0)
{
// the child to insert has a valid URL, use its display name as the node title
if ([treeAddition nodeName])
[node setNodeTitle:[treeAddition nodeName]];
else
[node setNodeTitle:[[NSFileManager defaultManager] displayNameAtPath:[node urlString]]];
}
else
{
// the child to insert will be an empty URL
[node setNodeTitle:UNTITLED_NAME];
[node setURL:HTTP_PREFIX];
}
}
// the user is adding a child node, tell the controller directly
[treeController insertObject:node atArrangedObjectIndexPath:indexPath];
[node release];
// adding a child automatically becomes selected by NSOutlineView, so keep its parent selected
if ([treeAddition selectItsParent])
[self selectParentFromSelection];
}
// -------------------------------------------------------------------------------
// addChild:url:withName:
// -------------------------------------------------------------------------------
- (void)addChild:(NSString *)url withName:(NSString *)nameStr selectParent:(BOOL)select
{
TreeAdditionObj *treeObjInfo = [[TreeAdditionObj alloc] initWithURL:url withName:nameStr selectItsParent:select];
if (buildingOutlineView)
{
// add the child node to the tree controller, but on the main thread to avoid lock ups
[self performSelectorOnMainThread:@selector(performAddChild:) withObject:treeObjInfo waitUntilDone:YES];
}
else
{
[self performAddChild:treeObjInfo];
}
[treeObjInfo release];
}
// -------------------------------------------------------------------------------
// addBookmarkAction:sender:
// -------------------------------------------------------------------------------
- (IBAction)addBookmarkAction:(id)sender
{
// ask our edit sheet for information on the new child to be added
NSMutableDictionary *newValues = [childEditController edit:nil from:self];
if (![childEditController wasCancelled] && newValues)
{
[self addChild:[newValues objectForKey:@"url"]
withName:([[newValues objectForKey:@"name"] length] > 0) ? [newValues objectForKey:@"name"] : UNTITLED_NAME
selectParent:NO]; // add empty untitled child
}
}
// -------------------------------------------------------------------------------
// editChildAction:sender:
// -------------------------------------------------------------------------------
- (IBAction)editBookmarkAction:(id)sender
{
NSIndexPath *indexPath = [treeController selectionIndexPath];
// get the selected item's name and url
NSInteger selectedRow = [myOutlineView selectedRow];
BaseNode* node = [[myOutlineView itemAtRow:selectedRow] representedObject];
NSDictionary* editInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[node nodeTitle], @"name",
[node urlString], @"url",
nil];
// only open the edit alert sheet for URL leafs (not folders or file system objects)
//
if (([[node urlString] length] == 0) || (![[node urlString] hasPrefix:@"http://"]))
{
// it's a folder or a file-system based object, just allow editing the cell title
[myOutlineView editColumn:0 row:selectedRow withEvent:[NSApp currentEvent] select:YES];
}
else
{
// ask our sheet to edit these two values
NSMutableDictionary *newValues = [childEditController edit:editInfo from:self];
if (![childEditController wasCancelled] && newValues)
{
// create a child node
ChildNode *node = [[ChildNode alloc] initLeaf];
[node setURL:[newValues objectForKey:@"url"]];
[node setNodeTitle:([[newValues objectForKey:@"name"] length] > 0) ? [newValues objectForKey:@"name"] : UNTITLED_NAME];
// remove the current selection and replace it with the newly edited child
[treeController remove:self];
[treeController insertObject:node atArrangedObjectIndexPath:indexPath];
}
}
}
// -------------------------------------------------------------------------------
// addEntries:
// -------------------------------------------------------------------------------
-(void)addEntries:(NSDictionary *)entries
{
NSEnumerator *entryEnum = [entries objectEnumerator];
id entry;
while ((entry = [entryEnum nextObject]))
{
if ([entry isKindOfClass:[NSDictionary class]])
{
NSString *urlStr = [entry objectForKey:KEY_URL];
if ([entry objectForKey:KEY_SEPARATOR])
{
// its a separator mark, we treat is as a leaf
[self addChild:nil withName:nil selectParent:YES];
}
else if ([entry objectForKey:KEY_FOLDER])
{
// its a file system based folder,
// we treat is as a leaf and show its contents in the NSCollectionView
NSString *folderName = [entry objectForKey:KEY_FOLDER];
[self addChild:urlStr withName:folderName selectParent:YES];
}
else if ([entry objectForKey:KEY_URL])
{
// its a leaf item with a URL
NSString *nameStr = [entry objectForKey:KEY_NAME];
[self addChild:urlStr withName:nameStr selectParent:YES];
}
else
{
// it's a generic container
NSString *folderName = [entry objectForKey:KEY_GROUP];
[self addFolder:folderName];
// add its children
NSDictionary *entries = [entry objectForKey:KEY_ENTRIES];
[self addEntries:entries];
[self selectParentFromSelection];
}
}
}
// inserting children automatically expands its parent, we want to close it
if ([[treeController selectedNodes] count] > 0)
{
NSTreeNode *lastSelectedNode = [[treeController selectedNodes] objectAtIndex:0];
[myOutlineView collapseItem:lastSelectedNode];
}
}
// -------------------------------------------------------------------------------
// populateOutline:
//
// Populate the tree controller from disk-based dictionary (Outline.dict)
// -------------------------------------------------------------------------------
- (void)populateOutline
{
NSDictionary *initData = [NSDictionary dictionaryWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:INITIAL_INFODICT ofType:@"dict"]];
NSDictionary *entries = [initData objectForKey:KEY_ENTRIES];
[self addEntries:entries];
}
// -------------------------------------------------------------------------------
// addDevicesSection:
// -------------------------------------------------------------------------------
- (void)addDevicesSection
{
// insert the "Devices" group at the top of our tree
[self addFolder:DEVICES_NAME];
// automatically add mounted and removable volumes to the "Devices" group
NSArray *mountedVols = [[NSWorkspace sharedWorkspace] mountedLocalVolumePaths];
if ([mountedVols count] > 0)
{
for (NSString *element in mountedVols)
[self addChild:element withName:nil selectParent:YES];
}
[self selectParentFromSelection];
}
// -------------------------------------------------------------------------------
// addPlacesSection:
// -------------------------------------------------------------------------------
- (void)addPlacesSection
{
// add the "Places" section
[self addFolder:PLACES_NAME];
// add its children
[self addChild:NSHomeDirectory() withName:nil selectParent:YES];
[self addChild:[NSHomeDirectory() stringByAppendingPathComponent:@"Pictures"] withName:nil selectParent:YES];
[self addChild:[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] withName:nil selectParent:YES];
[self addChild:@"/Applications" withName:nil selectParent:YES];
[self selectParentFromSelection];
}
// -------------------------------------------------------------------------------
// populateOutlineContents:inObject
//
// This method is being called on a separate thread to avoid blocking the UI
// a startup time.
// -------------------------------------------------------------------------------
- (void)populateOutlineContents:(id)inObject
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
buildingOutlineView = YES; // indicate to ourselves we are building the default tree at startup
[myOutlineView setHidden:YES]; // hide the outline view - don't show it as we are building the contents
[self addDevicesSection]; // add the "Devices" outline section
[self addPlacesSection]; // add the "Places" outline section
[self populateOutline]; // add the disk-based outline content
buildingOutlineView = NO; // we're done building our default tree
// remove the current selection
NSArray *selection = [treeController selectionIndexPaths];
[treeController removeSelectionIndexPaths:selection];
[myOutlineView setHidden:NO]; // we are done populating the outline view content, show it again
[pool release];
}
#pragma mark - WebView delegate
// -------------------------------------------------------------------------------
// webView:makeFirstResponder
//
// We want to keep the outline view in focus as the user clicks various URLs.
//
// So this workaround applies to an unwanted side affect to some web pages that might have
// JavaScript code thatt focus their text fields as we target the web view with a particular URL.
//
// -------------------------------------------------------------------------------
- (void)webView:(WebView *)sender makeFirstResponder:(NSResponder *)responder
{
if (retargetWebView)
{
// we are targeting the webview ourselves as a result of the user clicking
// a url in our outlineview: don't do anything, but reset our target check flag
//
retargetWebView = NO;
}
else
{
// continue the responder chain
[[self window] makeFirstResponder:sender];
}
}
// -------------------------------------------------------------------------------
// isSpecialGroup:
// -------------------------------------------------------------------------------
- (BOOL)isSpecialGroup:(BaseNode *)groupNode
{
return ([groupNode nodeIcon] == nil &&
[[groupNode nodeTitle] isEqualToString:DEVICES_NAME] || [[groupNode nodeTitle] isEqualToString:PLACES_NAME]);
}
#pragma mark - NSOutlineView delegate
// -------------------------------------------------------------------------------
// shouldSelectItem:item
// -------------------------------------------------------------------------------
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldSelectItem:(id)item;
{
// don't allow special group nodes (Devices and Places) to be selected
BaseNode* node = [item representedObject];
return (![self isSpecialGroup:node]);
}
// -------------------------------------------------------------------------------
// dataCellForTableColumn:tableColumn:row
// -------------------------------------------------------------------------------
- (NSCell *)outlineView:(NSOutlineView *)outlineView dataCellForTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
NSCell* returnCell = [tableColumn dataCell];
if ([[tableColumn identifier] isEqualToString:COLUMNID_NAME])
{
// we are being asked for the cell for the single and only column
BaseNode* node = [item representedObject];
if ([node nodeIcon] == nil && [[node nodeTitle] length] == 0)
returnCell = separatorCell;
}
return returnCell;
}
// -------------------------------------------------------------------------------
// textShouldEndEditing:
// -------------------------------------------------------------------------------
- (BOOL)control:(NSControl *)control textShouldEndEditing:(NSText *)fieldEditor
{
if ([[fieldEditor string] length] == 0)
{
// don't allow empty node names
return NO;
}
else
{
return YES;
}
}
// -------------------------------------------------------------------------------
// shouldEditTableColumn:tableColumn:item
//
// Decide to allow the edit of the given outline view "item".
// -------------------------------------------------------------------------------
- (BOOL)outlineView:(NSOutlineView *)outlineView shouldEditTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
BOOL result = YES;
item = [item representedObject];
if ([self isSpecialGroup:item])
{
result = NO; // don't allow special group nodes to be renamed
}
else
{
if ([[item urlString] isAbsolutePath])
result = NO; // don't allow file system objects to be renamed
}
return result;
}
// -------------------------------------------------------------------------------
// outlineView:willDisplayCell
// -------------------------------------------------------------------------------
- (void)outlineView:(NSOutlineView *)olv willDisplayCell:(NSCell*)cell forTableColumn:(NSTableColumn *)tableColumn item:(id)item
{
if ([[tableColumn identifier] isEqualToString:COLUMNID_NAME])
{
// we are displaying the single and only column
if ([cell isKindOfClass:[ImageAndTextCell class]])
{
item = [item representedObject];
if (item)
{
if ([item isLeaf])
{
// does it have a URL string?
NSString *urlStr = [item urlString];
if (urlStr)
{
if ([item isLeaf])
{
NSImage *iconImage;
if ([[item urlString] hasPrefix:HTTP_PREFIX])
iconImage = urlImage;
else
iconImage = [[NSWorkspace sharedWorkspace] iconForFile:urlStr];
[item setNodeIcon:iconImage];
}
else
{
NSImage* iconImage = [[NSWorkspace sharedWorkspace] iconForFile:urlStr];
[item setNodeIcon:iconImage];
}
}
else
{
// it's a separator, don't bother with the icon
}
}
else
{
// check if it's a special folder (DEVICES or PLACES), we don't want it to have an icon
if ([self isSpecialGroup:item])
{
[item setNodeIcon:nil];
}
else
{
// it's a folder, use the folderImage as its icon
[item setNodeIcon:folderImage];
}
}
}
// set the cell's image
[(ImageAndTextCell*)cell setImage:[item nodeIcon]];
}
}
}
// -------------------------------------------------------------------------------
// removeSubview:
// -------------------------------------------------------------------------------
- (void)removeSubview
{
// empty selection
NSArray *subViews = [placeHolderView subviews];
if ([subViews count] > 0)
{
[[subViews objectAtIndex:0] removeFromSuperview];
}
[placeHolderView displayIfNeeded]; // we want the removed views to disappear right away
}
// -------------------------------------------------------------------------------
// changeItemView:
// ------------------------------------------------------------------------------
- (void)changeItemView
{
NSArray *selection = [treeController selectedObjects];
BaseNode *node = [selection objectAtIndex:0];
NSString *urlStr = [node urlString];
if (urlStr)
{
NSURL *targetURL = [NSURL fileURLWithPath:urlStr];
if ([urlStr hasPrefix:HTTP_PREFIX])
{
// the url is a web-based url
if (currentView != webView)
{
// change to web view
[self removeSubview];
currentView = nil;
[placeHolderView addSubview:webView];
currentView = webView;
}
// this will tell our WebUIDelegate not to retarget first responder since some web pages force
// forus to their text fields - we want to keep our outline view in focus.
retargetWebView = YES;
[webView setMainFrameURL:nil]; // reset the webview to an empty frame
[webView setMainFrameURL:urlStr]; // re-target to the new url
}
else
{
// the url is file-system based (folder or file)
if (currentView != [fileViewController view] || currentView != [iconViewController view])
{
// add a spinning progress gear in case populating the icon view takes too long
NSRect bounds = [placeHolderView bounds];
CGFloat x = (bounds.size.width-32)/2;
CGFloat y = (bounds.size.height-32)/2;
NSProgressIndicator* busyGear = [[NSProgressIndicator alloc] initWithFrame:NSMakeRect(x, y, 32, 32)];
[busyGear setStyle:NSProgressIndicatorSpinningStyle];
[busyGear startAnimation:self];
[placeHolderView addSubview:busyGear];
[placeHolderView displayIfNeeded]; // we want the removed views to disappear right away
// detect if the url is a directory
Boolean isDirectory;
FSRef ref;
FSPathMakeRef((const UInt8 *)[urlStr fileSystemRepresentation], &ref, &isDirectory);
if (isDirectory)
{
// avoid a flicker effect by not removing the icon view if it is already embedded
if (!(currentView == [iconViewController view]))
{
// remove the old subview
[self removeSubview];
currentView = nil;
}
// change to icon view to display folder contents
[placeHolderView addSubview:[iconViewController view]];
currentView = [iconViewController view];
// its a directory - show its contents using NSCollectionView
iconViewController.url = targetURL;
}
else
{
// its a file, just show the item info
// remove the old subview
[self removeSubview];
currentView = nil;
// change to file view
[placeHolderView addSubview:[fileViewController view]];
currentView = [fileViewController view];
// update the file's info
fileViewController.url = targetURL;
}
[busyGear removeFromSuperview];
}