Fix XML-writer edge-case (empty content)
[ardour.git] / libs / pbd / shortpath.cc
1 /*
2  * Copyright (C) 2000-2015 Paul Davis <paul@linuxaudiosystems.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation; either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <stdint.h>
20 #include "pbd/shortpath.h"
21
22 using namespace Glib;
23 using namespace std;
24
25 ustring
26 short_path (const Glib::ustring& path, ustring::size_type target_characters)
27 {
28         ustring::size_type last_sep;
29         ustring::size_type len = path.length();
30         const char separator = '/';
31
32         if (len <= target_characters) {
33                 return path;
34         }
35
36         if ((last_sep = path.find_last_of (separator)) == ustring::npos) {
37
38                 /* just a filename, but its too long anyway */
39
40                 if (target_characters > 3) {
41                         return path.substr (0, target_characters - 3) + ustring ("...");
42                 } else {
43                         /* stupid caller, just hand back the whole thing */
44                         return path;
45                 }
46         }
47
48         if (len - last_sep >= target_characters) {
49
50                 /* even the filename itself is too long */
51
52                 if (target_characters > 3) {
53                         return path.substr (last_sep+1, target_characters - 3) + ustring ("...");
54                 } else {
55                         /* stupid caller, just hand back the whole thing */
56                         return path;
57                 }
58         }
59
60         uint32_t so_far = (len - last_sep);
61         uint32_t space_for = target_characters - so_far;
62
63         if (space_for >= 3) {
64                 ustring res = "...";
65                 res += path.substr (last_sep - space_for);
66                 return res;
67         } else {
68                 /* remove part of the end */
69                 ustring res = "...";
70                 res += path.substr (last_sep - space_for, len - last_sep + space_for - 3);
71                 res += "...";
72                 return res;
73
74         }
75 }