38c968a5899124bd6c833dddf5e3e7c557dcc752
[ardour.git] / libs / ardour / file_source.cc
1 /*
2     Copyright (C) 2006-2009 Paul Davis 
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
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <vector>
21
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <stdio.h> // for rename(), sigh
25 #include <unistd.h>
26 #include <fcntl.h>
27 #include <errno.h>
28
29 #include "pbd/convert.h"
30 #include "pbd/basename.h"
31 #include "pbd/mountpoint.h"
32 #include "pbd/stl_delete.h"
33 #include "pbd/strsplit.h"
34 #include "pbd/shortpath.h"
35 #include "pbd/enumwriter.h"
36
37 #include <glibmm/miscutils.h>
38 #include <glibmm/fileutils.h>
39 #include <glibmm/thread.h>
40
41 #include "ardour/file_source.h"
42 #include "ardour/session.h"
43 #include "ardour/session_directory.h"
44 #include "ardour/source_factory.h"
45 #include "ardour/filename_extensions.h"
46
47 #include "i18n.h"
48
49 using namespace ARDOUR;
50 using namespace PBD;
51 using namespace Glib;
52
53 static const std::string PATH_SEP = "/"; // I don't do windows
54
55 map<DataType, ustring> FileSource::search_paths;
56
57 FileSource::FileSource (Session& session, DataType type,
58                 const ustring& path, bool embedded, Source::Flag flag)
59         : Source(session, type, path, flag)
60         , _path(path)
61         , _file_is_new(true)
62         , _channel (0)
63         , _is_embedded(embedded)
64 {
65 }
66
67 FileSource::FileSource (Session& session, const XMLNode& node, bool must_exist)
68         : Source(session, node)
69         , _file_is_new(false)
70 {
71         _path = _name;
72         _is_embedded = (_path.find(PATH_SEP) != string::npos);
73 }
74
75 bool
76 FileSource::removable () const
77 {
78         return (_flags & Removable)
79                 && (   (_flags & RemoveAtDestroy)
80                         || ((_flags & RemovableIfEmpty) && length(timeline_position()) == 0));
81 }
82
83 int
84 FileSource::init (const ustring& pathstr, bool must_exist)
85 {
86         _timeline_position = 0;
87
88         if (!find (_type, pathstr, must_exist, _file_is_new, _channel)) {
89                 throw MissingSource ();
90         }
91
92         if (_file_is_new && must_exist) {
93                 return -1;
94         }
95         
96         return 0;
97 }
98
99 int
100 FileSource::set_state (const XMLNode& node)
101 {
102         const XMLProperty* prop;
103
104         if ((prop = node.property (X_("channel"))) != 0) {
105                 _channel = atoi (prop->value());
106         } else {
107                 _channel = 0;
108         }
109
110         _is_embedded = (_name.find(PATH_SEP) == string::npos);
111
112         return 0;
113 }
114
115 void
116 FileSource::mark_take (const ustring& id)
117 {
118         if (writable ()) {
119                 _take_id = id;
120         }
121 }
122
123 int
124 FileSource::move_to_trash (const ustring& trash_dir_name)
125 {
126         if (is_embedded()) {
127                 cerr << "tried to move an embedded region to trash" << endl;
128                 return -1;
129         }
130
131         if (!writable()) {
132                 return -1;
133         }
134
135         /* don't move the file across filesystems, just stick it in the
136            trash_dir_name directory on whichever filesystem it was already on
137         */
138         
139         ustring newpath;
140         newpath = Glib::path_get_dirname (_path);
141         newpath = Glib::path_get_dirname (newpath); 
142
143         newpath += string(PATH_SEP) + trash_dir_name + PATH_SEP;
144         newpath += Glib::path_get_basename (_path);
145
146         /* the new path already exists, try versioning */
147         if (access (newpath.c_str(), F_OK) == 0) {
148                 char buf[PATH_MAX+1];
149                 int version = 1;
150                 ustring newpath_v;
151
152                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
153                 newpath_v = buf;
154
155                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
156                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
157                         newpath_v = buf;
158                 }
159                 
160                 if (version == 999) {
161                         PBD::error << string_compose (
162                                         _("there are already 1000 files with names like %1; versioning discontinued"),
163                                         newpath) << endmsg;
164                 } else {
165                         newpath = newpath_v;
166                 }
167         }
168
169         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
170                 PBD::error << string_compose (
171                                 _("cannot rename file source from %1 to %2 (%3)"),
172                                 _path, newpath, strerror (errno)) << endmsg;
173                 return -1;
174         }
175
176         if (move_dependents_to_trash() != 0) {
177                 /* try to back out */
178                 rename (newpath.c_str(), _path.c_str());
179                 return -1;
180         }
181             
182         _path = newpath;
183         
184         /* file can not be removed twice, since the operation is not idempotent */
185         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
186
187         return 0;
188 }
189
190 /** Find the actual source file based on \a path.
191  * 
192  * If the source is embedded, \a path should be a filename (no slashes).
193  * If the source is external, \a path should be a full path.
194  * In either case, _path is set to the complete absolute path of the source file.
195  * \return true iff the file was found.
196  */
197 bool
198 FileSource::find (DataType type, const ustring& path, bool must_exist, bool& isnew, uint16_t& chan)
199 {
200         Glib::ustring search_path = search_paths[type];
201
202         ustring pathstr = path;
203         ustring::size_type pos;
204         bool ret = false;
205
206         isnew = false;
207
208         if (pathstr[0] != '/') {
209
210                 /* non-absolute pathname: find pathstr in search path */
211
212                 vector<ustring> dirs;
213                 int cnt;
214                 ustring fullpath;
215                 ustring keeppath;
216
217                 if (search_path.length() == 0) {
218                         error << _("FileSource: search path not set") << endmsg;
219                         goto out;
220                 }
221
222                 split (search_path, dirs, ':');
223
224                 cnt = 0;
225                 
226                 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
227                         fullpath = *i;
228                         if (fullpath[fullpath.length()-1] != '/') {
229                                 fullpath += '/';
230                         }
231
232                         fullpath += pathstr;
233
234                         /* i (paul) made a nasty design error by using ':' as a special character in
235                            Ardour 0.99 .. this hack tries to make things sort of work.
236                         */
237                         
238                         if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
239                                 
240                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
241
242                                         /* its a real file, no problem */
243                                         
244                                         keeppath = fullpath;
245                                         ++cnt;
246
247                                 } else {
248                                         
249                                         if (must_exist) {
250                                                 
251                                                 /* might be an older session using file:channel syntax. see if the version
252                                                    without the :suffix exists
253                                                  */
254                                                 
255                                                 ustring shorter = pathstr.substr (0, pos);
256                                                 fullpath = *i;
257
258                                                 if (fullpath[fullpath.length()-1] != '/') {
259                                                         fullpath += '/';
260                                                 }
261
262                                                 fullpath += shorter;
263
264                                                 if (Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
265                                                         chan = atoi (pathstr.substr (pos+1));
266                                                         pathstr = shorter;
267                                                         keeppath = fullpath;
268                                                         ++cnt;
269                                                 } 
270                                                 
271                                         } else {
272                                                 
273                                                 /* new derived file (e.g. for timefx) being created in a newer session */
274                                                 
275                                         }
276                                 }
277
278                         } else {
279
280                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
281                                         keeppath = fullpath;
282                                         ++cnt;
283                                 } 
284                         }
285                 }
286
287                 if (cnt > 1) {
288
289                         error << string_compose (
290                                         _("FileSource: \"%1\" is ambigous when searching %2\n\t"),
291                                         pathstr, search_path) << endmsg;
292                         goto out;
293
294                 } else if (cnt == 0) {
295
296                         if (must_exist) {
297                                 error << string_compose(
298                                                 _("Filesource: cannot find required file (%1): while searching %2"),
299                                                 pathstr, search_path) << endmsg;
300                                 goto out;
301                         } else {
302                                 isnew = true;
303                         }
304                 }
305
306                 /* Current find() is unable to parse relative path names to yet non-existant
307                    sources. QuickFix(tm) */
308                 if (keeppath == "") {
309                         if (must_exist) {
310                                 error << "FileSource::find(), keeppath = \"\", but the file must exist" << endl;
311                         } else {
312                                 keeppath = pathstr;
313                         }
314                 }
315
316                 _path = keeppath;
317                 
318                 ret = true;
319
320         } else {
321                 
322                 /* external files and/or very very old style sessions include full paths */
323
324                 /* ugh, handle ':' situation */
325
326                 if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
327                         
328                         ustring shorter = pathstr.substr (0, pos);
329
330                         if (Glib::file_test (shorter, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
331                                 chan = atoi (pathstr.substr (pos+1));
332                                 pathstr = shorter;
333                         }
334                 }
335                 
336                 _path = pathstr;
337
338                 if (!Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
339
340                         /* file does not exist or we cannot read it */
341                         
342                         if (must_exist) {
343                                 error << string_compose(
344                                                 _("Filesource: cannot find required file (%1): %2"),
345                                                 _path, strerror (errno)) << endmsg;
346                                 goto out;
347                         }
348                         
349                         if (errno != ENOENT) {
350                                 error << string_compose(
351                                                 _("Filesource: cannot check for existing file (%1): %2"),
352                                                 _path, strerror (errno)) << endmsg;
353                                 goto out;
354                         }
355                         
356                         /* a new file */
357                         isnew = true;
358                         ret = true;
359
360                 } else {
361                         
362                         /* already exists */
363                         ret = true;
364                 }
365         }
366         
367         if (_is_embedded) {
368                 _name = Glib::path_get_basename (_name);
369         }
370         
371 out:
372         return ret;
373 }
374
375 int
376 FileSource::set_source_name (const ustring& newname, bool destructive)
377 {
378         Glib::Mutex::Lock lm (_lock);
379         ustring oldpath = _path;
380         ustring newpath = Session::change_source_path_by_name (oldpath, _name, newname, destructive);
381         
382         if (newpath.empty()) {
383                 error << string_compose (_("programming error: %1"), "cannot generate a changed file path") << endmsg;
384                 return -1;
385         }
386
387         // Test whether newpath exists, if yes notify the user but continue. 
388         if (access(newpath.c_str(),F_OK) == 0) {
389                 error << _("Programming error! Ardour tried to rename a file over another file! It's safe to continue working, but please report this to the developers.") << endmsg;
390                 return -1;
391         }
392
393         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
394                 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
395                 return -1;
396         }
397
398         _name = Glib::path_get_basename (newpath);
399         _path = newpath;
400
401         return 0;
402 }
403
404 void
405 FileSource::set_search_path (DataType type, const ustring& p)
406 {
407         search_paths[type] = p;
408 }
409
410 void
411 FileSource::mark_immutable ()
412 {
413         /* destructive sources stay writable, and their other flags don't change.  */
414         if (!(_flags & Destructive)) {
415                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
416         }
417 }
418