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