forked from MrKepzie/SequenceParsing
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathSequenceParsing.cpp
1613 lines (1392 loc) · 50.9 KB
/
SequenceParsing.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
/* ***** BEGIN LICENSE BLOCK *****
* This file is part of Natron <https://natrongithub.github.io/>,
* (C) 2018-2022 The Natron developers
* (C) 2013-2018 INRIA and Alexandre Gauthier-Foichat
*
* Natron 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 2 of the License, or
* (at your option) any later version.
*
* Natron 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. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>
* ***** END LICENSE BLOCK ***** */
#include "SequenceParsing.h"
#include <cassert>
#include <cmath>
#include <climits>
#include <cctype> // isdigit(c)
#include <cstddef>
#ifdef DEBUG
#include <iostream>
#endif
#include <stdexcept>
#include <sstream>
#include <fstream>
#include <locale>
#include <istream>
#include <algorithm>
#include <memory>
#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
#include <windows.h>
#else
#include <sys/stat.h>
#endif
#include "tinydir/tinydir.h"
// Use: #pragma message WARN("My message")
#if _MSC_VER
# define FILE_LINE_LINK __FILE__ "(" STRINGISE(__LINE__) ") : "
# define WARN(exp) (FILE_LINE_LINK "WARNING: " exp)
#else//__GNUC__ - may need other defines for different compilers
# define WARN(exp) ("WARNING: " exp)
#endif
///the maximum number of non existing frame before Natron gives up trying to figure out a sequence layout.
#define NATRON_DIALOG_MAX_SEQUENCES_HOLE 1000
using std::size_t;
using std::map;
using std::string;
using std::stringstream;
using std::wstring;
using std::vector;
using std::pair;
using std::make_pair;
using namespace SequenceParsing;
namespace {
#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
static wstring
utf8_to_utf16(const string& str)
{
wstring native;
native.resize( MultiByteToWideChar (CP_UTF8, 0, str.data(), str.length(), NULL, 0) );
MultiByteToWideChar ( CP_UTF8, 0, str.data(), str.length(), &native[0], (int)native.size() );
return native;
} // utf8_to_utf16
static string
utf16_to_utf8 (const wstring& str)
{
string utf8;
utf8.resize(WideCharToMultiByte (CP_UTF8, 0, str.data(), str.length(), NULL, 0, NULL, NULL));
WideCharToMultiByte (CP_UTF8, 0, str.data(), str.length(), &utf8[0], (int)utf8.size(), NULL, NULL);
return utf8;
}
#endif
static std::size_t
getFileSize(const string& filename)
{
#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
wstring wfilename = utf8_to_utf16(filename);
LARGE_INTEGER file_size;
file_size.QuadPart = 0;
/*
On Windows there are 3 methods to get the size of a file, the most robust being the 1st one
but it is also the most expensive.
By order of performance: 3), 2), 1)
By order of reliability: 1), 2), 3)
Since in our use-case here the file size is just a hint, use the fastest alternative.
*/
/*
//Method 1, open the file
HANDLE file = CreateFileW(wfilename.c_str(),
GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
if(file && file != INVALID_HANDLE_VALUE){
if(!GetFileSizeEx(file, &file_size)){
file_size.QuadPart = 0; // clean-up on fail
}
CloseHandle(file);
}
*/
/*
//Method 2, find the file
WIN32_FIND_DATAW find_data;
HANDLE find_file = FindFirstFileW(wfilename.c_str(), &find_data);
if(find_file && find_file != INVALID_HANDLE_VALUE){
file_size.LowPart = find_data.nFileSizeLow;
file_size.HighPart = find_data.nFileSizeHigh;
FindClose(find_file);
}
*/
//Method 3, read the file attributes, this is the fastest
WIN32_FILE_ATTRIBUTE_DATA file_attr_data;
if ( GetFileAttributesExW(wfilename.c_str(), GetFileExInfoStandard, &file_attr_data) ) {
file_size.LowPart = file_attr_data.nFileSizeLow;
file_size.HighPart = file_attr_data.nFileSizeHigh;
}
return (std::size_t)file_size.QuadPart;
#else // !(defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
std::ifstream in(filename.c_str(), std::ifstream::ate | std::ifstream::binary);
return in.tellg();
#endif // (defined(_WIN32) || defined(__WIN32__) || defined(WIN32))
}
#if 0
// case-insensitive char_traits
// see http://www.gotw.ca/gotw/029.htm
// in order to use case insensitive search and compare, all functions should
// be templated and use basic_string<>:
// template<class _CharT, class _Traits, class _Allocator>
// void function(basic_string<_CharT, _Traits, _Allocator>& s, ...)
//
struct ci_char_traits
: public std::char_traits<char>
{
static bool eq(char c1,
char c2) { return toupper(c1) == toupper(c2); }
static bool ne(char c1,
char c2) { return toupper(c1) != toupper(c2); }
static bool lt(char c1,
char c2) { return toupper(c1) < toupper(c2); }
static int compare(const char* s1,
const char* s2,
size_t n)
{
while (n-- != 0) {
if ( toupper(*s1) < toupper(*s2) ) { return -1; }
if ( toupper(*s1) > toupper(*s2) ) { return 1; }
++s1; ++s2;
}
return 0;
}
static const char* find(const char* s,
int n,
char a)
{
while ( n-- > 0 && toupper(*s) != toupper(a) ) {
++s;
}
return s;
}
};
typedef std::basic_string<char, ci_char_traits> ci_string;
#endif
/**
* @brief Given the pattern unpathed without extension (e.g: "filename###") and the file extension (e.g "jpg") ; this
* functions extracts the common parts and the variables of the pattern ordered from left to right .
* For example: file%04dname### and the jpg extension would return:
* 3 common parts: "file","name",".jpg"
* 2 variables: "%04d", "###"
* The variables by order vector's second member is an int indicating how many non-variable (chars belonging to common parts) characters
* were found before this variable.
**/
static bool
extractCommonPartsAndVariablesFromPattern(const string& patternUnPathedWithoutExt,
const string& patternExtension,
StringList* commonParts,
vector<pair<string, int> >* variablesByOrder)
{
bool inPrintfLikeArg = false;
int printfLikeArgIndex = 0;
string commonPart;
string variable;
int commonCharactersFound = 0;
bool previousCharIsSharp = false;
for (int i = 0; i < (int)patternUnPathedWithoutExt.size(); ++i) {
const char& c = patternUnPathedWithoutExt[i];
if (c == '#') {
if ( !commonPart.empty() ) {
commonParts->push_back(commonPart);
commonCharactersFound += commonPart.size();
commonPart.clear();
}
if ( !previousCharIsSharp && !variable.empty() ) {
variablesByOrder->push_back( make_pair(variable, commonCharactersFound) );
variable.clear();
}
variable.push_back(c);
previousCharIsSharp = true;
} else if (c == '%') {
char next = '\0';
if (i < (int)patternUnPathedWithoutExt.size() - 1) {
next = patternUnPathedWithoutExt[i + 1];
}
char prev = '\0';
if (i > 0) {
prev = patternUnPathedWithoutExt[i - 1];
}
if (next == '\0') {
///if we're at end, just consider the % character as any other
commonPart.push_back(c);
} else if (prev == '%') {
///we escaped the previous %, append this one to the text
commonPart.push_back(c);
} else if (next != '%') {
///if next == % then we have escaped the character
///we don't support nested variables
if (inPrintfLikeArg) {
return false;
}
printfLikeArgIndex = 0;
inPrintfLikeArg = true;
if ( !commonPart.empty() ) {
commonParts->push_back(commonPart);
commonCharactersFound += commonPart.size();
commonPart.clear();
}
if ( !variable.empty() ) {
variablesByOrder->push_back( make_pair(variable, commonCharactersFound) );
variable.clear();
}
variable.push_back(c);
}
} else if ( ( ( c == 'd') || ( c == 'v') || ( c == 'V') ) && inPrintfLikeArg ) {
inPrintfLikeArg = false;
assert( !variable.empty() );
variable.push_back(c);
variablesByOrder->push_back( make_pair(variable, commonCharactersFound) );
variable.clear();
} else if (inPrintfLikeArg) {
++printfLikeArgIndex;
assert( !variable.empty() );
variable.push_back(c);
///if we're after a % character, and c is a letter different than d or v or V
///or c is digit different than 0, then we don't support this printf like style.
if ( std::isalpha( c, std::locale() ) ||
( ( printfLikeArgIndex == 1) && ( c != '0') ) ) {
commonParts->push_back(variable);
commonCharactersFound += variable.size();
variable.clear();
inPrintfLikeArg = false;
}
} else {
commonPart.push_back(c);
if ( !variable.empty() ) {
variablesByOrder->push_back( make_pair(variable, commonCharactersFound) );
variable.clear();
}
}
}
if ( !commonPart.empty() ) {
commonParts->push_back(commonPart);
commonCharactersFound += commonPart.size();
}
if ( !variable.empty() ) {
variablesByOrder->push_back( make_pair(variable, commonCharactersFound) );
}
if ( !patternExtension.empty() ) {
commonParts->push_back( string('.' + patternExtension) );
}
return true;
} // extractCommonPartsAndVariablesFromPattern
static size_t
findStr(const string& from,
const string& toSearch,
int pos)
{
return from.find(toSearch, pos);
// case insensitive version:
//return ci_string(from.c_str()).find(toSearch.c_str(), pos);
}
static bool
startsWith(const string& str,
const string& prefix)
{
return str.substr( 0, prefix.size() ) == prefix;
// case insensitive version:
//return ci_string(str.substr(0,prefix.size()).c_str()) == prefix.c_str();
}
static bool
endsWith(const string& str,
const string& suffix)
{
return ( ( str.size() >= suffix.size() ) &&
(str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0) );
}
static void
removeAllOccurences(string& str,
const string& toRemove)
{
if ( str.size() ) {
for ( size_t i = findStr(str, toRemove, 0);
i != string::npos;
i = findStr(str, toRemove, i) ) {
str.erase( i, toRemove.size() );
}
}
}
static int
stringToInt(const string& str)
{
// stringstream ss(str);
// int ret = 0;
// try {
// ss >> ret;
// } catch (const std::ios_base::failure& e) {
// return 0;
// }
// return ret;
return std::atoi( str.c_str() );
}
static string
stringFromInt(int nb)
{
stringstream ss;
ss << nb;
return ss.str();
}
static string
removeFileExtension(string& filename)
{
size_t lastdot = filename.find_last_of(".");
if (lastdot == string::npos) {
return "";
}
string extension = filename.substr(lastdot + 1);
filename = filename.substr(0, lastdot);
return extension;
}
static void
getFilesFromDir(tinydir_dir& dir,
StringList* ret)
{
///iterate through all the files in the directory
while (dir.has_next) {
tinydir_file file;
int status = tinydir_readfile(&dir, &file);
if ( ( status == 0) && !file.is_dir ) {
#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && defined(UNICODE)
wstring wfilename(file.name);
string filename(utf16_to_utf8(wfilename));
#else
string filename(file.name);
#endif
if ( ( filename != ".") && ( filename != "..") ) {
ret->push_back(filename);
}
}
tinydir_next(&dir);
}
}
/*
The following rules applying for matching frame numbers:
- If the number has at least as many digits as the digitsCount then it is OK
- If the number has more digits than the digitsCOunt, it is only OK if it has 0 leading zeroes
*/
static bool
numberMatchDigits(int digitsCount,
const string& number,
int *frameNumber)
{
assert(digitsCount > 0);
*frameNumber = stringToInt(number);
if ( (int)number.size() == digitsCount ) {
return true;
}
if ( (int)number.size() < digitsCount ) {
return false;
}
assert( (int)number.size() > digitsCount );
if (number[0] == '0') {
return false;
}
return true;
}
static bool
matchesHashTag(int sharpCount,
const string& filename,
size_t startingPos,
size_t *endPos,
int* frameNumber)
{
string variable;
size_t variableIt = startingPos;
for (variableIt = startingPos;
variableIt < filename.size() && std::isdigit(filename[variableIt]);
++variableIt) {
variable.push_back(filename[variableIt]);
}
*endPos = variableIt;
return numberMatchDigits(sharpCount, variable, frameNumber);
}
static bool
matchesPrintfLikeSyntax(int digitsCount,
const string& filename,
size_t startingPos,
size_t *endPos,
int* frameNumber)
{
string variable;
size_t variableIt;
for (variableIt = startingPos;
variableIt < filename.size() && std::isdigit(filename[variableIt]);
++variableIt) {
variable.push_back(filename[variableIt]);
}
*endPos = variableIt;
return numberMatchDigits(digitsCount, variable, frameNumber);
}
static bool
matchesView(bool longView,
const string& filename,
size_t startingPos,
size_t *endPos,
int* viewNumber)
{
string mid = filename.substr(startingPos);
if (!longView) {
if ( startsWith(mid, "r") ) {
*viewNumber = 1;
*endPos = startingPos + 1;
return true;
} else if ( startsWith(mid, "l") ) {
*viewNumber = 0;
*endPos = startingPos + 1;
return true;
} else if ( startsWith(mid, "view") ) {
string viewNoStr;
for (size_t it = 4; it < mid.size() && std::isdigit(mid[it]); ++it) {
viewNoStr.push_back(mid[it]);
}
if ( !viewNoStr.empty() ) {
*viewNumber = stringToInt(viewNoStr);
*endPos = startingPos + 4 + viewNoStr.size();
} else {
return false;
}
return true;
}
return false;
} else {
if ( startsWith(mid, "right") ) {
*viewNumber = 1;
*endPos = startingPos + 5;
return true;
} else if ( startsWith(mid, "left") ) {
*viewNumber = 0;
*endPos = startingPos + 4;
return true;
} else if ( startsWith(mid, "view") ) {
string viewNoStr;
for (size_t it = 4; it < mid.size() && std::isdigit(mid[it]); ++it) {
viewNoStr.push_back(mid[it]);
}
if ( !viewNoStr.empty() ) {
*viewNumber = stringToInt(viewNoStr);
*endPos = startingPos + 4 + viewNoStr.size();
} else {
return false;
}
return true;
}
return false;
}
} // matchesView
static bool
matchesPattern_v2(const string& filename,
const string& pattern,
const string& patternExtension,
int* frameNumber,
int* viewNumber)
{
///If the frame number is found twice or more, this is to verify if they are identical
bool wasFrameNumberSet = false;
///If the view number is found twice or more, this is to verify if they are identical
bool wasViewNumberSet = false;
///Default view number and frame number
assert(viewNumber && frameNumber);
*viewNumber = 0;
*frameNumber = -1;
///Iterators on the pattern and the filename
size_t filenameIt = 0;
size_t patternIt = 0;
///make a copy of the filename from which we remove the file extension
string filenameCpy = filename;
string fileExt = removeFileExtension(filenameCpy);
///Extensions not matching, exit.
if (fileExt != patternExtension) { //
return false;
}
///Iterating while not at end of either the pattern or the filename
while ( filenameIt < filenameCpy.size() && patternIt < pattern.size() ) {
///the count of '#' characters found
int sharpCount = 0;
///Actually start counting the #
string variable;
for (size_t sharpIt = patternIt;
sharpIt < pattern.size() && pattern[sharpIt] == '#';
++sharpIt) {
++sharpCount;
variable.push_back('#');
}
///Did we found a %d style syntax ?
bool foundPrintFLikeSyntax = false;
///Did we found a %v style syntax ?
bool foundShortView = false;
///Did we found a %V style syntax ?
bool foundLongView = false;
///How many digits the printf style %d syntax are desired, e.g %04d is 4
int printfDigitCount = 0;
///The number of characters that compose the %04d style variable, this is at least 2 (%d)
int printfLikeVariableSize = 2;
if (pattern[patternIt] == '%') {
///We found the '%' digit, start at the character right after to
///find digits
size_t printfIt;
string digitStr;
for (printfIt = patternIt + 1;
printfIt < pattern.size() && std::isdigit(pattern[printfIt]);
++printfIt) {
digitStr.push_back(pattern[printfIt]);
++printfLikeVariableSize;
}
///they are no more digit after the '%', check if this is correctly terminating by a 'd' character.
/// We also treat the view %v and %V cases here
if ( ( printfIt < pattern.size() ) && ( std::tolower(pattern[printfIt]) == 'd') ) {
foundPrintFLikeSyntax = true;
printfDigitCount = stringToInt(digitStr);
} else if ( ( printfIt < pattern.size() ) && ( pattern[printfIt] == 'V') ) {
foundLongView = true;
} else if ( ( printfIt < pattern.size() ) && ( pattern[printfIt] == 'v') ) {
foundShortView = true;
}
}
if (sharpCount > 0) { ///If we found #
///There cannot be another variable!
assert(!foundPrintFLikeSyntax && !foundLongView && !foundShortView);
size_t endHashTag = 0;
int fNumber = -1;
///check if the filename matches the number of hashes
if ( !matchesHashTag(sharpCount, filenameCpy, filenameIt, &endHashTag, &fNumber) ) {
return false;
}
///If the frame number had already been set and it was different, this filename doesn't match
///the pattern.
if ( wasFrameNumberSet && ( fNumber != *frameNumber) ) {
return false;
}
wasFrameNumberSet = true;
*frameNumber = fNumber;
///increment iterators to after the variable
filenameIt = endHashTag;
patternIt += sharpCount;
} else if (foundPrintFLikeSyntax) { ///If we found a %d style syntax
///There cannot be another variable!
assert(sharpCount == 0 && !foundLongView && !foundShortView);
size_t endPrintfLike = 0;
int fNumber = -1;
///check if the filename matches the %d syntax
if ( !matchesPrintfLikeSyntax(printfDigitCount, filenameCpy, filenameIt, &endPrintfLike, &fNumber) ) {
return false;
}
///If the frame number had already been set and it was different, this filename doesn't match
///the pattern.
if ( wasFrameNumberSet && ( fNumber != *frameNumber) ) {
return false;
}
wasFrameNumberSet = true;
*frameNumber = fNumber;
///increment iterators to after the variable
filenameIt = endPrintfLike;
patternIt += printfLikeVariableSize;
} else if (foundLongView) {
///There cannot be another variable!
assert(sharpCount == 0 && !foundPrintFLikeSyntax && !foundShortView);
size_t endVar;
int vNumber;
///check if the filename matches the %V syntax
if ( !matchesView(true, filenameCpy, filenameIt, &endVar, &vNumber) ) {
return false;
}
///If the view number had already been set and it was different, this filename doesn't match
///the pattern.
if ( wasViewNumberSet && ( vNumber != *viewNumber) ) {
return false;
}
wasViewNumberSet = true;
*viewNumber = vNumber;
///increment iterators to after the variable
filenameIt = endVar;
patternIt += 2;
} else if (foundShortView) {
///There cannot be another variable!
assert(sharpCount == 0 && !foundPrintFLikeSyntax && !foundLongView);
size_t endVar;
int vNumber;
///check if the filename matches the %v syntax
if ( !matchesView(false, filenameCpy, filenameIt, &endVar, &vNumber) ) {
return false;
}
///If the view number had already been set and it was different, this filename doesn't match
///the pattern.
if ( wasViewNumberSet && ( vNumber != *viewNumber) ) {
return false;
}
wasViewNumberSet = true;
*viewNumber = vNumber;
///increment iterators to after the variable
filenameIt = endVar;
patternIt += 2;
} else {
///we found nothing, just compare the characters
if (pattern[patternIt] != filenameCpy[filenameIt]) {
return false;
}
++patternIt;
++filenameIt;
}
}
bool fileNameAtEnd = filenameIt >= filenameCpy.size();
bool patternAtEnd = patternIt >= pattern.size();
if (!fileNameAtEnd || !patternAtEnd) {
return false;
}
return true;
} // matchesPattern_v2
static int countLeadingZeroes(const string& str)
{
int ret = 0;
std::size_t i = 0;
while ( i < str.size() ) {
if (str[i] == '0') {
++ret;
} else {
break;
}
++i;
}
return ret;
}
} // namespace {
namespace SequenceParsing {
/**
* @brief A small structure representing an element of a file name.
* It can be either a text part, or a view part or a frame number part.
**/
struct FileNameElement
{
enum Type { TEXT = 0, FRAME_NUMBER };
FileNameElement(const string& data,
FileNameElement::Type type)
: data(data)
, type(type)
{}
string data;
Type type;
};
////////////////////FileNameContent//////////////////////////
struct FileNameContentPrivate
{
///Ordered from left to right, these are the elements composing the filename without its path
vector<FileNameElement> orderedElements;
string absoluteFileName;
string filePath; //!< the filepath
string filename; //!< the filename without path
string extension; //!< the file extension
string generatedPattern;
int leadingZeroes; //!< leading zeroes for the last number seen in the file path??? why store this?
FileNameContentPrivate()
: orderedElements()
, absoluteFileName()
, filePath()
, filename()
, extension()
, generatedPattern()
, leadingZeroes(0)
{
}
};
FileNameContent::FileNameContent(const string& absoluteFilename)
: _imp( new FileNameContentPrivate() )
{
_imp->absoluteFileName = absoluteFilename;
_imp->filename = absoluteFilename;
_imp->filePath = removePath(_imp->filename);
std::locale loc;
string lastNumberStr;
string lastTextPart;
for (size_t i = 0; i < _imp->filename.size(); ++i) {
const char& c = _imp->filename[i];
if ( std::isdigit(c, loc) ) {
lastNumberStr += c;
if ( !lastTextPart.empty() ) {
_imp->orderedElements.push_back( FileNameElement(lastTextPart, FileNameElement::TEXT) );
lastTextPart.clear();
}
} else {
if ( !lastNumberStr.empty() ) {
_imp->orderedElements.push_back( FileNameElement(lastNumberStr, FileNameElement::FRAME_NUMBER) );
_imp->leadingZeroes = countLeadingZeroes(lastNumberStr); //< take into account only the last FRAME_NUMBER
lastNumberStr.clear();
}
lastTextPart.push_back(c);
}
}
if ( !lastNumberStr.empty() ) {
_imp->orderedElements.push_back( FileNameElement(lastNumberStr, FileNameElement::FRAME_NUMBER) );
_imp->leadingZeroes = countLeadingZeroes(lastNumberStr); //< take into account only the last FRAME_NUMBER
lastNumberStr.clear();
}
if ( !lastTextPart.empty() ) {
_imp->orderedElements.push_back( FileNameElement(lastTextPart, FileNameElement::TEXT) );
lastTextPart.clear();
}
// extension is everything after the last '.'
size_t lastDotPos = _imp->filename.find_last_of('.');
if (lastDotPos == string::npos) {
_imp->extension.clear();
} else {
_imp->extension = _imp->filename.substr(lastDotPos + 1);
}
}
FileNameContent::FileNameContent(const FileNameContent& other)
: _imp( new FileNameContentPrivate() )
{
*this = other;
}
FileNameContent::~FileNameContent()
{
}
void
FileNameContent::operator=(const FileNameContent& other)
{
_imp->orderedElements = other._imp->orderedElements;
_imp->absoluteFileName = other._imp->absoluteFileName;
_imp->filename = other._imp->filename;
_imp->filePath = other._imp->filePath;
_imp->extension = other._imp->extension;
_imp->generatedPattern = other._imp->generatedPattern;
}
int
FileNameContent::getLeadingZeroes() const
{
return _imp->leadingZeroes;
}
/**
* @brief Returns the file path, e.g: /Users/Lala/Pictures/ with the trailing separator.
**/
const string&
FileNameContent::getPath() const
{
return _imp->filePath;
}
/**
* @brief Returns the filename without its path.
**/
const string&
FileNameContent::fileName() const
{
return _imp->filename;
}
/**
* @brief Returns the absolute filename as it was given in the constructor arguments.
**/
const string&
FileNameContent::absoluteFileName() const
{
return _imp->absoluteFileName;
}
const string&
FileNameContent::getExtension() const
{
return _imp->extension;
}
/**
* @brief Returns the file pattern found in the filename with hash characters style for frame number (i.e: ###)
**/
const string&
FileNameContent::getFilePattern(int numHashes) const
{
if ( _imp->generatedPattern.empty() ) {
///now build the generated pattern with the ordered elements.
int numberIndex = 0;
for (size_t j = 0; j < _imp->orderedElements.size(); ++j) {
const FileNameElement& e = _imp->orderedElements[j];
switch (e.type) {
case FileNameElement::TEXT:
_imp->generatedPattern.append(e.data);
break;
case FileNameElement::FRAME_NUMBER: {
string hashStr;
for (int c = 0; c < numHashes; ++c) {
hashStr.push_back('#');
}
_imp->generatedPattern.append( hashStr + stringFromInt(numberIndex) );
++numberIndex;
}
break;
default:
break;
}
}
}
return _imp->generatedPattern;
}
/**
* @brief If the filename is composed of several numbers (e.g: file08_001.png),
* this functions returns the number at index as a string that will be stored in numberString.
* If Index is greater than the number of numbers in the filename or if this filename doesn't
* contain any number, this function returns false.
**/
bool
FileNameContent::getNumberByIndex(int index,
string* numberString) const
{
int numbersElementsIndex = 0;
for (size_t i = 0; i < _imp->orderedElements.size(); ++i) {
if (_imp->orderedElements[i].type == FileNameElement::FRAME_NUMBER) {
if (numbersElementsIndex == index) {
*numberString = _imp->orderedElements[i].data;
return true;
}
++numbersElementsIndex;
}
}
return false;
}
int
FileNameContent::getPotentialFrameNumbersCount() const
{
int count = 0;
for (size_t i = 0; i < _imp->orderedElements.size(); ++i) {
if (_imp->orderedElements[i].type == FileNameElement::FRAME_NUMBER) {
++count;
}
}
return count;
}
/**
* @brief Given the pattern of this file, it tries to match the other file name to this
* pattern.
* @param numberIndexToVary [out] In case the pattern contains several numbers (@see getNumberByIndex)
* this value will be fed the appropriate number index that should be used for frame number.
* For example, if this filename is myfile001_000.jpg and the other file is myfile001_001.jpg
* numberIndexToVary would be 1 as the frame number string identified in that case is the last number.
* @returns True if it identified 'other' as belonging to the same sequence, false otherwise.
**/
bool
FileNameContent::matchesPattern(const FileNameContent& other,