-
Notifications
You must be signed in to change notification settings - Fork 94
/
CHMDocument.m
1702 lines (1452 loc) · 46.3 KB
/
CHMDocument.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
//
// CHMDocument.m
// ichm
//
// Created by Robin Lu on 7/16/08.
// Copyright __MyCompanyName__ 2008 . All rights reserved.
//
#import <WebKit/WebKit.h>
#import "CHMDocument.h"
#import <chm_lib/chm_lib.h>
#import <PSMTabBarControl/PSMTabBarControl.h>
#import "ITSSProtocol.h"
#import "CHMTableOfContent.h"
#import "CHMWebViewController.h"
#import "ICHMApplication.h"
#import "CHMTextEncodingMenu.h"
#import "BookmarkController.h"
#import "CHMWebView.h"
#import "CHMExporter.h"
#import "lcid.h"
#define PREF_FILES_INFO @"files info"
#define PREF_UPDATED_AT @"updated at"
#define PREF_LAST_PATH @"last path"
#define PREF_SEARCH_TYPE @"search type"
#define PREF_VALUE_SEARCH_IN_INDEX @"index"
#define PREF_VALUE_SEARCH_IN_FILE @"file"
static NSString* ICHMToolbarIdentifier = @"ICHM Toolbar Identifier";
static NSString* HistoryToolbarItemIdentifier = @"History Item Identifier";
static NSString* TextSizeToolbarItemIdentifier = @"Text Size Item Identifier";
static NSString* SearchToolbarItemIdentifier = @"Search Item Identifier";
static NSString* HomeToolbarItemIdentifier = @"Home Item Identifier";
static NSString* SidebarToolbarItemIdentifier = @"Sidebar Item Identifier";
static NSString* WebVewPreferenceIndentifier = @"iCHM WebView Preferences";
static NSString* SidebarWidthName = @"Sidebar Width";
static float MinSidebarWidth = 160.0;
static BOOL firstDocument = YES;
@interface CHMConsole : NSObject
{
}
- (void)log:(NSString*)string;
@end
@implementation CHMConsole
- (void)log:(NSString*)string
{
NSLog(string);
}
+ (BOOL)isSelectorExcludedFromWebScript:(SEL)selector {
if (selector == @selector(log:)) {
return NO;
}
return YES;
}
+ (NSString *) webScriptNameForSelector:(SEL)selector {
if (@selector(log:)) {
return @"log";
}
return nil;
}
@end
@interface CHMDocument (Private)
- (void)setupToolbar;
- (void)updateHistoryButton;
- (void)loadPath:(NSString *)path;
- (NSString*)extractPathFromURL:(NSURL*)url;
- (void)prepareSearchIndex;
- (void)setupTabBar;
- (void)loadJavascript;
- (void)runJavascript:(NSString*)script;
- (void)restoreSidebar;
- (void)after_zoom;
- (NSTabViewItem*)createWebViewInTab:(id)sender;
- (void)setupTOCSource;
@end
@implementation CHMDocument
@synthesize filePath;
@synthesize docTitle;
- (id)init
{
self = [super init];
if (self) {
// Add your subclass-specific initialization here.
// If an error occurs here, send a [self release] message and return nil.
chmFileHandle = nil;
filePath = nil;
docTitle = nil;
homePath = nil;
tocPath = nil;
indexPath = nil;
skIndex = nil;
searchIndexObject = nil;
isIndexDone = false;
searchIndexCondition = [[NSCondition alloc] init];
tocSource = nil;
searchSource = nil;
webViews = [[NSMutableArray alloc] init];
console = [[CHMConsole alloc] init];
curWebView = nil;
customizedEncodingTag = 0;
isSidebarRestored = NO;
}
return self;
}
- (void) dealloc
{
if( chmFileHandle ) {
chm_close( chmFileHandle );
}
[filePath release];
[docTitle release];
[homePath release];
[tocPath release];
[indexPath release];
[tocSource release];
[searchSource release];
if(!skIndex)
SKIndexClose(skIndex);
[searchIndexObject release];
[searchIndexCondition release];
[webViews release];
[super dealloc];
}
#pragma mark Basic CHM reading operations
static inline NSStringEncoding nameToEncoding(NSString* name) {
if(!name || [name length] == 0)
return NSUTF8StringEncoding;
return CFStringConvertEncodingToNSStringEncoding(
CFStringConvertIANACharSetNameToEncoding((CFStringRef) name));
}
static inline unsigned short readShort( NSData *data, unsigned int offset ) {
NSRange valueRange = { offset, 2 };
unsigned short value;
[data getBytes:(void *)&value range:valueRange];
return NSSwapLittleShortToHost( value );
}
static inline unsigned long readLong( NSData *data, unsigned int offset ) {
NSRange valueRange = { offset, 4 };
unsigned long value;
[data getBytes:(void *)&value range:valueRange];
return NSSwapLittleLongToHost( value );
}
static inline NSString * readString( NSData *data, unsigned long offset, NSString *encodingName ) {
const char *stringData = (char *)[data bytes] + offset;
return [[NSString alloc] initWithCString:stringData encoding:nameToEncoding(encodingName)];
}
static inline NSString * readTrimmedString( NSData *data, unsigned long offset, NSString *encodingName ) {
NSString *str = readString(data, offset,encodingName);
return [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
static inline NSString * LCIDtoEncodingName(unsigned int lcid) {
NSString * name= nil;
switch (lcid) {
case LCID_CS: //1250
case LCID_HR: //1250
case LCID_HU: //1250
case LCID_PL: //1250
case LCID_RO: //1250
case LCID_SK: //1250
case LCID_SL: //1250
case LCID_SQ: //1250
case LCID_SR_SP: //1250
name = @"CP1250";
break;
case LCID_AZ_CY: //1251
case LCID_BE: //1251
case LCID_BG: //1251
case LCID_MS_MY: //1251
case LCID_RU: //1251
case LCID_SB: //1251
case LCID_SR_SP2: //1251
case LCID_TT: //1251
case LCID_UK: //1251
case LCID_UZ_UZ2: //1251
case LCID_YI: //1251
name = @"CP1251";
break;
case LCID_AF: //1252
case LCID_CA: //1252
case LCID_DA: //1252
case LCID_DE_AT: //1252
case LCID_DE_CH: //1252
case LCID_DE_DE: //1252
case LCID_DE_LI: //1252
case LCID_DE_LU: //1252
case LCID_EN_AU: //1252
case LCID_EN_BZ: //1252
case LCID_EN_CA: //1252
case LCID_EN_CB: //1252
case LCID_EN_GB: //1252
case LCID_EN_IE: //1252
case LCID_EN_JM: //1252
case LCID_EN_NZ: //1252
case LCID_EN_PH: //1252
case LCID_EN_TT: //1252
case LCID_EN_US: //1252
case LCID_EN_ZA: //1252
case LCID_ES_AR: //1252
case LCID_ES_BO: //1252
case LCID_ES_CL: //1252
case LCID_ES_CO: //1252
case LCID_ES_CR: //1252
case LCID_ES_DO: //1252
case LCID_ES_EC: //1252
case LCID_ES_ES: //1252
case LCID_ES_GT: //1252
case LCID_ES_HN: //1252
case LCID_ES_MX: //1252
case LCID_ES_NI: //1252
case LCID_ES_PA: //1252
case LCID_ES_PE: //1252
case LCID_ES_PR: //1252
case LCID_ES_PY: //1252
case LCID_ES_SV: //1252
case LCID_ES_UY: //1252
case LCID_ES_VE: //1252
case LCID_EU: //1252
case LCID_FI: //1252
case LCID_FO: //1252
case LCID_FR_BE: //1252
case LCID_FR_CA: //1252
case LCID_FR_CH: //1252
case LCID_FR_FR: //1252
case LCID_FR_LU: //1252
case LCID_GD: //1252
case LCID_HI: //1252
case LCID_ID: //1252
case LCID_IS: //1252
case LCID_IT_CH: //1252
case LCID_IT_IT: //1252
case LCID_MS_BN: //1252
case LCID_NL_BE: //1252
case LCID_NL_NL: //1252
case LCID_NO_NO: //1252
case LCID_NO_NO2: //1252
case LCID_PT_BR: //1252
case LCID_PT_PT: //1252
case LCID_SV_FI: //1252
case LCID_SV_SE: //1252
case LCID_SW: //1252
name = @"CP1252";
break;
case LCID_EL: //1253
name = @"CP1253";
break;
case LCID_AZ_LA: //1254
case LCID_TR: //1254
case LCID_UZ_UZ: //1254
name = @"CP1254";
break;
case LCID_HE: //1255
name = @"CP1255";
break;
case LCID_AR_AE: //1256
case LCID_AR_BH: //1256
case LCID_AR_DZ: //1256
case LCID_AR_EG: //1256
case LCID_AR_IQ: //1256
case LCID_AR_JO: //1256
case LCID_AR_KW: //1256
case LCID_AR_LB: //1256
case LCID_AR_LY: //1256
case LCID_AR_MA: //1256
case LCID_AR_OM: //1256
case LCID_AR_QA: //1256
case LCID_AR_SA: //1256
case LCID_AR_SY: //1256
case LCID_AR_TN: //1256
case LCID_AR_YE: //1256
case LCID_FA: //1256
case LCID_UR: //1256
name = @"CP1256";
break;
case LCID_ET: //1257
case LCID_LT: //1257
case LCID_LV: //1257
name = @"CP1257";
break;
case LCID_VI: //1258
name = @"CP1258";
break;
case LCID_TH: //874
name = @"CP874";
break;
case LCID_JA: //932
name = @"CP932";
break;
case LCID_ZH_CN: //936
case LCID_ZH_SG: //936
name = @"CP936";
break;
case LCID_KO: //949
name = @"CP949";
break;
case LCID_ZH_HK: //950
case LCID_ZH_MO: //950
case LCID_ZH_TW: //950
name = @"CP950";
break;
case LCID_GD_IE: //??
case LCID_MK: //??
case LCID_RM: //??
case LCID_RO_MO: //??
case LCID_RU_MO: //??
case LCID_ST: //??
case LCID_TN: //??
case LCID_TS: //??
case LCID_XH: //??
case LCID_ZU: //??
case LCID_HY: //0
case LCID_MR: //0
case LCID_MT: //0
case LCID_SA: //0
case LCID_TA: //0
default:
break;
}
return name;
}
# pragma mark chmlib
- (BOOL) exist: (NSString *)path
{
struct chmUnitInfo info;
if (chmFileHandle)
return chm_resolve_object( chmFileHandle, [path UTF8String], &info ) == CHM_RESOLVE_SUCCESS;
return NO;
}
- (NSData *)content: (NSString *)path
{
if( !path ) {
return nil;
}
if( [path hasPrefix:@"/"] ) {
if( [path hasPrefix:@"///"] ) {
path = [path substringFromIndex:2];
}
}
else {
path = [NSString stringWithFormat:@"/%@", path];
}
struct chmUnitInfo info;
void *buffer = nil;
@synchronized(self)
{
if (chm_resolve_object( chmFileHandle, [path UTF8String], &info ) == CHM_RESOLVE_SUCCESS)
{
buffer = malloc( info.length );
if( buffer ) {
if( !chm_retrieve_object( chmFileHandle, &info, buffer, 0, info.length ) ) {
NSLog( @"Failed to load %qu bytes for %@", (long long)info.length, path );
free( buffer );
buffer = nil;
}
}
}
}
if (buffer)
return [NSData dataWithBytesNoCopy:buffer length:info.length];
return nil;
}
- (BOOL)loadMetadata {
//--- Start with WINDOWS object ---
NSData *windowsData = [self content:@"/#WINDOWS"];
NSData *stringsData = [self content:@"/#STRINGS"];
if( windowsData && stringsData ) {
const unsigned long entryCount = readLong( windowsData, 0 );
const unsigned long entrySize = readLong( windowsData, 4 );
for( int entryIndex = 0; entryIndex < entryCount; ++entryIndex ) {
unsigned long entryOffset = 8 + ( entryIndex * entrySize );
if( !docTitle || ( [docTitle length] == 0 ) ) {
docTitle = readTrimmedString( stringsData, readLong( windowsData, entryOffset + 0x14), encodingName );
NSLog(@"STRINGS title: %@", docTitle);
}
if( !tocPath || ( [tocPath length] == 0 ) ) {
tocPath = readString( stringsData, readLong( windowsData, entryOffset + 0x60 ), encodingName );
NSLog(@"STRINGS path of TOC: %@", tocPath);
}
if( !indexPath || ( [indexPath length] == 0 ) ) {
indexPath = readString( stringsData, readLong( windowsData, entryOffset + 0x64 ), encodingName );
NSLog(@"STRINGS path of index file: %@", indexPath);
}
if( !homePath || ( [homePath length] == 0 ) ) {
homePath = readString( stringsData, readLong( windowsData, entryOffset + 0x68 ), encodingName );
NSLog(@"STRINGS path of home: %@", homePath);
}
}
}
//--- Use SYSTEM object ---
NSData *systemData = [self content:@"/#SYSTEM"];
if( systemData == nil ) {
return NO;
}
unsigned int maxOffset = [systemData length];
unsigned int offset = 4;
for( ;offset<maxOffset; ) {
switch( readShort( systemData, offset ) ) {
case 0:
if( !tocPath || ( [tocPath length] == 0 ) ) {
tocPath = readString( systemData, offset + 4, encodingName );
NSLog( @"SYSTEM Table of contents: %@", tocPath );
}
break;
case 1:
if( !indexPath || ( [indexPath length] == 0 ) ) {
indexPath = readString( systemData, offset + 4, encodingName );
NSLog( @"SYSTEM Index: %@", indexPath );
}
break;
case 2:
if( !homePath || ( [homePath length] == 0 ) ) {
homePath = readString( systemData, offset + 4, encodingName );
NSLog( @"SYSTEM Home: %@", homePath );
}
break;
case 3:
if( !docTitle || ( [docTitle length] == 0 ) ) {
docTitle = readTrimmedString( systemData, offset + 4, encodingName );
NSLog( @"SYSTEM Title: %@", docTitle );
}
break;
case 4:
{
unsigned int lcid = readLong(systemData, offset + 4);
NSLog(@"SYSTEM LCID: %d", lcid);
encodingName = LCIDtoEncodingName(lcid);
NSLog(@"SYSTEM encoding: %@", encodingName);
}
break;
case 6:
{
const char *data = (const char *)([systemData bytes] + offset + 4);
NSString *prefix = [[NSString alloc] initWithCString:data encoding:nameToEncoding(encodingName)];
if( !tocPath || [tocPath length] == 0 ) {
NSString *path = [NSString stringWithFormat:@"/%@.hhc", prefix];
if ([self exist:path])
{
tocPath = path;
}
}
if ( !indexPath || [indexPath length] == 0 )
{
NSString *path = [NSString stringWithFormat:@"/%@.hhk", prefix];
if ([self exist:path])
{
indexPath = path;
}
}
NSLog( @"SYSTEM Table of contents: %@", tocPath );
[prefix release];
}
break;
case 9:
break;
case 16:
break;
default:
NSLog(@"SYSTEM unhandled value:%d", readShort( systemData, offset ));
break;
}
offset += readShort(systemData, offset+2) + 4;
}
// Check for empty string titles
if( [docTitle length] == 0 ) {
docTitle = nil;
}
else {
[docTitle retain];
}
// Check for lack of index page
if( !homePath ) {
homePath = [self findHomeForPath:@"/"];
NSLog( @"Implicit home: %@", homePath );
}
[homePath retain];
[tocPath retain];
[indexPath retain];
return YES;
}
- (NSString *)findHomeForPath: (NSString *)basePath
{
NSString *testPath;
NSString *separator = [basePath hasSuffix:@"/"]? @"" : @"/";
testPath = [NSString stringWithFormat:@"%@%@index.htm", basePath, separator];
if( [self exist:testPath] ) {
return testPath;
}
testPath = [NSString stringWithFormat:@"%@%@default.html", basePath, separator];
if( [self exist:testPath] ) {
return testPath;
}
testPath = [NSString stringWithFormat:@"%@%@default.htm", basePath, separator];
if( [self exist:testPath] ) {
return testPath;
}
return [NSString stringWithFormat:@"%@%@index.html", basePath, separator];
}
# pragma mark NSDocument
- (NSString *)windowNibName
{
// Override returning the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this method and override -makeWindowControllers instead.
return @"CHMDocument";
}
- (void)windowControllerDidLoadNib:(NSWindowController *) aController
{
[super windowControllerDidLoadNib:aController];
[self setupTabBar];
[self addNewTab:self];
[tocView setDataSource:tocSource];
[tocView setAutoresizesOutlineColumn:NO];
if([tocSource rootChildrenCount]==0)
[self hideSidebar:self];
[self setupToolbar];
[self restoreSidebar];
// go to last viewed page
NSString *lastPath = (NSString*) [self getPreferenceforFile:filePath withKey:PREF_LAST_PATH];
if (nil == lastPath)
[self goHome:self];
else
[self loadPath:lastPath];
[self prepareSearchIndex];
// set search type and search menu
NSString* type = [self getPreferenceforFile:filePath withKey:PREF_SEARCH_TYPE];
if (type != nil && [type isEqualToString:PREF_VALUE_SEARCH_IN_INDEX])
[self setSearchInIndex:[[searchItemView cell] searchMenuTemplate] ];
// invoke search if query string provided in command line
if (firstDocument)
{
NSUserDefaults *args = [NSUserDefaults standardUserDefaults];
NSString *searchTerm = [args stringForKey:@"search"];
if (searchTerm &&
[[searchTerm stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0)
{
[searchItemView setStringValue:[searchTerm stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
[self searchInFile:self];
firstDocument = NO;
}
}
}
- (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError
{
// Insert code here to write your document to data of the specified type. If the given outError != NULL, ensure that you set *outError when returning nil.
// You can also choose to override -fileWrapperOfType:error:, -writeToURL:ofType:error:, or -writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
// For applications targeted for Panther or earlier systems, you should use the deprecated API -dataRepresentationOfType:. In this case you can also choose to override -fileWrapperRepresentationOfType: or -writeToFile:ofType: instead.
if ( outError != NULL ) {
*outError = [NSError errorWithDomain:NSOSStatusErrorDomain code:unimpErr userInfo:NULL];
}
return nil;
}
- (void)setupTOCSource{
if (tocPath && [tocPath length] > 0)
{
NSData * tocData = [self content:tocPath];
CHMTableOfContent* newTOC = [[CHMTableOfContent alloc] initWithData:tocData encodingName:[self currentEncodingName]];
CHMTableOfContent* oldTOC = tocSource;
tocSource = newTOC;
if(oldTOC)
[oldTOC release];
}
if (indexPath && [indexPath length] > 0)
{
NSData * tocData = [self content:indexPath];
CHMTableOfContent* newTOC = [[CHMTableOfContent alloc] initWithData:tocData encodingName:[self currentEncodingName]];
CHMTableOfContent* oldTOC = indexSource;
indexSource = newTOC;
[indexSource sort];
if(oldTOC)
[oldTOC release];
}
}
- (BOOL)readFromFile:(NSString *)fileName ofType:(NSString *)docType {
NSLog( @"CHMDocument:readFromFile:%@", fileName );
if(filePath) [filePath release];
filePath = fileName;
[filePath retain];
chmFileHandle = chm_open( [fileName fileSystemRepresentation] );
if( !chmFileHandle ) return NO;
[self loadMetadata];
[self setupTOCSource];
return YES;
}
- (void)close
{
[self resetEncodingMenu];
[super close];
}
- (NSURL*)composeURL:(NSString *)path
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"itss://chm/%@", path]];
if (!url)
url = [NSURL URLWithString:[NSString stringWithFormat:@"itss://chm/%@", [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
return url;
}
- (NSString*)extractPathFromURL:(NSURL*)url
{
return [[[url absoluteString] substringFromIndex:11] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}
- (void)loadPath:(NSString *)path
{
NSURL *url = [self composeURL:path];
[self loadURL:url];
}
- (void)loadURL:(NSURL *)url
{
if( url ) {
NSURLRequest *req = [NSURLRequest requestWithURL:url];
[[curWebView mainFrame] loadRequest:req];
}
}
- (void)setPreference:(id)object forFile:(NSString*)filename withKey:(NSString*)key
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *filesInfoList = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:PREF_FILES_INFO]];
NSMutableDictionary *fileInfo = [NSMutableDictionary dictionaryWithDictionary:[filesInfoList objectForKey:filename]];
[fileInfo setObject:object forKey:key];
[fileInfo setObject:[NSDate date] forKey:PREF_UPDATED_AT];
[filesInfoList setObject:fileInfo forKey:filename];
if ([filesInfoList count] > 20) {
NSDictionary *oldest = nil;
NSString* oldestKey = nil;
for (NSString *key in [filesInfoList allKeys] ) {
NSDictionary *info = [filesInfoList objectForKey:key];
if (oldest == nil ||
[[oldest objectForKey:PREF_UPDATED_AT] compare: [info objectForKey:PREF_UPDATED_AT]] == NSOrderedDescending)
{
oldest = info;
oldestKey = key;
}
}
[oldestKey retain];
[filesInfoList removeObjectForKey:oldestKey];
[oldestKey release];
}
[defaults setObject:filesInfoList forKey:PREF_FILES_INFO];
}
- (id)getPreferenceforFile:(NSString*)filename withKey:(NSString*)key
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSDictionary *filesInfoList = [defaults dictionaryForKey:PREF_FILES_INFO];
if (nil == filesInfoList)
return nil;
NSDictionary *fileInfo = [filesInfoList objectForKey:filename];
if (nil == fileInfo)
return nil;
return [fileInfo objectForKey:key];
}
#pragma mark Properties
- (NSString*)currentURL
{
if(curWebView)
return [curWebView mainFrameURL];
return nil;
}
- (NSString*)currentTitle
{
if(curWebView)
return [[docTabView selectedTabViewItem] label];
return nil;
}
# pragma mark WebFrameLoadDelegate
- (void)webView:(WebView *)sender didFinishLoadForFrame:(WebFrame *)frame
{
[self updateHistoryButton];
[self locateTOC:sender];
// set label for tab bar
NSURL * url = [[[frame dataSource] request] URL];
NSString *path = [self extractPathFromURL:url];
LinkItem* item = [[tocView dataSource] itemForPath:path withStack:nil];
NSTabViewItem *tabItem = [docTabView selectedTabViewItem];
NSString *name = [item name];
if(!name || [name length] == 0)
name = [curWebView mainFrameTitle];
if(name && [name length]>0)
[tabItem setLabel:name];
else
[tabItem setLabel:NSLocalizedString(@"(Untitled)",@"(Untitled)")];
if (frame == [sender mainFrame])
{
[[curWebView windowScriptObject] setValue:console forKey:@"console"];
[self loadJavascript];
NSString *searchString = [searchItemView stringValue];
if (0 != [searchString length])
{
[self highlightString:searchString];
[self findNext:self];
}
}
// setup last path
NSString *trimedPath = [NSString stringWithString:[url path]];
while ([trimedPath hasPrefix:@"/"])
trimedPath = [trimedPath substringFromIndex:1];
[self setPreference:trimedPath forFile:filePath withKey:PREF_LAST_PATH];
}
# pragma mark Javascript
- (void)loadJavascript
{
NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"highlight" ofType:@"js"];
[self runJavascript:[NSString stringWithContentsOfFile:scriptPath]];
}
- (void)runJavascript:(NSString*)script
{
[[curWebView windowScriptObject]
evaluateWebScript:[NSString stringWithFormat:@"try{ %@; } catch(e){console.log(e.toString());}", script]];
}
# pragma mark WebPolicyDelegate
- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation
request:(NSURLRequest *)request
frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener
{
if( [ITSSProtocol canInitWithRequest:request] ) {
int navigationType = [[actionInformation objectForKey:WebActionNavigationTypeKey] intValue];
unsigned int modifier = [[actionInformation objectForKey:WebActionModifierFlagsKey] unsignedIntValue];
// link click
if (navigationType == WebNavigationTypeLinkClicked && modifier) {
[self addNewTab:self];
[[curWebView mainFrame] loadRequest:request];
[listener ignore];
return;
}
[listener use];
} else {
[[NSWorkspace sharedWorkspace] openURL:[request URL]];
[listener ignore];
}
}
- (void)webView:(WebView *)sender
decidePolicyForNewWindowAction:(NSDictionary *)actionInformation
request:(NSURLRequest *)request
newFrameName:(NSString *)frameName
decisionListener:(id<WebPolicyDecisionListener>)listener
{
if( [ITSSProtocol canInitWithRequest:request] ) {
[listener use];
} else {
[[NSWorkspace sharedWorkspace] openURL:[request URL]];
[listener ignore];
}
}
# pragma mark WebResourceLoadDelegate
-(NSURLRequest *)webView:(WebView *)sender resource:(id)identifier
willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)redirectResponse
fromDataSource:(WebDataSource *)dataSource
{
if( [ITSSProtocol canInitWithRequest:request] ) {
NSMutableURLRequest *specialURLRequest = [[request mutableCopy] autorelease];
[specialURLRequest setChmDoc:self];
[specialURLRequest setEncodingName:[self currentEncodingName ]];
return specialURLRequest;
} else {
return request;
}
}
# pragma mark WebUIDelegate
- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request
{
WebView* wv = [[[self createWebViewInTab:sender] identifier] webView];
[[wv mainFrame] loadRequest:request];
return wv;
}
- (void)webViewShow:(WebView *)sender
{
for(NSTabViewItem* item in [docTabView tabViewItems])
{
CHMWebViewController *chmwv = [item identifier];
if([chmwv webView] == sender)
{
curWebView = sender;
[docTabView selectTabViewItem:item];
}
}
}
# pragma mark actions
- (IBAction)changeTopic:(id)sender
{
int selectedRow = [tocView selectedRow];
if( selectedRow >= 0 ) {
LinkItem *topic = [tocView itemAtRow:selectedRow];
[self loadPath:[topic path]];
}
}
- (IBAction)openInNewTab:(id)sender
{
[self addNewTab:sender];
[self changeTopic:sender];
}
- (IBAction)goForward:(id)sender
{
[curWebView goForward];
}
- (IBAction)goBack:(id)sender
{
[curWebView goBack];
}
- (IBAction)goHome:(id)sender
{
[self loadPath:homePath];
}
- (IBAction)goHistory:(id)sender
{
NSSegmentedCell * segCell = sender;
switch ([segCell selectedSegment]) {
case 0:
[self goBack:sender];
break;
case 1:
[self goForward:sender];
break;
default:
break;
}
}
- (IBAction)gotoNextPage:(id)sender
{
int selectedRow = [tocView selectedRow];
LinkItem *topic = [tocView itemAtRow:selectedRow];
LinkItem* nextPage = [tocSource getNextPage:topic];
if (nextPage)
[self loadPath:[nextPage path]];
}
- (IBAction)gotoPrevPage:(id)sender
{
int selectedRow = [tocView selectedRow];
LinkItem *topic = [tocView itemAtRow:selectedRow];
LinkItem* prevPage = [tocSource getPrevPage:topic];
if (prevPage)
[self loadPath:[prevPage path]];
}
- (IBAction)locateTOC:(id)sender
{
NSURL * url = [[[[curWebView mainFrame] dataSource] request] URL];
NSString *path = [self extractPathFromURL:url];
NSMutableArray *tocStack = [[NSMutableArray alloc] init];
LinkItem* item = [[tocView dataSource] itemForPath:path withStack:tocStack];
NSEnumerator *enumerator = [tocStack reverseObjectEnumerator];
for (LinkItem *p in enumerator) {
[tocView expandItem:p];
}
NSInteger idx = [tocView rowForItem:item];
NSIndexSet *idxSet = [[NSIndexSet alloc] initWithIndex:idx];
[tocView selectRowIndexes:idxSet byExtendingSelection:NO];
[tocView scrollRowToVisible:idx];
[tocStack release];
[idxSet release];
}
- (IBAction)zoomIn:(id)sender
{
[ curWebView makeTextLarger:sender ];
[self after_zoom];
}
- (IBAction)zoom:(id)sender
{
NSSegmentedCell * segCell = sender;
switch ([segCell selectedSegment]) {
case 0:
[self zoomIn:sender];
break;
case 1:
[self zoomOut:sender];
break;
default:
break;
}
}
- (IBAction)zoomOut:(id)sender
{
[ curWebView makeTextSmaller:sender ];
[self after_zoom];
}
- (void)after_zoom
{
[textSizeItemView setEnabled:[curWebView canMakeTextLarger] forSegment:0];
[textSizeItemView setEnabled:[curWebView canMakeTextSmaller] forSegment:1];
float zoomFactor = [curWebView textSizeMultiplier];
[[NSUserDefaults standardUserDefaults] setFloat:zoomFactor forKey:@"zoom factor"];