forked from sabrogden/Ditto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPath.cpp
1961 lines (1661 loc) · 60.6 KB
/
Path.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
// ==================================================================
//
// Path.cpp
//
// Created: 20.06.2004
//
// Copyright (C) Peter Hauptmann
//
// ------------------------------------------------------------------
///
/// for copyright & disclaimer see accompanying Path.h
///
/// \page pgChangeLog Change Log
///
/// June 20, 2004: Initial release
///
/// June 22, 2004
/// - \c fixed: nsPath::CPath::MakeSystemFolder implements unmake correctly
/// - \c added: nsPath::CPath::MakeSystemFolder and nsPath::CPath::SearchOnPath
/// set the windows error code to zero if the function succeeds (thanks Hans Dietrich)
/// - \c fixed: nsPath::CPath compiles correctly with warning level -W4
///
/// Mar 3, 2005
/// - fixed eppAutoQuote bug in GetStr (thanks Stlan)
/// - Added:
/// - \ref nsPath::FromRegistry "FromRegistry"
/// - \ref nsPath::CPath::ToRegistry "ToRegistry"
/// - \ref nsPath::CPath::GetRootType, "GetRootType"
/// - \ref nsPath::CPath::GetRoot "GetRoot" has a new implementation
/// - \ref nsPath::CPath::MakeAbsolute "MakeAbsolute"
/// - \ref nsPath::CPath::MakeRelative "MakeRelative"
/// - \ref nsPath::CPath::MakeFullPath "MakeFullPath"
/// - \ref nsPath::CPath::EnvUnexpandRoot "EnvUnexpandRoot"
/// - \ref nsPath::CPath::EnvUnexpandDefaultRoots "EnvUnexpandDefaultRoots"
/// - \b Breaking \b Changes (sorry)
/// - GetRoot -> ShellGetRoot (to distinct from extended GetRoot implementation)
/// - GetFileName --> GetName (consistency)
/// - GetFileTitle --> GetTitle (consistency)
/// - made the creation functions independent functions in the nsPath namespace
/// (they are well tugged away in the namespace so conflicts are easy to avoid)
///
/// Mar 17, 2005
/// - fixed bug in GetFileName (now: GetName): If the path ends in a backslash,
/// GetFileName did return the entire path instead of an empty string. (thanks woodland)
///
/// Aug 21, 2005
/// - fixed bug in GetStr(): re-quoting wasn't applied (doh!)
/// - fixed incompatibility with CStlString
/// - Added IsDot, IsDotDot, IsDotty (better names?)
/// - Added IsValid, ReplaceInvalid
/// - Added SplitRoot
/// -
///
///
///
// ------ Main Page --------------------
/// @mainpage
///
/// \ref pgDisclaimer, \ref pgChangeLog (recent changes August 2005, \b breaking \b changes Mar 2005)
///
/// \par Introduction
///
/// \ref nsPath::CPath "CPath" is a helper class to make manipulating file system path strings easier.
/// It is complementedby a few non-class functions (see nsPath namespace documentation)
///
/// CPath is based on the Shell Lightweight Utility API, but modifies / and extends this functionality
/// (and removes some quirks). It requires CString (see below why, and why this is not too bad).
///
/// \par Main Features:
///
/// CPath acts as a string class with special "understanding" and operations for path strings.
///
/// \code CPath path("c:\\temp"); \endcode
/// constructs a path string, and does some default cleanup (trimming white space, removing quotes, etc.)
/// The cleanup can be customized (see \ref nsPath::CPath::CPath "CPath Constructor",
/// \ref nsPath::EPathCleanup "EPathCleanup"). You can pass an ANSI or UNICODE string.
///
/// \code path = path & "file.txt"; \endcode
/// Appends "foo" to the path, making sure that the two segments are separated by exactly one backslash
/// no matter if the parts end/begin with a backslash.
///
/// The following functions give you access to the individual elements of the path:
///
/// - \ref nsPath::CPath::GetRoot "GetRoot"
/// - \ref nsPath::CPath::GetPath "GetPath"
/// - \ref nsPath::CPath::GetName "GetName"
/// - \ref nsPath::CPath::GetTitle "GetTitle"
/// - \ref nsPath::CPath::GetExtension "GetExtension"
///
/// \code CString s = path.GetStr() \endcode
/// returns a CString that is cleaned up again (re-quoted if necessary, etc). GetBStr() returns an _bstr_t
/// with the same features (that automatically casts to either ANSI or UNICODE).
/// To retrieve the unmodified CPath string, you can rely on the \c operator \c LPCTSTR
///
/// There's much more - see the full nsPath documentation for details!
///
/// @sa MSDN library: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/shlwapi/path/pathappend.asp
///
/// \par Why not CPathT ?
/// -# the class is intended for a VC6 project that won't move to VC7 to soon
/// -# CPathT contains the same quirks that made me almost give up on the Shell Helper functions.
/// -# I wanted the class to have additional features (such as the & operator, and automatic cleanup)
///
/// \par Why CString ?
/// -# The CString implementation provides a known performance (due to the guaranteed reference counted "copy
/// on write" implementation). I consider this preferrable over the weaker guarantees made b STL, especially
/// when designing a "convenient" class interface.
/// -# CString's ref counting mechanism is automatically reused by CPath, constructing a CPath from a CString
/// does not involve a copy operation.
/// -# CString is widely availble independent of MFC (WTL, custom implementations, "extract" macros are
/// available, and VC7 makes CString part of the ATL)
///
/// \note if you want to port to STL, it's probably easier to use a vector<TCHAR> instead of std:string
/// to hold the data internally
///
/// \par Why _bstr_t ?
/// To make implementation easier, the class internally works with "application native" strings (that is,
/// TCHAR strings - which are either ANSI or UNICODE depending on a compile setting). GetBStr provides
/// conversion to ANSI or UNICODE, whichever is required.\n
/// An independent implementation would return a temporary object with cast operators to LPCSTR and LPWSTR
/// - BUT _bstr_t does exactly that (admittedly, with some overhead).
///
#include "stdafx.h"
#include "Path.h"
#include <shlwapi.h> // Link to Shell Helper API
#pragma comment(lib, "shlwapi.lib")
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
namespace nsPath
{
/// contains helper classes for nsPath namespace
///
namespace nsDetail
{
// ==================================================================
// CStringLock
// ------------------------------------------------------------------
//
// Helper class for CString::GetBuffer and CString::ReleaseBuffer
// \todo: consider moving to common utility
// \todo: additional debug verification on release
//
class CStringLock
{
public:
CString * m_string;
LPTSTR m_buffer;
static LPTSTR NullBuffer;
public:
CStringLock(CString & s) : m_string(&s)
{
m_buffer = m_string->GetBuffer(0);
// fixes an incompatibility with CStdString, see "NullBuffer" in .cpp
if (!s.GetLength())
m_buffer = NullBuffer;
}
CStringLock(CString & s, int minChars) : m_string(&s)
{
m_buffer = m_string->GetBuffer(minChars);
// fixes an incompatibility with CStdString, see "NullBuffer" in .cpp
if (!s.GetLength() && !minChars)
m_buffer = NullBuffer;
}
operator LPTSTR() { return m_buffer; }
void Release(int newLen = -1)
{
if (m_string)
{
m_string->ReleaseBuffer(newLen);
m_string = NULL;
m_buffer = NULL;
}
}
~CStringLock() { Release(); }
};
/// CStdString incompatibility:
/// http://www.codeproject.com/string/stdstring.asp
/// If the contained string is empty, CStdString.GetBuffer returns a pointer to a constant
/// empty string, which may cause an access violation when I write the terminating zero
/// (which is in my understanding implicitely allowed the way I read the MSDN docs)
/// Solution: we return a pointer to another buffer
TCHAR NullBufferData[1] = { 0 };
LPTSTR CStringLock::NullBuffer = NullBufferData;
// Helper class for Close-On-Return HKEY
// \todo migrate template class
class CAutoHKEY
{
private:
CAutoHKEY const & operator =(CAutoHKEY const & ); // not implemented
CAutoHKEY(CAutoHKEY const &); // not implemented
protected:
HKEY key;
public:
CAutoHKEY() : key(0) {}
CAutoHKEY(HKEY key_) : key(key_) {}
~CAutoHKEY() { Close(); }
void Close()
{
if (key)
{
RegCloseKey(key);
key = 0;
}
}
HKEY * OutArg()
{
Close();
return &key;
}
operator HKEY() const { return key; }
}; // CAutoHKEY
/// Reads an environment variable into a CString
CString GetEnvVar(LPCTSTR envVar)
{
SetLastError(0);
// get length of buffer
DWORD result = GetEnvironmentVariable(envVar, _T(""), 0);
if (!result)
return CString();
CString s;
result = GetEnvironmentVariable(envVar, CStringLock(s, result), result);
return s;
}
/// Replace path root with environment variable
/// If the beginning of \c s matches the value of the environment variable %envVar%,
/// it is replaced with the %envVar% value
/// (e.g. "C:\Windows" with "%windir%"
/// \param s [CString &, in/out]: the string to modify
/// \param envVar [LPCTSTR]: name of the environment variable
/// \returns true if s was modified, false otherwise.
bool EnvUnsubstRoot(CString & s, LPCTSTR envVar)
{
// get environment value string
CString envValue = GetEnvVar(envVar);
if (!envValue.GetLength())
return false;
if (s.GetLength() >= envValue.GetLength() &&
_tcsnicmp(s, envValue, envValue.GetLength())==0)
{
CString modified = CString('%');
modified += envVar;
modified += '%';
modified += s.Mid(envValue.GetLength());
s = modified;
return true;
}
return false;
}
} // namespace nsPath::nsDetail
using namespace nsDetail;
const TCHAR Backslash = '\\';
// ==============================================
// Trim
// ----------------------------------------------
/// Trims whitespaces from left and right side.
/// \param s [CString]: String to modify in-place.
void Trim(CString & string)
{
if (_istspace(GetFirstChar(string)))
string.TrimLeft();
if (_istspace(GetLastChar(string)))
string.TrimRight();
}
// ==================================================================
// GetDriveLetter(ch)
// ------------------------------------------------------------------
/// checks if the specified letter \c ch is a drive letter, and casts it to uppercase
///
/// \returns [TCHAR]: if \c is a valid drive letter (A..Z, or a..z), returns the drive letter
/// cast to uppercase (A..Z). >Otherwise, returns 0
TCHAR GetDriveLetter(TCHAR ch)
{
if ( (ch >= 'A' && ch <= 'Z'))
return ch;
if (ch >= 'a' && ch <= 'z')
return (TCHAR) (ch - 'a' + 'A');
return 0;
}
// ==================================================================
// GetDriveLetter(string)
// ------------------------------------------------------------------
/// returnd the drive letter of a path.
/// The drive letter returned is always uppercase ('A'.`'Z').
/// \param s [LPCTSTR]: the path string
/// \returns [TCHAR]: the drive letter, converted to uppercase, if the path starts with an
/// X: drive specification. Otherwise, returns 0
//
TCHAR GetDriveLetter(LPCTSTR s)
{
if (s == NULL || *s == 0 || s[1] != ':')
return 0;
return GetDriveLetter(s[0]);
}
// ==================================================================
// QuoteSpaces
// ------------------------------------------------------------------
///
/// Quotes the string if it is not already quoted, and contains spaces
/// see also MSDN: \c PathQuoteSpaces
/// \note If the string is already quoted, an additional pair of quotes is added.
/// \param str [CString const &]: path string to add quotes to
/// \returns [CString]: path string with quotes added if required
//
CString QuoteSpaces(CString const & str)
{
// preserve refcounting if no changes will be made
if (str.Find(' ')>=0) // if the string contains any spaces...
{
CString copy(str);
CStringLock buffer(copy, copy.GetLength() + 2);
PathQuoteSpaces(buffer);
buffer.Release();
return copy;
}
return str; // unmodified
}
/// helper function for GetRootType
inline ERootType GRT_Return(ERootType type, int len, int * pLen)
{
if (pLen)
*pLen = len;
return type;
}
// ==================================================================
// GetRootType
// ------------------------------------------------------------------
///
/// returns the type of the path root, and it's length.
/// For supported root types, see \ref nsPath::ERootType "ERootType" enumeration
///
/// \param path [LPCTSTR]: The path to analyze
/// \param pLen [int *, out]: if not NULL, receives the length of the root part (in characters)
/// \param greedy [bool=true]: Affects len and type of the following root types:
/// - \c "\\server\share" : with greedy=true, it is treated as one \c rtServerShare root,
/// otherwise, it is treated as \c rtServer root
///
/// \returns [ERootType]: type of the root element
///
///
ERootType GetRootType(LPCTSTR path, int * pLen, bool greedy)
{
// ERootType type = rtNoRoot;
// int len = 0;
const TCHAR * invalidChars = _T("\\/:*/\"<>|");
const TCHAR bk = '\\';
if (!path || !*path)
return GRT_Return(rtNoRoot, 0, pLen);
// drive spec
if (_istalpha(*path) && path[1] == ':')
{
if (path[2] == bk) { return GRT_Return(rtDriveRoot, 3, pLen); }
else { return GRT_Return(rtDriveCur, 2, pLen); }
}
// anything starting with two backslashes
if (path[0] == bk && path[1] == bk)
{
// UNC long path?
if (path[2] == '?' && path[3] == bk)
{
int extraLen = 0;
GetRootType(path+4, &extraLen) ;
return GRT_Return(rtLongPath, 4 + extraLen, pLen);
}
// position of next backslash or colon
int len = 2 + (int)_tcscspn(path+2, invalidChars);
TCHAR const * end = path+len;
// server only, no backslash
if (*end == 0)
return GRT_Return(rtServerOnly, len, pLen);
// server only, terminated with backslash
if (*end == bk && end[1] == 0)
return GRT_Return(rtServerOnly, len+1, pLen);
// server, backslash, and more...
if (*end == bk)
{
if (!greedy) // return server only
return GRT_Return(rtServer, len, pLen);
len += 1 + (int)_tcscspn(end+1, invalidChars);
end = path + len;
// server, share, no backslash
if (*end == 0)
return GRT_Return(rtServerShare, len, pLen);
// server, share, backslash
if (*end == '\\')
return GRT_Return(rtServerShare, len+1, pLen);
}
// fall through to other tests
}
int len = (int)_tcscspn(path, invalidChars);
TCHAR const * end = path + len;
// (pseudo) protocol:
if (len > 0 && *end == ':')
{
if (end[1] == '/' && end[2] == '/')
return GRT_Return(rtProtocol, len+3, pLen);
else
return GRT_Return(rtPseudoProtocol, len+1, pLen);
}
return GRT_Return(rtNoRoot, 0, pLen);
}
// ==================================================================
// CPath::Trim
// ------------------------------------------------------------------
///
/// removes leading and trailing spaces.
//
CPath & CPath::Trim()
{
nsPath::Trim(m_path);
return *this;
}
// ==================================================================
// CPath::Unquote
// ------------------------------------------------------------------
///
/// removes (double) quotes from around the string
//
CPath & CPath::Unquote()
{
if (GetFirstChar(m_path) == '"' && GetLastChar(m_path) == '"')
m_path = m_path.Mid(1, m_path.GetLength()-2);
return *this;
}
// ==================================================================
// CPath::Canonicalize
// ------------------------------------------------------------------
///
/// Collapses "\\..\\" and "\\.\\" path parts.
/// see also MSDN: PathCanonicalize
/// \note
/// PathCanonicalize works strange on relative paths like "..\\..\\x" -
/// it is changed to "\x", which is clearly not correct. SearchAndQualify is affected
/// by the same problem
/// \todo handle this separately?
///
/// \par Implementation Differences
/// \c PathCanonicalize does turn an empty path into a single backspace.
/// CPath::Canonicalize does not modify an empty path.
//
CPath & CPath::Canonicalize()
{
if (!m_path.GetLength()) // PathCanonicalize turns an empty path into "\\" - I don't want this..
return *this;
if (m_path.Find(_T("\\."))>=0)
{
CString target = m_path; // PathCanonicalize requires a copy to work with
CStringLock buffer(target, m_path.GetLength()+2); // might add a backslash sometimes !
PathCanonicalize(buffer, m_path);
buffer.Release();
m_path = target;
}
return *this;
}
// ==================================================================
// CPath::ShrinkXXLPath
// ------------------------------------------------------------------
///
/// Removes an "Extra long file name" specification
/// Unicode API allows pathes longer than MAX_PATH, if they start with "\\\\?\\". This function
/// removes such a specification if present. See also MSDN: "File Name Conventions".
//
CPath & CPath::ShrinkXXLPath()
{
if (m_path.GetLength() >= 6 && // at least 6 chars for [\\?\C:]
_tcsncmp(m_path, _T("\\\\?\\"), 4) == 0)
{
LPCTSTR path = m_path;
if (nsPath::GetDriveLetter(path[4]) != 0 && path[5] == ':')
m_path = m_path.Mid(4);
else if (m_path.GetLength() >= 8) // at least 8 chars for [\\?\UNC\]
{
if (_tcsnicmp(path + 4, _T("UNC\\"), 4) == 0)
{
// remove chars [2]..[7]
int len = m_path.GetLength() - 8; //
CStringLock buffer(m_path);
memmove(buffer+2, buffer+8, len * sizeof(TCHAR));
buffer.Release(len+2);
}
}
}
return *this;
}
// ==================================================================
// CPath::Assign
// ------------------------------------------------------------------
///
/// Assigns a string to the path object, optionally applying cleanup of the path name
///
/// \param str [CString const &]: The string to assign to the path
/// \param cleanup [DWORD, default = epc_Default]: operations to apply to the path
/// \returns [CPath &]: reference to the path object itself
///
/// see CPath::Clean for a description of the cleanup options
//
CPath & CPath::Assign(CString const & str, DWORD cleanup)
{
m_path = str;
Clean(cleanup);
return *this;
}
// ==================================================================
// CPath::MakePretty
// ------------------------------------------------------------------
///
/// Turns an all-uppercase path to all -lowercase. A path containing any lowercase
/// character is not modified.
/// (This is Microsoft#s idea of prettyfying a path. I don't know what to say)
///
CPath & CPath::MakePretty()
{
CStringLock buffer(m_path);
PathMakePretty(buffer);
return *this;
}
// ==================================================================
// CPath::Clean
// ------------------------------------------------------------------
///
/// Applies multiple "path cleanup" operations
///
/// \param cleanup [DWORD]: a combination of zero or more nsPath::EPathCleanup flags (see below)
/// \returns [CPath &]: a reference to the path object
///
/// The following cleanup operations are defined:
/// - \c epcRemoveArgs: call PathRemoveArgs to remove arguments
/// - \c epcRemoveIconLocation: call to PathParseIconLocation to remove icon location
/// - \c \b epcTrim: trim leading and trailing whitespaces
/// - \c \b epcUnquote: remove quotes
/// - \c \b epcTrimInQuote: trim whitespaces again after unqouting.
/// - \c \b epcCanonicalize: collapse "\\.\\" and "\\..\\" segments
/// - \c \b epcRemoveXXL: remove an "\\\\?\\" prefix for path lengths exceeding \c MAX_PATH
/// - \c epcSlashToBackslash: (not implemented) change forward slashes to back slashes (does not modify a "xyz://" protocol root)
/// - \c epcMakePretty: applies PathMakePretty
/// - \c epcRemoveArgs: remove command line arguments
/// - \c epcRemoveIconLocation: remove icon location number
/// - \c \b epcExpandEnvStrings: Expand environment strings
///
/// This function is called by most assignment constructors and assignment operators, using
/// the \c epc_Default cleanup options (typically those set in bold above, but check the enum
/// documentation in case I forgot to update this one).
///
/// Constructors and Assignment operators that take a string (\c LPCTSTR, \c LPCTSTR, \c CString) call
/// this function. Copy or assignment from another \c CPath object does not call this function.
///
///
//
CPath & CPath::Clean(DWORD cleanup)
{
if (cleanup & epcRemoveArgs)
{
// remove leading spaces, otherwise PathRemoveArgs considers everything a space
if (cleanup & epcTrim)
m_path.TrimLeft();
PathRemoveArgs(CStringLock(m_path));
}
if (cleanup & epcRemoveIconLocation)
PathParseIconLocation(CStringLock(m_path));
if (cleanup & epcTrim)
Trim();
if (cleanup & epcUnquote)
{
Unquote();
if (cleanup & epcTrimInQuote)
Trim();
}
if (cleanup & epcExpandEnvStrings)
ExpandEnvStrings();
if (cleanup & epcCanonicalize)
Canonicalize();
if (cleanup & epcRemoveXXL)
ShrinkXXLPath();
if (cleanup & epcSlashToBackslash)
m_path.Replace('/', '\\');
if (cleanup & epcMakePretty)
MakePretty();
return *this;
}
// Extractors
CString CPath::GetStr(DWORD packing) const
{
CString str = m_path;
// _ASSERTE(!(packing & eppAutoXXL)); // TODO
if (packing & eppAutoQuote)
str = QuoteSpaces(str);
if (packing & eppBackslashToSlash)
str.Replace('\\', '/'); // TODO: suport server-share and protocol correctly
return str;
}
_bstr_t CPath::GetBStr(DWORD packing) const
{
return _bstr_t( GetStr(packing).operator LPCTSTR());
}
// ==================================================================
// Constructors
// ------------------------------------------------------------------
//
CPath::CPath(LPCSTR path) : m_path(path)
{
Clean();
}
CPath::CPath(LPCWSTR path) : m_path(path)
{
Clean();
}
CPath::CPath(CString const & path) : m_path(path)
{
Clean();
}
CPath::CPath(CPath const & path) : m_path(path.m_path) {} // we assume it is already cleaned
CPath::CPath(CString const & path,DWORD cleanup) : m_path(path)
{
Clean(cleanup);
}
// ==================================================================
// Assignment
// ------------------------------------------------------------------
//
CPath & CPath::operator=(LPCSTR rhs)
{
#ifndef _UNICODE // avoidf self-assignment
if (rhs == m_path.operator LPCTSTR())
return *this;
#endif
m_path = rhs;
Clean();
return *this;
}
CPath & CPath::operator=(LPCWSTR rhs)
{
#ifdef _UNICODE // avoid self-assignment
if (rhs == m_path.operator LPCTSTR())
return *this;
#endif
m_path = rhs;
Clean();
return *this;
}
CPath & CPath::operator=(CString const & rhs)
{
// our own test for self-assignment, so we can skip CClean in this case
if (rhs.operator LPCTSTR() == m_path.operator LPCTSTR())
return *this;
m_path = rhs;
Clean();
return *this;
}
CPath & CPath::operator=(CPath const & rhs)
{
if (rhs.m_path.operator LPCTSTR() == m_path.operator LPCTSTR())
return *this;
m_path = rhs;
return *this;
}
// ==================================================================
// CPath::operator &=
// ------------------------------------------------------------------
///
/// appends a path segment, making sure it is separated by exactly one backslash
/// \returns reference to the modified \c CPath instance.
//
CPath & CPath::operator &=(LPCTSTR rhs)
{
return CPath::Append(rhs);
}
// ==================================================================
// CPath::AddBackslash
// ------------------------------------------------------------------
///
/// makes sure the contained path is terminated with a backslash
/// \returns [CPath &]: reference to the modified path
/// see also: \c PathAddBackslash Shell Lightweight Utility API
//
CPath & CPath::AddBackslash()
{
if (GetLastChar(m_path) != Backslash)
{
CStringLock buffer(m_path, m_path.GetLength()+1);
PathAddBackslash(buffer);
}
return *this;
}
// ==================================================================
// CPath::RemoveBackslash
// ------------------------------------------------------------------
///
/// If the path ends with a backslash, it is removed.
/// \returns [CPath &]: a reference to the modified path.
//
CPath & CPath::RemoveBackslash()
{
if (GetLastChar(m_path) == Backslash)
{
CStringLock buffer(m_path, m_path.GetLength()+1);
PathRemoveBackslash(buffer);
}
return *this;
}
// ==================================================================
// CPath::Append
// ------------------------------------------------------------------
///
/// Concatenates two paths
/// \par Differences to \c PathAddBackslash:
/// Unlike \c PathAddBackslash, \c CPath::Append appends a single backslash if rhs is empty (and
/// the path does not already end with a backslash)
///
/// \param rhs [LPCTSTR]: the path component to append
/// \returns [CPath &]: reference to \c *this
//
CPath & CPath::Append(LPCTSTR rhs)
{
if (rhs == NULL || *rhs == '\0')
{
AddBackslash();
}
else
{
int rhsLen = rhs ? (int)_tcslen(rhs) : 0;
CStringLock buffer(m_path, m_path.GetLength()+rhsLen+1);
PathAppend(buffer, rhs);
}
return *this;
}
// ==================================================================
// CPath::ShellGetRoot
// ------------------------------------------------------------------
///
/// Retrieves the Root of the path, as returned by \c PathSkipRoot.
///
/// \note For a more detailed (but "hand-made") implementation see GetRoot and GetRootType.
///
/// The functionality of \c PathSkipRoot is pretty much limited:
/// - Drives ("C:\\" but not "C:")
/// - UNC Shares ("\\\\server\\share\\", but neither "\\\\server" nor "\\\\server\\share")
/// - UNC long drive ("\\\\?\\C:\\")
///
/// \returns [CString]: the rot part of the string
///
CString CPath::ShellGetRoot() const
{
LPCTSTR path = m_path;
LPCTSTR rootEnd = PathSkipRoot(path);
if (rootEnd == NULL)
return CString();
return m_path.Left((int)(rootEnd - path));
}
// ==================================================================
// GetRootType
// ------------------------------------------------------------------
///
/// returns the type of the root, and it's length.
/// For supported tpyes, see \ref nsPath::ERootType "ERootType".
/// see also \ref nsPath::GetRootType
///
ERootType CPath::GetRootType(int * len, bool greedy) const
{
return nsPath::GetRootType(m_path, len, greedy);
}
// ==================================================================
// GetRoot
// ------------------------------------------------------------------
///
/// \param rt [ERootType * =NULL]: if given, receives the type of the root segment.
/// \return [CString]: the root, as a string.
///
/// For details which root types are supported, and how the length is calculated, see
/// \ref nsPath::ERootType "ERootType" and \ref nsPath::GetRootType
///
CString CPath::GetRoot(ERootType * rt, bool greedy) const
{
int len = 0;
ERootType rt_ = nsPath::GetRootType(m_path, &len, greedy);
if (rt)
*rt = rt_;
return m_path.Left(len);
}
// ==================================================================
// CPath::SplitRoot
// ------------------------------------------------------------------
///
/// removes and returns the root element from the contained path
/// You can call SplitRoot repeatedly to retrieve the path segments in order
///
/// \param rt [ERootType * =NULL] if not NULL, receives the type of the root element
/// note: the root element type can be recognized correctly only for the first segment
/// \returns [CString]: the root element of the original path
/// \par Side Effects: root element removed from contained path
///
CString CPath::SplitRoot(ERootType * rt)
{
CString head;
if (!m_path.GetLength())
return head;
int rootLen = 0;
ERootType rt_ = nsPath::GetRootType(m_path, &rootLen, false);
if (rt)
*rt = rt_;
if (rt_ == rtNoRoot) // not a typical root element
{
int start = 0;
if (GetFirstChar(m_path) == '\\') // skip leading backslash (double backslas handled before)
++start;
int ipos = m_path.Find('\\', start);
if (ipos < 0)
{
head = start ? m_path.Mid(start) : m_path;
m_path.Empty();
}
else
{
head = m_path.Mid(start, ipos-start);
m_path = m_path.Mid(ipos+1);
}
}
else
{
head = m_path.Left(rootLen);
if (rootLen < m_path.GetLength() && m_path[rootLen] == '\\')
++rootLen;
m_path = m_path.Mid(rootLen);
}
return head;
}
// ==================================================================
// CPath::GetPath
// ------------------------------------------------------------------
///
/// returns the path (without file name and extension)
/// \param includeRoot [bool=true]: if \c true (default), the root is included in the retuerned path.
/// \returns [CPath]: the path, excluding file name and
/// \par Implementation:
/// Uses \c PathFindFileName, and \c PathSkipRoot
/// \todo
/// - in "c:\\temp\\", \c PathFindFileName considers "temp\\" to be a file name and returns
/// "c:\\" only. This is clearly not my idea of a path
/// - when Extending \c CPath::GetRoot, this function should be adjusted as well
///
//
CPath CPath::GetPath(bool includeRoot ) const
{
LPCTSTR path = m_path;
LPCTSTR fileName = PathFindFileName(path);
if (fileName == NULL) // seems to find something in any way!
fileName = path + m_path.GetLength();