-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathIRIndexDocument.m
1812 lines (1710 loc) · 73.8 KB
/
IRIndexDocument.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
//
// IRIndexDocument.m
// Cindex
//
// Created by PL on 11/27/04.
// Copyright Indexing Research 2004. All rights reserved.
//
#import "IRIndexDocumentController.h"
#import "IRIndexDocument.h"
#import "IRIndexArchive.h"
#import "IRIndexDocWController.h"
#import "IRIndexTextWController.h"
#import "IRIndexRecordWController.h"
#import "ExportOptionsController.h"
#import "FindController.h"
#import "ReplaceController.h"
#import "SearchController.h"
#import "formattedtext.h"
#import "drafttext.h"
#import "commandutils.h"
#import "strings_c.h"
#import "index.h"
#import "sort.h"
#import "group.h"
#import "records.h"
#import "cindexmenuitems.h"
#import "type.h"
#import "export.h"
#import "rtfwriter.h"
#import "taggedtextwriter.h"
#import "xpresswriter.h"
#import "xmlwriter.h"
#import "imwriter.h"
#import "indesign.h"
#import "textwriter.h"
#import "tags.h"
#import "swap.h"
#import "search.h"
#import "collate.h"
#import "utime.h"
#import "IRPrintAccessoryController.h"
NSString * CINIndexType = @"com.example.cindex";
NSString * CINStationeryType = @"com.example.cindex.template";
NSString * CINXMLRecordType = @"com.example.cindex.ixml";
NSString * CINArchiveType = @"com.example.cindex.archive";
NSString * CINDelimitedRecords = @"com.example.delimited";
NSString * CINPlainTextType = @"public.plain-text";
NSString * CINRTFType = @"public.rtf";
NSString * CINQuarkType = @"com.quark.xpress";
NSString * CINInDesignType = @"com.adobe.indesign";
NSString * CINIMType = @"com.index.manager";
NSString * CINXMLType = @"public.xml";
NSString * CINTaggedText = @"com.example.cindex.sgml";
NSString * CINStyleSheetType = @"com.example.cindex.stylesheet";
NSString * CINV1IndexType = @"com.example.cindex-v1";
NSString * CINV2IndexType = @"com.example.cindex-v2";
NSString * CINV2StationeryType = @"com.example.cindex-v2.template";
NSString * CINV1StationeryType = @"com.example.cindex-v1.template";
NSString * CINAbbrevType = @"com.example.cindex.abbreviations";
NSString * CINV2StyleSheetType = @"com.example.cindex.stylesheet-v2";
NSString * CINV1StyleSheetType = @"com.example.cindex.stylesheet-v1";
NSString * DOSDataType = @"com.example.cindex.dos-data";
NSString * SkyType = @"com.sky.text";
NSString * MBackupType = @"com.macrex.backup";
NSString * CINDataType = @"Delimited Data";
NSString * IRDocumentException = @"IRDocumentException";
NSString * IRRecordException = @"IRRecordException";
NSString * IRMappingException = @"IRMappingException";
NSString * CINIndexExtension = @"ucdx";
NSString * CINIndexV2Extension = @"cdxf";
NSString * CINIndexV1Extension = @"ndxf";
NSString * CINStationeryExtension = @"utpl";
NSString * CINArchiveExtension = @"xaf";
NSString * CINAbbrevExtension = @"abrf";
NSString * CINStyleSheetExtension = @"ustl";
NSString * CINV2StyleSheetExtension = @"cfr2";
NSString * CINV1StyleSheetExtension = @"cfrm";
NSString * CINTagExtension = @"cstg";
NSString * CINXMLTagExtension = @"cxtg";
NSString * CINMainDicExtension = @"dic";
NSString * CINPDicExtension = @"pdic";
NSString * NOTE_HEADERFOOTERCHANGED = @"headerFooterChanged";
NSString * NOTE_REDISPLAYDOC = @"redisplayIndex";
NSString * NOTE_REVISEDLAYOUT = @"layoutIndex";
NSString * NOTE_FONTSCHANGED = @"fontChanged";
NSString * NOTE_NEWKEYTEXT = @"functionKeyChanged";
NSString * NOTE_INDEXWILLCLOSE = @"indexWillCLose";
NSString * NOTE_CONDITIONALOPENRECORD = @"conditionalOpenRecord";
NSString * NOTE_PAGEFORMATTED = @"pageFormatted";
//NSString * NOTE_AUTOSAVE = @"autoSave";
NSString * NOTE_PREFERENCESCHANGED = @"preferencesChanged";
NSString * NOTE_GLOBALLYCHANGING = @"globallyChanging";
NSString * NOTE_STRUCTURECHANGED = @"structureChanged";
NSString * NOTE_ACTIVEINDEXCHANGED = @"indexChanged";
NSString * NOTE_SCROLLKEYEVENT = @"scrollKeyEvent";
// notification dictionary keys
NSString * TextRangeKey = @"textRange";
NSString * TextLengthChangeKey = @"textLengthChange";
NSString * RecordNumberKey = @"recordNumber";
NSString * RecordRangeKey = @"recordRange";
NSString * ViewModeKey = @"viewMode";
NSString * RecordAttributesKey = @"recordAttributes";
/********************************************/
@interface IRIndexDocument () {
// NSTimer * saveTimer;
}
@property (weak) NSTimer * saveTimer;
- (IRIndexDocument *)_buildSummary;
//- (void)_setLastSavedName:(NSString *)name;
- (BOOL)_installIndex;
- (void)_checkFixes; // does minor version fixups
- (BOOL)_savePrivateBackup; // saves private backup of active in
- (BOOL)_duplicateIndexToFile:(NSString *)file;
- (void)_prefsChanged;
- (void)setAutosave:(double)seconds;
@end
@implementation IRIndexDocument
#if 0
+ (id)newDocumentWithMessage:(NSString *)message error:(NSError **)err { // creates new index file
NSSavePanel * savepanel = [NSSavePanel savePanel];
NSString * defaultFolder = [[NSUserDefaults standardUserDefaults] stringForKey:CIOpenFolder];
if (defaultFolder)
[savepanel setDirectoryURL:[NSURL fileURLWithPath:defaultFolder isDirectory:YES]];
[savepanel setTitle:@"New Index"];
[savepanel setMessage:message];
[savepanel setNameFieldLabel:@"Create as"];
[savepanel setAllowedFileTypes:[NSArray arrayWithObject:CINIndexExtension]];
[savepanel setCanSelectHiddenExtension:YES];
if ([savepanel runModal] == NSFileHandlingPanelOKButton)
// return [[IRIndexDocument alloc] initWithName:[[savepanel URL] path] hideExtension:[savepanel isExtensionHidden] error:err];
return [[IRIndexDocument alloc] initWithName:[[savepanel URL] path] template:nil hideExtension:[savepanel isExtensionHidden] error:err];
if (err)
*err = [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]; // canceled; suppress any error
return nil;
}
#endif
+ (id)newDocumentFromURL:(NSURL *)url error:(NSError **)err { // creates new index (from template or archive as relevant)
NSSavePanel * savepanel = [NSSavePanel savePanel];
NSString * defaultFolder = [[NSUserDefaults standardUserDefaults] stringForKey:CIOpenFolder];
NSString * message;
if (url) { // if from template or archive
NSString * ext = [[url path] pathExtension];
if ([ext caseInsensitiveCompare:@"utpl"] == NSOrderedSame)
message = [NSString stringWithFormat:@"Create a new index from the template \"%@\"",[[url path] lastPathComponent]];
else {
message = [NSString stringWithFormat:@"Create a new index from the archive \"%@\"",[[url path] lastPathComponent]];
url = nil; // make sure we don't mistake archive for template
}
}
else
message = @"";
if (defaultFolder)
[savepanel setDirectoryURL:[NSURL fileURLWithPath:defaultFolder isDirectory:YES]];
[savepanel setTitle:@"New Index"];
[savepanel setMessage:message];
[savepanel setNameFieldLabel:@"Create as:"];
[savepanel setAllowedFileTypes:[NSArray arrayWithObject:CINIndexExtension]];
[savepanel setCanSelectHiddenExtension:YES];
if ([savepanel runModal] == NSFileHandlingPanelOKButton)
return [[IRIndexDocument alloc] initWithName:[[savepanel URL] path] template:url hideExtension:[savepanel isExtensionHidden] error:err];
if (err)
*err = [NSError errorWithDomain:NSCocoaErrorDomain code:NSUserCancelledError userInfo:nil]; // canceled; suppress any error
return nil;
}
- (id)init {
if (self = [super init]) {
_index.head.endian = TARGET_RT_LITTLE_ENDIAN;
_index.head.headsize = HEADSIZE; /* size of header */
_index.head.version = CINVERSION; /* version under which file created */
_index.head.indexpars = g_prefs.indexpars;
_index.head.sortpars = g_prefs.sortpars;
// _index.head.sortpars.sversion = SORTVERSION;
_index.head.refpars = g_prefs.refpars;
_index.head.privpars = g_prefs.privpars;
_index.head.formpars = g_prefs.formpars;
str_xcpy(_index.head.stylestrings,g_prefs.stylestrings); /* copy style strings */
strcpy(_index.head.flipwords,g_prefs.flipwords); // copy flip words
memcpy(_index.head.fm,g_prefs.gen.fm,sizeof(g_prefs.gen.fm)); /* copy local font set */
type_checkfonts(_index.head.fm); /* sets up font ids */
_index.lastflush = time(NULL);
_index.head.createtime = _index.head.squeezetime = _index.opentime = (time_c)_index.lastflush;
_index.owner = self;
_index.formBuffer = malloc(EBUFSIZE+2)+2; // buffer is prefixed by 2 empty chars for addressing underflow (e.g., transposepunct)
[self setHasUndoManager:NO];
// [self setPrintInfo:[NSPrintInfo sharedPrintInfo]];
// initializing export type labels
[self initializeExportTypes];
}
return self;
}
- (id)initWithName:(NSString *)name template:(NSURL *)template hideExtension:(BOOL)hide error:(NSError **)err { // creates new index with name
NSError * dError;
if ([self initWithTemplateURL:template error:err]) {
// initializing export type labels
[self initializeExportTypes];
if ([[NSData data] writeToFile:name options:NSDataWritingWithoutOverwriting error:&dError]) {
NSMutableDictionary * adic = [NSMutableDictionary dictionaryWithCapacity:3];
[adic setObject:[NSNumber numberWithBool:hide] forKey:NSFileExtensionHidden];
[adic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[adic setObject:[NSNumber numberWithUnsignedLong:CIN_NDX] forKey:NSFileHFSTypeCode];
[self setFileURL:[NSURL fileURLWithPath:name]];
[self setFileType:CINIndexType];
[[NSFileManager defaultManager] setAttributes:adic ofItemAtPath:name error:nil];
if (mfile_open(&_index.mf,(char *)[name UTF8String],O_RDWR|O_EXLOCK,HEADSIZE)) {
if ([self _installIndex]) // if can complete setup
return self;
mfile_close(&_index.mf);
}
}
[self close];
[[NSFileManager defaultManager] removeItemAtPath:name error:NULL]; // delete file
if (err)
*err = makeNSError(FILEOPENERR, [[dError localizedDescription] UTF8String]);
}
return nil; // no file
}
- (void) initializeExportTypes {
// initializing export type labels
NSArray<NSString *> * labels = @[
@"Cindex Index",
@"Cindex Template",
@"XML Records",
@"Cindex Archive",
@"Delimited Records",
@"Plain Text",
@"Rich Text Format",
@"QuarkXPress",
@"InDesign",
@"Index-Manager",
@"XML Tagged Text",
@"SGML Tagged Text",
];
NSArray<NSString *> * types = @[
CINIndexType,
CINStationeryType,
CINXMLRecordType,
CINArchiveType,
CINDelimitedRecords,
CINPlainTextType,
CINRTFType,
CINQuarkType,
CINInDesignType,
CINIMType,
CINXMLType,
CINTaggedText
];
_exportTypeLabels = [NSDictionary dictionaryWithObjects:labels forKeys:types];
}
#if 0
- (id)initWithTemplateURL:(NSURL *)url error:(NSError **)outError {
HEAD * header = (HEAD *)[[NSData dataWithContentsOfFile:[url path]] bytes];
if (header) {
swap_Header(header); // swap bytes as necessary
_index.head.indexpars = header->indexpars;
_index.head.sortpars = header->sortpars;
_index.head.refpars = header->refpars;
_index.head.privpars = header->privpars;
_index.head.formpars = header->formpars;
str_xcpy(_index.head.stylestrings,g_prefs.stylestrings); // copy style strings
strcpy(_index.head.flipwords,g_prefs.flipwords); // copy flip words
memcpy(_index.head.fm,header->fm,sizeof(header->fm)); /* copy local font set */
if ([self _installIndex])
return self;
}
if (outError)
*outError = makeNSError(FILEOPENERR, @"The template cannot be read.");
return nil;
}
#else
- (id)initWithTemplateURL:(NSURL *)url error:(NSError **)outError {
if (self = [super init]) {
if (url) { // if want from template
HEAD * header = (HEAD *)[[NSData dataWithContentsOfFile:[url path]] bytes];
if (header) {
swap_Header(header); // swap bytes as necessary
_index.head.headsize = header->headsize; /* size of header */
_index.head.version = header->version; /* version under which file created */
_index.head.indexpars = header->indexpars;
_index.head.sortpars = header->sortpars;
_index.head.refpars = header->refpars;
_index.head.privpars = header->privpars;
_index.head.formpars = header->formpars;
str_xcpy(_index.head.stylestrings,header->stylestrings); // copy styled strings
strcpy(_index.head.flipwords,header->flipwords); // copy flip words
memcpy(_index.head.fm,header->fm,sizeof(header->fm)); /* copy local font set */
}
else {
if (outError)
*outError = makeNSError(FILEOPENERR, @"The template cannot be read.");
return nil;
}
}
else { // new index with defult settings
_index.head.headsize = HEADSIZE; /* size of header */
_index.head.version = CINVERSION; /* version under which file created */
_index.head.indexpars = g_prefs.indexpars;
_index.head.sortpars = g_prefs.sortpars;
_index.head.refpars = g_prefs.refpars;
_index.head.privpars = g_prefs.privpars;
_index.head.formpars = g_prefs.formpars;
str_xcpy(_index.head.stylestrings,g_prefs.stylestrings); /* copy styled strings */
strcpy(_index.head.flipwords,g_prefs.flipwords); // copy flip words
memcpy(_index.head.fm,g_prefs.gen.fm,sizeof(g_prefs.gen.fm)); /* copy local font set */
type_checkfonts(_index.head.fm); /* set up font ids */
}
_index.head.endian = TARGET_RT_LITTLE_ENDIAN;
_index.lastflush = time(NULL);
_index.head.createtime = _index.head.squeezetime = _index.opentime = (time_c)_index.lastflush;
_index.owner = self;
_index.formBuffer = malloc(EBUFSIZE+2)+2; // buffer is prefixed by 2 empty chars for addressing underflow (e.g., transposepunct)
[self setHasUndoManager:NO];
}
return self;
}
#endif
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
free(_index.formBuffer-2); // allowing for the prefix chars
ucol_close(_index.collator.ucol);
[self closeSummary];
grp_closecurrent(&_index);
if (_index.lastfile)
grp_dispose(_index.lastfile);
self.lastSavedName = nil;
if (!(self == IRdc.IRrevertsource)) // if we're not the source of a reversion
[[NSFileManager defaultManager] removeItemAtPath:_backupPath error:NULL]; // remove any backup file
IRdc.IRrevertsource = nil;
}
- (void)makeWindowControllers {
_mainWindowController = [[IRIndexDocWController alloc] init];
[self addWindowController:(NSWindowController *)_mainWindowController];
}
- (void)removeWindowController:(NSWindowController *)controller {
if (controller == _textWindowController)
_textWindowController = nil;
if (controller == _recordWindowController) {
_recordWindowController = nil;
[_mainWindowController setDisplayForEditing:NO adding:NO];
}
[super removeWindowController:controller];
}
- (BOOL)_duplicateIndexToFile:(NSString *)file {
BOOL result = NO;
if ([self flush]) {
if (index_setworkingsize(&_index,0)) { // if can resize index
[[NSFileManager defaultManager] removeItemAtPath:file error:NULL]; // remove any existing file with name of destination
result = [[NSFileManager defaultManager] copyItemAtURL:[self fileURL] toURL:[NSURL fileURLWithPath:file] error:nil];
index_setworkingsize(&_index,MAPMARGIN);
}
}
return result;
}
- (IBAction)saveDocument:(id)sender {
// need to intercept this because in 10.5 & higher following call posts alert about file change
//- (void)saveDocumentWithDelegate:(id)delegate didSaveSelector:(SEL)didSaveSelector contextInfo:(void *)contextInfo
if (![self _savePrivateBackup]) {
senderr(FILEOPENERR,WARN,"There was an error while saving the index.");
}
}
#if 0
- (BOOL)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation error:(NSError **)outError {
NSString * file = [absoluteURL path];
if ([typeName isEqualToString:CINIndexType]) { // saving native index
if ([IRdc documentForURL:absoluteURL]) { // if trying to overwrite an open index
if (outError)
*outError = makeNSError(FILEOPENERR,"You cannot replace an index that is in use.");
return NO;
}
}
if ([typeName isEqualToString:CINTaggedText]) { // if might want to change extension on tagged text
char * extn = ts_gettagsetextension(ts_getactivetagsetpath(SGMLTAGS));
if (*extn) { // if want to supply extension for the file
file = [[file stringByDeletingPathExtension] stringByAppendingPathExtension:[NSString stringWithUTF8String:extn]];
absoluteURL = [NSURL fileURLWithPath:file];
}
}
// [self _setLastSavedName:[file lastPathComponent]]; // reset reported filename
self.lastSavedName = [file lastPathComponent];
return [super saveToURL:absoluteURL ofType:typeName forSaveOperation:saveOperation error:outError];
}
#else
- (void)saveToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName forSaveOperation:(NSSaveOperationType)saveOperation completionHandler:(void (^)(NSError *errorOrNil))completionHandler {
NSString * file = [absoluteURL path];
NSError * outError = nil;
// override typeName to our stored type
if ( _selectedTypeForSaveToOperation != nil && ![typeName isEqual:_selectedTypeForSaveToOperation] ) {
typeName = _selectedTypeForSaveToOperation;
}
if ([typeName isEqualToString:CINIndexType]) { // saving native index
if ([IRdc documentForURL:absoluteURL]) { // if trying to overwrite an open index
outError = makeNSError(FILEOPENERR,"You cannot replace an index that is in use.");
completionHandler(outError);
return;
}
}
if ([typeName isEqualToString:CINTaggedText]) { // if might want to change extension on tagged text
char * extn = ts_gettagsetextension(ts_getactivetagsetpath(SGMLTAGS));
if (*extn) { // if want to supply extension for the file
file = [[file stringByDeletingPathExtension] stringByAppendingPathExtension:[NSString stringWithUTF8String:extn]];
absoluteURL = [NSURL fileURLWithPath:file];
}
}
// [self _setLastSavedName:[file lastPathComponent]]; // reset reported filename
self.lastSavedName = [file lastPathComponent];
[super saveToURL:absoluteURL ofType:typeName forSaveOperation:saveOperation completionHandler:completionHandler];
}
#endif
- (NSDictionary *)fileAttributesToWriteToURL:(NSURL *)nURL ofType:(NSString *)type forSaveOperation:(NSSaveOperationType)op originalContentsURL:(NSURL *)oURL error:(NSError **)error {
NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:[super fileAttributesToWriteToURL:nURL ofType:type forSaveOperation:op originalContentsURL:oURL error:error]];
[dic setObject:[NSNumber numberWithBool:[self fileNameExtensionWasHiddenInLastRunSavePanel]] forKey:NSFileExtensionHidden];
if ([type isEqualToString:CINIndexType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_NDX] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINArchiveType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_MDAT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINXMLRecordType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_XMLDAT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINStationeryType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_STAT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINDelimitedRecords]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_TEXT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:DOSDataType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_REF] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_TEXT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINRTFType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:'MSWD'] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:'RTF '] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINQuarkType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:'XPR3'] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_TEXT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINPlainTextType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_WILD] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_TEXT] forKey:NSFileHFSTypeCode];
}
else if ([type isEqualToString:CINIMType]) {
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_WILD] forKey:NSFileHFSCreatorCode];
[dic setObject:[NSNumber numberWithUnsignedLong:CIN_TEXT] forKey:NSFileHFSTypeCode];
}
return dic;
}
// Method to handle extension change for the custom `accessoryView` for `Save To` NSSavePanel
- (IBAction) typeSelectorChange:(id)sender {
// only continue for `Save To` operation
if ( _saveOp != NSSaveToOperation )
return;
// get selected label
NSString * selectedOption = [(NSPopUpButton *) sender titleOfSelectedItem];
// identify tagged formats for their changed names
if ( [selectedOption containsString:[_exportTypeLabels objectForKey:CINXMLType]] || [selectedOption containsString:[_exportTypeLabels objectForKey:CINTaggedText]] ) {
selectedOption = ( [selectedOption containsString:[_exportTypeLabels objectForKey:CINXMLType]] ) ? [_exportTypeLabels objectForKey:CINXMLType] : [_exportTypeLabels objectForKey:CINTaggedText];
}
// parse the type from selected label
NSString * selectedType = [_exportTypeLabels allKeysForObject:selectedOption][0];
// Parse the extension from the selected type
NSString * selectedExtension = [self fileNameExtensionForType:selectedType saveOperation:NSSaveToOperation];
if ( selectedExtension == nil ) {
NSLog(@"Invalid extension; exiting...");
// unset stored extension
_selectedTypeForSaveToOperation = nil;
return;
}
// fetch the parent NSSavePanel
NSSavePanel * savePanel = (NSSavePanel *)[sender window];
// set the correct extension for the file type
[savePanel setAllowedFileTypes:@[selectedExtension]];
// save selected type in our variable for use in `saveToURL` method
_selectedTypeForSaveToOperation = selectedType;
// set export params and `Options` button state
[self setExportParams:selectedType];
}
- (NSArray<NSString *> *)writableTypesForSaveOperation:(NSSaveOperationType)saveOperation {
// checking if _exportTypeLabels is initialized
if ( _exportTypeLabels == NULL )
[self initializeExportTypes];
if ( saveOperation == NSSaveToOperation ) {
// get allowed file types
NSArray * types = [super writableTypesForSaveOperation:saveOperation];
// initialize type selector NSPopUpButton
_typeSelector = [[NSPopUpButton alloc] initWithFrame:NSMakeRect(10, 0, 50, 50)];
// iterate through the types array and add them to the NSPopUpButton
for ( NSString * docType in types ) {
// get the label from the label dictionary
NSString * typeLabel = [_exportTypeLabels objectForKey:docType];
// process tagged labels (XML Tagged Text, SGML Tagged Text)
if ( [docType isEqual:CINXMLType] || [docType isEqual:CINTaggedText] ) {
typeLabel = [NSString stringWithFormat:@"%@ [%@]", typeLabel,ts_getactivetagsetname(( [docType isEqual:CINXMLType] ) ? XMLTAGS : SGMLTAGS)];
}
NSMenuItem * menuItem = [[NSMenuItem alloc] initWithTitle:typeLabel action:NULL keyEquivalent:@""];
[[_typeSelector menu] addItem:menuItem];
}
[_typeSelector setAction:@selector(typeSelectorChange:)];
}
return [super writableTypesForSaveOperation:saveOperation];
}
- (BOOL)prepareSavePanel:(NSSavePanel *)savePanel { // to customize save panel for saving
if (_saveOp == NSSaveToOperation) { // if need to deal with accessory views
NSStackView * stack = [[NSStackView alloc] init];
// initialize `Options` button and disable it by default
_optionsButton = [[NSButton alloc] initWithFrame:NSMakeRect(0,0,103,32)];
[_optionsButton setBezelStyle:NSRoundedBezelStyle];
[_optionsButton setTitle:@"Options…"];
[_optionsButton sizeToFit];
[_optionsButton setAction:@selector(getExportOptions:)];
[_optionsButton setEnabled:NO];
// Text field label for the type selector
NSTextField * typeSelectorLabel = [NSTextField labelWithString:@"File Format: "];
[typeSelectorLabel setFont:[NSFont fontWithName:[[typeSelectorLabel font] fontName] size:11]];
// Append all elements to the NSStackView
[stack setViews:@[typeSelectorLabel, _typeSelector, _optionsButton] inGravity:NSStackViewGravityCenter];
stack.edgeInsets = NSEdgeInsetsMake(20, 10, 20, 20);
// set the accessoryView for the "Save To" NSSavePanel
[savePanel setAccessoryView:stack];
export_setdefaultparams(&_index,E_NATIVE);
[savePanel setDelegate:self];
}
return YES;
}
- (IBAction)getExportOptions:(id)sender {
NSWindowController * panel = [[ExportOptionsController alloc] init];
[panel setDocument:self];
[NSApp runModalForWindow:[panel window]];
}
- (void)panelSelectionDidChange:(id)sender {
// NSLog(@"selection changed");
}
// Modifying the existing method to accommodate the param change
- (void)setExportParams:(NSString *) dataType {
if ([dataType isEqualToString:CINIndexType]) {
[_optionsButton setEnabled:NO];
export_setdefaultparams(&_index,E_NATIVE);
}
else if ([dataType isEqualToString:CINStationeryType]) {
[_optionsButton setEnabled:NO];
export_setdefaultparams(&_index,E_STATIONERY);
}
else if ([dataType isEqualToString:CINArchiveType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_ARCHIVE);
}
else if ([dataType isEqualToString:CINXMLRecordType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_XMLRECORDS);
}
else if ([dataType isEqualToString:CINDelimitedRecords]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_TAB);
}
else if ([dataType isEqualToString:CINPlainTextType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_TEXTNOBREAK);
}
else if ([dataType isEqualToString:DOSDataType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_DOS);
}
else if ([dataType isEqualToString:CINRTFType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_RTF);
}
else if ([dataType isEqualToString:CINQuarkType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_XPRESS);
}
else if ([dataType isEqualToString:CINInDesignType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_INDESIGN);
}
else if ([dataType isEqualToString:CINXMLType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_XMLTAGGED);
}
else if ([dataType isEqualToString:CINTaggedText]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_TAGGED);
}
else if ([dataType isEqualToString:CINIMType]) {
[_optionsButton setEnabled:YES];
export_setdefaultparams(&_index,E_INDEXMANAGER);
}
else
[_optionsButton setEnabled:NO];
}
//- (void)_setLastSavedName:(NSString *)name {
// _eparams.lastSavedName = name;
//}
- (void)runModalSavePanelForSaveOperation:(NSSaveOperationType)op delegate:(id)delegate didSaveSelector:(SEL)sel contextInfo:(void *)contextInfo {
_saveOp = NSSaveToOperation; // control display of accessory view
[super runModalSavePanelForSaveOperation:op delegate:self didSaveSelector:@selector(document:didSave:contextInfo:) contextInfo:&_eparams];
}
- (NSString *)displayName {
return [[super displayName] stringByDeletingPathExtension];
}
- (void)document:(NSDocument *)doc didSave:(BOOL)didSave contextInfo:(void *)contextInfo {
if (didSave && contextInfo) {
EXPORTPARAMS * ep = contextInfo;
if (ep->type == E_ARCHIVE || ep->type == E_XMLRECORDS || ep->type == E_TAB || ep->type == E_DOS) { // records
if (ep->errorcount)
infoSheet(self.windowForSheet, WRITERECINFOWITHERROR, ep->records, [self.lastSavedName UTF8String], ep->longest, ep->errorcount);
else
infoSheet(self.windowForSheet, WRITERECINFO, ep->records, [self.lastSavedName UTF8String], ep->longest);
}
else if (ep->type == E_RTF || ep->type == E_XPRESS || ep->type == E_INDESIGN || ep->type == E_XMLTAGGED || ep->type == E_TAGGED || ep->type == E_TEXTNOBREAK || ep->type == E_INDEXMANAGER) // formatted
infoSheet(self.windowForSheet, FILESTATSINFO, [self.lastSavedName UTF8String], _index.pf.entries, _index.pf.lines, _index.pf.prefs, _index.pf.crefs);
}
}
- (BOOL)writeToURL:(NSURL *)absoluteURL ofType:(NSString *)typeName error:(NSError **)outError {
if ([typeName isEqualToString:CINIndexType]) { // saving native index
if (![self _duplicateIndexToFile:[absoluteURL path]]) {
if (outError)
*outError = makeNSError(FILEOPENERR,"There was an error when saving a copy of the index.");
return NO;
}
return YES;
}
return [super writeToURL:absoluteURL ofType:typeName error:outError];
}
- (NSData *)dataOfType:(NSString *)aType error:(NSError **)error {
if ([aType isEqualToString:CINArchiveType] || [aType isEqualToString:CINXMLRecordType]
|| [aType isEqualToString:CINDelimitedRecords] || [aType isEqualToString:DOSDataType]) { // if records
if ([aType isEqualToString:CINXMLRecordType]) { // if need syntax check on records
GROUPHANDLE gh = grp_startgroup(&_index); /* initialize a group */
if (grp_buildfromcheck(&_index,&gh)) {
grp_installtemp(&_index,gh);
[self setViewType:VIEW_TEMP name:nil];
if (error)
*error = makeNSError(RECORDSYNTAXERR);
return nil;
}
grp_dispose(gh);
}
return export_writerecords(&_index,&_eparams);
}
if ([aType isEqualToString:CINStationeryType]) // if stationery
return export_writestationery(&_index,&_eparams);
if ([aType isEqualToString:CINRTFType]) // if rtf
return formexport_write(&_index,&_eparams, &rtfcontrol);
if ([aType isEqualToString:CINQuarkType]) // if quark
return formexport_write(&_index,&_eparams, &xpresscontrol);
if ([aType isEqualToString:CINInDesignType]) // if InDesign
return formexport_write(&_index,&_eparams, &indesigncontrol);
if ([aType isEqualToString:CINXMLType]) // if xml text
return formexport_write(&_index,&_eparams, &xmlcontrol);
if ([aType isEqualToString:CINPlainTextType]) // if plain text
return formexport_write(&_index,&_eparams, &textcontrol);
if ([aType isEqualToString:CINTaggedText]) // if tagged
return formexport_write(&_index,&_eparams, &tagcontrol);
if ([aType isEqualToString:CINIMType]) // if index manager
return formexport_write(&_index,&_eparams, &imcontrol);
return nil;
}
- (void)setAutosave:(double)seconds {
[self.saveTimer invalidate];
self.saveTimer = nil;
if (seconds && !_index.readonly)
self.saveTimer = [NSTimer scheduledTimerWithTimeInterval:seconds target:self selector:@selector(timerFired:) userInfo:nil repeats:NO];
}
- (void)timerFired:(NSTimer *)timer {
// NSLog(@"Timer Fired");
if (_index.mf.base) // precaution: unknown circumstances (which shouldn't arise) might have timer fire after indexClose, so mfile config is gone
[self _savePrivateBackup];
// [self setAutosave:g_prefs.gen.saveinterval]; // reset save timer
}
- (void)_prefsChanged {
[self setAutosave:g_prefs.gen.saveinterval];
}
- (BOOL)_installIndex {
NSDictionary * attr = [[NSFileManager defaultManager] attributesOfItemAtPath:[[self fileURL] path] error:NULL];
short tdirty = _index.head.dirty;
short farray[FONTLIMIT];
_index.wholerec = RECSIZE+_index.head.indexpars.recsize;
self.modtime = [[attr fileModificationDate] copy];
col_init(&_index.head.sortpars,&_index); // initialize collator
[self buildStyledStrings]; // set up styled strings
[self configurePrintInfo]; // set print defaults
if (index_setworkingsize(&_index, MAPMARGIN)) { // set mapping size
RECN nomrtot = (RECN)(_index.mf.size-_index.head.groupsize-HEADSIZE)/(_index.head.indexpars.recsize+RECSIZE); // max possible capacity
int error;
if ([self resizeIndex:_index.head.indexpars.recsize]) { // 6/24/18 ensure record size is multiple of 4
error = index_checkintegrity(&_index, nomrtot);
if (_index.readonly && (tdirty && !error || error > 0)) { /* wanting readonly but dirty or damaged */
sendinfo(INFO_INDEXNEEDSREPAIR); /* send info */
return FALSE;
}
if (error < 0) { // fatal damage to header; can't repair
senderr(FATALDAMAGEERR, WARN);
return FALSE;
}
if (error > 0) { // record error(s)
if (sendwarning(DAMAGEDINDEXWARNING)) {
RECN mcount;
if (_index.head.rtot > nomrtot) // if claim too many records
_index.head.rtot = nomrtot; // force from size of file
tdirty = FALSE;
mcount = index_repair(&_index); // do repairs
_index.needsresort = TRUE;
if (mcount)
sendinfo(INFO_REPAIRMARKED,mcount);
}
else // don't want to repair
return FALSE;
}
if (_index.head.rtot <= nomrtot || sendwarning(MISSINGRECORDS, nomrtot, _index.head.rtot)
&& (_index.head.rtot = nomrtot) && index_writehead(&_index)) { // if # records matches, or repaired OK
if (tdirty) { /* if badly closed */
if (sendwarning(CORRUPTINDEX)) { /* if want resort */
_index.needsresort = TRUE;
// [self flush]; // 7/25/18; redundant
}
else
_index.readonly = TRUE;
}
if (!grp_checkintegrity(&_index)) { // if corrupt groups
if (sendwarning(DAMAGEDGROUPS)) // if want repair
grp_repair(&_index);
else
return FALSE;
}
_index.startnum = _index.head.rtot;
if (!_index.readonly) {
[self _checkFixes]; // do minor version fixups
if (_index.needsresort) {
sort_resort(&_index);
[self flush];
}
}
if (_index.head.privpars.vmode == VM_SUMMARY) // if closed in summary
_index.head.privpars.vmode = VM_DRAFT;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_prefsChanged) name:NOTE_PREFERENCESCHANGED object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateDisplay) name:NOTE_STRUCTURECHANGED object:self];
type_findlostfonts(&_index);
if (!type_scanfonts(&_index,farray)) // if there are unused fonts
type_adjustfonts(&_index,farray); // remove them
if (type_checkfonts(_index.head.fm) || [ManageFontController manageFonts:_index.head.fm]) { /* if fonts ok or fixed */
[self setAutosave:g_prefs.gen.saveinterval];
if (IRdc.IRrevertsource) { // if reverting
_index.head.mainviewrect = [IRdc.IRrevertsource iIndex]->head.mainviewrect; // get main view rect from source;
[self setFileURL:[IRdc.IRrevertsource fileURL]]; // make sure new index will display proper name (actual file renamed in cleanup)
}
else if (!_index.readonly) // if not readonly && if not reverting reverting -- underlying file not yet safely renamed if reverting
[self _savePrivateBackup]; // make private backup
return YES;
}
}
}
}
return NO;
}
- (BOOL)readFromURL:(NSURL *)url ofType:(NSString *)aType error:(NSError **)error {
if ([aType isEqualToString:CINIndexType]) { // if index
// NSDictionary * attributes = [[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:nil];
// short ppermissions = [[attributes objectForKey:@"NSFilePosixPermissions"] shortValue];
// _index.readonly = [[attributes objectForKey:@"NSFileImmutable"] boolValue] || !([[attributes objectForKey:@"NSFilePosixPermissions"] shortValue]&0200); // if locked or not writable by owner
_index.readonly = ![[NSFileManager defaultManager] isWritableFileAtPath:url.path];
int flags = _index.readonly ? O_RDONLY|O_EXLOCK|O_NONBLOCK : O_RDWR|O_EXLOCK|O_NONBLOCK;
if (mfile_open(&_index.mf,[url.path UTF8String],flags,0)) {
if (_index.mf.size >= HEADSIZE) { // if could be index
memcpy(&_index.head,_index.mf.base,HEADSIZE); // install header
BOOL goodversion = _index.head.version >= BASEVERSION && _index.head.version <= TOPVERSION;
if (_index.head.headsize == HEADSIZE && goodversion) { /* if compatible versions */
if ([self _installIndex]) // set up and check everything
return YES;
else {
mfile_close(&_index.mf);
return NO;
}
}
else if (!goodversion) {
mfile_close(&_index.mf);
senderr(FILEVERSERR, WARN, (float)_index.head.version/100); /* bad version */
return NO;
}
}
mfile_close(&_index.mf);
senderr(UNKNOWNFILERR, WARN, [[url.path lastPathComponent] UTF8String]); // not an index
}
else
senderr(FILEOPENERR,WARN,strerror(errno));
}
else if ([aType isEqualToString:CINStyleSheetType] ) {
STYLESHEET * ssp = (STYLESHEET *)[[NSData dataWithContentsOfFile:url.path] bytes];
return [IRdc loadStyleSheet:ssp];
}
return NO;
}
#if 0
#if 0 // April 5 2018
- (void)canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo {
if ([self closeIndex]) { // if no error closing
[super canCloseDocumentWithDelegate:delegate shouldCloseSelector:shouldCloseSelector contextInfo:contextInfo];
[self close]; // Dec 3 2017
}
}
#endif
// following method from April 5 2018
- (void)shouldCloseWindowController:(NSWindowController *)windowController delegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo {
if (windowController == _mainWindowController) {
if ([self closeIndex]) // if no error closing
[self close];
}
else
[super shouldCloseWindowController:windowController delegate:delegate shouldCloseSelector:shouldCloseSelector contextInfo:contextInfo];
}
#else
- (void)canCloseDocumentWithDelegate:(id)delegate shouldCloseSelector:(SEL)shouldCloseSelector contextInfo:(void *)contextInfo {
// NSTimer * xx = self.saveTimer;
// NSLog(@"Pre:%d",xx.isValid);
[self document:self shouldClose:[self closeIndex] contextInfo:contextInfo];
// NSLog(@"Post:%d",xx.isValid);
}
- (void)document:(NSDocument *)document shouldClose:(BOOL)shouldClose contextInfo:(void *)contextInfo {
if (shouldClose)
[self close];
}
#endif
- (BOOL)_savePrivateBackup { // saves private backup of active index
if (!_backupPath) { // if have no backup name
NSString * name = @"."; // as prefix to file name makes it hidden
name = [name stringByAppendingString:[[self fileURL] lastPathComponent]];
_backupPath = [[[[self fileURL] path] stringByDeletingLastPathComponent] stringByAppendingPathComponent:name];
}
[self setAutosave:0]; // kill save timer (could be running if this save is other than autosave)
_hasBackup = [self _duplicateIndexToFile:_backupPath];
[self setAutosave:g_prefs.gen.saveinterval]; // reset save timer
return _hasBackup;
}
#if 1
- (IBAction)revertToSaved:(id)sender { // reverts to private backup
if (sendwarning(REVERTWARNING)) {
NSURL * burl = [NSURL fileURLWithPath:_backupPath];
NSURL * furl = [self fileURL];
IRdc.IRrevertsource = self;
[IRdc openDocumentWithContentsOfURL:burl display:YES completionHandler:^(NSDocument *document, BOOL alreadyOpen, NSError *error){
// by now, the reverted doc has retrieved and displayed the right internal name
if (document) {
[[[self mainWindowController] window] performClose:self]; // close us
[[NSFileManager defaultManager] removeItemAtURL:furl error:NULL]; // remove file underlying self
[[NSFileManager defaultManager] moveItemAtURL:burl toURL:furl error:nil]; // rename what was the backup file
[(IRIndexDocument *)document _savePrivateBackup]; // make new private backup
}
else {
IRdc.IRrevertsource = nil;
senderr(INTERNALERR, WARN, "Cannot revert to saved document");
}
}];
}
}
#else
- (IBAction)revertToSaved:(id)sender { // reverts to private backup
if (sendwarning(REVERTWARNING)) {
if (_backupPath) {
NSURL * burl = [NSURL fileURLWithPath:_backupPath];
NSURL * furl = [self fileURL];
IRIndexDocument * ndoc;
NSError * error;
IRrevertsource = self;
if (ndoc = [IRdc openDocumentWithContentsOfURL:burl display:YES error:&error]) { // open and display backup
// by now, the reverted doc has retrieved and displayed the right internal name
[[[self mainWindowController] window] performClose:self]; // close us
[[NSFileManager defaultManager] removeItemAtURL:furl error:NULL]; // remove file underlying self
[[NSFileManager defaultManager] moveItemAtURL:burl toURL:furl error:nil]; // rename what was the backup file
[ndoc _savePrivateBackup]; // make new private backup
return;
}
IRrevertsource = nil;
}
senderr(INTERNALERR, WARN, "Cannot revert to saved document");
}
}
#endif
- (BOOL)readForbidden:(NSInteger)itemID {
static int fcommand[] = {
MI_SAVE,MI_REVERT,MI_IMPORT,MI_SAVEGROUP,
MI_UNDO,MI_REDO,MI_CUT,MI_DEMOTE,MI_DELETED,MI_LABEL0,MI_LABEL1,MI_LABEL2,MI_LABEL3,MI_LABEL4,MI_LABEL5,MI_LABEL6,MI_LABEL7,MI_NEWRECORD,MI_EDITRECORD,MI_DUPLICATE,MI_REPLACE,MI_SPELL,
MI_REMOVEMARK,
MI_RECSTRUCTURE,/* MI_REFSYNTAX, MI_FLIPWORDS, */
MI_RECONCILE,MI_GENERATE,MI_ALTER,MI_SPLIT,MI_SORT,MI_COMPRESS,MI_EXPAND,MI_GROUPS,
};
if (_index.readonly) {
for (int rindex = 0; rindex < sizeof(fcommand)/sizeof(int); rindex++) {
if (fcommand[rindex] == itemID)
return YES;
}
}
return NO;
}
- (BOOL)validateMenuItem:(NSMenuItem *)mitem {
NSInteger itemid = [mitem tag];
// NSLog([mitem title]);
if (self.currentSheet || [self readForbidden:itemid])
return NO;
if([[_textWindowController window] isMainWindow])
return (itemid == MI_PRINT || itemid == MI_PAGESETUP);
if (_recordWindowController && // if have record window
itemid != MI_NEWRECORD && itemid != MI_FINDAGAIN && itemid != MI_CHECK && itemid != MI_COUNT && itemid != MI_STATISTICS)
return NO;
if (itemid == MI_EDITRECORD)
return [self selectedRecords].location > 0 && [self selectedRecords].location == [self selectedRecords].length;
if (itemid == MI_NEWGROUP || itemid == MI_DUPLICATE || itemid == MI_DELETED || itemid == MI_DEMOTE || itemid == MI_REMOVEMARK)
return [self selectedRecords].location > 0;
if (itemid == MI_FINDAGAIN)
return [self.currentSearchController canFindAgainInDocument:self];
if (itemid == MI_HIDEBYATTRIBUTE)
return _index.head.privpars.vmode == VM_FULL;
if (itemid == MI_NEWRECORDS)
return _index.startnum < _index.head.rtot;
if (itemid == MI_TEMPORARYGROUP)
return _index.lastfile ? YES : NO;
if (itemid == MI_SHOWNUMBERS)
return _index.head.privpars.vmode != VM_FULL;
if (itemid == MI_WRAPLINES)
return _index.head.privpars.vmode == VM_NONE;
if (itemid == MI_SHOWSORTED)
return !(_index.curfile || _index.viewtype == VIEW_NEW); // no unsorted if group or new
if (itemid == MI_REVERT)
return _hasBackup && (_index.head.dirty || _index.wasdirty);
if (itemid == MI_SAVEGROUP)
return _index.lastfile && _index.viewtype == VIEW_TEMP ? YES : NO;
if (itemid == MI_GROUPS)
return [_groupmenu numberOfItems] > 0;
if (itemid == MI_GENERATE || itemid == MI_CHECK)
return _index.head.sortpars.fieldorder[0] != PAGEINDEX;