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