7eac1a23ea2a10fa52845b109ad99536154f6aa2
[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/directory_names.h"
43 #include "ardour/session.h"
44 #include "ardour/session_directory.h"
45 #include "ardour/source_factory.h"
46 #include "ardour/filename_extensions.h"
47
48 #include "i18n.h"
49
50 using namespace std;
51 using namespace ARDOUR;
52 using namespace PBD;
53 using namespace Glib;
54
55 PBD::Signal3<int,std::string,std::string,std::vector<std::string> > FileSource::AmbiguousFileName;
56
57 FileSource::FileSource (Session& session, DataType type, const string& path, Source::Flag flag)
58         : Source(session, type, path, flag)
59         , _path(path)
60         , _file_is_new(true)
61         , _channel (0)
62 {
63         set_within_session_from_path (path);
64 }
65
66 FileSource::FileSource (Session& session, const XMLNode& node, bool /*must_exist*/)
67         : Source(session, node)
68         , _file_is_new (false)
69 {
70         /* this setting of _path is temporary - we expect derived classes
71            to call ::init() which will actually locate the file
72            and reset _path and _within_session correctly.
73         */
74
75         _path = _name;
76         _within_session = true;
77 }
78
79 bool
80 FileSource::removable () const
81 {
82         bool r = (_path.find (stub_dir_name) != string::npos) ||
83                 ((_flags & Removable)
84                  && ((_flags & RemoveAtDestroy) || 
85                      ((_flags & RemovableIfEmpty) && empty() == 0)));
86
87         return r;
88 }
89
90 int
91 FileSource::init (const string& pathstr, bool must_exist)
92 {
93         _timeline_position = 0;
94
95         if (Stateful::loading_state_version < 3000) {
96                 if (!find_2X (_session, _type, pathstr, must_exist, _file_is_new, _channel, _path)) {
97                         throw MissingSource (pathstr, _type);
98                 }
99         } else {
100                 if (!find (_session, _type, pathstr, must_exist, _file_is_new, _channel, _path)) {
101                         throw MissingSource (pathstr, _type);
102                 }
103         }
104
105         set_within_session_from_path (pathstr);
106
107         if (!within_session()) {
108                 _session.ensure_search_path_includes (Glib::path_get_dirname (pathstr), _type);
109         }
110
111         _name = Glib::path_get_basename (pathstr);
112
113         if (_file_is_new && must_exist) {
114                 return -1;
115         }
116
117         return 0;
118 }
119
120 int
121 FileSource::set_state (const XMLNode& node, int /*version*/)
122 {
123         const XMLProperty* prop;
124
125         if ((prop = node.property (X_("channel"))) != 0) {
126                 _channel = atoi (prop->value());
127         } else {
128                 _channel = 0;
129         }
130
131         return 0;
132 }
133
134 void
135 FileSource::mark_take (const string& id)
136 {
137         if (writable ()) {
138                 _take_id = id;
139         }
140 }
141
142 int
143 FileSource::move_to_trash (const string& trash_dir_name)
144 {
145         if (!within_session() || !writable()) {
146                 return -1;
147         }
148
149         /* don't move the file across filesystems, just stick it in the
150            trash_dir_name directory on whichever filesystem it was already on
151         */
152
153         vector<string> v;
154         v.push_back (Glib::path_get_dirname (Glib::path_get_dirname (_path)));
155         v.push_back (trash_dir_name);
156         v.push_back (Glib::path_get_basename (_path));
157
158         string newpath = Glib::build_filename (v);
159
160         /* the new path already exists, try versioning */
161
162         if (Glib::file_test (newpath.c_str(), Glib::FILE_TEST_EXISTS)) {
163                 char buf[PATH_MAX+1];
164                 int version = 1;
165                 string newpath_v;
166
167                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
168                 newpath_v = buf;
169
170                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
171                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
172                         newpath_v = buf;
173                 }
174
175                 if (version == 999) {
176                         PBD::error << string_compose (
177                                         _("there are already 1000 files with names like %1; versioning discontinued"),
178                                         newpath) << endmsg;
179                 } else {
180                         newpath = newpath_v;
181                 }
182         }
183
184         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
185                 PBD::error << string_compose (
186                                 _("cannot rename file source from %1 to %2 (%3)"),
187                                 _path, newpath, strerror (errno)) << endmsg;
188                 return -1;
189         }
190
191         if (move_dependents_to_trash() != 0) {
192                 /* try to back out */
193                 rename (newpath.c_str(), _path.c_str());
194                 return -1;
195         }
196
197         _path = newpath;
198
199         /* file can not be removed twice, since the operation is not idempotent */
200         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
201
202         return 0;
203 }
204
205 /** Find the actual source file based on \a filename.
206  *
207  * If the source is within the session tree, \a filename should be a simple filename (no slashes).
208  * If the source is external, \a filename should be a full path.
209  * In either case, found_path is set to the complete absolute path of the source file.
210  * \return true iff the file was found.
211  */
212 bool
213 FileSource::find (Session& s, DataType type, const string& path, bool must_exist,
214                   bool& isnew, uint16_t& chan, string& found_path)
215 {
216         bool ret = false;
217         string keeppath;
218
219         isnew = false;
220         
221         if (!Glib::path_is_absolute (path)) {
222                 vector<string> dirs;
223                 vector<string> hits;
224                 int cnt;
225                 string fullpath;
226
227                 string search_path = s.source_search_path (type);
228
229                 if (search_path.length() == 0) {
230                         error << _("FileSource: search path not set") << endmsg;
231                         goto out;
232                 }
233
234                 split (search_path, dirs, ':');
235                 
236                 cnt = 0;
237                 hits.clear ();
238                 
239                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
240                         
241                         fullpath = Glib::build_filename (*i, path);
242                         
243                         if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
244                                 keeppath = fullpath;
245                                 hits.push_back (fullpath);
246                                 ++cnt;
247                         }
248                 }
249                 
250                 if (cnt > 1) {
251                         
252                         int which = FileSource::AmbiguousFileName (path, search_path, hits).get_value_or (-1);
253                         
254                         if (which < 0) {
255                                 goto out;
256                         } else {
257                                 keeppath = hits[which];
258                         }
259                         
260                 } else if (cnt == 0) {
261                         
262                         if (must_exist) {
263                                 error << string_compose(
264                                         _("Filesource: cannot find required file (%1): while searching %2"),
265                                         path, search_path) << endmsg;
266                                 goto out;
267                         } else {
268                                 isnew = true;
269                         }
270                 }
271         } else {
272                 keeppath = path;
273         }
274         
275         /* Current find() is unable to parse relative path names to yet non-existant
276            sources. QuickFix(tm) 
277         */
278         if (keeppath == "") {
279                 if (must_exist) {
280                         error << "FileSource::find(), keeppath = \"\", but the file must exist" << endl;
281                 } else {
282                         keeppath = path;
283                 }
284         }
285         
286         found_path = keeppath;
287         
288         ret = true;
289         
290   out:
291         return ret;
292 }
293
294 /** Find the actual source file based on \a filename.
295  *
296  * If the source is within the session tree, \a filename should be a simple filename (no slashes).
297  * If the source is external, \a filename should be a full path.
298  * In either case, found_path is set to the complete absolute path of the source file.
299  * \return true iff the file was found.
300  */
301 bool
302 FileSource::find_2X (Session& s, DataType type, const string& path, bool must_exist,
303                      bool& isnew, uint16_t& chan, string& found_path)
304 {
305         string search_path = s.source_search_path (type);
306
307         string pathstr = path;
308         string::size_type pos;
309         bool ret = false;
310
311         isnew = false;
312
313         if (!Glib::path_is_absolute (pathstr)) {
314
315                 /* non-absolute pathname: find pathstr in search path */
316
317                 vector<string> dirs;
318                 int cnt;
319                 string fullpath;
320                 string keeppath;
321
322                 if (search_path.length() == 0) {
323                         error << _("FileSource: search path not set") << endmsg;
324                         goto out;
325                 }
326
327                 split (search_path, dirs, ':');
328
329                 cnt = 0;
330
331                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
332                         
333                         fullpath = Glib::build_filename (*i, pathstr);
334
335                         /* i (paul) made a nasty design error by using ':' as a special character in
336                            Ardour 0.99 .. this hack tries to make things sort of work.
337                         */
338
339                         if ((pos = pathstr.find_last_of (':')) != string::npos) {
340
341                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
342
343                                         /* its a real file, no problem */
344
345                                         keeppath = fullpath;
346                                         ++cnt;
347
348                                 } else {
349
350                                         if (must_exist) {
351
352                                                 /* might be an older session using file:channel syntax. see if the version
353                                                    without the :suffix exists
354                                                  */
355
356                                                 string shorter = pathstr.substr (0, pos);
357                                                 fullpath = Glib::build_filename (*i, shorter);
358
359                                                 if (Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
360                                                         chan = atoi (pathstr.substr (pos+1));
361                                                         pathstr = shorter;
362                                                         keeppath = fullpath;
363                                                         ++cnt;
364                                                 }
365
366                                         } else {
367
368                                                 /* new derived file (e.g. for timefx) being created in a newer session */
369
370                                         }
371                                 }
372
373                         } else {
374
375                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
376                                         keeppath = fullpath;
377                                         ++cnt;
378                                 }
379                         }
380                 }
381
382                 if (cnt > 1) {
383
384                         error << string_compose (
385                                         _("FileSource: \"%1\" is ambigous when searching %2\n\t"),
386                                         pathstr, search_path) << endmsg;
387                         goto out;
388
389                 } else if (cnt == 0) {
390
391                         if (must_exist) {
392                                 error << string_compose(
393                                                 _("Filesource: cannot find required file (%1): while searching %2"),
394                                                 pathstr, search_path) << endmsg;
395                                 goto out;
396                         } else {
397                                 isnew = true;
398                         }
399                 }
400
401                 /* Current find() is unable to parse relative path names to yet non-existant
402                    sources. QuickFix(tm) */
403                 if (keeppath == "") {
404                         if (must_exist) {
405                                 error << "FileSource::find(), keeppath = \"\", but the file must exist" << endl;
406                         } else {
407                                 keeppath = pathstr;
408                         }
409                 }
410
411                 found_path = keeppath;
412
413                 ret = true;
414
415         } else {
416
417                 /* external files and/or very very old style sessions include full paths */
418
419                 /* ugh, handle ':' situation */
420
421                 if ((pos = pathstr.find_last_of (':')) != string::npos) {
422
423                         string shorter = pathstr.substr (0, pos);
424
425                         if (Glib::file_test (shorter, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
426                                 chan = atoi (pathstr.substr (pos+1));
427                                 pathstr = shorter;
428                         }
429                 }
430
431                 found_path = pathstr;
432
433                 if (!Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
434
435                         /* file does not exist or we cannot read it */
436
437                         if (must_exist) {
438                                 error << string_compose(
439                                                 _("Filesource: cannot find required file (%1): %2"),
440                                                 path, strerror (errno)) << endmsg;
441                                 goto out;
442                         }
443
444                         if (errno != ENOENT) {
445                                 error << string_compose(
446                                                 _("Filesource: cannot check for existing file (%1): %2"),
447                                                 path, strerror (errno)) << endmsg;
448                                 goto out;
449                         }
450
451                         /* a new file */
452                         isnew = true;
453                         ret = true;
454
455                 } else {
456
457                         /* already exists */
458                         ret = true;
459                 }
460         }
461
462 out:
463         return ret;
464 }
465
466 int
467 FileSource::set_source_name (const string& newname, bool destructive)
468 {
469         Glib::Mutex::Lock lm (_lock);
470         string oldpath = _path;
471         string newpath = _session.change_source_path_by_name (oldpath, _name, newname, destructive);
472
473         if (newpath.empty()) {
474                 error << string_compose (_("programming error: %1"), "cannot generate a changed file path") << endmsg;
475                 return -1;
476         }
477
478         // Test whether newpath exists, if yes notify the user but continue.
479         if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
480                 error << string_compose (_("Programming error! %1 tried to rename a file over another file! It's safe to continue working, but please report this to the developers."), PROGRAM_NAME) << endmsg;
481                 return -1;
482         }
483         
484         if (::rename (oldpath.c_str(), newpath.c_str()) != 0) {
485                 error << string_compose (_("cannot rename file %1 to %2 (%3)"), oldpath, newpath, strerror(errno)) << endmsg;
486                 return -1;
487         }
488
489         _name = Glib::path_get_basename (newpath);
490         _path = newpath;
491
492         return 0;
493 }
494
495 void
496 FileSource::mark_immutable ()
497 {
498         /* destructive sources stay writable, and their other flags don't change.  */
499         if (!(_flags & Destructive)) {
500                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
501         }
502 }
503
504 void
505 FileSource::mark_nonremovable ()
506 {
507         _flags = Flag (_flags & ~(Removable|RemovableIfEmpty|RemoveAtDestroy));
508 }
509
510 void
511 FileSource::set_within_session_from_path (const std::string& path)
512 {
513         _within_session = _session.path_is_within_session (path);
514 }
515
516 int
517 FileSource::unstubify ()
518 {
519         string::size_type pos = _path.find (stub_dir_name);
520
521         if (pos == string::npos || (_flags & Destructive)) {
522                 return 0;
523         }
524
525         vector<string> v;
526
527         v.push_back (Glib::path_get_dirname (Glib::path_get_dirname (_path)));
528         v.push_back (Glib::path_get_basename(_path));
529         
530         string newpath = Glib::build_filename (v);
531
532         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
533                 error << string_compose (_("rename from %1 to %2 failed: %3)"), _path, newpath, strerror (errno)) << endmsg;
534                 return -1;
535         }
536
537         set_path (newpath);
538
539         return 0;
540 }
541
542 void
543 FileSource::set_path (const std::string& newpath)
544 {
545         _path = newpath;
546 }
547
548 void 
549 FileSource::inc_use_count ()
550 {
551         Source::inc_use_count ();
552 }
553