Move raw_convert into libdcp.
[dcpomatic.git] / src / lib / image_filename_sorter.cc
1 /*
2     Copyright (C) 2015-2016 Carl Hetherington <cth@carlh.net>
3
4     This file is part of DCP-o-matic.
5
6     DCP-o-matic is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     DCP-o-matic is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18
19 */
20
21 #include "image_filename_sorter.h"
22 #include <dcp/raw_convert.h>
23 #include <boost/filesystem.hpp>
24 #include <boost/foreach.hpp>
25 #include <iostream>
26
27 using std::list;
28 using dcp::raw_convert;
29
30 bool
31 ImageFilenameSorter::operator() (boost::filesystem::path a, boost::filesystem::path b)
32 {
33         std::list<int> na = extract_numbers (a);
34         std::list<int> nb = extract_numbers (b);
35         if (na.empty() || nb.empty()) {
36                 return a.string() < b.string();
37         }
38
39         if (na.size() != nb.size()) {
40                 /* Just use the first one */
41                 return na.front() < nb.front();
42         }
43
44         std::list<int>::const_iterator i = na.begin ();
45         std::list<int>::const_iterator j = nb.begin ();
46
47         while (i != na.end()) {
48                 if (*i != *j) {
49                         return *i < *j;
50                 }
51                 ++i;
52                 ++j;
53         }
54
55         /* All the same */
56         return false;
57
58 }
59
60 list<int>
61 ImageFilenameSorter::extract_numbers (boost::filesystem::path p)
62 {
63         p = p.leaf ();
64
65         std::list<std::string> numbers;
66
67         std::string current;
68         for (size_t i = 0; i < p.string().size(); ++i) {
69                 if (isdigit (p.string()[i])) {
70                         current += p.string()[i];
71                 } else {
72                         if (!current.empty ()) {
73                                 numbers.push_back (current);
74                                 current.clear ();
75                         }
76                 }
77         }
78
79         if (!current.empty ()) {
80                 numbers.push_back (current);
81         }
82
83         std::list<int> numbers_as_int;
84         BOOST_FOREACH (std::string i, numbers) {
85                 numbers_as_int.push_back (raw_convert<int> (i));
86         }
87
88         return numbers_as_int;
89 }