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