/
Document.cpp
2344 lines (1933 loc) · 68.3 KB
/
Document.cpp
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
/*******************************************************************************
*
* Copyright (C) 2009, Alexander Stigsen, e-texteditor.com
*
* This software is licensed under the Open Company License as described
* in the file license.txt, which you should have received as part of this
* distribution. The terms are also available at http://opencompany.org/license.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
******************************************************************************/
#include "Document.h"
#include "DataList.h"
#include <wx/fontmap.h>
#include <wx/wfstream.h>
#include "doc_byte_iter.h"
#include "cx_pcre.h"
#include "Utf.h"
#include "eSettings.h"
#include "Strings.h"
#include "eDocumentPath.h"
Document::Document(const doc_id& di, CatalystWrapper cw):
m_catalyst(cw.m_catalyst),
dispatcher(cw.GetDispatcher()),
m_textData(cw.m_catalyst),
in_change(false),
change_level(0),
do_notify(true),
do_notify_top(0),
m_re(NULL),
m_trackChanges(NULL)
{
SetDocument(di);
// Make sure we get notified if the document gets deleted
dispatcher.SubscribeC(wxT("DOC_DELETED"), (CALL_BACK)OnDocDeleted, this);
}
Document::Document(CatalystWrapper cw):
m_catalyst(cw.m_catalyst),
dispatcher(cw.GetDispatcher()),
m_docId(DRAFT,-1,-1),
m_textData(cw.m_catalyst),
in_change(false),
change_level(0),
do_notify(true),
do_notify_top(0),
m_re(NULL),
m_trackChanges(NULL)
{
// Make sure we get notified if the document gets deleted
dispatcher.SubscribeC(wxT("DOC_DELETED"), (CALL_BACK)OnDocDeleted, this);
}
Document::~Document() {
dispatcher.UnSubscribe(wxT("DOC_DELETED"), (CALL_BACK)OnDocDeleted, this);
// Do standard clean-up
if (IsOk()) Close();
// Clean up stuff not handled by Close()
if (m_re) free(m_re); // check if we have a cached regex
}
// - Public API ---
void Document::CreateNew(const ISettings& settings) {
// Create the new document
SetDocument(m_catalyst.NewDocument());
// The user may have defined a default encoding
SetDefaultsFromSettings(settings);
}
void Document::SetDefaultsFromSettings(const ISettings& settings) {
// Check if we need to set eol property
wxString eolStr;
if (settings.GetSettingString(wxT("formatEol"), eolStr)) {
wxTextFileType eol = wxTextBuffer::typeDefault;
if (eolStr == wxT("crlf")) eol = wxTextFileType_Dos;
else if (eolStr == wxT("lf")) eol = wxTextFileType_Unix;
else if (eolStr == wxT("cr")) eol = wxTextFileType_Mac;
SetPropertyEOL(eol);
}
// Check if we need to set encoding property
wxString encStr;
if (settings.GetSettingString(wxT("formatEncoding"), encStr)) {
const wxFontEncoding enc = wxFontMapper::GetEncodingFromName(encStr);
SetPropertyEncoding(enc);
}
// Check if we need to set bom property
bool bom;
if (settings.GetSettingBool(wxT("formatBom"), bom))
SetPropertyBOM(bom);
}
bool Document::operator==(const doc_id& di) const {
wxASSERT(IsOk());
return m_docId == di;
}
bool Document::operator!=(const doc_id& di) const {
wxASSERT(IsOk());
return m_docId != di;
}
void Document::Close() {
wxASSERT(m_docId.document_id != -1 && m_docId.version_id != -1); // Cannot close invalid document
m_textData.Close();
// Invalidate document
m_docId.document_id = m_docId.version_id = -1;
}
bool Document::IsOk() const {
bool bad_document = m_docId.document_id == -1 || m_docId.version_id == -1;
return !bad_document;
}
bool Document::IsEmpty() const {
wxASSERT(IsOk());
// Document can have a single empty revision and still
// be considered empty (ignore property changes)
return (m_docId.type == DRAFT && vHistory.GetSize() <= 1 && GetLength() == 0); // && GetPropnode().node_id == -1);
}
void Document::Commit(const wxString& label, const wxString& desc) {
wxASSERT(IsOk());
wxASSERT(label.Find('\n') == -1); // label should not contain newlines
// If the document version is already committed we have to
// create a new draft to start out with.
if (m_docId.IsDocument()) NewRevision();
// Check if the Draft has a parent
c4_View vDocuments = m_catalyst.GetDocView();
const doc_id parent = GetParent();
// If it does not have a parent, we have to create a new document
const int new_doc_id = parent.IsOk() ? parent.document_id : m_catalyst.CreateDocument();
wxASSERT(new_doc_id != -1);
c4_RowRef rDoc = vDocuments[new_doc_id];
wxASSERT(pBuffPath(rDoc) != 0);
c4_View vDocHistory = pHistory(rDoc);
// Create new version
const int new_version_id = vDocHistory.Add(c4_Row());
c4_RowRef rVersion = vDocHistory[new_version_id];
const doc_id new_doc(DOCUMENT, new_doc_id, new_version_id);
// Add it as a child of the parent document
// (root points to itself (rev_id=0) as parent)
if (parent.IsOk()) {
pParent(rVersion) = parent.version_id;
// Add it to parents list of children
c4_View vChildren = pChildren(vDocHistory[parent.version_id]);
vChildren.Add(pType[DOCUMENT] + pChildref[new_version_id]);
}
// Get the Draft
const c4_RowRef rDraft = vRevisions[m_docId.document_id];
// Set Date (to same date as latest change to draft)
pDate(rVersion) = pDate(rDraft);
pTimezone(rVersion) = wxDateTime::TimeZone(wxDateTime::Local).GetOffset();
// Set Label
if (label.IsEmpty()) pLabelNode(rVersion) = -1;
else {
DataText labelText(m_catalyst, m_docId);
labelText.Insert(0, label);
const node_ref new_labelnode = labelText.Consolidate(new_doc);
wxASSERT(new_labelnode.version_id == new_doc.version_id);
pLabelNode(rVersion) = new_labelnode.node_id;
}
// Set Description
if (desc.IsEmpty()) pDescNode(rVersion) = -1;
else {
DataText descText(m_catalyst, m_docId);
descText.Insert(0, desc);
const node_ref new_descnode = descText.Consolidate(new_doc);
wxASSERT(new_descnode.version_id == new_doc.version_id);
pDescNode(rVersion) = new_descnode.node_id;
}
// Consolidate properties
const node_ref propnode = GetPropnode();
if(propnode.IsOk()) {
DataList properties(m_catalyst, m_docId, propnode);
const node_ref new_propnode = properties.Consolidate(new_doc);
pPropVer(rVersion) = new_propnode.version_id;
pPropnode(rVersion) = new_propnode.node_id;
}
else {
pPropVer(rVersion) = -1;
pPropnode(rVersion) = -1;
}
// Consolidate data
const node_ref headnode = m_textData.Consolidate(new_doc);
pHeadVer(rVersion) = headnode.version_id;
pHeadnode(rVersion) = headnode.node_id;
// Set State and Length
pState(rVersion) = cxREVSTATE_NORMAL;
pLength(rVersion) = m_textData.GetLength();
// Create the Document Signature
m_catalyst.SignRevision(new_doc);
// Move any file mirrors to point to the new document version
wxArrayString mirrors;
wxDateTime modifiedDate;
doc_id mirrorId;
if (m_catalyst.GetMirrorPathsForDraft(m_docId, mirrors)) {
for (unsigned int i = 0; i < mirrors.GetCount(); ++i) {
if (m_catalyst.GetFileMirror(mirrors[0], mirrorId, modifiedDate)) {
if (mirrorId == m_docId) {
m_catalyst.SetFileMirror(mirrors[i], new_doc, modifiedDate);
}
else {
// If there are mirrors from intermediate revisions in the draft
// we have to invalidate them.
m_catalyst.SetFileMirrorToModified(mirrors[i], new_doc);
}
}
else wxASSERT(false);
}
}
// Delete the Draft
m_catalyst.DeleteDraft(m_docId);
const doc_id old_doc = m_docId;
SetDocument(new_doc);
MakeHead();
// Notify that we have commited the document
// so that other who might have a version of the draft open
// get a chance to upgrade to the new doc.
const docid_pair docPair(old_doc, new_doc);
if (do_notify) {
m_catalyst.UnLock();
dispatcher.Notify(wxT("DOC_COMMITED"), &docPair, 0);
m_catalyst.ReLock();
}
}
wxString Document::GetText() const {
wxASSERT(IsOk());
m_catalyst.ResetIdle();
if (GetLength() == 0) return wxString();
return m_textData.GetText();
}
void Document::WriteText(wxOutputStream& stream) const {
m_textData.WriteText(stream);
}
void Document::StartChange(bool doNotify) {
wxASSERT(IsOk());
// Always freeze before starting grouped changes
if (change_level == 0) {
Freeze();
in_change = true;
}
// If notification is stopped at any nesting level
// no lower level can enable it
if (do_notify && !doNotify) {
do_notify = false;
do_notify_top = change_level;
}
++change_level;
}
void Document::EndChange(int forceTo) {
wxASSERT(IsOk());
wxASSERT(change_level > 0);
wxASSERT(forceTo < change_level);
// Change nesting level
if (forceTo == -1) --change_level;
else change_level = forceTo;
// Restore notifications
if (change_level <= do_notify_top) {
do_notify = true;
do_notify_top = 0;
}
// Freeze when the entire change is complete
if (change_level == 0) {
in_change = false;
Freeze();
// Notify subscribers that the revision has changed
m_catalyst.UnLock();
dispatcher.Notify(wxT("DOC_UPDATEREVISION"), &m_docId, 0);
m_catalyst.ReLock();
}
}
wxString Document::GetTextPart(int start_pos, int end_pos) const {
wxASSERT(IsOk());
m_catalyst.ResetIdle();
wxString text;
m_textData.GetTextPart(start_pos, end_pos, text);
return text;
}
wxString Document::GetTextPart(const doc_id& version, int start_pos, int end_pos) const {
wxASSERT(IsOk());
wxASSERT(version.IsOk());
const DataText textData(m_catalyst, version, GetHeadnode(version));
m_catalyst.ResetIdle();
wxString text;
textData.GetTextPart(start_pos, end_pos, text);
return text;
}
void Document::GetTextPart(int start_pos, int end_pos, vector<char>& buffer) const {
wxASSERT(IsOk());
m_catalyst.ResetIdle();
const unsigned int len = end_pos - start_pos;
if (len == 0) return;
// Make sure that there is room for text in the buffer
buffer.resize(len);
// Get the text
unsigned char* buffptr = (unsigned char*)&*buffer.begin();
m_textData.GetTextPart(start_pos, end_pos, buffptr);
}
wxChar Document::GetChar(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetChar(pos);
}
unsigned int Document::GetLength() const {
wxASSERT(IsOk());
if (m_textData.IsOk()) return m_textData.GetLength();
return 0;
}
unsigned int Document::GetLengthInChars(unsigned int start_pos, unsigned int end_pos) const {
wxASSERT(IsOk());
return m_textData.GetLengthInChars(start_pos, end_pos);
}
// This function can count both forward and backward, but if the count
// goes beyond the contents it returns the last valid pos.
unsigned int Document::GetCharPos(unsigned int offset, int char_count) const {
wxASSERT(IsOk());
return m_textData.GetCharPos(offset, char_count);
}
unsigned int Document::GetCharPos(const doc_id& version, unsigned int offset, int char_count) const {
wxASSERT(IsOk());
wxASSERT(m_catalyst.IsOk(version));
const DataText textData(m_catalyst, m_docId, GetHeadnode(version));
return textData.GetCharPos(offset, char_count);
}
unsigned int Document::GetCharLength(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetCharLength(pos);
}
unsigned int Document::GetNextCharPos(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetNextCharPos(pos);
}
unsigned int Document::GetPrevCharPos(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetPrevCharPos(pos);
}
unsigned int Document::GetValidCharPos(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetValidCharPos(pos);
}
unsigned int Document::GetLineStart(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetLineStart(pos);
}
unsigned int Document::GetLineEnd(unsigned int pos) const {
wxASSERT(IsOk());
return m_textData.GetLineEnd(pos);
}
void Document::Clear(bool initialRevision) {
wxASSERT(IsOk());
wxASSERT(m_docId.type == DRAFT); // Only Drafts can be cleared
const c4_RowRef rDoc = vRevisions[m_docId.document_id];
// Clear the entire document (removes all revisions)
// (We cannot just clear the entire row as there might
// be other revisions that have cached views)
vNodes.RemoveAll();
vHistory.RemoveAll();
((c4_View)pFreenodes(rDoc)).RemoveAll();
pBuffPath(rDoc) = 0;
// Refresh references
m_textData.Invalidate();
if (initialRevision) NewRevision();
}
cxFileResult Document::LoadText(const wxFileName& path, vector<unsigned int>& offsets, wxFontEncoding enc, const wxString& mirror) {
wxASSERT(IsOk());
wxASSERT(path.IsOk());
wxASSERT(path.IsAbsolute());
wxASSERT(offsets.empty());
// Clean up the cache first, so that we do not later risk
// referencing an out-of-sync memorymap
m_textData.ClearBuffCache();
// Setup variables
wxFileOffset len;
MMapBuffer buffer;
// Get the filename
const wxString filename = mirror.empty() ? path.GetFullName() : mirror.AfterLast(wxT('/'));
// Open the file & load the text
wxDateTime fileDate;
if (!path.FileExists()) len = 0; // fileDate will be invalid
else {
fileDate = path.GetModificationTime();
// Use memory mapped files
buffer.Open(path);
if (!buffer.IsOpened()) return cxFILE_OPEN_ERROR; // Could not open file
len = buffer.Length();
}
// Load the text
if (len > 0)
{
if (!buffer.IsMapped()) return cxFILE_OPEN_ERROR; // Could not memory map file
}
else {
// Empty file is ok
// We want the new revision to either be the first (base) revision
// or if there is a parent, directly following it.
if (IsEmpty()) {
Clear();
NewRevision();
}
else DeleteAll();
// Set the name
SetPropertyName(filename);
// Set the date
if (fileDate.IsValid()) {
pDate(vRevisions[m_docId.document_id]) = fileDate.GetValue().GetValue();
}
else {
pDate(vRevisions[m_docId.document_id]) = wxDateTime::Now().GetValue().GetValue();
}
const ISettings& settings = eGetSettings();
SetDefaultsFromSettings(settings);
Freeze();
// An invalid date indicates that the document is modified
// or in this case does not yet exist.
const wxString pathStr = mirror.empty() ? path.GetFullPath() : mirror;
if (fileDate.IsValid()) m_catalyst.SetFileMirror(pathStr, m_docId, fileDate);
else m_catalyst.SetFileMirrorToModified(pathStr, m_docId);
// Notify that document mirror info has changed
const doc_id di = m_docId;
m_catalyst.UnLock();
dispatcher.Notify(wxT("DOC_UPDATED"), (void*)&di, 0);
m_catalyst.ReLock();
return cxFILE_OK;
}
const char* bufptr = buffer.data();
wxASSERT(bufptr);
// See if we can detect the encoding
unsigned int bom_len = 0;
wxFontEncoding det_enc;
const bool result = DetectTextEncoding(bufptr, len, det_enc, bom_len);
if (result && enc == wxFONTENCODING_SYSTEM) {
enc = det_enc; // Initial system means we should follow detection
}
if (enc == wxFONTENCODING_DEFAULT) enc = wxFONTENCODING_SYSTEM; // Set default to the system default
// If there is a Byte Order Marker (BOM), we have to adjust offset & length
if (bom_len) {
bufptr += bom_len;
len -= bom_len;
}
int buff_file_num = m_docId.IsDocument() ? 0 : pBuffPath(vRevisions[m_docId.document_id]);
wxFileName buff_path = m_catalyst.GetDraftPath();
if (buff_file_num == 0) { // Get a unique filename for buffer file
do {
buff_file_num = m_catalyst.GetRand();
const wxString random_filename = wxString::Format(wxT("%x"), buff_file_num);
buff_path.SetFullName(random_filename);
} while (buff_file_num == 0 || buff_path.FileExists());
}
else buff_path.SetFullName(wxString::Format(wxT("%x"), buff_file_num));
// Create the buffer file
wxFFile bufferfile(buff_path.GetFullPath(), _("ab"));
if (!bufferfile.IsOpened()) {
wxASSERT_MSG(false, wxT("Could not open buffer file"));
return cxFILE_OPEN_ERROR;
}
bufferfile.SeekEnd();
wxFileOffset buff_offset = bufferfile.Tell();
// Pre-reserve entries to avoid unneeded allocs in vector
offsets.reserve(len/35);
unsigned int pos = 0;
unsigned int nl_count_dos = 0;
unsigned int nl_count_mac = 0;
unsigned int nl_count_unix = 0;
if (enc == wxFONTENCODING_UTF8) {
// Convert and save one line at a time while counting newlines
char nl = '\n';
bool prev_r = false;
int linestart = 0;
int utf_bytes = 0;
for (off_t i = 0; i < len; ++i) {
const char c = bufptr[i];
// Detect invalid UTF-8 sequences
if (utf_bytes == 0) {
if ((c & 0xC0) == 0x80 || c == 0) goto decode_error;
else {
utf_bytes = utf8_len(c) - 1;
if (utf_bytes > 3) goto decode_error;
}
}
else if ((c & 0xC0) == 0x80) --utf_bytes;
else goto decode_error;
switch (c) {
case '\r':
if (prev_r) ++nl_count_mac;
bufferfile.Write(&bufptr[linestart], i - linestart);
pos += i - linestart;
bufferfile.Write(&nl, 1); ++pos;
offsets.push_back(pos);
linestart = i+1;
prev_r = true;
break;
case '\n':
if (!prev_r) {
++nl_count_unix;
bufferfile.Write(&bufptr[linestart], (i - linestart)+1);
pos += (i - linestart)+1;
offsets.push_back(pos);
} else ++nl_count_dos;
linestart = i+1;
prev_r = false;
break;
default:
if (prev_r) ++nl_count_mac;
prev_r = false;
}
}
// Add text after last newline
if (linestart < len) {
bufferfile.Write(&bufptr[linestart], len - linestart);
pos += len - linestart;
offsets.push_back(pos);
}
}
else {
// Allocate buffers
size_t temp_buff_len = 128;
wxCharBuffer temp_buff(temp_buff_len);
size_t wchar_buff_len = 128;
wxWCharBuffer wchar_buff(wchar_buff_len);
size_t utf8_buff_len = 128;
wxCharBuffer utf8_buff(utf8_buff_len);
// Initialize variables
wxCSConv conv(enc);
unsigned int char_len;
const char* nulls = "\0\0\0\0";
const char* nl;
const char* cr;
switch (enc) {
case wxFONTENCODING_UTF32BE:
char_len = 4;
nl = "\x00\x00\x00\x0A";
cr = "\x00\x00\x00\x0D";
break;
case wxFONTENCODING_UTF32LE:
char_len = 4;
nl = "\x0A\x00\x00\x00";
cr = "\x0D\x00\x00\x00";
break;
case wxFONTENCODING_UTF16BE:
char_len = 2;
nl = "\x00\x0A";
cr = "\x00\x0D";
break;
case wxFONTENCODING_UTF16LE:
char_len = 2;
nl = "\x0A\x00";
cr = "\x0D\x00";
break;
default:
char_len = 1;
nl = "\n";
cr = "\r";
}
// Convert and save one line at a time while counting newlines
bool prev_r = false;
int linestart = 0;
for (off_t i = 0; i < len; i += char_len) {
if (memcmp(cr, &bufptr[i], char_len) == 0) { // '\r'
if (prev_r) ++nl_count_mac;
if (i - linestart > 0) {
size_t convlen = ConvertToUTF8(&bufptr[linestart], i - linestart, conv, temp_buff, temp_buff_len, wchar_buff, wchar_buff_len, utf8_buff, utf8_buff_len, char_len);
if (convlen == (size_t)-1) goto decode_error; // conversion failed
bufferfile.Write(utf8_buff, convlen);
pos += convlen;
}
bufferfile.Write("\n", 1); pos += 1;
offsets.push_back(pos);
linestart = i+char_len;
prev_r = true;
}
else if (memcmp(nl, &bufptr[i], char_len) == 0) { // '\n'
if (!prev_r) {
++nl_count_unix;
size_t convlen = ConvertToUTF8(&bufptr[linestart], (i - linestart)+char_len, conv, temp_buff, temp_buff_len, wchar_buff, wchar_buff_len, utf8_buff, utf8_buff_len, char_len);
if (convlen == (size_t)-1) goto decode_error; // conversion failed
bufferfile.Write(utf8_buff, convlen);
pos += convlen;
offsets.push_back(pos);
} else ++nl_count_dos;
linestart = i+char_len;
prev_r = false;
}
else if (memcmp(nulls, &bufptr[i], char_len) == 0) { // conversion fails on null bytes
if (i - linestart > 0) {
size_t convlen = ConvertToUTF8(&bufptr[linestart], i - linestart, conv, temp_buff, temp_buff_len, wchar_buff, wchar_buff_len, utf8_buff, utf8_buff_len, char_len);
if (convlen == (size_t)-1) goto decode_error; // conversion failed
bufferfile.Write(utf8_buff, convlen);
pos += convlen;
}
bufferfile.Write("\xEF\xA3\xBF", 3); pos += 3; // Private use character as stand-in for null
linestart = i+char_len;
prev_r = false;
}
else {
if (prev_r) ++nl_count_mac;
prev_r = false;
}
}
// Add text after last newline
if (linestart < len) {
size_t convlen = ConvertToUTF8(&bufptr[linestart], len - linestart, conv, temp_buff, temp_buff_len, wchar_buff, wchar_buff_len, utf8_buff, utf8_buff_len, char_len);
if (convlen == (size_t)-1) goto decode_error; // conversion failed
bufferfile.Write(utf8_buff, convlen);
pos += convlen;
offsets.push_back(pos);
}
// With null bytes in the text the end offset might not have been set yet.
if (pos && (offsets.empty() || offsets.back() != pos)) offsets.push_back(pos);
}
if (buff_offset + pos != bufferfile.Length()) goto decode_error;
// Close buffer file to ensure changes af flushed to disk
bufferfile.Close();
// Create the new revision
StartChange();
{
// We want the new revision to either be the first (base) revision
// or if there is a parent, directly following it.
if (IsEmpty()) {
Clear();
NewRevision();
}
else PrepareForChange();
m_textData.SetToFile(buff_offset, pos);
UpdateHeadnode();
// Update version info
pLength(vHistory[m_docId.version_id]) = pos;
pBuffPath(vRevisions[m_docId.document_id]) = buff_file_num;
// Set the date
pDate(vRevisions[m_docId.document_id]) = fileDate.GetValue().GetValue();
// Set the document name
SetPropertyName(filename);
// Determine newline type
wxTextFileType nl_type = wxTextFileType_None;
if (nl_count_dos >= nl_count_unix && nl_count_dos >= nl_count_mac) nl_type = wxTextFileType_Dos;
else if (nl_count_unix >= nl_count_dos && nl_count_unix >= nl_count_mac) nl_type = wxTextFileType_Unix;
else if (nl_count_mac >= nl_count_dos && nl_count_mac >= nl_count_unix) nl_type = wxTextFileType_Mac;
if (nl_type != wxTextFileType_None && nl_type != wxTextBuffer::typeDefault) SetPropertyEOL(nl_type);
// Set Encoding & BOM
if (enc != wxFONTENCODING_SYSTEM && enc != wxFONTENCODING_DEFAULT) SetPropertyEncoding(enc);
if (bom_len > 0) SetPropertyBOM(true);
Freeze();
// Set file mirror
if (mirror.empty()) m_catalyst.SetFileMirror(path.GetFullPath(), m_docId, fileDate);
else m_catalyst.SetFileMirror(mirror, m_docId, fileDate);
}
EndChange();
// Notify that document mirror info has changed
// (needs own scope to avoid interferring with goto)
{
const doc_id di = m_docId;
m_catalyst.UnLock();
dispatcher.Notify(wxT("DOC_UPDATED"), (void*)&di, 0);
m_catalyst.ReLock();
}
//wxLogDebug(wxT("reserved %d needed %u"), (int)(len/35), offsets.size());
return cxFILE_OK;
decode_error:
// This is where we end up if the decoding fails
// Clean up the buffer file
if (IsEmpty() && buff_offset == 0) {
bufferfile.Close();
wxRemoveFile(buff_path.GetFullPath());
}
else {
// Remove any data added during this session
#ifdef __WXMSW__
const int fd = _fileno(bufferfile.fp());
bufferfile.Seek(buff_offset);
HANDLE hFile = (HANDLE)_get_osfhandle(fd);
SetEndOfFile(hFile);
#else
const int fd = fileno(bufferfile.fp());
ftruncate(fd, buff_offset);
#endif
}
// Notify the user that decoding failed
return cxFILE_CONV_ERROR;
}
cxFileResult Document::SaveText(const wxFileName& path, bool forceNativeEOL, const wxString& realpath, bool keepMirrorDate, bool noAtomic) {
wxASSERT(IsOk());
wxASSERT(path.IsOk());
wxASSERT(path.IsAbsolute());
const wxString fullPath = path.GetFullPath();
const wxString tmpPath = noAtomic ? fullPath : fullPath + wxT(".etmp");
if (path.FileExists() && !path.IsFileWritable()) {
//wxMessageBox(fullPath + _T(" is write protected."), _T("e Error"), wxICON_ERROR);
return cxFILE_WRITABLE_ERROR;
}
// Do the actual saving
{
// Open the file
// (it will close itself when we exit scope)
wxFFile file(tmpPath, _("wb"));
if (!file.IsOpened()) {
wxLogDebug(wxT("Could not open file"));
return cxFILE_OPEN_ERROR;
}
// Set end-of-line type
wxTextFileType eol = GetPropertyEOL();
if (eol == wxTextFileType_None || forceNativeEOL) eol = wxTextBuffer::typeDefault;
wxFontEncoding propEncoding = GetPropertyEncoding();
const char* nl = "";
const char* nulls = "\0\0\0\0";
unsigned int nl_len = 0;
unsigned int char_len = 0;
switch (propEncoding) {
case wxFONTENCODING_UTF32BE:
if (eol == wxTextFileType_Mac) {
nl = "\x00\x00\x00\x0D";
nl_len = 4;
}
else if (eol == wxTextFileType_Dos) {
nl = "\x00\x00\x00\x0D\x00\x00\x00\x0A";
nl_len = 8;
}
char_len = 4;
break;
case wxFONTENCODING_UTF32LE:
if (eol == wxTextFileType_Mac) {
nl = "\x0D\x00\x00\x00";
nl_len = 4;
}
else if (eol == wxTextFileType_Dos) {
nl = "\x0D\x00\x00\x00\x0A\x00\x00\x00";
nl_len = 8;
}
char_len = 4;
break;
case wxFONTENCODING_UTF16BE:
if (eol == wxTextFileType_Mac) {
nl = "\x00\x0D";
nl_len = 2;
}
else if (eol == wxTextFileType_Dos) {
nl = "\x00\x0D\x00\x0A";
nl_len = 4;
}
char_len = 2;
break;
case wxFONTENCODING_UTF16LE:
if (eol == wxTextFileType_Mac) {
nl = "\x0D\x00";
nl_len = 2;
}
else if (eol == wxTextFileType_Dos) {
nl = "\x0D\x00\x0A\x00";
nl_len = 4;
}
char_len = 2;
break;
default:
if (eol == wxTextFileType_Mac) {
nl = "\x0D";
nl_len = 1;
}
else if (eol == wxTextFileType_Dos) {
nl = "\x0D\x0A";
nl_len = 2;
}
char_len = 1;
}
// Write Byte-Order-Marker
if (GetPropertyBOM()) {
switch (propEncoding) {
case wxFONTENCODING_UTF32BE:
file.Write("\x00\x00\xFE\xFF", 4);
break;
case wxFONTENCODING_UTF32LE:
file.Write("\xFF\xFE\x00\x00", 4);
break;
case wxFONTENCODING_UTF16BE:
file.Write("\xFE\xFF", 2);
break;
case wxFONTENCODING_UTF16LE:
file.Write("\xFF\xFE", 2);
break;
case wxFONTENCODING_UTF8:
file.Write("\xEF\xBB\xBF", 3);
break;
case wxFONTENCODING_UTF7:
file.Write("\x2B\x2F\x76\x38\x2D", 5);
break;
default:
wxASSERT(false);
}
}
// Prepare converter & buffers
wxFontEncoding enc = propEncoding == wxFONTENCODING_DEFAULT ? wxFONTENCODING_SYSTEM : propEncoding;
wxCSConv conv(enc);
size_t utf8_buff_len = 128;
wxCharBuffer utf8_buff(utf8_buff_len);
size_t wchar_buff_len = 128;
wxWCharBuffer wchar_buff(wchar_buff_len);
size_t out_buff_len = 128;
wxCharBuffer out_buff(out_buff_len);
// Convert and save one line at a time
int len = GetLength();
unsigned int line_start = 0;
for(doc_byte_iter dbi(*this); dbi.GetIndex() < len; ++dbi) {
if (*dbi == '\n') {
// Define the line
unsigned int line_end = dbi.GetIndex();
if (eol == wxTextFileType_Unix) ++line_end; // Only include newline in conversion when same as internal
unsigned int line_len = line_end - line_start;
if (line_len) {
// Copy line into temp buffer
if (utf8_buff_len < line_len+1) {
utf8_buff_len = line_len+1;
utf8_buff = wxCharBuffer(utf8_buff_len);
}
m_textData.GetNodeTextPart((unsigned char*)utf8_buff.data(), GetHeadnode(), line_start, line_end);
utf8_buff.data()[line_len] = '\0';
// Write line to file
if (enc == wxFONTENCODING_UTF8) file.Write(utf8_buff.data(), line_len);
else {
size_t out_len = ConvertFromUTF8(utf8_buff, conv, wchar_buff, wchar_buff_len, out_buff, out_buff_len, char_len);
if (out_len == (size_t)-1) {
goto conv_failed; // Conversion failed
}
if (out_len) file.Write(out_buff.data(), out_len);
}
}
if (eol != wxTextFileType_Unix) file.Write(nl, nl_len);
line_start = dbi.GetIndex() + 1;
}
else if ((char)*dbi == '\xEF' && dbi.GetIndex()+2 < len) { // Check for null stand-in & conv to real nulls if needed
if ((char)dbi[1] == '\xA3' && (char)dbi[2] == '\xBF') {
// Define the line
unsigned int line_end = dbi.GetIndex();
unsigned int line_len = line_end - line_start;
if (line_len) {
// Copy line into temp buffer
if (utf8_buff_len < line_len+1) {
utf8_buff_len = line_len+1;
utf8_buff = wxCharBuffer(utf8_buff_len);
}
m_textData.GetNodeTextPart((unsigned char*)utf8_buff.data(), GetHeadnode(), line_start, line_end);
utf8_buff.data()[line_len] = '\0';
// Write line to file
if (enc == wxFONTENCODING_UTF8) file.Write(utf8_buff.data(), line_len);
else {
size_t out_len = ConvertFromUTF8(utf8_buff, conv, wchar_buff, wchar_buff_len, out_buff, out_buff_len, char_len);
if (out_len == (size_t)-1) {
goto conv_failed; // Conversion failed
}
if (out_len) file.Write(out_buff.data(), out_len);
}
}
file.Write(nulls, char_len);
line_start = dbi.GetIndex() + 3;
dbi += 2;
}
}
}
if ((int)line_start < len) { // Save rest after last newline
unsigned int line_len = len - line_start;
// Copy line into temp buffer
if (utf8_buff_len < line_len+1) {
utf8_buff_len = line_len+1;
utf8_buff = wxCharBuffer(utf8_buff_len);
}
m_textData.GetNodeTextPart((unsigned char*)utf8_buff.data(), GetHeadnode(), line_start, len);
utf8_buff.data()[line_len] = '\0';