/
Buffer.cpp
1767 lines (1479 loc) · 53.2 KB
/
Buffer.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
// This file is part of Notepad++ project
// Copyright (C)2021 Don HO <don.h@free.fr>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// at your option any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
#include <deque>
#include <algorithm>
#include <time.h>
#include <locale>
#include <codecvt>
#include <sys/stat.h>
#include "Buffer.h"
#include "Scintilla.h"
#include "ILexer.h"
#include "Lexilla.h"
#include "Parameters.h"
#include "Notepad_plus.h"
#include "ScintillaEditView.h"
#include "EncodingMapper.h"
#include "uchardet.h"
#include "FileInterface.h"
static const int blockSize = 128 * 1024 + 4;
static const int CR = 0x0D;
static const int LF = 0x0A;
long Buffer::_recentTagCtr = 0;
namespace // anonymous
{
static EolType getEOLFormatForm(const char* const data, size_t length, EolType defvalue = EolType::osdefault)
{
assert(length == 0 || (data != nullptr && "invalid buffer for getEOLFormatForm()"));
for (size_t i = 0; i != length; ++i)
{
if (data[i] == CR)
{
if (i + 1 < length && data[i + 1] == LF)
return EolType::windows;
return EolType::macos;
}
if (data[i] == LF)
return EolType::unix;
}
return defvalue; // fallback unknown
}
} // anonymous namespace
Buffer::Buffer(FileManager * pManager, BufferID id, Document doc, DocFileStatus type, const TCHAR *fileName, bool isLargeFile)
// type must be either DOC_REGULAR or DOC_UNNAMED
: _pManager(pManager) , _id(id), _doc(doc), _lang(L_TEXT), _isLargeFile(isLargeFile)
{
NppParameters& nppParamInst = NppParameters::getInstance();
const NewDocDefaultSettings& ndds = (nppParamInst.getNppGUI()).getNewDocDefaultSettings();
_eolFormat = ndds._format;
_unicodeMode = ndds._unicodeMode;
_encoding = ndds._codepage;
if (_encoding != -1)
_unicodeMode = uniCookie;
_currentStatus = type;
setFileName(fileName);
updateTimeStamp();
checkFileState();
// reset after initialization
_canNotify = true;
}
void Buffer::doNotify(int mask)
{
if (_canNotify)
{
assert(_pManager != nullptr);
_pManager->beNotifiedOfBufferChange(this, mask);
}
}
void Buffer::setDirty(bool dirty)
{
_isDirty = dirty;
doNotify(BufferChangeDirty);
}
void Buffer::setEncoding(int encoding)
{
_encoding = encoding;
doNotify(BufferChangeUnicode | BufferChangeDirty);
}
void Buffer::setUnicodeMode(UniMode mode)
{
_unicodeMode = mode;
doNotify(BufferChangeUnicode | BufferChangeDirty);
}
void Buffer::setLangType(LangType lang, const TCHAR* userLangName)
{
if (lang == _lang && lang != L_USER)
return;
_lang = lang;
if (_lang == L_USER)
_userLangExt = userLangName;
_needLexer = true; //change of lang means lexern needs updating
doNotify(BufferChangeLanguage|BufferChangeLexing);
}
void Buffer::updateTimeStamp()
{
FILETIME timeStampLive = {};
WIN32_FILE_ATTRIBUTE_DATA attributes{};
if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
timeStampLive = attributes.ftLastWriteTime;
}
LONG res = CompareFileTime(&_timeStamp, &timeStampLive);
if (res == -1 || res == 1)
// (res == -1) => timeStampLive is later, it means the file has been modified outside of Notepad++ - usual case
//
// (res == 1) => timeStampLive (get directly from the file on disk) is earlier than buffer's timestamp - unusual case
// It can happen when user copies a backup of editing file somewhere-else firstly, then modifies the editing file in Notepad++ and saves it.
// Now user copies the backup back to erase the modified editing file outside Notepad++ (via Explorer).
{
if (res == 1)
{
NppParameters& nppParam = NppParameters::getInstance();
if (nppParam.doNppLogNetworkDriveIssue())
{
generic_string issueFn = nppLogNetworkDriveIssue;
issueFn += TEXT(".log");
generic_string nppIssueLog = nppParam.getUserPath();
pathAppend(nppIssueLog, issueFn);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string msg = converter.to_bytes(_fullPathName);
char buf[1024];
sprintf(buf, " in updateTimeStamp(): timeStampLive (%lu/%lu) < _timeStamp (%lu/%lu)", timeStampLive.dwLowDateTime, timeStampLive.dwHighDateTime, _timeStamp.dwLowDateTime, _timeStamp.dwHighDateTime);
msg += buf;
writeLog(nppIssueLog.c_str(), msg.c_str());
}
}
_timeStamp = timeStampLive;
doNotify(BufferChangeTimestamp);
}
// else (res == 0) => nothing to change
}
// Set full path file name in buffer object,
// and determinate its language by its extension.
void Buffer::setFileName(const TCHAR *fn)
{
NppParameters& nppParamInst = NppParameters::getInstance();
if (_fullPathName == fn)
{
updateTimeStamp();
doNotify(BufferChangeTimestamp);
return;
}
_fullPathName = fn;
_fileName = PathFindFileName(_fullPathName.c_str());
// for _lang
LangType determinatedLang = L_TEXT;
TCHAR *ext = PathFindExtension(_fullPathName.c_str());
if (*ext == '.') // extension found
{
ext += 1;
// Define User Lang firstly
const TCHAR* langName = nppParamInst.getUserDefinedLangNameFromExt(ext, _fileName);
if (langName)
{
determinatedLang = L_USER;
_userLangExt = langName;
}
else // if it's not user lang, then check if it's supported lang
{
_userLangExt.clear();
determinatedLang = nppParamInst.getLangFromExt(ext);
}
}
if (determinatedLang == L_TEXT) //language can probably be refined
{
if ((OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("makefile")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("GNUmakefile")) == 0))
determinatedLang = L_MAKEFILE;
else if (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("CmakeLists.txt")) == 0)
determinatedLang = L_CMAKE;
else if ((OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("SConstruct")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("SConscript")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("wscript")) == 0))
determinatedLang = L_PYTHON;
else if ((OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("Rakefile")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("Vagrantfile")) == 0))
determinatedLang = L_RUBY;
else if ((OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("crontab")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("PKGBUILD")) == 0) || (OrdinalIgnoreCaseCompareStrings(_fileName, TEXT("APKBUILD")) == 0))
determinatedLang = L_BASH;
}
updateTimeStamp();
BufferStatusInfo lang2Change = BufferChangeNone;
if (!_hasLangBeenSetFromMenu && (determinatedLang != _lang || _lang == L_USER))
{
if (_isLargeFile)
{
_lang = L_TEXT;
}
else
{
_lang = determinatedLang;
lang2Change = BufferChangeLanguage;
}
}
doNotify(BufferChangeFilename | BufferChangeTimestamp | lang2Change);
}
bool Buffer::checkFileState() // returns true if the status has been changed (it can change into DOC_REGULAR too). false otherwise
{
// 1. Unsaved document cannot change by environment
// 2. Monitoring is sent by NPPM_INTERNAL_RELOADSCROLLTOEND
// So no need to check file status for both the above cases
if (_currentStatus == DOC_UNNAMED || isMonitoringOn())
return false;
WIN32_FILE_ATTRIBUTE_DATA attributes{};
bool isWow64Off = false;
NppParameters& nppParam = NppParameters::getInstance();
if (!PathFileExists(_fullPathName.c_str()))
{
nppParam.safeWow64EnableWow64FsRedirection(FALSE);
isWow64Off = true;
}
bool isOK = false;
if (_currentStatus != DOC_DELETED && !PathFileExists(_fullPathName.c_str())) //document has been deleted
{
_currentStatus = DOC_DELETED;
_isFileReadOnly = false;
_isDirty = true; //dirty sicne no match with filesystem
_timeStamp = {};
doNotify(BufferChangeStatus | BufferChangeReadonly | BufferChangeTimestamp);
isOK = true;
}
else if (_currentStatus == DOC_DELETED && PathFileExists(_fullPathName.c_str()))
{ //document has returned from its grave
if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
_isFileReadOnly = attributes.dwFileAttributes & FILE_ATTRIBUTE_READONLY;
_currentStatus = DOC_MODIFIED;
_timeStamp = attributes.ftLastWriteTime;
if (_reloadFromDiskRequestGuard.try_lock())
{
doNotify(BufferChangeStatus | BufferChangeReadonly | BufferChangeTimestamp);
_reloadFromDiskRequestGuard.unlock();
}
isOK = true;
}
}
else if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
int mask = 0; //status always 'changes', even if from modified to modified
bool isFileReadOnly = attributes.dwFileAttributes & FILE_ATTRIBUTE_READONLY;
if (isFileReadOnly != _isFileReadOnly)
{
_isFileReadOnly = isFileReadOnly;
mask |= BufferChangeReadonly;
}
LONG res = CompareFileTime(&_timeStamp, &attributes.ftLastWriteTime);
if (res == -1 || res == 1)
// (res == -1) => attributes.ftLastWriteTime is later, it means the file has been modified outside of Notepad++ - usual case
//
// (res == 1) => The timestamp get directly from the file on disk is earlier than buffer's timestamp - unusual case
// It can happen when user copies a backup of editing file somewhere-else firstly, then modifies the editing file in Notepad++ and saves it.
// Now user copies the backup back to erase the modified editing file outside Notepad++ (via Explorer).
{
if (res == 1)
{
NppParameters& nppParam = NppParameters::getInstance();
if (nppParam.doNppLogNetworkDriveIssue())
{
generic_string issueFn = nppLogNetworkDriveIssue;
issueFn += TEXT(".log");
generic_string nppIssueLog = nppParam.getUserPath();
pathAppend(nppIssueLog, issueFn);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string msg = converter.to_bytes(_fullPathName);
char buf[1024];
sprintf(buf, " in checkFileState(): attributes.ftLastWriteTime (%lu/%lu) < _timeStamp (%lu/%lu)", attributes.ftLastWriteTime.dwLowDateTime, attributes.ftLastWriteTime.dwHighDateTime, _timeStamp.dwLowDateTime, _timeStamp.dwHighDateTime);
msg += buf;
writeLog(nppIssueLog.c_str(), msg.c_str());
}
}
_timeStamp = attributes.ftLastWriteTime;
mask |= BufferChangeTimestamp;
_currentStatus = DOC_MODIFIED;
mask |= BufferChangeStatus; //status always 'changes', even if from modified to modified
}
// else res == 0 => nothing to change
if (mask != 0)
{
if (_reloadFromDiskRequestGuard.try_lock())
{
doNotify(mask);
_reloadFromDiskRequestGuard.unlock();
return true;
}
}
return false;
}
if (isWow64Off)
{
nppParam.safeWow64EnableWow64FsRedirection(TRUE);
}
return isOK;
}
void Buffer::reload()
{
WIN32_FILE_ATTRIBUTE_DATA attributes{};
if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
_timeStamp = attributes.ftLastWriteTime;
_currentStatus = DOC_NEEDRELOAD;
doNotify(BufferChangeTimestamp | BufferChangeStatus);
}
}
int64_t Buffer::getFileLength() const
{
if (_currentStatus == DOC_UNNAMED)
return -1;
WIN32_FILE_ATTRIBUTE_DATA attributes{};
if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
LARGE_INTEGER size{};
size.LowPart = attributes.nFileSizeLow;
size.HighPart = attributes.nFileSizeHigh;
return size.QuadPart;
}
return -1;
}
generic_string Buffer::getFileTime(fileTimeType ftt) const
{
generic_string result;
if (_currentStatus != DOC_UNNAMED)
{
WIN32_FILE_ATTRIBUTE_DATA attributes{};
if (GetFileAttributesEx(_fullPathName.c_str(), GetFileExInfoStandard, &attributes) != 0)
{
FILETIME rawtime;
switch (ftt)
{
case ft_created:
rawtime = attributes.ftCreationTime;
break;
case ft_modified:
rawtime = attributes.ftLastWriteTime;
break;
default:
rawtime = attributes.ftLastAccessTime;
break;
}
SYSTEMTIME utcSystemTime, localSystemTime;
FileTimeToSystemTime(&rawtime, &utcSystemTime);
SystemTimeToTzSpecificLocalTime(nullptr, &utcSystemTime, &localSystemTime);
const size_t dateTimeStrLen = 256;
TCHAR bufDate[dateTimeStrLen] = {'\0'};
GetDateFormat(LOCALE_USER_DEFAULT, 0, &localSystemTime, nullptr, bufDate, dateTimeStrLen);
result += bufDate;
result += ' ';
TCHAR bufTime[dateTimeStrLen] = {'\0'};
GetTimeFormat(LOCALE_USER_DEFAULT, 0, &localSystemTime, nullptr, bufTime, dateTimeStrLen);
result += bufTime;
}
}
return result;
}
void Buffer::setPosition(const Position & pos, ScintillaEditView * identifier)
{
int index = indexOfReference(identifier);
if (index == -1)
return;
_positions[index] = pos;
}
Position& Buffer::getPosition(ScintillaEditView* identifier)
{
int index = indexOfReference(identifier);
return _positions.at(index);
}
void Buffer::setHeaderLineState(const std::vector<size_t> & folds, ScintillaEditView * identifier)
{
int index = indexOfReference(identifier);
if (index == -1)
return;
//deep copy
std::vector<size_t> & local = _foldStates[index];
local.clear();
size_t size = folds.size();
for (size_t i = 0; i < size; ++i)
local.push_back(folds[i]);
}
const std::vector<size_t> & Buffer::getHeaderLineState(const ScintillaEditView * identifier) const
{
int index = indexOfReference(identifier);
return _foldStates.at(index);
}
Lang * Buffer::getCurrentLang() const
{
NppParameters& nppParam = NppParameters::getInstance();
int i = 0;
Lang *l = nppParam.getLangFromIndex(i);
++i;
while (l)
{
if (l->_langID == _lang)
return l;
l = nppParam.getLangFromIndex(i);
++i;
}
return nullptr;
}
int Buffer::indexOfReference(const ScintillaEditView * identifier) const
{
size_t size = _referees.size();
for (size_t i = 0; i < size; ++i)
{
if (_referees[i] == identifier)
return static_cast<int>(i);
}
return -1; //not found
}
int Buffer::addReference(ScintillaEditView * identifier)
{
if (indexOfReference(identifier) != -1)
return _references;
_referees.push_back(identifier);
_positions.push_back(Position());
_foldStates.push_back(std::vector<size_t>());
++_references;
return _references;
}
int Buffer::removeReference(ScintillaEditView * identifier)
{
int indexToPop = indexOfReference(identifier);
if (indexToPop == -1)
return _references;
_referees.erase(_referees.begin() + indexToPop);
_positions.erase(_positions.begin() + indexToPop);
_foldStates.erase(_foldStates.begin() + indexToPop);
_references--;
return _references;
}
void Buffer::setHideLineChanged(bool isHide, size_t location)
{
//First run through all docs without removing markers
for (int i = 0; i < _references; ++i)
_referees.at(i)->notifyMarkers(this, isHide, location, false); // (i == _references-1));
if (!isHide) // no deleting if hiding lines
{
//Then all docs to remove markers.
for (int i = 0; i < _references; ++i)
_referees.at(i)->notifyMarkers(this, isHide, location, true);
}
}
void Buffer::setDeferredReload() // triggers a reload on the next Document access
{
_isDirty = false; //when reloading, just set to false, since it should be marked as clean
_needReloading = true;
doNotify(BufferChangeDirty);
}
bool Buffer::allowBraceMach() const
{
NppGUI& nppGui = NppParameters::getInstance().getNppGUI();
return (!_isLargeFile || nppGui._largeFileRestriction._allowBraceMatch) || !nppGui._largeFileRestriction._isEnabled;
}
bool Buffer::allowAutoCompletion() const
{
NppGUI& nppGui = NppParameters::getInstance().getNppGUI();
return (!_isLargeFile || nppGui._largeFileRestriction._allowAutoCompletion) || !nppGui._largeFileRestriction._isEnabled;
}
bool Buffer::allowSmartHilite() const
{
NppGUI& nppGui = NppParameters::getInstance().getNppGUI();
return (!_isLargeFile || nppGui._largeFileRestriction._allowSmartHilite) || !nppGui._largeFileRestriction._isEnabled;
}
bool Buffer::allowClickableLink() const
{
NppGUI& nppGui = NppParameters::getInstance().getNppGUI();
return (!_isLargeFile || nppGui._largeFileRestriction._allowClickableLink) || !nppGui._largeFileRestriction._isEnabled;
}
//filemanager
FileManager::~FileManager()
{
for (std::vector<Buffer *>::iterator it = _buffers.begin(), end = _buffers.end(); it != end; ++it)
{
delete *it;
}
}
void FileManager::init(Notepad_plus * pNotepadPlus, ScintillaEditView * pscratchTilla)
{
_pNotepadPlus = pNotepadPlus;
_pscratchTilla = pscratchTilla;
_pscratchTilla->execute(SCI_SETUNDOCOLLECTION, false); //dont store any undo information
_scratchDocDefault = (Document)_pscratchTilla->execute(SCI_GETDOCPOINTER);
_pscratchTilla->execute(SCI_ADDREFDOCUMENT, 0, _scratchDocDefault);
}
void FileManager::checkFilesystemChanges(bool bCheckOnlyCurrentBuffer)
{
if (bCheckOnlyCurrentBuffer)
{
Buffer* buffer = _pNotepadPlus->getCurrentBuffer();
buffer->checkFileState();
}
else
{
for (int i = int(_nbBufs) - 1; i >= 0; i--)
{
if (i >= int(_nbBufs))
{
if (_nbBufs == 0)
return;
i = int(_nbBufs) - 1;
}
_buffers[i]->checkFileState(); //something has changed. Triggers update automatically
}
}
}
size_t FileManager::getNbDirtyBuffers() const
{
size_t nb_dirtyBufs = 0;
for (size_t i = 0; i < _nbBufs; ++i)
{
if (_buffers[i]->_isDirty)
++nb_dirtyBufs;
}
return nb_dirtyBufs;
}
int FileManager::getBufferIndexByID(BufferID id)
{
for (size_t i = 0; i < _nbBufs; ++i)
{
if (_buffers[i]->_id == id)
return static_cast<int>(i);
}
return -1;
}
Buffer* FileManager::getBufferByIndex(size_t index)
{
if (index >= _buffers.size())
return nullptr;
return _buffers.at(index);
}
void FileManager::beNotifiedOfBufferChange(Buffer* theBuf, int mask)
{
_pNotepadPlus->notifyBufferChanged(theBuf, mask);
}
void FileManager::addBufferReference(BufferID buffer, ScintillaEditView * identifier)
{
Buffer* buf = getBufferByID(buffer);
buf->addReference(identifier);
}
void FileManager::closeBuffer(BufferID id, ScintillaEditView * identifier)
{
int index = getBufferIndexByID(id);
Buffer* buf = getBufferByIndex(index);
int refs = buf->removeReference(identifier);
if (!refs) // buffer can be deallocated
{
_pscratchTilla->execute(SCI_RELEASEDOCUMENT, 0, buf->_doc); //release for FileManager, Document is now gone
_buffers.erase(_buffers.begin() + index);
delete buf;
_nbBufs--;
}
}
// backupFileName is sentinel of backup mode: if it's not NULL, then we use it (load it). Otherwise we use filename
BufferID FileManager::loadFile(const TCHAR* filename, Document doc, int encoding, const TCHAR* backupFileName, FILETIME fileNameTimestamp)
{
if (!filename)
return BUFFER_INVALID;
//Get file size
int64_t fileSize = -1;
const TCHAR* pPath = filename;
if (!::PathFileExists(pPath))
{
pPath = backupFileName;
}
if (pPath)
{
FILE* fp = _wfopen(pPath, TEXT("rb"));
if (fp)
{
_fseeki64(fp, 0, SEEK_END);
fileSize = _ftelli64(fp);
fclose(fp);
}
}
// * the auto-completion feature will be disabled for large files
// * the session snapshotsand periodic backups feature will be disabled for large files
// * the backups on save feature will be disabled for large files
NppGUI& nppGui = NppParameters::getInstance().getNppGUI();
bool isLargeFile = false;
if (nppGui._largeFileRestriction._isEnabled)
isLargeFile = fileSize >= nppGui._largeFileRestriction._largeFileSizeDefInByte;
// Due to the performance issue, the Word Wrap feature will be disabled if it's ON
if (isLargeFile && nppGui._largeFileRestriction._deactivateWordWrap)
{
bool isWrap = _pNotepadPlus->_pEditView->isWrap();
if (isWrap)
{
_pNotepadPlus->command(IDM_VIEW_WRAP);
}
}
bool ownDoc = false;
if (!doc)
{
// If file exceeds 200MB, activate large file mode
doc = (Document)_pscratchTilla->execute(SCI_CREATEDOCUMENT, 0, isLargeFile ? SC_DOCUMENTOPTION_STYLES_NONE | SC_DOCUMENTOPTION_TEXT_LARGE : 0);
ownDoc = true;
}
WCHAR fullpath[MAX_PATH] = { 0 };
if (isWin32NamespacePrefixedFileName(filename))
{
// use directly the raw file name, skip the GetFullPathName WINAPI
wcsncpy_s(fullpath, _countof(fullpath), filename, _TRUNCATE);
}
else
{
::GetFullPathName(filename, MAX_PATH, fullpath, NULL);
if (wcschr(fullpath, '~'))
{
::GetLongPathName(fullpath, fullpath, MAX_PATH);
}
}
bool isSnapshotMode = backupFileName != NULL && PathFileExists(backupFileName);
if (isSnapshotMode && !PathFileExists(fullpath)) // if backup mode and fullpath doesn't exist, we guess is UNTITLED
{
wcscpy_s(fullpath, MAX_PATH, filename); // we restore fullpath with filename, in our case is "new #"
}
Utf8_16_Read UnicodeConvertor; //declare here so we can get information after loading is done
char* data = new char[blockSize + 8]; // +8 for incomplete multibyte char
LoadedFileFormat loadedFileFormat;
loadedFileFormat._encoding = encoding;
loadedFileFormat._eolFormat = EolType::unknown;
loadedFileFormat._language = L_TEXT;
bool res = loadFileData(doc, fileSize, backupFileName ? backupFileName : fullpath, data, &UnicodeConvertor, loadedFileFormat);
delete[] data;
if (res)
{
Buffer* newBuf = new Buffer(this, _nextBufferID, doc, DOC_REGULAR, fullpath, isLargeFile);
BufferID id = newBuf;
newBuf->_id = id;
if (backupFileName != NULL)
{
newBuf->_backupFileName = backupFileName;
if (!PathFileExists(fullpath))
newBuf->_currentStatus = DOC_UNNAMED;
}
const FILETIME zeroTimeStamp = {};
LONG res = CompareFileTime(&fileNameTimestamp, &zeroTimeStamp);
if (res != 0) // res == 1 or res == -1
newBuf->_timeStamp = fileNameTimestamp;
_buffers.push_back(newBuf);
++_nbBufs;
Buffer* buf = _buffers.at(_nbBufs - 1);
// restore the encoding (ANSI based) while opening the existing file
buf->setEncoding(-1);
// if not a large file, no file extension, and the language has been detected, we use the detected value
if (!newBuf->_isLargeFile && ((buf->getLangType() == L_TEXT) && (loadedFileFormat._language != L_TEXT)))
buf->setLangType(loadedFileFormat._language);
setLoadedBufferEncodingAndEol(buf, UnicodeConvertor, loadedFileFormat._encoding, loadedFileFormat._eolFormat);
//determine buffer properties
++_nextBufferID;
return id;
}
else //failed loading, release document
{
if (ownDoc)
_pscratchTilla->execute(SCI_RELEASEDOCUMENT, 0, doc); //Failure, so release document
return BUFFER_INVALID;
}
}
bool FileManager::reloadBuffer(BufferID id)
{
Buffer* buf = getBufferByID(id);
Document doc = buf->getDocument();
Utf8_16_Read UnicodeConvertor;
LoadedFileFormat loadedFileFormat;
loadedFileFormat._encoding = buf->getEncoding();
loadedFileFormat._eolFormat = EolType::unknown;
loadedFileFormat._language = buf->getLangType();
buf->setLoadedDirty(false); // Since the buffer will be reloaded from the disk, and it will be clean (not dirty), we can set _isLoadedDirty false safetly.
// Set _isLoadedDirty false before calling "_pscratchTilla->execute(SCI_CLEARALL);" in loadFileData() to avoid setDirty in SCN_SAVEPOINTREACHED / SCN_SAVEPOINTLEFT
//Get file size
FILE* fp = _wfopen(buf->getFullPathName(), TEXT("rb"));
if (!fp)
return false;
_fseeki64(fp, 0, SEEK_END);
int64_t fileSize = _ftelli64(fp);
fclose(fp);
char* data = new char[blockSize + 8]; // +8 for incomplete multibyte char
buf->_canNotify = false; //disable notify during file load, we don't want dirty status to be triggered
bool res = loadFileData(doc, fileSize, buf->getFullPathName(), data, &UnicodeConvertor, loadedFileFormat);
buf->_canNotify = true;
delete[] data;
if (res)
{
// now we are synchronized with the file on disk, so reset relevant flags
buf->setUnsync(false);
buf->setDirty(false); // if the _isUnsync was true before the reloading, the _isDirty had been set to true somehow in the loadFileData()
buf->setSavePointDirty(false);
setLoadedBufferEncodingAndEol(buf, UnicodeConvertor, loadedFileFormat._encoding, loadedFileFormat._eolFormat);
}
return res;
}
void FileManager::setLoadedBufferEncodingAndEol(Buffer* buf, const Utf8_16_Read& UnicodeConvertor, int encoding, EolType bkformat)
{
if (encoding == -1)
{
NppParameters& nppParamInst = NppParameters::getInstance();
const NewDocDefaultSettings & ndds = (nppParamInst.getNppGUI()).getNewDocDefaultSettings();
UniMode um = UnicodeConvertor.getEncoding();
if (um == uni7Bit)
um = (ndds._openAnsiAsUtf8) ? uniCookie : uni8Bit;
buf->setUnicodeMode(um);
}
else
{
// Test if encoding is set to UTF8 w/o BOM (usually for utf8 indicator of xml or html)
buf->setEncoding((encoding == SC_CP_UTF8)?-1:encoding);
buf->setUnicodeMode(uniCookie);
}
// Since the buffer will be reloaded from the disk, EOL might have been changed
if (bkformat != EolType::unknown)
buf->setEolFormat(bkformat);
}
bool FileManager::reloadBufferDeferred(BufferID id)
{
Buffer* buf = getBufferByID(id);
buf->setDeferredReload();
return true;
}
bool FileManager::deleteFile(BufferID id)
{
Buffer* buf = getBufferByID(id);
generic_string fileNamePath = buf->getFullPathName();
// Make sure to form a string with double '\0' terminator.
fileNamePath.append(1, '\0');
if (!PathFileExists(fileNamePath.c_str()))
return false;
SHFILEOPSTRUCT fileOpStruct = {};
fileOpStruct.hwnd = NULL;
fileOpStruct.pFrom = fileNamePath.c_str();
fileOpStruct.pTo = NULL;
fileOpStruct.wFunc = FO_DELETE;
fileOpStruct.fFlags = FOF_ALLOWUNDO;
fileOpStruct.fAnyOperationsAborted = false;
fileOpStruct.hNameMappings = NULL;
fileOpStruct.lpszProgressTitle = NULL;
return SHFileOperation(&fileOpStruct) == 0;
}
bool FileManager::moveFile(BufferID id, const TCHAR * newFileName)
{
Buffer* buf = getBufferByID(id);
const TCHAR *fileNamePath = buf->getFullPathName();
if (::MoveFileEx(fileNamePath, newFileName, MOVEFILE_REPLACE_EXISTING | MOVEFILE_COPY_ALLOWED | MOVEFILE_WRITE_THROUGH) == 0)
return false;
buf->setFileName(newFileName);
return true;
}
/*
Specs and Algorithm of session snapshot & periodic backup system:
Notepad++ quits without asking for saving unsaved file.
It restores all the unsaved files and document as the states they left.
For existing file (c:\tmp\foo.h)
- Open
In the next session, Notepad++
1. load backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) if exist, otherwise load FILENAME (c:\tmp\foo.h).
2. if backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) is loaded, set it dirty (red).
3. if backup\FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) is loaded, last modif timestamp of FILENAME (c:\tmp\foo.h), compare with tracked timestamp (in session.xml).
4. in the case of unequal result, tell user the FILENAME (c:\tmp\foo.h) was modified. ask user if he want to reload FILENAME(c:\tmp\foo.h)
- Editing
when a file starts being modified, a file will be created with name: FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776)
the Buffer object will associate with this FILENAME@CREATION_TIMESTAMP file (backup\foo.h@198776).
1. sync: (each 3-5 second) backup file will be saved, if buffer is dirty, and modification is present (a bool on modified notificatin).
2. sync: each save file, or close file, the backup file will be deleted (if buffer is not dirty).
3. before switch off to another tab (or close files on exit), check 1 & 2 (sync with backup).
- Close
In the current session, Notepad++
1. track FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) if exist (in session.xml).
2. track last modified timestamp of FILENAME (c:\tmp\foo.h) if FILENAME@CREATION_TIMESTAMP (backup\foo.h@198776) was tracked (in session.xml).
For untitled document (new 4)
- Open
In the next session, Notepad++
1. open file UNTITLED_NAME@CREATION_TIMESTAMP (backup\new 4@198776)
2. set label as UNTITLED_NAME (new 4) and disk icon as red.
- Editing
when a untitled document starts being modified, a backup file will be created with name: UNTITLED_NAME@CREATION_TIMESTAMP (backup\new 4@198776)
the Buffer object will associate with this UNTITLED_NAME@CREATION_TIMESTAMP file (backup\new 4@198776).
1. sync: (each 3-5 second) backup file will be saved, if buffer is dirty, and modification is present (a bool on modified notificatin).
2. sync: if untitled document is saved, or closed, the backup file will be deleted.
3. before switch off to another tab (or close documents on exit), check 1 & 2 (sync with backup).
- CLOSE
In the current session, Notepad++
1. track UNTITLED_NAME@CREATION_TIMESTAMP (backup\new 4@198776) in session.xml.
*/
std::mutex backup_mutex;
bool FileManager::backupCurrentBuffer()
{
Buffer* buffer = _pNotepadPlus->getCurrentBuffer();
if (buffer->isLargeFile())
return false;
std::lock_guard<std::mutex> lock(backup_mutex);
bool result = false;
bool hasModifForSession = false;
if (buffer->isDirty())
{
if (buffer->isModified()) // buffer dirty and modified, write the backup file
{
UniMode mode = buffer->getUnicodeMode();
if (mode == uniCookie)
mode = uni8Bit; //set the mode to ANSI to prevent converter from adding BOM and performing conversions, Scintilla's data can be copied directly
Utf8_16_Write UnicodeConvertor;
UnicodeConvertor.setEncoding(mode);
int encoding = buffer->getEncoding();
generic_string backupFilePath = buffer->getBackupFileName();
if (backupFilePath.empty())
{
// Create file
backupFilePath = NppParameters::getInstance().getUserPath();
backupFilePath += TEXT("\\backup\\");
// if "backup" folder doesn't exist, create it.
if (!PathFileExists(backupFilePath.c_str()))
{
::CreateDirectory(backupFilePath.c_str(), NULL);
}
backupFilePath += buffer->getFileName();
const int temBufLen = 32;
TCHAR tmpbuf[temBufLen];