forward port 2.X changes up to and including rev 6909
[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 map<DataType, ustring> FileSource::search_paths;
56
57 FileSource::FileSource (Session& session, DataType type, const ustring& 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         cerr << "is " << _path << " removable ? " << r << endl;
88
89         return r;
90 }
91
92 int
93 FileSource::init (const ustring& pathstr, bool must_exist)
94 {
95         _timeline_position = 0;
96
97         if (!find (_type, pathstr, must_exist, _file_is_new, _channel, _path)) {
98                 throw MissingSource ();
99         }
100
101         set_within_session_from_path (pathstr);
102
103         if (_within_session) {
104                 _name = Glib::path_get_basename (_name);
105         }
106
107         if (_file_is_new && must_exist) {
108                 return -1;
109         }
110
111         return 0;
112 }
113
114 int
115 FileSource::set_state (const XMLNode& node, int /*version*/)
116 {
117         const XMLProperty* prop;
118
119         if ((prop = node.property (X_("channel"))) != 0) {
120                 _channel = atoi (prop->value());
121         } else {
122                 _channel = 0;
123         }
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 (!within_session() || !writable()) {
140                 return -1;
141         }
142
143         /* don't move the file across filesystems, just stick it in the
144            trash_dir_name directory on whichever filesystem it was already on
145         */
146
147         vector<string> v;
148         v.push_back (Glib::path_get_dirname (Glib::path_get_dirname (_path)));
149         v.push_back (trash_dir_name);
150         v.push_back (Glib::path_get_basename (_path));
151
152         string newpath = Glib::build_filename (v);
153
154         /* the new path already exists, try versioning */
155
156         if (Glib::file_test (newpath.c_str(), Glib::FILE_TEST_EXISTS)) {
157                 char buf[PATH_MAX+1];
158                 int version = 1;
159                 ustring newpath_v;
160
161                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
162                 newpath_v = buf;
163
164                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
165                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
166                         newpath_v = buf;
167                 }
168
169                 if (version == 999) {
170                         PBD::error << string_compose (
171                                         _("there are already 1000 files with names like %1; versioning discontinued"),
172                                         newpath) << endmsg;
173                 } else {
174                         newpath = newpath_v;
175                 }
176         }
177
178         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
179                 PBD::error << string_compose (
180                                 _("cannot rename file source from %1 to %2 (%3)"),
181                                 _path, newpath, strerror (errno)) << endmsg;
182                 return -1;
183         }
184
185         if (move_dependents_to_trash() != 0) {
186                 /* try to back out */
187                 rename (newpath.c_str(), _path.c_str());
188                 return -1;
189         }
190
191         _path = newpath;
192
193         /* file can not be removed twice, since the operation is not idempotent */
194         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
195
196         return 0;
197 }
198
199 /** Find the actual source file based on \a filename.
200  *
201  * If the source is within the session tree, \a filename should be a simple filename (no slashes).
202  * If the source is external, \a filename should be a full path.
203  * In either case, found_path is set to the complete absolute path of the source file.
204  * \return true iff the file was found.
205  */
206 bool
207 FileSource::find (DataType type, const ustring& path, bool must_exist,
208                   bool& isnew, uint16_t& chan, ustring& found_path)
209 {
210         Glib::ustring search_path = search_paths[type];
211
212         ustring pathstr = path;
213         ustring::size_type pos;
214         bool ret = false;
215
216         isnew = false;
217
218         if (!Glib::path_is_absolute (pathstr)) {
219
220                 /* non-absolute pathname: find pathstr in search path */
221
222                 vector<ustring> dirs;
223                 int cnt;
224                 ustring fullpath;
225                 ustring keeppath;
226
227                 if (search_path.length() == 0) {
228                         error << _("FileSource: search path not set") << endmsg;
229                         goto out;
230                 }
231
232                 split (search_path, dirs, ':');
233
234                 cnt = 0;
235
236                 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
237                         
238                         fullpath = Glib::build_filename (*i, pathstr);
239
240                         /* i (paul) made a nasty design error by using ':' as a special character in
241                            Ardour 0.99 .. this hack tries to make things sort of work.
242                         */
243
244                         if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
245
246                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
247
248                                         /* its a real file, no problem */
249
250                                         keeppath = fullpath;
251                                         ++cnt;
252
253                                 } else {
254
255                                         if (must_exist) {
256
257                                                 /* might be an older session using file:channel syntax. see if the version
258                                                    without the :suffix exists
259                                                  */
260
261                                                 ustring shorter = pathstr.substr (0, pos);
262                                                 fullpath = Glib::build_filename (*i, 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                 found_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                 found_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 out:
368         return ret;
369 }
370
371 int
372 FileSource::set_source_name (const ustring& newname, bool destructive)
373 {
374         Glib::Mutex::Lock lm (_lock);
375         ustring oldpath = _path;
376         ustring newpath = _session.change_source_path_by_name (oldpath, _name, newname, destructive);
377
378         if (newpath.empty()) {
379                 error << string_compose (_("programming error: %1"), "cannot generate a changed file path") << endmsg;
380                 return -1;
381         }
382
383         // Test whether newpath exists, if yes notify the user but continue.
384         if (Glib::file_test (newpath, Glib::FILE_TEST_EXISTS)) {
385                 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;
386                 return -1;
387         }
388         
389         if (::rename (oldpath.c_str(), newpath.c_str()) != 0) {
390                 error << string_compose (_("cannot rename file %1 to %2 (%3)"), oldpath, newpath, strerror(errno)) << endmsg;
391                 return -1;
392         }
393
394         _name = Glib::path_get_basename (newpath);
395         _path = newpath;
396
397         return 0;
398 }
399
400 void
401 FileSource::set_search_path (DataType type, const ustring& p)
402 {
403         search_paths[type] = p;
404 }
405
406 void
407 FileSource::mark_immutable ()
408 {
409         /* destructive sources stay writable, and their other flags don't change.  */
410         if (!(_flags & Destructive)) {
411                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
412         }
413 }
414
415 void
416 FileSource::mark_nonremovable ()
417 {
418         _flags = Flag (_flags & ~(Removable|RemovableIfEmpty|RemoveAtDestroy));
419 }
420
421 void
422 FileSource::set_within_session_from_path (const std::string& path)
423 {
424         _within_session = _session.path_is_within_session (path);
425 }
426
427 int
428 FileSource::unstubify ()
429 {
430         string::size_type pos = _path.find (stub_dir_name);
431
432         if (pos == string::npos || (_flags & Destructive)) {
433                 return 0;
434         }
435
436         vector<string> v;
437
438         v.push_back (Glib::path_get_dirname (Glib::path_get_dirname (_path)));
439         v.push_back (Glib::path_get_basename(_path));
440         
441         string newpath = Glib::build_filename (v);
442
443         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
444                 error << string_compose (_("rename from %1 to %2 failed: %3)"), _path, newpath, strerror (errno)) << endmsg;
445                 return -1;
446         }
447
448         set_path (newpath);
449
450         return 0;
451 }
452
453 void
454 FileSource::set_path (const std::string& newpath)
455 {
456         _path = newpath;
457 }
458
459 void 
460 FileSource::inc_use_count ()
461 {
462         Source::inc_use_count ();
463 }
464