Fix vertical order of MIDI notes.
[ardour.git] / gtk2_ardour / sfdb_ui.cc
1 /*
2     Copyright (C) 2005-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 <map>
21 #include <cerrno>
22 #include <sstream>
23
24 #include <sys/stat.h>
25
26 #include <gtkmm/box.h>
27 #include <gtkmm/stock.h>
28
29 #include <pbd/convert.h>
30 #include <pbd/tokenizer.h>
31
32 #include <gtkmm2ext/utils.h>
33
34 #include <ardour/audio_library.h>
35 #include <ardour/audioregion.h>
36 #include <ardour/audiofilesource.h>
37 #include <ardour/region_factory.h>
38 #include <ardour/source_factory.h>
39
40 #include "ardour_ui.h"
41 #include "editing.h"
42 #include "gui_thread.h"
43 #include "prompter.h"
44 #include "sfdb_ui.h"
45 #include "utils.h"
46
47 #include "i18n.h"
48
49 using namespace ARDOUR;
50 using namespace PBD;
51 using namespace std;
52
53 Glib::ustring SoundFileBrowser::persistent_folder;
54
55 SoundFileBox::SoundFileBox ()
56         :
57         _session(0),
58         current_pid(0),
59         main_box (false, 3),
60         bottom_box (true, 4),
61         play_btn(_("Play")),
62         stop_btn(_("Stop")),
63         apply_btn(_("Apply"))
64 {
65         set_name (X_("SoundFileBox"));
66         
67         set_size_request (250, 500);
68         
69         border_frame.set_label (_("Soundfile Info"));
70         border_frame.add (main_box);
71
72         Gtk::Label* tag_label = manage(new Gtk::Label(_("comma seperated tags")));
73
74         pack_start (border_frame);
75         set_border_width (4);
76
77         main_box.set_border_width (4);
78
79         main_box.pack_start(length, false, false);
80         main_box.pack_start(format, false, false);
81         main_box.pack_start(channels, false, false);
82         main_box.pack_start(samplerate, false, false);
83         main_box.pack_start(timecode, false, false);
84         main_box.pack_start(*tag_label, false, false);
85         main_box.pack_start(tags_entry, false, false);
86         main_box.pack_start(apply_btn, false, false);
87         main_box.pack_start(bottom_box, false, false);
88
89         bottom_box.set_homogeneous(true);
90         bottom_box.pack_start(play_btn);
91         bottom_box.pack_start(stop_btn);
92
93         play_btn.signal_clicked().connect (mem_fun (*this, &SoundFileBox::play_btn_clicked));
94         stop_btn.signal_clicked().connect (mem_fun (*this, &SoundFileBox::stop_btn_clicked));
95         apply_btn.signal_clicked().connect (mem_fun (*this, &SoundFileBox::apply_btn_clicked));
96         tags_entry.signal_activate().connect (mem_fun (*this, &SoundFileBox::apply_btn_clicked));
97
98         length.set_alignment (0.0f, 0.0f);
99         format.set_alignment (0.0f, 0.0f);
100         channels.set_alignment (0.0f, 0.0f);
101         samplerate.set_alignment (0.0f, 0.0f);
102         timecode.set_alignment (0.0f, 0.0f);
103
104         stop_btn.set_no_show_all (true);
105         stop_btn.hide();
106         
107         show_all();
108 }
109
110 void
111 SoundFileBox::set_session(Session* s)
112 {
113         _session = s;
114
115         if (!_session) {
116                 play_btn.set_sensitive(false);
117         } else {
118                 _session->AuditionActive.connect(mem_fun (*this, &SoundFileBox::audition_status_changed));
119         }
120 }
121
122 bool
123 SoundFileBox::setup_labels (string filename) 
124 {
125         path = filename;
126
127         string error_msg;
128
129         if(!AudioFileSource::get_soundfile_info (filename, sf_info, error_msg)) {
130                 length.set_text (_("Length: n/a"));
131                 format.set_text (_("Format: n/a"));
132                 channels.set_text (_("Channels: n/a"));
133                 samplerate.set_text (_("Samplerate: n/a"));
134                 timecode.set_text (_("Timecode: n/a"));
135                 tags_entry.set_text ("");
136                 
137                 tags_entry.set_sensitive (false);
138                 play_btn.set_sensitive (false);
139                 apply_btn.set_sensitive (false);
140                 
141                 return false;
142         }
143
144         length.set_text (string_compose(_("Length: %1"), length2string(sf_info.length, sf_info.samplerate)));
145         format.set_text (sf_info.format_name);
146         channels.set_text (string_compose(_("Channels: %1"), sf_info.channels));
147         samplerate.set_text (string_compose(_("Samplerate: %1"), sf_info.samplerate));
148         timecode.set_text (string_compose (_("Timecode: %1"), length2string(sf_info.timecode, sf_info.samplerate)));
149
150         vector<string> tags = Library->get_tags (filename);
151         
152         stringstream tag_string;
153         for (vector<string>::iterator i = tags.begin(); i != tags.end(); ++i) {
154                 if (i != tags.begin()) {
155                         tag_string << ", ";
156                 }
157                 tag_string << *i;
158         }
159         tags_entry.set_text (tag_string.str());
160         
161         tags_entry.set_sensitive (true);
162         if (_session) {
163                 play_btn.set_sensitive (true);
164         }
165         apply_btn.set_sensitive (true);
166         
167         return true;
168 }
169
170 bool
171 SoundFileBox::tags_entry_left (GdkEventFocus* event)
172 {       
173         apply_btn_clicked ();
174         
175         return true;
176 }
177
178 void
179 SoundFileBox::play_btn_clicked ()
180 {
181         if (!_session) {
182                 return;
183         }
184
185         _session->cancel_audition();
186
187         if (access(path.c_str(), R_OK)) {
188                 warning << string_compose(_("Could not read file: %1 (%2)."), path, strerror(errno)) << endmsg;
189                 return;
190         }
191
192         typedef std::map<string, boost::shared_ptr<AudioRegion> > RegionCache; 
193         static  RegionCache region_cache;
194         RegionCache::iterator the_region;
195
196         if ((the_region = region_cache.find (path)) == region_cache.end()) {
197                 SourceList srclist;
198                 boost::shared_ptr<AudioFileSource> afs;
199                 
200                 for (int n = 0; n < sf_info.channels; ++n) {
201                         try {
202                                 afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (DataType::AUDIO, *_session, path, n, AudioFileSource::Flag (0)));
203                                 srclist.push_back(afs);
204
205                         } catch (failed_constructor& err) {
206                                 error << _("Could not access soundfile: ") << path << endmsg;
207                                 return;
208                         }
209                 }
210
211                 if (srclist.empty()) {
212                         return;
213                 }
214
215                 string rname;
216
217                 _session->region_name (rname, Glib::path_get_basename(srclist[0]->name()), false);
218
219                 pair<string,boost::shared_ptr<AudioRegion> > newpair;
220                 pair<RegionCache::iterator,bool> res;
221
222                 newpair.first = path;
223                 newpair.second = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (srclist, 0, srclist[0]->length(), rname, 0, Region::DefaultFlags, false));
224
225                 res = region_cache.insert (newpair);
226                 the_region = res.first;
227         }
228
229         play_btn.hide();
230         stop_btn.show();
231
232         boost::shared_ptr<Region> r = boost::static_pointer_cast<Region> (the_region->second);
233
234         _session->audition_region(r);
235 }
236
237 void
238 SoundFileBox::stop_btn_clicked ()
239 {
240         if (_session) {
241                 _session->cancel_audition();
242                 play_btn.show();
243                 stop_btn.hide();
244         }
245 }
246
247 void
248 SoundFileBox::apply_btn_clicked ()
249 {
250         string tag_string = tags_entry.get_text ();
251
252         vector<string> tags;
253
254     if (!PBD::tokenize (tag_string, string(","), std::back_inserter (tags), true)) {
255                 warning << _("SoundFileBox: Could not tokenize string: ") << tag_string << endmsg;
256                 return;
257         }
258         
259         Library->set_tags (path, tags);
260         Library->save_changes ();
261 }
262
263 void
264 SoundFileBox::audition_status_changed (bool active)
265 {
266         ENSURE_GUI_THREAD(bind (mem_fun (*this, &SoundFileBox::audition_status_changed), active));
267         
268         if (!active) {
269                 stop_btn_clicked ();
270         }
271 }
272
273 // this needs to be kept in sync with the ImportMode enum defined in editing.h and editing_syms.h.
274 static const char *import_mode_strings[] = {
275         N_("Add to Region list"),
276         N_("Add to selected Track(s)"),
277         N_("Add as new Track(s)"),
278         N_("Add as new Tape Track(s)"),
279         0
280 };
281
282 SoundFileBrowser::SoundFileBrowser (string title, ARDOUR::Session* s)
283         : ArdourDialog (title, false),
284           chooser (Gtk::FILE_CHOOSER_ACTION_OPEN),
285           found_list (Gtk::ListStore::create(found_list_columns)),
286           found_list_view (found_list),
287           found_search_btn (_("Search"))
288 {
289         set_default_size (700, 500);
290         Gtk::HBox* hbox = manage(new Gtk::HBox);
291         hbox->pack_start(notebook);
292         hbox->pack_start(preview, Gtk::PACK_SHRINK);
293         get_vbox()->pack_start(*hbox);
294
295         hbox = manage(new Gtk::HBox);
296         hbox->pack_start (found_entry);
297         hbox->pack_start (found_search_btn);
298         
299         Gtk::VBox* vbox = manage(new Gtk::VBox);
300         vbox->pack_start (*hbox, Gtk::PACK_SHRINK);
301         vbox->pack_start (found_list_view);
302         found_list_view.append_column(_("Paths"), found_list_columns.pathname);
303         
304         notebook.append_page (chooser, _("Files"));
305         notebook.append_page (*vbox, _("Tags"));
306
307         found_list_view.get_selection()->set_mode (Gtk::SELECTION_MULTIPLE);
308
309         custom_filter.add_custom (Gtk::FILE_FILTER_FILENAME, mem_fun(*this, &SoundFileBrowser::on_custom));
310         custom_filter.set_name (_("Probable audio files"));
311
312         matchall_filter.add_pattern ("*.*");
313         matchall_filter.set_name (_("All files"));
314
315         chooser.add_filter (custom_filter);
316         chooser.add_filter (matchall_filter);
317         chooser.set_select_multiple (true);
318         chooser.signal_update_preview().connect(mem_fun(*this, &SoundFileBrowser::update_preview));
319
320         if (!persistent_folder.empty()) {
321                 chooser.set_current_folder (persistent_folder);
322         }
323
324         found_list_view.get_selection()->signal_changed().connect(mem_fun(*this, &SoundFileBrowser::found_list_view_selected));
325         
326         found_search_btn.signal_clicked().connect(mem_fun(*this, &SoundFileBrowser::found_search_clicked));
327         found_entry.signal_activate().connect(mem_fun(*this, &SoundFileBrowser::found_search_clicked));
328         
329         show_all ();
330         
331         set_session (s);
332 }
333
334 SoundFileBrowser::~SoundFileBrowser ()
335 {
336         persistent_folder = chooser.get_current_folder();
337 }
338
339 void
340 SoundFileBrowser::set_session (Session* s)
341 {
342         preview.set_session(s);
343 }
344
345 bool
346 SoundFileBrowser::on_custom (const Gtk::FileFilter::Info& filter_info)
347 {
348         return AudioFileSource::safe_file_extension(filter_info.filename);
349 }
350
351 void
352 SoundFileBrowser::update_preview ()
353 {
354         preview.setup_labels(chooser.get_filename());
355 }
356
357 void
358 SoundFileBrowser::found_list_view_selected ()
359 {
360         string file;
361         
362         Gtk::TreeView::Selection::ListHandle_Path rows = found_list_view.get_selection()->get_selected_rows ();
363         
364         if (!rows.empty()) {
365                 Gtk::TreeIter iter = found_list->get_iter(*rows.begin());
366                 file = (*iter)[found_list_columns.pathname];
367                 chooser.set_filename (file);
368         }
369         preview.setup_labels (file);
370 }
371
372 void
373 SoundFileBrowser::found_search_clicked ()
374 {
375         string tag_string = found_entry.get_text ();
376
377         vector<string> tags;
378
379     if (!PBD::tokenize (tag_string, string(","), std::back_inserter (tags), true)) {
380                 warning << _("SoundFileBrowser: Could not tokenize string: ") << tag_string << endmsg;
381                 return;
382         }
383
384         vector<string> results;
385         Library->search_members_and (results, tags);
386         
387         found_list->clear();
388         for (vector<string>::iterator i = results.begin(); i != results.end(); ++i) {
389                 Gtk::TreeModel::iterator new_row = found_list->append();
390                 Gtk::TreeModel::Row row = *new_row;
391                 row[found_list_columns.pathname] = *i;
392         }
393 }
394
395 SoundFileChooser::SoundFileChooser (string title, ARDOUR::Session* s)
396         :
397         SoundFileBrowser(title, s)
398 {
399         add_button (Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
400         add_button (Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
401         
402         chooser.set_select_multiple (false);
403         found_list_view.get_selection()->set_mode (Gtk::SELECTION_SINGLE);
404         show_all ();
405 }
406
407 string
408 SoundFileChooser::get_filename ()
409 {
410         Gtk::TreeModel::iterator iter;
411         Gtk::TreeModel::Row row;
412         
413         string filename;
414         switch (notebook.get_current_page()) {
415                 case 0:
416                         filename = chooser.get_filename();
417                 case 1:
418                         iter = found_list_view.get_selection()->get_selected();
419                         row = *iter;
420                         filename = row[found_list_columns.pathname];
421                 default:
422                         /* NOT REACHED */
423                         return "";
424         }
425         
426         struct stat buf;
427         if (stat (filename.c_str(), &buf) || !S_ISREG(buf.st_mode)) {
428                 return "";
429         }
430         
431         return filename;
432 }
433
434 vector<string> SoundFileOmega::mode_strings;
435
436 SoundFileOmega::SoundFileOmega (string title, ARDOUR::Session* s)
437         : SoundFileBrowser (title, s),
438           split_check (_("Split Channels"))
439 {
440         ARDOUR_UI::instance()->tooltips().set_tip(split_check, 
441                         _("Create a region for each channel"));
442
443         Gtk::Button* btn = add_button (_("Embed"), ResponseEmbed);
444         ARDOUR_UI::instance()->tooltips().set_tip(*btn, 
445                         _("Link to an external file"));
446
447         btn = add_button (_("Import"), ResponseImport);
448         ARDOUR_UI::instance()->tooltips().set_tip(*btn, 
449                         _("Copy a file to the session folder"));
450
451         add_button (Gtk::Stock::CLOSE, Gtk::RESPONSE_CLOSE);
452         
453         if (mode_strings.empty()) {
454                 mode_strings = I18N (import_mode_strings);
455         }
456         Gtkmm2ext::set_popdown_strings (mode_combo, mode_strings);
457
458         set_mode (Editing::ImportAsRegion);
459
460         get_action_area()->pack_start (split_check);
461         get_action_area()->pack_start (mode_combo);
462
463         mode_combo.signal_changed().connect (mem_fun (*this, &SoundFileOmega::mode_changed));
464         
465         show_all ();
466 }
467
468 bool
469 SoundFileOmega::get_split ()
470 {
471         return split_check.get_active();
472 }
473
474 vector<Glib::ustring>
475 SoundFileOmega::get_paths ()
476 {
477         vector<Glib::ustring> results;
478         
479         int n = notebook.get_current_page ();
480         
481         if (n == 0) {
482                 vector<Glib::ustring> filenames = chooser.get_filenames();
483                 vector<Glib::ustring>::iterator i;
484                 for (i = filenames.begin(); i != filenames.end(); ++i) {
485                         struct stat buf;
486                         if ((!stat((*i).c_str(), &buf)) && S_ISREG(buf.st_mode)) {
487                                 results.push_back (*i);
488                         }
489                 }
490                 return results;
491                 
492         } else {
493                 
494                 typedef Gtk::TreeView::Selection::ListHandle_Path ListPath;
495                 
496                 ListPath rows = found_list_view.get_selection()->get_selected_rows ();
497                 for (ListPath::iterator i = rows.begin() ; i != rows.end(); ++i) {
498                         Gtk::TreeIter iter = found_list->get_iter(*i);
499                         string str = (*iter)[found_list_columns.pathname];
500                         
501                         results.push_back (str);
502                 }
503                 return results;
504         }
505 }
506
507 void
508 SoundFileOmega::set_mode (Editing::ImportMode mode)
509 {
510         mode_combo.set_active_text (mode_strings[(int)mode]);
511
512         switch (mode) {
513         case Editing::ImportAsRegion:
514                 split_check.set_sensitive (true);
515                 break;
516         case Editing::ImportAsTrack:
517                 split_check.set_sensitive (true);
518                 break;
519         case Editing::ImportToTrack:
520                 split_check.set_sensitive (false);
521                 break;
522         case Editing::ImportAsTapeTrack:
523                 split_check.set_sensitive (true);
524                 break;
525         }
526 }
527
528 Editing::ImportMode
529 SoundFileOmega::get_mode ()
530 {
531         vector<string>::iterator i;
532         uint32_t n;
533         string str = mode_combo.get_active_text ();
534
535         for (n = 0, i = mode_strings.begin (); i != mode_strings.end(); ++i, ++n) {
536                 if (str == (*i)) {
537                         break;
538                 }
539         }
540
541         if (i == mode_strings.end()) {
542                 fatal << string_compose (_("programming error: %1"), X_("unknown import mode string")) << endmsg;
543                 /*NOTREACHED*/
544         }
545
546         return (Editing::ImportMode) (n);
547 }
548
549 void
550 SoundFileOmega::mode_changed ()
551 {
552         Editing::ImportMode mode = get_mode();
553
554         switch (mode) {
555         case Editing::ImportAsRegion:
556                 split_check.set_sensitive (true);
557                 break;
558         case Editing::ImportAsTrack:
559                 split_check.set_sensitive (true);
560                 break;
561         case Editing::ImportToTrack:
562                 split_check.set_sensitive (false);
563                 break;
564         case Editing::ImportAsTapeTrack:
565                 split_check.set_sensitive (true);
566                 break;
567         }
568 }
569