remove stay-on-top behavior from import dialog, and set its WM class
[ardour.git] / gtk2_ardour / editor_audio_import.cc
1 /*
2     Copyright (C) 2000-2006 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 <sys/types.h>
21 #include <sys/stat.h>
22 #include <sys/time.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <algorithm>
26
27 #include <sndfile.h>
28
29 #include "pbd/pthread_utils.h"
30 #include "pbd/basename.h"
31 #include "pbd/shortpath.h"
32 #include "pbd/stateful_diff_command.h"
33
34 #include <gtkmm2ext/choice.h>
35
36 #include "ardour/audio_track.h"
37 #include "ardour/audiofilesource.h"
38 #include "ardour/audioregion.h"
39 #include "ardour/midi_region.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/operations.h"
42 #include "ardour/region_factory.h"
43 #include "ardour/smf_source.h"
44 #include "ardour/source_factory.h"
45 #include "ardour/utils.h"
46 #include "pbd/memento_command.h"
47
48 #include "ardour_ui.h"
49 #include "editor.h"
50 #include "sfdb_ui.h"
51 #include "editing.h"
52 #include "audio_time_axis.h"
53 #include "midi_time_axis.h"
54 #include "session_import_dialog.h"
55 #include "utils.h"
56 #include "gui_thread.h"
57 #include "interthread_progress_window.h"
58 #include "mouse_cursors.h"
59 #include "editor_cursors.h"
60
61 #include "i18n.h"
62
63 using namespace std;
64 using namespace ARDOUR;
65 using namespace PBD;
66 using namespace Gtk;
67 using namespace Gtkmm2ext;
68 using namespace Editing;
69 using std::string;
70
71 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
72
73 void
74 Editor::add_external_audio_action (ImportMode mode_hint)
75 {
76         if (_session == 0) {
77                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
78                 msg.run ();
79                 return;
80         }
81
82         if (sfbrowser == 0) {
83                 sfbrowser = new SoundFileOmega (_("Add Existing Media"), _session, 0, true, mode_hint);
84         } else {
85                 sfbrowser->set_mode (mode_hint);
86         }
87
88         external_audio_dialog ();
89 }
90
91 void
92 Editor::external_audio_dialog ()
93 {
94         vector<string> paths;
95         uint32_t audio_track_cnt;
96         uint32_t midi_track_cnt;
97
98         if (_session == 0) {
99                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
100                 msg.run ();
101                 return;
102         }
103
104         audio_track_cnt = 0;
105         midi_track_cnt = 0;
106
107         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
108                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*x);
109
110                 if (atv) {
111                         if (atv->is_audio_track()) {
112                                 audio_track_cnt++;
113                         } 
114
115                 } else {
116                         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(*x);
117
118                         if (mtv) {
119                                 if (mtv->is_midi_track()) {
120                                         midi_track_cnt++;
121                                 }
122                         }
123                 }
124         }
125
126         if (sfbrowser == 0) {
127                 sfbrowser = new SoundFileOmega (_("Add Existing Media"), _session, audio_track_cnt, midi_track_cnt, true);
128         } else {
129                 sfbrowser->reset (audio_track_cnt, midi_track_cnt);
130         }
131
132         sfbrowser->show_all ();
133 }
134
135 void
136 Editor::session_import_dialog ()
137 {
138         SessionImportDialog dialog (_session);
139         ensure_float (dialog);
140         dialog.run ();
141 }
142
143 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
144
145 /**
146  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_files()
147  *
148  * all_or_nothing:
149  *   true  = show "Update", "Import" and "Skip"
150  *   false = show "Import", and "Cancel"
151  *
152  * Returns:
153  *     0  To update an existing source of the same name
154  *     1  To import/embed the file normally (make sure the new name will be unique)
155  *     2  If the user wants to skip this file
156  **/
157 int
158 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
159 {
160         string wave_name (Glib::path_get_basename(path));
161
162         SourceMap all_sources = _session->get_sources();
163         bool already_exists = false;
164         uint32_t existing;
165
166         if ((existing = _session->count_sources_by_origin (path)) > 0) {
167                 already_exists = true;
168         }
169
170         int function = 1;
171
172         if (already_exists) {
173                 string message;
174                 if (all_or_nothing) {
175                         // updating is still disabled
176                         //message = string_compose(_("The session already contains a source file named %1. Do you want to update that file (and thus all regions using the file) or import this file as a new file?"),wave_name);
177                         message = string_compose (_("The session already contains a source file named %1.  Do you want to import %1 as a new file, or skip it?"), wave_name);
178                 } else {
179                         message = string_compose (_("The session already contains a source file named %1.  Do you want to import %2 as a new source, or skip it?"), wave_name, wave_name);
180
181                 }
182                 MessageDialog dialog(message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
183
184                 if (all_or_nothing) {
185                         // disabled
186                         //dialog.add_button("Update", 0);
187                         dialog.add_button("Import", 1);
188                         dialog.add_button("Skip",   2);
189                 } else {
190                         dialog.add_button("Import", 1);
191                         dialog.add_button("Cancel", 2);
192                 }
193
194                 //dialog.add_button("Skip all", 4); // All or rest?
195
196                 dialog.show();
197
198                 function = dialog.run ();
199
200                 dialog.hide();
201         }
202
203         return function;
204 }
205
206 boost::shared_ptr<AudioTrack>
207 Editor::get_nth_selected_audio_track (int nth) const
208 {
209         AudioTimeAxisView* atv;
210         TrackSelection::iterator x;
211
212         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
213
214                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
215
216                 if (!atv) {
217                         continue;
218                 } else if (atv->is_audio_track()) {
219                         --nth;
220                 }
221         }
222
223         if (x == selection->tracks.end()) {
224                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
225         } else {
226                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
227         }
228
229         if (!atv || !atv->is_audio_track()) {
230                 return boost::shared_ptr<AudioTrack>();
231         }
232
233         return atv->audio_track();
234 }
235
236 boost::shared_ptr<MidiTrack>
237 Editor::get_nth_selected_midi_track (int nth) const
238 {
239         MidiTimeAxisView* mtv;
240         TrackSelection::iterator x;
241
242         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
243
244                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
245
246                 if (!mtv) {
247                         continue;
248                 } else if (mtv->is_midi_track()) {
249                         --nth;
250                 }
251         }
252
253         if (x == selection->tracks.end()) {
254                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
255         } else {
256                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
257         }
258
259         if (!mtv || !mtv->is_midi_track()) {
260                 return boost::shared_ptr<MidiTrack>();
261         }
262
263         return mtv->midi_track();
264 }
265
266 void
267 Editor::do_import (vector<string> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, framepos_t& pos)
268 {
269         boost::shared_ptr<Track> track;
270         vector<string> to_import;
271         int nth = 0;
272         bool use_timestamp = (pos == -1);
273
274         current_interthread_info = &import_status;
275         import_status.current = 1;
276         import_status.total = paths.size ();
277         import_status.all_done = false;
278
279         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
280
281         bool ok = true;
282
283         if (chns == Editing::ImportMergeFiles) {
284
285                 /* create 1 region from all paths, add to 1 track,
286                    ignore "track"
287                 */
288
289                 bool cancel = false;
290                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
291                         int check = check_whether_and_how_to_import(*a, false);
292                         if (check == 2) {
293                                 cancel = true;
294                                 break;
295                         }
296                 }
297
298                 if (cancel) {
299                         ok = false;
300                 } else {
301                         ipw.show ();
302                         ok = (import_sndfiles (paths, mode, quality, pos, 1, 1, track, false) == 0);
303                 }
304
305         } else {
306
307                 bool replace = false;
308
309                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
310
311                         const int check = check_whether_and_how_to_import (*a, true);
312
313                         switch (check) {
314                         case 2:
315                                 // user said skip
316                                 continue;
317                         case 0:
318                                 fatal << "Updating existing sources should be disabled!" << endmsg;
319                                 /* NOTREACHED*/
320                                 break;
321                         case 1:
322                                 replace = false;
323                                 break;
324                         default:
325                                 fatal << "Illegal return " << check <<  " from check_whether_and_how_to_import()!" << endmsg;
326                                 /* NOTREACHED*/
327                         }
328
329                         /* have to reset this for every file we handle */
330
331                         if (use_timestamp) {
332                                 pos = -1;
333                         }
334
335                         ipw.show ();
336
337                         switch (chns) {
338                         case Editing::ImportDistinctFiles:
339
340                                 to_import.clear ();
341                                 to_import.push_back (*a);
342
343                                 if (mode == Editing::ImportToTrack) {
344                                         track = get_nth_selected_audio_track (nth++);
345                                 }
346
347                                 ok = (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, replace) == 0);
348                                 break;
349
350                         case Editing::ImportDistinctChannels:
351
352                                 to_import.clear ();
353                                 to_import.push_back (*a);
354
355                                 ok = (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, replace) == 0);
356                                 break;
357
358                         case Editing::ImportSerializeFiles:
359
360                                 to_import.clear ();
361                                 to_import.push_back (*a);
362
363                                 ok = (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, replace) == 0);
364                                 break;
365
366                         case Editing::ImportMergeFiles:
367                                 // Not entered, handled in earlier if() branch
368                                 break;
369                         }
370                 }
371         }
372
373         if (ok) {
374                 _session->save_state ("");
375         }
376
377         import_status.all_done = true;
378 }
379
380 void
381 Editor::do_embed (vector<string> paths, ImportDisposition chns, ImportMode mode, framepos_t& pos)
382 {
383         boost::shared_ptr<Track> track;
384         bool check_sample_rate = true;
385         bool ok = false;
386         vector<string> to_embed;
387         bool multi = paths.size() > 1;
388         int nth = 0;
389         bool use_timestamp = (pos == -1);
390
391         switch (chns) {
392         case Editing::ImportDistinctFiles:
393                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
394
395                         /* have to reset this for every file we handle */
396                         if (use_timestamp) {
397                                 pos = -1;
398                         }
399
400                         to_embed.clear ();
401                         to_embed.push_back (*a);
402
403                         if (mode == Editing::ImportToTrack) {
404                                 track = get_nth_selected_audio_track (nth++);
405                         }
406
407                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
408                                 goto out;
409                         }
410                 }
411                 break;
412
413         case Editing::ImportDistinctChannels:
414                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
415
416                         /* have to reset this for every file we handle */
417                         if (use_timestamp) {
418                                 pos = -1;
419                         }
420
421                         to_embed.clear ();
422                         to_embed.push_back (*a);
423
424                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
425                                 goto out;
426                         }
427                 }
428                 break;
429
430         case Editing::ImportMergeFiles:
431                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
432                         goto out;
433                 }
434                 break;
435
436         case Editing::ImportSerializeFiles:
437                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
438
439                         /* have to reset this for every file we handle */
440                         if (use_timestamp) {
441                                 pos = -1;
442                         }
443
444                         to_embed.clear ();
445                         to_embed.push_back (*a);
446
447                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
448                                 goto out;
449                         }
450                 }
451                 break;
452         }
453
454         ok = true;
455
456   out:
457         if (ok) {
458                 _session->save_state ("");
459         }
460 }
461
462 int
463 Editor::import_sndfiles (vector<string> paths, ImportMode mode, SrcQuality quality, framepos_t& pos,
464                          int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool replace)
465 {
466         import_status.paths = paths;
467         import_status.done = false;
468         import_status.cancel = false;
469         import_status.freeze = false;
470         import_status.quality = quality;
471         import_status.replace_existing_source = replace;
472
473         import_status.mode = mode;
474         import_status.pos = pos;
475         import_status.target_tracks = target_tracks;
476         import_status.target_regions = target_regions;
477         import_status.track = track;
478         import_status.replace = replace;
479
480         set_canvas_cursor (_cursors->wait);
481         gdk_flush ();
482
483         /* start import thread for this spec. this will ultimately call Session::import_files()
484            which, if successful, will add the files as regions to the region list. its up to us
485            (the GUI) to direct additional steps after that.
486         */
487
488         pthread_create_and_store ("import", &import_status.thread, _import_thread, this);
489         pthread_detach (import_status.thread);
490
491         while (!import_status.done && !import_status.cancel) {
492                 gtk_main_iteration ();
493         }
494
495         import_status.done = true;
496
497         int result = -1;
498
499         if (!import_status.cancel && !import_status.sources.empty()) {
500                 result = add_sources (
501                         import_status.paths,
502                         import_status.sources,
503                         import_status.pos,
504                         import_status.mode,
505                         import_status.target_regions,
506                         import_status.target_tracks,
507                         track, false
508                         );
509
510                 /* update position from results */
511
512                 pos = import_status.pos;
513         }
514
515         set_canvas_cursor (current_canvas_cursor);
516         return result;
517 }
518
519 int
520 Editor::embed_sndfiles (vector<string> paths, bool multifile,
521                         bool& check_sample_rate, ImportMode mode, framepos_t& pos, int target_regions, int target_tracks,
522                         boost::shared_ptr<Track>& track)
523 {
524         boost::shared_ptr<AudioFileSource> source;
525         SourceList sources;
526         string linked_path;
527         SoundFileInfo finfo;
528         int ret = 0;
529
530         set_canvas_cursor (_cursors->wait);
531         gdk_flush ();
532
533         for (vector<string>::iterator p = paths.begin(); p != paths.end(); ++p) {
534
535                 string path = *p;
536                 string error_msg;
537
538                 /* note that we temporarily truncated _id at the colon */
539
540                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
541                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
542                         goto out;
543                 }
544
545                 if (check_sample_rate  && (finfo.samplerate != (int) _session->frame_rate())) {
546                         vector<string> choices;
547
548                         if (multifile) {
549                                 choices.push_back (_("Cancel entire import"));
550                                 choices.push_back (_("Don't embed it"));
551                                 choices.push_back (_("Embed all without questions"));
552
553                                 Gtkmm2ext::Choice rate_choice (
554                                         _("Sample rate"),
555                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
556                                                         short_path (path, 40)),
557                                         choices, false
558                                         );
559
560                                 int resx = rate_choice.run ();
561
562                                 switch (resx) {
563                                 case 0: /* stop a multi-file import */
564                                         ret = -2;
565                                         goto out;
566                                 case 1: /* don't embed this one */
567                                         ret = -1;
568                                         goto out;
569                                 case 2: /* do it, and the rest without asking */
570                                         check_sample_rate = false;
571                                         break;
572                                 case 3: /* do it */
573                                         break;
574                                 default:
575                                         ret = -2;
576                                         goto out;
577                                 }
578                         } else {
579                                 choices.push_back (_("Cancel"));
580                                 choices.push_back (_("Embed it anyway"));
581
582                                 Gtkmm2ext::Choice rate_choice (
583                                         _("Sample rate"),
584                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
585                                         choices, false
586                                         );
587
588                                 int resx = rate_choice.run ();
589
590                                 switch (resx) {
591                                 case 0: /* don't import */
592                                         ret = -1;
593                                         goto out;
594                                 case 1: /* do it */
595                                         break;
596                                 default:
597                                         ret = -2;
598                                         goto out;
599                                 }
600                         }
601                 }
602
603                 set_canvas_cursor (_cursors->wait);
604
605                 for (int n = 0; n < finfo.channels; ++n) {
606                         try {
607
608                                 /* check if we have this thing embedded already */
609
610                                 boost::shared_ptr<Source> s;
611
612                                 if ((s = _session->source_by_path_and_channel (path, n)) == 0) {
613
614                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
615                                                 SourceFactory::createReadable (DataType::AUDIO, *_session,
616                                                                                path, n,
617                                                                                (mode == ImportAsTapeTrack
618                                                                                 ? Source::Destructive
619                                                                                 : Source::Flag (0)),
620                                                                         true, true));
621                                 } else {
622                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
623                                 }
624
625                                 sources.push_back(source);
626                         }
627
628                         catch (failed_constructor& err) {
629                                 error << string_compose(_("could not open %1"), path) << endmsg;
630                                 goto out;
631                         }
632
633                         ARDOUR_UI::instance()->flush_pending ();
634                 }
635         }
636
637         if (sources.empty()) {
638                 goto out;
639         }
640
641         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
642
643   out:
644         set_canvas_cursor (current_canvas_cursor);
645         return ret;
646 }
647
648 int
649 Editor::add_sources (vector<string> paths, SourceList& sources, framepos_t& pos, ImportMode mode,
650                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool /*add_channel_suffix*/)
651 {
652         vector<boost::shared_ptr<Region> > regions;
653         string region_name;
654         uint32_t input_chan = 0;
655         uint32_t output_chan = 0;
656         bool use_timestamp;
657
658         use_timestamp = (pos == -1);
659
660         // kludge (for MIDI we're abusing "channel" for "track" here)
661         if (SMFSource::safe_midi_file_extension (paths.front())) {
662                 target_regions = -1;
663         }
664
665         if (target_regions == 1) {
666
667                 /* take all the sources we have and package them up as a region */
668
669                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
670
671                 /* we checked in import_sndfiles() that there were not too many */
672
673                 while (RegionFactory::region_by_name (region_name)) {
674                         region_name = bump_name_once (region_name, '.');
675                 }
676
677                 PropertyList plist;
678
679                 plist.add (ARDOUR::Properties::start, 0);
680                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
681                 plist.add (ARDOUR::Properties::name, region_name);
682                 plist.add (ARDOUR::Properties::layer, 0);
683                 plist.add (ARDOUR::Properties::whole_file, true);
684                 plist.add (ARDOUR::Properties::external, true);
685
686                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
687
688                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
689                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
690                 }
691
692                 regions.push_back (r);
693
694
695         } else if (target_regions == -1 || target_regions > 1) {
696
697                 /* take each source and create a region for each one */
698
699                 SourceList just_one;
700                 SourceList::iterator x;
701                 uint32_t n;
702
703                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
704
705                         just_one.clear ();
706                         just_one.push_back (*x);
707
708                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
709
710                         if (fs) {
711                                 region_name = region_name_from_path (fs->path(), false, false, sources.size(), n);
712                         } else{
713                                 region_name = (*x)->name();
714                         }
715
716                         PropertyList plist;
717
718                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
719                            for want of a better idea.  It can't be too small, otherwise if this
720                            is a MIDI region the conversion from frames -> beats -> frames will
721                            round it back down to 0 again.
722                         */
723                         framecnt_t len = (*x)->length (pos);
724                         if (len == 0) {
725                                 len = (60.0 / 120.0) * _session->frame_rate ();
726                         }
727
728                         plist.add (ARDOUR::Properties::start, 0);
729                         plist.add (ARDOUR::Properties::length, len);
730                         plist.add (ARDOUR::Properties::name, region_name);
731                         plist.add (ARDOUR::Properties::layer, 0);
732                         plist.add (ARDOUR::Properties::whole_file, true);
733                         plist.add (ARDOUR::Properties::external, true);
734
735                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
736
737                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
738                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
739                         }
740
741                         regions.push_back (r);
742                 }
743         }
744
745         if (target_regions == 1) {
746                 input_chan = regions.front()->n_channels();
747         } else {
748                 if (target_tracks == 1) {
749                         input_chan = regions.size();
750                 } else {
751                         input_chan = 1;
752                 }
753         }
754
755         if (Config->get_output_auto_connect() & AutoConnectMaster) {
756                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
757         } else {
758                 output_chan = input_chan;
759         }
760
761         int n = 0;
762         framepos_t rlen = 0;
763
764         begin_reversible_command (Operations::insert_file);
765         
766         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
767                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
768
769                 if (use_timestamp) {
770                         if (ar) {
771
772                                 /* get timestamp for this region */
773
774                                 const boost::shared_ptr<Source> s (ar->sources().front());
775                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
776
777                                 assert (as);
778
779                                 if (as->natural_position() != 0) {
780                                         pos = as->natural_position();
781                                 } else if (target_tracks == 1) {
782                                         /* hmm, no timestamp available, put it after the previous region
783                                          */
784                                         if (n == 0) {
785                                                 pos = get_preferred_edit_position ();
786                                         } else {
787                                                 pos += rlen;
788                                         }
789                                 } else {
790                                         pos = get_preferred_edit_position ();
791                                 }
792                         } else {
793                                 /* should really get first position in MIDI file, but for now, use edit position*/
794                                 pos = get_preferred_edit_position ();
795                         }
796                 }
797
798
799                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
800
801                 rlen = (*r)->length();
802
803                 if (target_tracks != 1) {
804                         track.reset ();
805                 } else {
806                         if (!use_timestamp || !ar) {
807                                 /* line each one up right after the other */
808                                 pos += (*r)->length();
809                         }
810                 }
811         }
812
813         commit_reversible_command ();
814         
815         /* setup peak file building in another thread */
816
817         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
818                 SourceFactory::setup_peakfile (*x, true);
819         }
820
821         return 0;
822 }
823
824 int
825 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, framepos_t& pos,
826                                      ImportMode mode, boost::shared_ptr<Track>& existing_track)
827 {
828         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
829         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
830
831         switch (mode) {
832         case ImportAsRegion:
833                 /* relax, its been done */
834                 break;
835
836         case ImportToTrack:
837         {
838                 if (!existing_track) {
839
840                         if (ar) {
841                                 existing_track = get_nth_selected_audio_track (0);
842                         } else if (mr) {
843                                 existing_track = get_nth_selected_midi_track (0);
844                         }
845
846                         if (!existing_track) {
847                                 return -1;
848                         }
849                 }
850
851                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
852                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
853                 playlist->clear_changes ();
854                 playlist->add_region (copy, pos);
855                 _session->add_command (new StatefulDiffCommand (playlist));
856                 break;
857         }
858
859         case ImportAsTrack:
860         {
861                 if (!existing_track) {
862                         if (ar) {
863                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
864
865                                 if (at.empty()) {
866                                         return -1;
867                                 }
868
869                                 existing_track = at.front();
870                         } else if (mr) {
871                                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (ChanCount (DataType::MIDI, 1),
872                                                                                                   ChanCount (DataType::MIDI, 1),
873                                                                                                   boost::shared_ptr<PluginInfo>(), 
874                                                                                                   Normal, 0, 1));
875
876                                 if (mt.empty()) {
877                                         return -1;
878                                 }
879
880                                 existing_track = mt.front();
881                         }
882
883                         existing_track->set_name (region->name());
884                 }
885
886                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
887                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
888                 playlist->clear_changes ();
889                 playlist->add_region (copy, pos);
890                 _session->add_command (new StatefulDiffCommand (playlist));
891                 break;
892         }
893
894         case ImportAsTapeTrack:
895         {
896                 if (!ar) {
897                         return -1;
898                 }
899
900                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Destructive));
901                 if (!at.empty()) {
902                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
903                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
904                         playlist->clear_changes ();
905                         playlist->add_region (copy, pos);
906                         _session->add_command (new StatefulDiffCommand (playlist));
907                 }
908                 break;
909         }
910         }
911
912         return 0;
913 }
914
915 void *
916 Editor::_import_thread (void *arg)
917 {
918         SessionEvent::create_per_thread_pool ("import events", 64);
919
920         Editor *ed = (Editor *) arg;
921         return ed->import_thread ();
922 }
923
924 void *
925 Editor::import_thread ()
926 {
927         _session->import_files (import_status);
928         pthread_exit_pbd (0);
929         /*NOTREACHED*/
930         return 0;
931 }