-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
Common.cpp
1715 lines (1477 loc) · 45.2 KB
/
Common.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 <algorithm>
#include <stdexcept>
#include <shlwapi.h>
#include <uxtheme.h>
#include <cassert>
#include <codecvt>
#include <locale>
#include "StaticDialog.h"
#include "CustomFileDialog.h"
#include "FileInterface.h"
#include "Common.h"
#include "Utf8.h"
#include <Parameters.h>
#include "Buffer.h"
void printInt(int int2print)
{
TCHAR str[32];
wsprintf(str, TEXT("%d"), int2print);
::MessageBox(NULL, str, TEXT(""), MB_OK);
}
void printStr(const TCHAR *str2print)
{
::MessageBox(NULL, str2print, TEXT(""), MB_OK);
}
generic_string commafyInt(size_t n)
{
generic_stringstream ss;
ss.imbue(std::locale(""));
ss << n;
return ss.str();
}
std::string getFileContent(const TCHAR *file2read)
{
if (!::PathFileExists(file2read))
return "";
const size_t blockSize = 1024;
char data[blockSize];
std::string wholeFileContent = "";
FILE *fp = generic_fopen(file2read, TEXT("rb"));
size_t lenFile = 0;
do
{
lenFile = fread(data, 1, blockSize, fp);
if (lenFile <= 0) break;
wholeFileContent.append(data, lenFile);
}
while (lenFile > 0);
fclose(fp);
return wholeFileContent;
}
char getDriveLetter()
{
char drive = '\0';
TCHAR current[MAX_PATH];
::GetCurrentDirectory(MAX_PATH, current);
int driveNbr = ::PathGetDriveNumber(current);
if (driveNbr != -1)
drive = 'A' + char(driveNbr);
return drive;
}
generic_string relativeFilePathToFullFilePath(const TCHAR *relativeFilePath)
{
generic_string fullFilePathName;
TCHAR fullFileName[MAX_PATH];
BOOL isRelative = ::PathIsRelative(relativeFilePath);
if (isRelative)
{
::GetFullPathName(relativeFilePath, MAX_PATH, fullFileName, NULL);
fullFilePathName += fullFileName;
}
else
{
if ((relativeFilePath[0] == '\\' && relativeFilePath[1] != '\\') || relativeFilePath[0] == '/')
{
fullFilePathName += getDriveLetter();
fullFilePathName += ':';
}
fullFilePathName += relativeFilePath;
}
return fullFilePathName;
}
void writeFileContent(const TCHAR *file2write, const char *content2write)
{
Win32_IO_File file(file2write);
if (file.isOpened())
file.writeStr(content2write);
}
void writeLog(const TCHAR *logFileName, const char *log2write)
{
const DWORD accessParam{ GENERIC_READ | GENERIC_WRITE };
const DWORD shareParam{ FILE_SHARE_READ | FILE_SHARE_WRITE };
const DWORD dispParam{ OPEN_ALWAYS }; // Open existing file for writing without destroying it or create new
const DWORD attribParam{ FILE_ATTRIBUTE_NORMAL };
HANDLE hFile = ::CreateFileW(logFileName, accessParam, shareParam, NULL, dispParam, attribParam, NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
LARGE_INTEGER offset;
offset.QuadPart = 0;
::SetFilePointerEx(hFile, offset, NULL, FILE_END);
SYSTEMTIME currentTime = {};
::GetLocalTime(¤tTime);
generic_string dateTimeStrW = getDateTimeStrFrom(TEXT("yyyy-MM-dd HH:mm:ss"), currentTime);
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
std::string log2writeStr = converter.to_bytes(dateTimeStrW);
log2writeStr += " ";
log2writeStr += log2write;
log2writeStr += "\n";
DWORD bytes_written = 0;
::WriteFile(hFile, log2writeStr.c_str(), static_cast<DWORD>(log2writeStr.length()), &bytes_written, NULL);
::FlushFileBuffers(hFile);
::CloseHandle(hFile);
}
}
generic_string folderBrowser(HWND parent, const generic_string & title, int outputCtrlID, const TCHAR *defaultStr)
{
generic_string folderName;
CustomFileDialog dlg(parent);
dlg.setTitle(title.c_str());
// Get an initial directory from the edit control or from argument provided
TCHAR directory[MAX_PATH] = {};
if (outputCtrlID != 0)
::GetDlgItemText(parent, outputCtrlID, directory, _countof(directory));
directory[_countof(directory) - 1] = '\0';
if (!directory[0] && defaultStr)
dlg.setFolder(defaultStr);
else if (directory[0])
dlg.setFolder(directory);
folderName = dlg.pickFolder();
if (!folderName.empty())
{
// Send the result back to the edit control
if (outputCtrlID != 0)
::SetDlgItemText(parent, outputCtrlID, folderName.c_str());
}
return folderName;
}
generic_string getFolderName(HWND parent, const TCHAR *defaultDir)
{
return folderBrowser(parent, TEXT("Select a folder"), 0, defaultDir);
}
void ClientRectToScreenRect(HWND hWnd, RECT* rect)
{
POINT pt;
pt.x = rect->left;
pt.y = rect->top;
::ClientToScreen( hWnd, &pt );
rect->left = pt.x;
rect->top = pt.y;
pt.x = rect->right;
pt.y = rect->bottom;
::ClientToScreen( hWnd, &pt );
rect->right = pt.x;
rect->bottom = pt.y;
}
std::vector<generic_string> tokenizeString(const generic_string & tokenString, const char delim)
{
//Vector is created on stack and copied on return
std::vector<generic_string> tokens;
// Skip delimiters at beginning.
generic_string::size_type lastPos = tokenString.find_first_not_of(delim, 0);
// Find first "non-delimiter".
generic_string::size_type pos = tokenString.find_first_of(delim, lastPos);
while (pos != std::string::npos || lastPos != std::string::npos)
{
// Found a token, add it to the vector.
tokens.push_back(tokenString.substr(lastPos, pos - lastPos));
// Skip delimiters. Note the "not_of"
lastPos = tokenString.find_first_not_of(delim, pos);
// Find next "non-delimiter"
pos = tokenString.find_first_of(delim, lastPos);
}
return tokens;
}
void ScreenRectToClientRect(HWND hWnd, RECT* rect)
{
POINT pt;
pt.x = rect->left;
pt.y = rect->top;
::ScreenToClient( hWnd, &pt );
rect->left = pt.x;
rect->top = pt.y;
pt.x = rect->right;
pt.y = rect->bottom;
::ScreenToClient( hWnd, &pt );
rect->right = pt.x;
rect->bottom = pt.y;
}
int filter(unsigned int code, struct _EXCEPTION_POINTERS *)
{
if (code == EXCEPTION_ACCESS_VIOLATION)
return EXCEPTION_EXECUTE_HANDLER;
return EXCEPTION_CONTINUE_SEARCH;
}
bool isInList(const TCHAR *token, const TCHAR *list)
{
if ((!token) || (!list))
return false;
const size_t wordLen = 64;
size_t listLen = lstrlen(list);
TCHAR word[wordLen];
size_t i = 0;
size_t j = 0;
for (; i <= listLen; ++i)
{
if ((list[i] == ' ')||(list[i] == '\0'))
{
if (j != 0)
{
word[j] = '\0';
j = 0;
if (!generic_stricmp(token, word))
return true;
}
}
else
{
word[j] = list[i];
++j;
if (j >= wordLen)
return false;
}
}
return false;
}
generic_string purgeMenuItemString(const TCHAR * menuItemStr, bool keepAmpersand)
{
const size_t cleanedNameLen = 64;
TCHAR cleanedName[cleanedNameLen] = TEXT("");
size_t j = 0;
size_t menuNameLen = lstrlen(menuItemStr);
if (menuNameLen >= cleanedNameLen)
menuNameLen = cleanedNameLen - 1;
for (size_t k = 0 ; k < menuNameLen ; ++k)
{
if (menuItemStr[k] == '\t')
{
cleanedName[k] = 0;
break;
}
else
{
if (menuItemStr[k] == '&')
{
if (keepAmpersand)
cleanedName[j++] = menuItemStr[k];
//else skip
}
else
cleanedName[j++] = menuItemStr[k];
}
}
cleanedName[j] = 0;
return cleanedName;
}
const wchar_t * WcharMbcsConvertor::char2wchar(const char * mbcs2Convert, size_t codepage, int lenMbcs, int* pLenWc, int* pBytesNotProcessed)
{
// Do not process NULL pointer
if (!mbcs2Convert)
return nullptr;
// Do not process empty strings
if (lenMbcs == 0 || lenMbcs == -1 && mbcs2Convert[0] == 0)
{
_wideCharStr.empty();
return _wideCharStr;
}
UINT cp = static_cast<UINT>(codepage);
int bytesNotProcessed = 0;
int lenWc = 0;
// If length not specified, simply convert without checking
if (lenMbcs == -1)
{
lenWc = MultiByteToWideChar(cp, 0, mbcs2Convert, lenMbcs, NULL, 0);
}
// Otherwise, test if we are cutting a multi-byte character at end of buffer
else if (lenMbcs != -1 && cp == CP_UTF8) // For UTF-8, we know how to test it
{
int indexOfLastChar = Utf8::characterStart(mbcs2Convert, lenMbcs-1); // get index of last character
if (indexOfLastChar != 0 && !Utf8::isValid(mbcs2Convert+indexOfLastChar, lenMbcs-indexOfLastChar)) // if it is not valid we do not process it right now (unless its the only character in string, to ensure that we always progress, e.g. that bytesNotProcessed < lenMbcs)
{
bytesNotProcessed = lenMbcs-indexOfLastChar;
}
lenWc = MultiByteToWideChar(cp, 0, mbcs2Convert, lenMbcs-bytesNotProcessed, NULL, 0);
}
else // For other encodings, ask system if there are any invalid characters; note that it will not correctly know if last character is cut when there are invalid characters inside the text
{
lenWc = MultiByteToWideChar(cp, (lenMbcs == -1) ? 0 : MB_ERR_INVALID_CHARS, mbcs2Convert, lenMbcs, NULL, 0);
if (lenWc == 0 && GetLastError() == ERROR_NO_UNICODE_TRANSLATION)
{
// Test without last byte
if (lenMbcs > 1) lenWc = MultiByteToWideChar(cp, MB_ERR_INVALID_CHARS, mbcs2Convert, lenMbcs-1, NULL, 0);
if (lenWc == 0) // don't have to check that the error is still ERROR_NO_UNICODE_TRANSLATION, since only the length parameter changed
{
// TODO: should warn user about incorrect loading due to invalid characters
// We still load the file, but the system will either strip or replace invalid characters (including the last character, if cut in half)
lenWc = MultiByteToWideChar(cp, 0, mbcs2Convert, lenMbcs, NULL, 0);
}
else
{
// We found a valid text by removing one byte.
bytesNotProcessed = 1;
}
}
}
if (lenWc > 0)
{
_wideCharStr.sizeTo(lenWc);
MultiByteToWideChar(cp, 0, mbcs2Convert, lenMbcs-bytesNotProcessed, _wideCharStr, lenWc);
}
else
_wideCharStr.empty();
if (pLenWc)
*pLenWc = lenWc;
if (pBytesNotProcessed)
*pBytesNotProcessed = bytesNotProcessed;
return _wideCharStr;
}
// "mstart" and "mend" are pointers to indexes in mbcs2Convert,
// which are converted to the corresponding indexes in the returned wchar_t string.
const wchar_t * WcharMbcsConvertor::char2wchar(const char * mbcs2Convert, size_t codepage, intptr_t* mstart, intptr_t* mend)
{
// Do not process NULL pointer
if (!mbcs2Convert) return NULL;
UINT cp = static_cast<UINT>(codepage);
int len = MultiByteToWideChar(cp, 0, mbcs2Convert, -1, NULL, 0);
if (len > 0)
{
_wideCharStr.sizeTo(len);
len = MultiByteToWideChar(cp, 0, mbcs2Convert, -1, _wideCharStr, len);
if ((size_t)*mstart < strlen(mbcs2Convert) && (size_t)*mend <= strlen(mbcs2Convert))
{
*mstart = MultiByteToWideChar(cp, 0, mbcs2Convert, static_cast<int>(*mstart), _wideCharStr, 0);
*mend = MultiByteToWideChar(cp, 0, mbcs2Convert, static_cast<int>(*mend), _wideCharStr, 0);
if (*mstart >= len || *mend >= len)
{
*mstart = 0;
*mend = 0;
}
}
}
else
{
_wideCharStr.empty();
*mstart = 0;
*mend = 0;
}
return _wideCharStr;
}
const char* WcharMbcsConvertor::wchar2char(const wchar_t * wcharStr2Convert, size_t codepage, int lenWc, int* pLenMbcs)
{
if (nullptr == wcharStr2Convert)
return nullptr;
UINT cp = static_cast<UINT>(codepage);
int lenMbcs = WideCharToMultiByte(cp, 0, wcharStr2Convert, lenWc, NULL, 0, NULL, NULL);
if (lenMbcs > 0)
{
_multiByteStr.sizeTo(lenMbcs);
WideCharToMultiByte(cp, 0, wcharStr2Convert, lenWc, _multiByteStr, lenMbcs, NULL, NULL);
}
else
_multiByteStr.empty();
if (pLenMbcs)
*pLenMbcs = lenMbcs;
return _multiByteStr;
}
const char * WcharMbcsConvertor::wchar2char(const wchar_t * wcharStr2Convert, size_t codepage, intptr_t* mstart, intptr_t* mend)
{
if (nullptr == wcharStr2Convert)
return nullptr;
UINT cp = static_cast<UINT>(codepage);
int len = WideCharToMultiByte(cp, 0, wcharStr2Convert, -1, NULL, 0, NULL, NULL);
if (len > 0)
{
_multiByteStr.sizeTo(len);
len = WideCharToMultiByte(cp, 0, wcharStr2Convert, -1, _multiByteStr, len, NULL, NULL); // not needed?
if (*mstart < lstrlenW(wcharStr2Convert) && *mend < lstrlenW(wcharStr2Convert))
{
*mstart = WideCharToMultiByte(cp, 0, wcharStr2Convert, (int)*mstart, NULL, 0, NULL, NULL);
*mend = WideCharToMultiByte(cp, 0, wcharStr2Convert, (int)*mend, NULL, 0, NULL, NULL);
if (*mstart >= len || *mend >= len)
{
*mstart = 0;
*mend = 0;
}
}
}
else
_multiByteStr.empty();
return _multiByteStr;
}
std::wstring string2wstring(const std::string & rString, UINT codepage)
{
int len = MultiByteToWideChar(codepage, 0, rString.c_str(), -1, NULL, 0);
if (len > 0)
{
std::vector<wchar_t> vw(len);
MultiByteToWideChar(codepage, 0, rString.c_str(), -1, &vw[0], len);
return &vw[0];
}
return std::wstring();
}
std::string wstring2string(const std::wstring & rwString, UINT codepage)
{
int len = WideCharToMultiByte(codepage, 0, rwString.c_str(), -1, NULL, 0, NULL, NULL);
if (len > 0)
{
std::vector<char> vw(len);
WideCharToMultiByte(codepage, 0, rwString.c_str(), -1, &vw[0], len, NULL, NULL);
return &vw[0];
}
return std::string();
}
// Escapes ampersands in file name to use it in menu
template <typename T>
generic_string convertFileName(T beg, T end)
{
generic_string strTmp;
for (T it = beg; it != end; ++it)
{
if (*it == '&') strTmp.push_back('&');
strTmp.push_back(*it);
}
return strTmp;
}
generic_string intToString(int val)
{
std::vector<TCHAR> vt;
bool isNegative = val < 0;
// can't use abs here because std::numeric_limits<int>::min() has no positive representation
//val = std::abs(val);
vt.push_back('0' + static_cast<TCHAR>(std::abs(val % 10)));
val /= 10;
while (val != 0)
{
vt.push_back('0' + static_cast<TCHAR>(std::abs(val % 10)));
val /= 10;
}
if (isNegative)
vt.push_back('-');
return generic_string(vt.rbegin(), vt.rend());
}
generic_string uintToString(unsigned int val)
{
std::vector<TCHAR> vt;
vt.push_back('0' + static_cast<TCHAR>(val % 10));
val /= 10;
while (val != 0)
{
vt.push_back('0' + static_cast<TCHAR>(val % 10));
val /= 10;
}
return generic_string(vt.rbegin(), vt.rend());
}
// Build Recent File menu entries from given
generic_string BuildMenuFileName(int filenameLen, unsigned int pos, const generic_string &filename, bool ordinalNumber)
{
generic_string strTemp;
if (ordinalNumber)
{
if (pos < 9)
{
strTemp.push_back('&');
strTemp.push_back('1' + static_cast<TCHAR>(pos));
}
else if (pos == 9)
{
strTemp.append(TEXT("1&0"));
}
else
{
div_t splitDigits = div(pos + 1, 10);
strTemp.append(uintToString(splitDigits.quot));
strTemp.push_back('&');
strTemp.append(uintToString(splitDigits.rem));
}
strTemp.append(TEXT(": "));
}
else
{
strTemp.push_back('&');
}
if (filenameLen > 0)
{
std::vector<TCHAR> vt(filenameLen + 1);
// W removed from PathCompactPathExW due to compiler errors for ANSI version.
PathCompactPathEx(&vt[0], filename.c_str(), filenameLen + 1, 0);
strTemp.append(convertFileName(vt.begin(), vt.begin() + lstrlen(&vt[0])));
}
else
{
// (filenameLen < 0)
generic_string::const_iterator it = filename.begin();
if (filenameLen == 0)
it += PathFindFileName(filename.c_str()) - filename.c_str();
// MAX_PATH is still here to keep old trimming behaviour.
if (filename.end() - it < MAX_PATH)
{
strTemp.append(convertFileName(it, filename.end()));
}
else
{
strTemp.append(convertFileName(it, it + MAX_PATH / 2 - 3));
strTemp.append(TEXT("..."));
strTemp.append(convertFileName(filename.end() - MAX_PATH / 2, filename.end()));
}
}
return strTemp;
}
generic_string PathRemoveFileSpec(generic_string& path)
{
generic_string::size_type lastBackslash = path.find_last_of(TEXT('\\'));
if (lastBackslash == generic_string::npos)
{
if (path.size() >= 2 && path[1] == TEXT(':')) // "C:foo.bar" becomes "C:"
path.erase(2);
else
path.erase();
}
else
{
if (lastBackslash == 2 && path[1] == TEXT(':') && path.size() >= 3) // "C:\foo.exe" becomes "C:\"
path.erase(3);
else if (lastBackslash == 0 && path.size() > 1) // "\foo.exe" becomes "\"
path.erase(1);
else
path.erase(lastBackslash);
}
return path;
}
generic_string pathAppend(generic_string& strDest, const generic_string& str2append)
{
if (strDest.empty() && str2append.empty()) // "" + ""
{
strDest = TEXT("\\");
return strDest;
}
if (strDest.empty() && !str2append.empty()) // "" + titi
{
strDest = str2append;
return strDest;
}
if (strDest[strDest.length() - 1] == '\\' && (!str2append.empty() && str2append[0] == '\\')) // toto\ + \titi
{
strDest.erase(strDest.length() - 1, 1);
strDest += str2append;
return strDest;
}
if ((strDest[strDest.length() - 1] == '\\' && (!str2append.empty() && str2append[0] != '\\')) // toto\ + titi
|| (strDest[strDest.length() - 1] != '\\' && (!str2append.empty() && str2append[0] == '\\'))) // toto + \titi
{
strDest += str2append;
return strDest;
}
// toto + titi
strDest += TEXT("\\");
strDest += str2append;
return strDest;
}
COLORREF getCtrlBgColor(HWND hWnd)
{
COLORREF crRet = CLR_INVALID;
if (hWnd && IsWindow(hWnd))
{
RECT rc;
if (GetClientRect(hWnd, &rc))
{
HDC hDC = GetDC(hWnd);
if (hDC)
{
HDC hdcMem = CreateCompatibleDC(hDC);
if (hdcMem)
{
HBITMAP hBmp = CreateCompatibleBitmap(hDC,
rc.right, rc.bottom);
if (hBmp)
{
HGDIOBJ hOld = SelectObject(hdcMem, hBmp);
if (hOld)
{
if (SendMessage(hWnd, WM_ERASEBKGND, reinterpret_cast<WPARAM>(hdcMem), 0))
{
crRet = GetPixel(hdcMem, 2, 2); // 0, 0 is usually on the border
}
SelectObject(hdcMem, hOld);
}
DeleteObject(hBmp);
}
DeleteDC(hdcMem);
}
ReleaseDC(hWnd, hDC);
}
}
}
return crRet;
}
generic_string stringToUpper(generic_string strToConvert)
{
std::transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(),
[](TCHAR ch){ return static_cast<TCHAR>(_totupper(ch)); }
);
return strToConvert;
}
generic_string stringToLower(generic_string strToConvert)
{
std::transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(), ::towlower);
return strToConvert;
}
generic_string stringReplace(generic_string subject, const generic_string& search, const generic_string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
std::vector<generic_string> stringSplit(const generic_string& input, const generic_string& delimiter)
{
size_t start = 0U;
size_t end = input.find(delimiter);
std::vector<generic_string> output;
const size_t delimiterLength = delimiter.length();
while (end != std::string::npos)
{
output.push_back(input.substr(start, end - start));
start = end + delimiterLength;
end = input.find(delimiter, start);
}
output.push_back(input.substr(start, end));
return output;
}
bool str2numberVector(generic_string str2convert, std::vector<size_t>& numVect)
{
numVect.clear();
for (auto i : str2convert)
{
switch (i)
{
case ' ':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
// correct. do nothing
}
break;
default:
return false;
}
}
std::vector<generic_string> v = stringSplit(str2convert, TEXT(" "));
for (auto i : v)
{
// Don't treat empty string and the number greater than 9999
if (!i.empty() && i.length() < 5)
{
numVect.push_back(std::stoi(i));
}
}
return true;
}
generic_string stringJoin(const std::vector<generic_string>& strings, const generic_string& separator)
{
generic_string joined;
size_t length = strings.size();
for (size_t i = 0; i < length; ++i)
{
joined += strings.at(i);
if (i != length - 1)
{
joined += separator;
}
}
return joined;
}
generic_string stringTakeWhileAdmissable(const generic_string& input, const generic_string& admissable)
{
// Find first non-admissable character in "input", and remove everything after it.
size_t idx = input.find_first_not_of(admissable);
if (idx == std::string::npos)
{
return input;
}
else
{
return input.substr(0, idx);
}
}
double stodLocale(const generic_string& str, _locale_t loc, size_t* idx)
{
// Copied from the std::stod implementation but uses _wcstod_l instead of wcstod.
const wchar_t* ptr = str.c_str();
errno = 0;
wchar_t* eptr;
#ifdef __MINGW32__
double ans = ::wcstod(ptr, &eptr);
#else
double ans = ::_wcstod_l(ptr, &eptr, loc);
#endif
if (ptr == eptr)
throw std::invalid_argument("invalid stod argument");
if (errno == ERANGE)
throw std::out_of_range("stod argument out of range");
if (idx != NULL)
*idx = (size_t)(eptr - ptr);
return ans;
}
// Source: https://blogs.msdn.microsoft.com/greggm/2005/09/21/comparing-file-names-in-native-code/
// Modified to use TCHAR's instead of assuming Unicode and reformatted to conform with Notepad++ code style
static TCHAR ToUpperInvariant(TCHAR input)
{
TCHAR result;
LONG lres = LCMapString(LOCALE_INVARIANT, LCMAP_UPPERCASE, &input, 1, &result, 1);
if (lres == 0)
{
assert(false and "LCMapString failed to convert a character to upper case");
result = input;
}
return result;
}
// Source: https://blogs.msdn.microsoft.com/greggm/2005/09/21/comparing-file-names-in-native-code/
// Modified to use TCHAR's instead of assuming Unicode and reformatted to conform with Notepad++ code style
int OrdinalIgnoreCaseCompareStrings(LPCTSTR sz1, LPCTSTR sz2)
{
if (sz1 == sz2)
{
return 0;
}
if (sz1 == nullptr) sz1 = _T("");
if (sz2 == nullptr) sz2 = _T("");
for (;; sz1++, sz2++)
{
const TCHAR c1 = *sz1;
const TCHAR c2 = *sz2;
// check for binary equality first
if (c1 == c2)
{
if (c1 == 0)
{
return 0; // We have reached the end of both strings. No difference found.
}
}
else
{
if (c1 == 0 || c2 == 0)
{
return (c1-c2); // We have reached the end of one string
}
// IMPORTANT: this needs to be upper case to match the behavior of the operating system.
// See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dndotnet/html/StringsinNET20.asp
const TCHAR u1 = ToUpperInvariant(c1);
const TCHAR u2 = ToUpperInvariant(c2);
if (u1 != u2)
{
return (u1-u2); // strings are different
}
}
}
}
bool str2Clipboard(const generic_string &str2cpy, HWND hwnd)
{
size_t len2Allocate = (str2cpy.size() + 1) * sizeof(TCHAR);
HGLOBAL hglbCopy = ::GlobalAlloc(GMEM_MOVEABLE, len2Allocate);
if (hglbCopy == NULL)
{
return false;
}
if (!::OpenClipboard(hwnd))
{
::GlobalFree(hglbCopy);
::CloseClipboard();
return false;
}
if (!::EmptyClipboard())
{
::GlobalFree(hglbCopy);
::CloseClipboard();
return false;
}
// Lock the handle and copy the text to the buffer.
TCHAR *pStr = (TCHAR *)::GlobalLock(hglbCopy);
if (pStr == NULL)
{
::GlobalUnlock(hglbCopy);
::GlobalFree(hglbCopy);
::CloseClipboard();
return false;
}
_tcscpy_s(pStr, len2Allocate / sizeof(TCHAR), str2cpy.c_str());
::GlobalUnlock(hglbCopy);
// Place the handle on the clipboard.
unsigned int clipBoardFormat = CF_UNICODETEXT;
if (::SetClipboardData(clipBoardFormat, hglbCopy) == NULL)
{
::GlobalFree(hglbCopy);
::CloseClipboard();
return false;
}
if (!::CloseClipboard())
{
return false;
}
return true;
}
bool buf2Clipborad(const std::vector<Buffer*>& buffers, bool isFullPath, HWND hwnd)
{
const generic_string crlf = _T("\r\n");
generic_string selection;
for (auto&& buf : buffers)
{
if (buf)
{
const TCHAR* fileName = isFullPath ? buf->getFullPathName() : buf->getFileName();
if (fileName)
selection += fileName;
}
if (!selection.empty() && !endsWith(selection, crlf))
selection += crlf;
}
if (!selection.empty())
return str2Clipboard(selection, hwnd);
return false;
}
bool matchInList(const TCHAR *fileName, const std::vector<generic_string> & patterns)
{
bool is_matched = false;
for (size_t i = 0, len = patterns.size(); i < len; ++i)
{
if (patterns[i].length() > 1 && patterns[i][0] == '!')
{
if (PathMatchSpec(fileName, patterns[i].c_str() + 1))
return false;
continue;
}
if (PathMatchSpec(fileName, patterns[i].c_str()))
is_matched = true;
}
return is_matched;
}
bool matchInExcludeDirList(const TCHAR* dirName, const std::vector<generic_string>& patterns, size_t level)
{
for (size_t i = 0, len = patterns.size(); i < len; ++i)
{
size_t patterLen = patterns[i].length();
if (patterLen > 3 && patterns[i][0] == '!' && patterns[i][1] == '+' && patterns[i][2] == '\\') // check for !+\folderPattern: for all levels - search this pattern recursively
{
if (PathMatchSpec(dirName, patterns[i].c_str() + 3))
return true;