/[svn]/gigedit/trunk/src/gigedit/mainwindow.cpp
ViewVC logotype

Annotation of /gigedit/trunk/src/gigedit/mainwindow.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1339 - (hide annotations) (download)
Mon Sep 10 19:56:26 2007 UTC (12 years, 9 months ago) by schoenebeck
File size: 56020 byte(s)
* bugfix: signals triggered before and after sensible modifications didn't
  ever make it to the outer world (i.e. to LinuxSampler)

1 schoenebeck 1225 /*
2     * Copyright (C) 2006, 2007 Andreas Persson
3     *
4     * This program is free software; you can redistribute it and/or
5     * modify it under the terms of the GNU General Public License as
6     * published by the Free Software Foundation; either version 2, or (at
7     * your option) any later version.
8     *
9     * This program is distributed in the hope that it will be useful, but
10     * WITHOUT ANY WARRANTY; without even the implied warranty of
11     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12     * General Public License for more details.
13     *
14     * You should have received a copy of the GNU General Public License
15     * along with program; see the file COPYING. If not, write to the Free
16     * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
17     * 02110-1301 USA.
18     */
19    
20     #include <libintl.h>
21     #include <iostream>
22    
23     #include <gtkmm/filechooserdialog.h>
24     #include <gtkmm/messagedialog.h>
25     #include <gtkmm/stock.h>
26     #include <gtkmm/targetentry.h>
27     #include <gtkmm/main.h>
28    
29 persson 1261 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2
30 schoenebeck 1225 #define ABOUT_DIALOG
31     #include <gtkmm/aboutdialog.h>
32     #endif
33    
34 persson 1303 #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2
35     namespace Glib {
36     Glib::ustring filename_display_basename(const std::string& filename)
37     {
38     gchar* gstr = g_path_get_basename(filename.c_str());
39     Glib::ustring str(gstr);
40     g_free(gstr);
41     return Glib::filename_to_utf8(str);
42     }
43     }
44     #endif
45    
46 schoenebeck 1225 #include <stdio.h>
47     #include <sndfile.h>
48    
49     #include "mainwindow.h"
50    
51     #define _(String) gettext(String)
52    
53     template<class T> inline std::string ToString(T o) {
54     std::stringstream ss;
55     ss << o;
56     return ss.str();
57     }
58    
59     MainWindow::MainWindow()
60     {
61     // set_border_width(5);
62     // set_default_size(400, 200);
63    
64    
65     add(m_VBox);
66    
67     // Handle selection
68     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
69     tree_sel_ref->signal_changed().connect(
70     sigc::mem_fun(*this, &MainWindow::on_sel_change));
71    
72     // m_TreeView.set_reorderable();
73    
74     m_TreeView.signal_button_press_event().connect_notify(
75     sigc::mem_fun(*this, &MainWindow::on_button_release));
76    
77     // Add the TreeView tab, inside a ScrolledWindow, with the button underneath:
78     m_ScrolledWindow.add(m_TreeView);
79     // m_ScrolledWindow.set_size_request(200, 600);
80     m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
81    
82     m_ScrolledWindowSamples.add(m_TreeViewSamples);
83     m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
84    
85    
86     m_TreeViewNotebook.set_size_request(300);
87    
88     m_HPaned.add1(m_TreeViewNotebook);
89     m_HPaned.add2(dimreg_edit);
90    
91    
92     m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");
93     m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");
94    
95    
96     actionGroup = Gtk::ActionGroup::create();
97    
98     actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
99     actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),
100     sigc::mem_fun(
101     *this, &MainWindow::on_action_file_new));
102     Glib::RefPtr<Gtk::Action> action =
103     Gtk::Action::create("Open", Gtk::Stock::OPEN);
104     action->property_label() = action->property_label() + "...";
105     actionGroup->add(action,
106     sigc::mem_fun(
107     *this, &MainWindow::on_action_file_open));
108     actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),
109     sigc::mem_fun(
110     *this, &MainWindow::on_action_file_save));
111     action = Gtk::Action::create("SaveAs", Gtk::Stock::SAVE_AS);
112     action->property_label() = action->property_label() + "...";
113     actionGroup->add(action,
114 persson 1261 Gtk::AccelKey("<shift><control>s"),
115 schoenebeck 1225 sigc::mem_fun(
116 persson 1261 *this, &MainWindow::on_action_file_save_as));
117 schoenebeck 1225 actionGroup->add(Gtk::Action::create("Properties",
118     Gtk::Stock::PROPERTIES),
119     sigc::mem_fun(
120     *this, &MainWindow::on_action_file_properties));
121     actionGroup->add(Gtk::Action::create("InstrProperties",
122     Gtk::Stock::PROPERTIES),
123     sigc::mem_fun(
124     *this, &MainWindow::show_instr_props));
125     actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
126     sigc::mem_fun(
127 persson 1261 *this, &MainWindow::on_action_quit));
128 schoenebeck 1225 actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));
129    
130     action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
131     actionGroup->add(Gtk::Action::create("MenuHelp",
132     action->property_label()));
133     #ifdef ABOUT_DIALOG
134     actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),
135     sigc::mem_fun(
136     *this, &MainWindow::on_action_help_about));
137     #endif
138     actionGroup->add(
139     Gtk::Action::create("AddInstrument", _("Add _Instrument")),
140     sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
141     );
142     actionGroup->add(
143     Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
144     sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
145     );
146    
147     // sample right-click popup actions
148     actionGroup->add(
149     Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
150     sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
151     );
152     actionGroup->add(
153     Gtk::Action::create("AddGroup", _("Add _Group")),
154     sigc::mem_fun(*this, &MainWindow::on_action_add_group)
155     );
156     actionGroup->add(
157     Gtk::Action::create("AddSample", _("Add _Sample(s)")),
158     sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
159     );
160     actionGroup->add(
161     Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),
162     sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
163     );
164    
165     uiManager = Gtk::UIManager::create();
166     uiManager->insert_action_group(actionGroup);
167 persson 1261 add_accel_group(uiManager->get_accel_group());
168 schoenebeck 1225
169     Glib::ustring ui_info =
170     "<ui>"
171     " <menubar name='MenuBar'>"
172     " <menu action='MenuFile'>"
173     " <menuitem action='New'/>"
174     " <menuitem action='Open'/>"
175     " <separator/>"
176     " <menuitem action='Save'/>"
177     " <menuitem action='SaveAs'/>"
178     " <separator/>"
179     " <menuitem action='Properties'/>"
180     " <separator/>"
181     " <menuitem action='Quit'/>"
182     " </menu>"
183     " <menu action='MenuInstrument'>"
184     " </menu>"
185     #ifdef ABOUT_DIALOG
186     " <menu action='MenuHelp'>"
187     " <menuitem action='About'/>"
188     " </menu>"
189     #endif
190     " </menubar>"
191     " <popup name='PopupMenu'>"
192     " <menuitem action='InstrProperties'/>"
193     " <menuitem action='AddInstrument'/>"
194     " <separator/>"
195     " <menuitem action='RemoveInstrument'/>"
196     " </popup>"
197     " <popup name='SamplePopupMenu'>"
198     " <menuitem action='SampleProperties'/>"
199     " <menuitem action='AddGroup'/>"
200     " <menuitem action='AddSample'/>"
201     " <separator/>"
202     " <menuitem action='RemoveSample'/>"
203     " </popup>"
204     "</ui>";
205     uiManager->add_ui_from_string(ui_info);
206    
207     popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
208    
209     Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
210     m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
211     m_VBox.pack_start(m_HPaned);
212     m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
213     m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
214    
215 persson 1261 m_RegionChooser.signal_region_selected().connect(
216 schoenebeck 1225 sigc::mem_fun(*this, &MainWindow::region_changed) );
217 persson 1261 m_DimRegionChooser.signal_dimregion_selected().connect(
218 schoenebeck 1225 sigc::mem_fun(*this, &MainWindow::dimreg_changed) );
219    
220    
221     // Create the Tree model:
222     m_refTreeModel = Gtk::ListStore::create(m_Columns);
223     m_TreeView.set_model(m_refTreeModel);
224     m_refTreeModel->signal_row_changed().connect(
225     sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
226     );
227    
228     // Add the TreeView's view columns:
229     m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);
230     m_TreeView.set_headers_visible(false);
231    
232     // create samples treeview (including its data model)
233     m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
234     m_TreeViewSamples.set_model(m_refSamplesTreeModel);
235     // m_TreeViewSamples.set_reorderable();
236     m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);
237     m_TreeViewSamples.set_headers_visible(false);
238     m_TreeViewSamples.signal_button_press_event().connect_notify(
239     sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
240     );
241     m_refSamplesTreeModel->signal_row_changed().connect(
242     sigc::mem_fun(*this, &MainWindow::sample_name_changed)
243     );
244    
245     // establish drag&drop between samples tree view and dimension region 'Sample' text entry
246     std::list<Gtk::TargetEntry> drag_target_gig_sample;
247     drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );
248     m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
249 persson 1303 m_TreeViewSamples.signal_drag_begin().connect(
250     sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
251     );
252 schoenebeck 1225 m_TreeViewSamples.signal_drag_data_get().connect(
253     sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_data_get)
254     );
255     dimreg_edit.wSample->drag_dest_set(drag_target_gig_sample);
256     dimreg_edit.wSample->signal_drag_data_received().connect(
257     sigc::mem_fun(*this, &MainWindow::on_sample_label_drop_drag_data_received)
258     );
259 persson 1261 dimreg_edit.signal_dimreg_changed().connect(
260 schoenebeck 1322 sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
261 persson 1261 m_RegionChooser.signal_instrument_changed().connect(
262     sigc::mem_fun(*this, &MainWindow::file_changed));
263     m_DimRegionChooser.signal_region_changed().connect(
264     sigc::mem_fun(*this, &MainWindow::file_changed));
265     instrumentProps.signal_instrument_changed().connect(
266     sigc::mem_fun(*this, &MainWindow::file_changed));
267 schoenebeck 1322
268     dimreg_edit.signal_dimreg_to_be_changed().connect(
269     dimreg_to_be_changed_signal.make_slot());
270     dimreg_edit.signal_dimreg_changed().connect(
271     dimreg_changed_signal.make_slot());
272     dimreg_edit.signal_sample_ref_changed().connect(
273     sample_ref_changed_signal.make_slot());
274    
275     m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
276     sigc::hide(
277     sigc::bind(
278     file_structure_to_be_changed_signal.make_slot(),
279     sigc::ref(this->file)
280     )
281     )
282     );
283     m_RegionChooser.signal_instrument_struct_changed().connect(
284     sigc::hide(
285     sigc::bind(
286     file_structure_changed_signal.make_slot(),
287     sigc::ref(this->file)
288     )
289     )
290     );
291     m_RegionChooser.signal_region_to_be_changed().connect(
292     region_to_be_changed_signal.make_slot());
293     m_RegionChooser.signal_region_changed_signal().connect(
294     region_changed_signal.make_slot());
295    
296 schoenebeck 1225 file = 0;
297 persson 1261 file_is_changed = false;
298 schoenebeck 1225
299     show_all_children();
300 schoenebeck 1300
301     // start with a new gig file by default
302     on_action_file_new();
303 schoenebeck 1225 }
304    
305     MainWindow::~MainWindow()
306     {
307     }
308    
309 persson 1261 bool MainWindow::on_delete_event(GdkEventAny* event)
310     {
311     return file_is_changed && !close_confirmation_dialog();
312     }
313    
314     void MainWindow::on_action_quit()
315     {
316     if (file_is_changed && !close_confirmation_dialog()) return;
317     hide();
318     }
319    
320 schoenebeck 1225 void MainWindow::region_changed()
321     {
322     m_DimRegionChooser.set_region(m_RegionChooser.get_region());
323     }
324    
325     void MainWindow::dimreg_changed()
326     {
327     dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());
328     }
329    
330     void MainWindow::on_sel_change()
331     {
332     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
333    
334     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();
335     if (it) {
336     Gtk::TreeModel::Row row = *it;
337     std::cout << row[m_Columns.m_col_name] << std::endl;
338    
339     m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);
340     } else {
341     m_RegionChooser.set_instrument(0);
342     }
343     }
344    
345     void loader_progress_callback(gig::progress_t* progress)
346     {
347     Loader* loader = static_cast<Loader*>(progress->custom);
348     loader->progress_callback(progress->factor);
349     }
350    
351     void Loader::progress_callback(float fraction)
352     {
353     {
354     Glib::Mutex::Lock lock(progressMutex);
355     progress = fraction;
356     }
357     progress_dispatcher();
358     }
359    
360     void Loader::thread_function()
361     {
362     printf("thread_function self=%x\n", Glib::Thread::self());
363     printf("Start %s\n", filename);
364     RIFF::File* riff = new RIFF::File(filename);
365     gig = new gig::File(riff);
366     gig::progress_t progress;
367     progress.callback = loader_progress_callback;
368     progress.custom = this;
369    
370     gig->GetInstrument(0, &progress);
371     printf("End\n");
372     finished_dispatcher();
373     }
374    
375     Loader::Loader(const char* filename)
376     : thread(0), filename(filename)
377     {
378     }
379    
380     void Loader::launch()
381     {
382     thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
383     printf("launch thread=%x\n", thread);
384     }
385    
386     float Loader::get_progress()
387     {
388     float res;
389     {
390     Glib::Mutex::Lock lock(progressMutex);
391     res = progress;
392     }
393     return res;
394     }
395    
396     Glib::Dispatcher& Loader::signal_progress()
397     {
398     return progress_dispatcher;
399     }
400    
401     Glib::Dispatcher& Loader::signal_finished()
402     {
403     return finished_dispatcher;
404     }
405    
406     LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)
407     : Gtk::Dialog(title, parent, true)
408     {
409     get_vbox()->pack_start(progressBar);
410     show_all_children();
411     }
412    
413     // Clear all GUI elements / controls. This method is typically called
414     // before a new .gig file is to be created or to be loaded.
415     void MainWindow::__clear() {
416     // remove all entries from "Instrument" menu
417     Gtk::MenuItem* instrument_menu =
418     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));
419     instrument_menu->hide();
420     for (int i = 0; i < instrument_menu->get_submenu()->items().size(); i++) {
421     delete &instrument_menu->get_submenu()->items()[i];
422     }
423     instrument_menu->get_submenu()->items().clear();
424     // forget all samples that ought to be imported
425     m_SampleImportQueue.clear();
426     // clear the samples and instruments tree views
427     m_refTreeModel->clear();
428     m_refSamplesTreeModel->clear();
429     // free libgig's gig::File instance
430     if (file) {
431     delete file;
432     file = NULL;
433     }
434     }
435    
436     void MainWindow::on_action_file_new()
437     {
438 persson 1261 if (file_is_changed && !close_confirmation_dialog()) return;
439    
440 schoenebeck 1225 // clear all GUI elements
441     __clear();
442     // create a new .gig file (virtually yet)
443     gig::File* pFile = new gig::File;
444     // already add one new instrument by default
445     gig::Instrument* pInstrument = pFile->AddInstrument();
446     pInstrument->pInfo->Name = "Unnamed Instrument";
447     // update GUI with that new gig::File
448 persson 1261 load_gig(pFile, 0 /*no file name yet*/);
449 schoenebeck 1225 }
450    
451 persson 1261 bool MainWindow::close_confirmation_dialog()
452     {
453     gchar* msg = g_strdup_printf(_("Save changes to \"%s\" before closing?"),
454     Glib::filename_display_basename(filename).c_str());
455     Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
456     g_free(msg);
457 persson 1303 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2
458 persson 1261 dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
459 persson 1303 #endif
460 persson 1261 dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
461     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
462     dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);
463     dialog.set_default_response(Gtk::RESPONSE_YES);
464     int response = dialog.run();
465 persson 1303 dialog.hide();
466 persson 1261 if (response == Gtk::RESPONSE_YES) return file_save();
467     return response != Gtk::RESPONSE_CANCEL;
468     }
469    
470 schoenebeck 1225 void MainWindow::on_action_file_open()
471     {
472 persson 1261 if (file_is_changed && !close_confirmation_dialog()) return;
473    
474 schoenebeck 1225 Gtk::FileChooserDialog dialog(*this, _("Open file"));
475     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
476     dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
477 persson 1261 dialog.set_default_response(Gtk::RESPONSE_OK);
478 schoenebeck 1225 Gtk::FileFilter filter;
479     filter.add_pattern("*.gig");
480     dialog.set_filter(filter);
481 persson 1261 if (current_dir != "") {
482     dialog.set_current_folder(current_dir);
483     }
484 schoenebeck 1225 if (dialog.run() == Gtk::RESPONSE_OK) {
485 persson 1261 std::string filename = dialog.get_filename();
486     printf("filename=%s\n", filename.c_str());
487 schoenebeck 1225 printf("on_action_file_open self=%x\n", Glib::Thread::self());
488 persson 1261 load_file(filename.c_str());
489     current_dir = Glib::path_get_dirname(filename);
490 schoenebeck 1225 }
491     }
492    
493     void MainWindow::load_file(const char* name)
494     {
495 persson 1303 __clear();
496 schoenebeck 1225 load_dialog = new LoadDialog("Loading...", *this);
497     load_dialog->show_all();
498     loader = new Loader(strdup(name));
499     loader->signal_progress().connect(
500     sigc::mem_fun(*this, &MainWindow::on_loader_progress));
501     loader->signal_finished().connect(
502     sigc::mem_fun(*this, &MainWindow::on_loader_finished));
503     loader->launch();
504     }
505    
506     void MainWindow::load_instrument(gig::Instrument* instr) {
507     if (!instr) {
508     Glib::ustring txt = "Provided instrument is NULL!\n";
509     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
510     msg.run();
511     Gtk::Main::quit();
512     }
513 schoenebeck 1328 // clear all GUI elements
514     __clear();
515     // load the instrument
516 schoenebeck 1225 gig::File* pFile = (gig::File*) instr->GetParent();
517 persson 1261 load_gig(pFile, 0 /*file name*/);
518 schoenebeck 1225 //TODO: automatically select the given instrument
519     }
520    
521     void MainWindow::on_loader_progress()
522     {
523     load_dialog->set_fraction(loader->get_progress());
524     }
525    
526     void MainWindow::on_loader_finished()
527     {
528     printf("Loader finished!\n");
529     printf("on_loader_finished self=%x\n", Glib::Thread::self());
530     load_gig(loader->gig, loader->filename);
531     load_dialog->hide();
532     }
533    
534     void MainWindow::on_action_file_save()
535     {
536 persson 1261 file_save();
537     }
538    
539 persson 1303 bool MainWindow::check_if_savable()
540     {
541     if (!file) return false;
542    
543     if (!file->GetFirstSample()) {
544     Gtk::MessageDialog(*this, _("The file could not be saved "
545     "because it contains no samples"),
546     false, Gtk::MESSAGE_ERROR).run();
547     return false;
548     }
549    
550     for (gig::Instrument* instrument = file->GetFirstInstrument() ; instrument ;
551     instrument = file->GetNextInstrument()) {
552     if (!instrument->GetFirstRegion()) {
553     Gtk::MessageDialog(*this, _("The file could not be saved "
554     "because there are instruments "
555     "that have no regions"),
556     false, Gtk::MESSAGE_ERROR).run();
557     return false;
558     }
559     }
560     return true;
561     }
562    
563 persson 1261 bool MainWindow::file_save()
564     {
565 persson 1303 if (!check_if_savable()) return false;
566 persson 1261 if (!file_has_name) return file_save_as();
567    
568 schoenebeck 1225 std::cout << "Saving file\n" << std::flush;
569 schoenebeck 1322 file_structure_to_be_changed_signal.emit(this->file);
570 schoenebeck 1225 try {
571     file->Save();
572 persson 1261 if (file_is_changed) {
573     set_title(get_title().substr(1));
574     file_is_changed = false;
575     }
576 schoenebeck 1225 } catch (RIFF::Exception e) {
577 schoenebeck 1322 file_structure_changed_signal.emit(this->file);
578 schoenebeck 1225 Glib::ustring txt = "Could not save file: " + e.Message;
579     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
580     msg.run();
581 persson 1261 return false;
582 schoenebeck 1225 }
583     std::cout << "Saving file done\n" << std::flush;
584     __import_queued_samples();
585 schoenebeck 1322 file_structure_changed_signal.emit(this->file);
586 persson 1261 return true;
587 schoenebeck 1225 }
588    
589     void MainWindow::on_action_file_save_as()
590     {
591 persson 1303 if (!check_if_savable()) return;
592 persson 1261 file_save_as();
593     }
594    
595     bool MainWindow::file_save_as()
596     {
597     Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
598 schoenebeck 1225 dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
599     dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
600 persson 1261 dialog.set_default_response(Gtk::RESPONSE_OK);
601    
602     #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 2
603     dialog.set_do_overwrite_confirmation();
604     // TODO: an overwrite dialog for gtkmm < 2.8
605     #endif
606 schoenebeck 1225 Gtk::FileFilter filter;
607     filter.add_pattern("*.gig");
608     dialog.set_filter(filter);
609 persson 1261
610     if (Glib::path_is_absolute(filename)) {
611     dialog.set_filename(filename);
612     } else if (current_dir != "") {
613     dialog.set_current_folder(current_dir);
614     }
615     dialog.set_current_name(Glib::filename_display_basename(filename));
616    
617 schoenebeck 1225 if (dialog.run() == Gtk::RESPONSE_OK) {
618 schoenebeck 1322 file_structure_to_be_changed_signal.emit(this->file);
619 schoenebeck 1225 try {
620 persson 1261 std::string filename = dialog.get_filename();
621     if (!Glib::str_has_suffix(filename, ".gig")) {
622     filename += ".gig";
623     }
624     printf("filename=%s\n", filename.c_str());
625     file->Save(filename);
626     this->filename = filename;
627     current_dir = Glib::path_get_dirname(filename);
628     set_title(Glib::filename_display_basename(filename));
629     file_has_name = true;
630     file_is_changed = false;
631 schoenebeck 1225 } catch (RIFF::Exception e) {
632 schoenebeck 1322 file_structure_changed_signal.emit(this->file);
633 schoenebeck 1225 Glib::ustring txt = "Could not save file: " + e.Message;
634     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
635     msg.run();
636 persson 1261 return false;
637 schoenebeck 1225 }
638     __import_queued_samples();
639 schoenebeck 1322 file_structure_changed_signal.emit(this->file);
640 persson 1261 return true;
641 schoenebeck 1225 }
642 persson 1261 return false;
643 schoenebeck 1225 }
644    
645     // actually write the sample(s)' data to the gig file
646     void MainWindow::__import_queued_samples() {
647     std::cout << "Starting sample import\n" << std::flush;
648     Glib::ustring error_files;
649     printf("Samples to import: %d\n", m_SampleImportQueue.size());
650     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
651     iter != m_SampleImportQueue.end(); ) {
652     printf("Importing sample %s\n",(*iter).sample_path.c_str());
653     SF_INFO info;
654     info.format = 0;
655     SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
656     try {
657     if (!hFile) throw std::string("could not open file");
658     // determine sample's bit depth
659     int bitdepth;
660     switch (info.format & 0xff) {
661     case SF_FORMAT_PCM_S8:
662     case SF_FORMAT_PCM_16:
663 persson 1265 case SF_FORMAT_PCM_U8:
664 schoenebeck 1225 bitdepth = 16;
665     break;
666     case SF_FORMAT_PCM_24:
667     case SF_FORMAT_PCM_32:
668     case SF_FORMAT_FLOAT:
669     case SF_FORMAT_DOUBLE:
670 persson 1265 bitdepth = 24;
671 schoenebeck 1225 break;
672     default:
673     sf_close(hFile); // close sound file
674     throw std::string("format not supported"); // unsupported subformat (yet?)
675     }
676 persson 1265
677     const int bufsize = 10000;
678 schoenebeck 1225 switch (bitdepth) {
679 persson 1265 case 16: {
680     short* buffer = new short[bufsize * info.channels];
681     sf_count_t cnt = info.frames;
682     while (cnt) {
683     // libsndfile does the conversion for us (if needed)
684     int n = sf_readf_short(hFile, buffer, bufsize);
685     // write from buffer directly (physically) into .gig file
686     iter->gig_sample->Write(buffer, n);
687     cnt -= n;
688     }
689     delete[] buffer;
690 schoenebeck 1225 break;
691 persson 1265 }
692     case 24: {
693     int* srcbuf = new int[bufsize * info.channels];
694     uint8_t* dstbuf = new uint8_t[bufsize * 3 * info.channels];
695     sf_count_t cnt = info.frames;
696     while (cnt) {
697     // libsndfile returns 32 bits, convert to 24
698     int n = sf_readf_int(hFile, srcbuf, bufsize);
699     int j = 0;
700     for (int i = 0 ; i < n * info.channels ; i++) {
701     dstbuf[j++] = srcbuf[i] >> 8;
702     dstbuf[j++] = srcbuf[i] >> 16;
703     dstbuf[j++] = srcbuf[i] >> 24;
704     }
705     // write from buffer directly (physically) into .gig file
706     iter->gig_sample->Write(dstbuf, n);
707     cnt -= n;
708     }
709     delete[] srcbuf;
710     delete[] dstbuf;
711 schoenebeck 1225 break;
712 persson 1265 }
713 schoenebeck 1225 }
714     // cleanup
715     sf_close(hFile);
716     // on success we remove the sample from the import queue,
717     // otherwise keep it, maybe it works the next time ?
718     std::list<SampleImportItem>::iterator cur = iter;
719     ++iter;
720     m_SampleImportQueue.erase(cur);
721     } catch (std::string what) {
722     // remember the files that made trouble (and their cause)
723     if (error_files.size()) error_files += "\n";
724     error_files += (*iter).sample_path += " (" + what + ")";
725     ++iter;
726     }
727     }
728     // show error message box when some sample(s) could not be imported
729     if (error_files.size()) {
730     Glib::ustring txt = "Could not import the following sample(s):\n" + error_files;
731     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
732     msg.run();
733     }
734     }
735    
736     void MainWindow::on_action_file_properties()
737     {
738     propDialog.show();
739     propDialog.deiconify();
740     }
741    
742     void MainWindow::on_action_help_about()
743     {
744     #ifdef ABOUT_DIALOG
745     Gtk::AboutDialog dialog;
746     dialog.set_version(VERSION);
747     dialog.run();
748     #endif
749     }
750    
751     PropDialog::PropDialog()
752     : table(2,1)
753     {
754     table.set_col_spacings(5);
755     const char* propLabels[] = {
756     "Name:",
757     "CreationDate:",
758     "Comments:", // TODO: multiline
759     "Product:",
760     "Copyright:",
761     "Artists:",
762     "Genre:",
763     "Keywords:",
764     "Engineer:",
765     "Technician:",
766     "Software:", // TODO: readonly
767     "Medium:",
768     "Source:",
769     "SourceForm:",
770     "Commissioned:",
771     "Subject:"
772     };
773     for (int i = 0 ; i < sizeof(propLabels) / sizeof(char*) ; i++) {
774     label[i].set_text(propLabels[i]);
775     label[i].set_alignment(Gtk::ALIGN_LEFT);
776     table.attach(label[i], 0, 1, i, i + 1, Gtk::FILL, Gtk::SHRINK);
777     table.attach(entry[i], 1, 2, i, i + 1, Gtk::FILL | Gtk::EXPAND,
778     Gtk::SHRINK);
779     }
780    
781     add(table);
782     // add_button(Gtk::Stock::CANCEL, 0);
783     // add_button(Gtk::Stock::OK, 1);
784     show_all_children();
785     }
786    
787     void PropDialog::set_info(DLS::Info* info)
788     {
789     entry[0].set_text(info->Name);
790     entry[1].set_text(info->CreationDate);
791     entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));
792     entry[3].set_text(info->Product);
793     entry[4].set_text(info->Copyright);
794     entry[5].set_text(info->Artists);
795     entry[6].set_text(info->Genre);
796     entry[7].set_text(info->Keywords);
797     entry[8].set_text(info->Engineer);
798     entry[9].set_text(info->Technician);
799     entry[10].set_text(info->Software);
800     entry[11].set_text(info->Medium);
801     entry[12].set_text(info->Source);
802     entry[13].set_text(info->SourceForm);
803     entry[14].set_text(info->Commissioned);
804     entry[15].set_text(info->Subject);
805     }
806    
807 persson 1262 void InstrumentProps::add_prop(BoolEntry& boolentry)
808     {
809     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
810     Gtk::FILL, Gtk::SHRINK);
811     rowno++;
812     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
813     }
814    
815     void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)
816     {
817     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
818     Gtk::FILL, Gtk::SHRINK);
819     rowno++;
820     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
821     }
822    
823 schoenebeck 1225 void InstrumentProps::add_prop(LabelWidget& prop)
824     {
825     table.attach(prop.label, 0, 1, rowno, rowno + 1,
826     Gtk::FILL, Gtk::SHRINK);
827     table.attach(prop.widget, 1, 2, rowno, rowno + 1,
828     Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);
829     rowno++;
830 persson 1261 prop.signal_changed_by_user().connect(instrument_changed.make_slot());
831 schoenebeck 1225 }
832    
833     InstrumentProps::InstrumentProps()
834     : table(2,1),
835     quitButton(Gtk::Stock::CLOSE),
836     eName("Name"),
837 persson 1262 eIsDrum("Is drum"),
838     eMIDIBank("MIDI bank", 0, 16383),
839     eMIDIProgram("MIDI program"),
840 schoenebeck 1225 eAttenuation("Attenuation", 0, 96, 0, 1),
841     eGainPlus6("Gain +6dB", eAttenuation, -6),
842 persson 1262 eEffectSend("Effect send", 0, 65535),
843     eFineTune("Fine tune", -8400, 8400),
844     ePitchbendRange("Pitchbend range", 0, 12),
845     ePianoReleaseMode("Piano release mode"),
846     eDimensionKeyRangeLow("Dimension key range low"),
847     eDimensionKeyRangeHigh("Dimension key range high")
848 schoenebeck 1225 {
849     set_title("Instrument properties");
850    
851     rowno = 0;
852     table.set_col_spacings(5);
853    
854     add_prop(eName);
855     add_prop(eIsDrum);
856     add_prop(eMIDIBank);
857     add_prop(eMIDIProgram);
858     add_prop(eAttenuation);
859     add_prop(eGainPlus6);
860     add_prop(eEffectSend);
861     add_prop(eFineTune);
862     add_prop(ePitchbendRange);
863     add_prop(ePianoReleaseMode);
864     add_prop(eDimensionKeyRangeLow);
865     add_prop(eDimensionKeyRangeHigh);
866    
867 persson 1261 eDimensionKeyRangeLow.signal_changed_by_user().connect(
868 schoenebeck 1225 sigc::mem_fun(*this, &InstrumentProps::key_range_low_changed));
869 persson 1261 eDimensionKeyRangeHigh.signal_changed_by_user().connect(
870 schoenebeck 1225 sigc::mem_fun(*this, &InstrumentProps::key_range_high_changed));
871    
872     add(vbox);
873     table.set_border_width(5);
874     vbox.pack_start(table);
875     table.show();
876     vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
877     buttonBox.set_layout(Gtk::BUTTONBOX_END);
878     buttonBox.set_border_width(5);
879     buttonBox.show();
880     buttonBox.pack_start(quitButton);
881     quitButton.set_flags(Gtk::CAN_DEFAULT);
882     quitButton.grab_focus();
883    
884     quitButton.signal_clicked().connect(
885     sigc::mem_fun(*this, &InstrumentProps::hide));
886    
887     quitButton.show();
888     vbox.show();
889     show_all_children();
890     }
891    
892     void InstrumentProps::set_instrument(gig::Instrument* instrument)
893     {
894     eName.set_ptr(&instrument->pInfo->Name);
895     eIsDrum.set_ptr(&instrument->IsDrum);
896     eMIDIBank.set_ptr(&instrument->MIDIBank);
897     eMIDIProgram.set_ptr(&instrument->MIDIProgram);
898     eAttenuation.set_ptr(&instrument->Attenuation);
899     eGainPlus6.set_ptr(&instrument->Attenuation);
900     eEffectSend.set_ptr(&instrument->EffectSend);
901     eFineTune.set_ptr(&instrument->FineTune);
902     ePitchbendRange.set_ptr(&instrument->PitchbendRange);
903     ePianoReleaseMode.set_ptr(&instrument->PianoReleaseMode);
904 persson 1261 eDimensionKeyRangeLow.set_ptr(0);
905     eDimensionKeyRangeHigh.set_ptr(0);
906 schoenebeck 1225 eDimensionKeyRangeLow.set_ptr(&instrument->DimensionKeyRange.low);
907     eDimensionKeyRangeHigh.set_ptr(&instrument->DimensionKeyRange.high);
908     }
909    
910     void InstrumentProps::key_range_low_changed()
911     {
912     double l = eDimensionKeyRangeLow.get_value();
913     double h = eDimensionKeyRangeHigh.get_value();
914     if (h < l) eDimensionKeyRangeHigh.set_value(l);
915     }
916    
917     void InstrumentProps::key_range_high_changed()
918     {
919     double l = eDimensionKeyRangeLow.get_value();
920     double h = eDimensionKeyRangeHigh.get_value();
921     if (h < l) eDimensionKeyRangeLow.set_value(h);
922     }
923    
924 schoenebeck 1339 sigc::signal<void>& InstrumentProps::signal_instrument_changed()
925 schoenebeck 1225 {
926 persson 1261 return instrument_changed;
927     }
928 schoenebeck 1225
929 persson 1261 void MainWindow::file_changed()
930     {
931     if (file && !file_is_changed) {
932     set_title("*" + get_title());
933     file_is_changed = true;
934 schoenebeck 1225 }
935 persson 1261 }
936 schoenebeck 1225
937 persson 1261 void MainWindow::load_gig(gig::File* gig, const char* filename)
938     {
939     file = 0;
940    
941     this->filename = filename ? filename : _("Unsaved Gig File");
942     set_title(Glib::filename_display_basename(this->filename));
943     file_has_name = filename;
944     file_is_changed = false;
945    
946 schoenebeck 1225 propDialog.set_info(gig->pInfo);
947    
948     Gtk::MenuItem* instrument_menu =
949     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));
950    
951     int instrument_index = 0;
952     Gtk::RadioMenuItem::Group instrument_group;
953     for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
954     instrument = gig->GetNextInstrument()) {
955     Gtk::TreeModel::iterator iter = m_refTreeModel->append();
956     Gtk::TreeModel::Row row = *iter;
957     row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
958     row[m_Columns.m_col_instr] = instrument;
959     // create a menu item for this instrument
960     Gtk::RadioMenuItem* item =
961     new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());
962     instrument_menu->get_submenu()->append(*item);
963     item->signal_activate().connect(
964     sigc::bind(
965     sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
966     instrument_index
967     )
968     );
969     instrument_index++;
970     }
971     instrument_menu->show();
972     instrument_menu->get_submenu()->show_all_children();
973    
974     for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
975     if (group->Name != "") {
976     Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
977     Gtk::TreeModel::Row rowGroup = *iterGroup;
978     rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
979     rowGroup[m_SamplesModel.m_col_group] = group;
980     rowGroup[m_SamplesModel.m_col_sample] = NULL;
981     for (gig::Sample* sample = group->GetFirstSample();
982     sample; sample = group->GetNextSample()) {
983     Gtk::TreeModel::iterator iterSample =
984     m_refSamplesTreeModel->append(rowGroup.children());
985     Gtk::TreeModel::Row rowSample = *iterSample;
986     rowSample[m_SamplesModel.m_col_name] = sample->pInfo->Name.c_str();
987     rowSample[m_SamplesModel.m_col_sample] = sample;
988     rowSample[m_SamplesModel.m_col_group] = NULL;
989     }
990     }
991     }
992    
993 persson 1261 file = gig;
994    
995 schoenebeck 1225 // select the first instrument
996     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
997     tree_sel_ref->select(Gtk::TreePath("0"));
998     }
999    
1000     void MainWindow::show_instr_props()
1001     {
1002     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
1003     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();
1004     if (it)
1005     {
1006     Gtk::TreeModel::Row row = *it;
1007     if (row[m_Columns.m_col_instr])
1008     {
1009     instrumentProps.set_instrument(row[m_Columns.m_col_instr]);
1010     instrumentProps.show();
1011     instrumentProps.deiconify();
1012     }
1013     }
1014     }
1015    
1016     void MainWindow::on_button_release(GdkEventButton* button)
1017     {
1018     if (button->type == GDK_2BUTTON_PRESS) {
1019     show_instr_props();
1020     } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1021     popup_menu->popup(button->button, button->time);
1022     }
1023     }
1024    
1025     void MainWindow::on_instrument_selection_change(int index) {
1026     m_RegionChooser.set_instrument(file->GetInstrument(index));
1027     }
1028    
1029     void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
1030     if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1031     Gtk::Menu* sample_popup =
1032     dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
1033     // update enabled/disabled state of sample popup items
1034     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1035     Gtk::TreeModel::iterator it = sel->get_selected();
1036     bool group_selected = false;
1037     bool sample_selected = false;
1038     if (it) {
1039     Gtk::TreeModel::Row row = *it;
1040     group_selected = row[m_SamplesModel.m_col_group];
1041     sample_selected = row[m_SamplesModel.m_col_sample];
1042     }
1043     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
1044     set_sensitive(group_selected || sample_selected);
1045     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
1046     set_sensitive(group_selected || sample_selected);
1047     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
1048     set_sensitive(file);
1049     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
1050     set_sensitive(group_selected || sample_selected);
1051     // show sample popup
1052     sample_popup->popup(button->button, button->time);
1053     }
1054     }
1055    
1056     void MainWindow::on_action_add_instrument() {
1057     static int __instrument_indexer = 0;
1058     if (!file) return;
1059     gig::Instrument* instrument = file->AddInstrument();
1060     __instrument_indexer++;
1061     instrument->pInfo->Name =
1062     "Unnamed Instrument " + ToString(__instrument_indexer);
1063     // update instrument tree view
1064     Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
1065     Gtk::TreeModel::Row rowInstr = *iterInstr;
1066     rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
1067     rowInstr[m_Columns.m_col_instr] = instrument;
1068 persson 1261 file_changed();
1069 schoenebeck 1225 }
1070    
1071     void MainWindow::on_action_remove_instrument() {
1072     if (!file) return;
1073     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1074     Gtk::TreeModel::iterator it = sel->get_selected();
1075     if (it) {
1076     Gtk::TreeModel::Row row = *it;
1077     gig::Instrument* instr = row[m_Columns.m_col_instr];
1078     try {
1079     // remove instrument from the gig file
1080     if (instr) file->DeleteInstrument(instr);
1081     // remove respective row from instruments tree view
1082     m_refTreeModel->erase(it);
1083 persson 1261 file_changed();
1084 schoenebeck 1225 } catch (RIFF::Exception e) {
1085     Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1086     msg.run();
1087     }
1088     }
1089     }
1090    
1091     void MainWindow::on_action_sample_properties() {
1092     //TODO: show a dialog where the selected sample's properties can be edited
1093     Gtk::MessageDialog msg(
1094     *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO
1095     );
1096     msg.run();
1097     }
1098    
1099     void MainWindow::on_action_add_group() {
1100     static int __sample_indexer = 0;
1101     if (!file) return;
1102     gig::Group* group = file->AddGroup();
1103     group->Name = "Unnamed Group";
1104     if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
1105     __sample_indexer++;
1106     // update sample tree view
1107     Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1108     Gtk::TreeModel::Row rowGroup = *iterGroup;
1109     rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
1110     rowGroup[m_SamplesModel.m_col_sample] = NULL;
1111     rowGroup[m_SamplesModel.m_col_group] = group;
1112 persson 1261 file_changed();
1113 schoenebeck 1225 }
1114    
1115     void MainWindow::on_action_add_sample() {
1116     if (!file) return;
1117     // get selected group
1118     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1119     Gtk::TreeModel::iterator it = sel->get_selected();
1120     if (!it) return;
1121     Gtk::TreeModel::Row row = *it;
1122     gig::Group* group = row[m_SamplesModel.m_col_group];
1123     if (!group) { // not a group, but a sample is selected (probably)
1124     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1125     if (!sample) return;
1126     it = row.parent(); // resolve parent (that is the sample's group)
1127     if (!it) return;
1128     row = *it;
1129     group = row[m_SamplesModel.m_col_group];
1130     if (!group) return;
1131     }
1132     // show 'browse for file' dialog
1133     Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));
1134     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1135     dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
1136     dialog.set_select_multiple(true);
1137     Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile
1138 persson 1262 const char* const supportedFileTypes[] = {
1139 schoenebeck 1225 "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
1140     "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
1141     "*.svx", "*.SVX", "*.sf", "*.SF", "*.voc", "*.VOC", "*.w64",
1142     "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
1143     "*.caf", "*.CAF", NULL
1144     };
1145     for (int i = 0; supportedFileTypes[i]; i++)
1146     soundfilter.add_pattern(supportedFileTypes[i]);
1147     soundfilter.set_name("Sound Files");
1148     Gtk::FileFilter allpassfilter; // matches every file
1149     allpassfilter.add_pattern("*.*");
1150     allpassfilter.set_name("All Files");
1151     dialog.add_filter(soundfilter);
1152     dialog.add_filter(allpassfilter);
1153     if (dialog.run() == Gtk::RESPONSE_OK) {
1154     Glib::ustring error_files;
1155     Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();
1156     for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();
1157     iter != filenames.end(); ++iter) {
1158     printf("Adding sample %s\n",(*iter).c_str());
1159     // use libsndfile to retrieve file informations
1160     SF_INFO info;
1161     info.format = 0;
1162     SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
1163     try {
1164     if (!hFile) throw std::string("could not open file");
1165     int bitdepth;
1166     switch (info.format & 0xff) {
1167     case SF_FORMAT_PCM_S8:
1168     case SF_FORMAT_PCM_16:
1169 persson 1265 case SF_FORMAT_PCM_U8:
1170 schoenebeck 1225 bitdepth = 16;
1171     break;
1172     case SF_FORMAT_PCM_24:
1173     case SF_FORMAT_PCM_32:
1174     case SF_FORMAT_FLOAT:
1175     case SF_FORMAT_DOUBLE:
1176 persson 1265 bitdepth = 24;
1177 schoenebeck 1225 break;
1178     default:
1179     sf_close(hFile); // close sound file
1180     throw std::string("format not supported"); // unsupported subformat (yet?)
1181     }
1182     // add a new sample to the .gig file
1183     gig::Sample* sample = file->AddSample();
1184     // file name without path
1185 persson 1262 Glib::ustring filename = Glib::filename_display_basename(*iter);
1186     // remove file extension if there is one
1187     for (int i = 0; supportedFileTypes[i]; i++) {
1188     if (Glib::str_has_suffix(filename, supportedFileTypes[i] + 1)) {
1189     filename.erase(filename.length() - strlen(supportedFileTypes[i] + 1));
1190     break;
1191     }
1192     }
1193     sample->pInfo->Name = filename;
1194 schoenebeck 1225 sample->Channels = info.channels;
1195     sample->BitDepth = bitdepth;
1196     sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
1197     sample->SamplesPerSecond = info.samplerate;
1198 persson 1265 sample->AverageBytesPerSecond = sample->FrameSize * sample->SamplesPerSecond;
1199     sample->BlockAlign = sample->FrameSize;
1200     sample->SamplesTotal = info.frames;
1201    
1202     SF_INSTRUMENT instrument;
1203     if (sf_command(hFile, SFC_GET_INSTRUMENT,
1204     &instrument, sizeof(instrument)) != SF_FALSE)
1205     {
1206     sample->MIDIUnityNote = instrument.basenote;
1207    
1208 persson 1303 #if HAVE_SF_INSTRUMENT_LOOPS
1209 persson 1265 if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
1210     sample->Loops = 1;
1211    
1212     switch (instrument.loops[0].mode) {
1213     case SF_LOOP_FORWARD:
1214     sample->LoopType = gig::loop_type_normal;
1215     break;
1216     case SF_LOOP_BACKWARD:
1217     sample->LoopType = gig::loop_type_backward;
1218     break;
1219     case SF_LOOP_ALTERNATING:
1220     sample->LoopType = gig::loop_type_bidirectional;
1221     break;
1222     }
1223     sample->LoopStart = instrument.loops[0].start;
1224     sample->LoopEnd = instrument.loops[0].end;
1225     sample->LoopPlayCount = instrument.loops[0].count;
1226     sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
1227     }
1228 persson 1303 #endif
1229 persson 1265 }
1230    
1231 schoenebeck 1225 // schedule resizing the sample (which will be done
1232     // physically when File::Save() is called)
1233     sample->Resize(info.frames);
1234     // make sure sample is part of the selected group
1235     group->AddSample(sample);
1236     // schedule that physical resize and sample import
1237     // (data copying), performed when "Save" is requested
1238     SampleImportItem sched_item;
1239     sched_item.gig_sample = sample;
1240     sched_item.sample_path = *iter;
1241     m_SampleImportQueue.push_back(sched_item);
1242     // add sample to the tree view
1243     Gtk::TreeModel::iterator iterSample =
1244     m_refSamplesTreeModel->append(row.children());
1245     Gtk::TreeModel::Row rowSample = *iterSample;
1246 persson 1262 rowSample[m_SamplesModel.m_col_name] = filename;
1247 schoenebeck 1225 rowSample[m_SamplesModel.m_col_sample] = sample;
1248     rowSample[m_SamplesModel.m_col_group] = NULL;
1249     // close sound file
1250     sf_close(hFile);
1251 persson 1261 file_changed();
1252 schoenebeck 1225 } catch (std::string what) { // remember the files that made trouble (and their cause)
1253     if (error_files.size()) error_files += "\n";
1254     error_files += *iter += " (" + what + ")";
1255     }
1256     }
1257     // show error message box when some file(s) could not be opened / added
1258     if (error_files.size()) {
1259     Glib::ustring txt = "Could not add the following sample(s):\n" + error_files;
1260     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1261     msg.run();
1262     }
1263     }
1264     }
1265    
1266     void MainWindow::on_action_remove_sample() {
1267     if (!file) return;
1268     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1269     Gtk::TreeModel::iterator it = sel->get_selected();
1270     if (it) {
1271     Gtk::TreeModel::Row row = *it;
1272     gig::Group* group = row[m_SamplesModel.m_col_group];
1273     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1274     Glib::ustring name = row[m_SamplesModel.m_col_name];
1275     try {
1276     // remove group or sample from the gig file
1277     if (group) {
1278     // temporarily remember the samples that bolong to
1279     // that group (we need that to clean the queue)
1280     std::list<gig::Sample*> members;
1281     for (gig::Sample* pSample = group->GetFirstSample();
1282     pSample; pSample = group->GetNextSample()) {
1283     members.push_back(pSample);
1284     }
1285 schoenebeck 1322 // notify everybody that we're going to remove these samples
1286     samples_to_be_removed_signal.emit(members);
1287 schoenebeck 1225 // delete the group in the .gig file including the
1288     // samples that belong to the group
1289     file->DeleteGroup(group);
1290 schoenebeck 1322 // notify that we're done with removal
1291     samples_removed_signal.emit();
1292 schoenebeck 1225 // if sample(s) were just previously added, remove
1293     // them from the import queue
1294     for (std::list<gig::Sample*>::iterator member = members.begin();
1295     member != members.end(); ++member) {
1296     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1297     iter != m_SampleImportQueue.end(); ++iter) {
1298     if ((*iter).gig_sample == *member) {
1299     printf("Removing previously added sample '%s' from group '%s'\n",
1300     (*iter).sample_path.c_str(), name.c_str());
1301     m_SampleImportQueue.erase(iter);
1302     break;
1303     }
1304     }
1305     }
1306 persson 1261 file_changed();
1307 schoenebeck 1225 } else if (sample) {
1308 schoenebeck 1322 // notify everybody that we're going to remove this sample
1309     std::list<gig::Sample*> lsamples;
1310     lsamples.push_back(sample);
1311     samples_to_be_removed_signal.emit(lsamples);
1312 schoenebeck 1225 // remove sample from the .gig file
1313     file->DeleteSample(sample);
1314 schoenebeck 1322 // notify that we're done with removal
1315     samples_removed_signal.emit();
1316 schoenebeck 1225 // if sample was just previously added, remove it from
1317     // the import queue
1318     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1319     iter != m_SampleImportQueue.end(); ++iter) {
1320     if ((*iter).gig_sample == sample) {
1321     printf("Removing previously added sample '%s'\n",
1322     (*iter).sample_path.c_str());
1323     m_SampleImportQueue.erase(iter);
1324     break;
1325     }
1326     }
1327 persson 1303 dimreg_changed();
1328 persson 1261 file_changed();
1329 schoenebeck 1225 }
1330     // remove respective row(s) from samples tree view
1331     m_refSamplesTreeModel->erase(it);
1332     } catch (RIFF::Exception e) {
1333 schoenebeck 1322 // pretend we're done with removal (i.e. to avoid dead locks)
1334     samples_removed_signal.emit();
1335     // show error message
1336 schoenebeck 1225 Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1337     msg.run();
1338     }
1339     }
1340     }
1341    
1342 persson 1303 // For some reason drag_data_get gets called two times for each
1343     // drag'n'drop (at least when target is an Entry). This work-around
1344     // makes sure the code in drag_data_get and drop_drag_data_received is
1345     // only executed once, as drag_begin only gets called once.
1346     void MainWindow::on_sample_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
1347     {
1348     first_call_to_drag_data_get = true;
1349     }
1350    
1351 schoenebeck 1225 void MainWindow::on_sample_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
1352     Gtk::SelectionData& selection_data, guint, guint)
1353     {
1354 persson 1303 if (!first_call_to_drag_data_get) return;
1355     first_call_to_drag_data_get = false;
1356    
1357 schoenebeck 1225 // get selected sample
1358     gig::Sample* sample = NULL;
1359     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1360     Gtk::TreeModel::iterator it = sel->get_selected();
1361     if (it) {
1362     Gtk::TreeModel::Row row = *it;
1363     sample = row[m_SamplesModel.m_col_sample];
1364     }
1365     // pass the gig::Sample as pointer
1366     selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&sample,
1367     sizeof(sample)/*length of data in bytes*/);
1368     }
1369    
1370     void MainWindow::on_sample_label_drop_drag_data_received(
1371     const Glib::RefPtr<Gdk::DragContext>& context, int, int,
1372     const Gtk::SelectionData& selection_data, guint, guint time)
1373     {
1374     gig::Sample* sample = *((gig::Sample**) selection_data.get_data());
1375    
1376 persson 1265 if (sample && selection_data.get_length() == sizeof(gig::Sample*)) {
1377 persson 1303 std::cout << "Drop received sample \"" <<
1378     sample->pInfo->Name << "\"" << std::endl;
1379     // drop success
1380     context->drop_reply(true, time);
1381    
1382 schoenebeck 1322 //TODO: we should better move most of the following code to DimRegionEdit::set_sample()
1383    
1384     // notify everybody that we're going to alter the region
1385     gig::Region* region = m_RegionChooser.get_region();
1386     region_to_be_changed_signal.emit(region);
1387    
1388 persson 1303 // find the samplechannel dimension
1389     gig::dimension_def_t* stereo_dimension = 0;
1390     for (int i = 0 ; i < region->Dimensions ; i++) {
1391     if (region->pDimensionDefinitions[i].dimension ==
1392     gig::dimension_samplechannel) {
1393     stereo_dimension = &region->pDimensionDefinitions[i];
1394     break;
1395     }
1396 schoenebeck 1225 }
1397 persson 1303 bool channels_changed = false;
1398     if (sample->Channels == 1 && stereo_dimension) {
1399     // remove the samplechannel dimension
1400     region->DeleteDimension(stereo_dimension);
1401     channels_changed = true;
1402     region_changed();
1403     }
1404     dimreg_edit.set_sample(sample);
1405    
1406     if (sample->Channels == 2 && !stereo_dimension) {
1407     // add samplechannel dimension
1408     gig::dimension_def_t dim;
1409     dim.dimension = gig::dimension_samplechannel;
1410     dim.bits = 1;
1411     dim.zones = 2;
1412     region->AddDimension(&dim);
1413     channels_changed = true;
1414     region_changed();
1415     }
1416     if (channels_changed) {
1417     // unmap all samples with wrong number of channels
1418     // TODO: maybe there should be a warning dialog for this
1419     for (int i = 0 ; i < region->DimensionRegions ; i++) {
1420     gig::DimensionRegion* d = region->pDimensionRegions[i];
1421     if (d->pSample && d->pSample->Channels != sample->Channels) {
1422 schoenebeck 1322 gig::Sample* oldref = d->pSample;
1423     d->pSample = NULL;
1424     sample_ref_changed_signal.emit(oldref, NULL);
1425 persson 1303 }
1426     }
1427     }
1428    
1429 schoenebeck 1322 // notify we're done with altering
1430     region_changed_signal.emit(region);
1431    
1432 persson 1303 return;
1433 schoenebeck 1225 }
1434     // drop failed
1435     context->drop_reply(false, time);
1436     }
1437    
1438     void MainWindow::sample_name_changed(const Gtk::TreeModel::Path& path,
1439     const Gtk::TreeModel::iterator& iter) {
1440     if (!iter) return;
1441     Gtk::TreeModel::Row row = *iter;
1442     Glib::ustring name = row[m_SamplesModel.m_col_name];
1443     gig::Group* group = row[m_SamplesModel.m_col_group];
1444     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1445     if (group) {
1446 persson 1261 if (group->Name != name) {
1447     group->Name = name;
1448     printf("group name changed\n");
1449     file_changed();
1450     }
1451 schoenebeck 1225 } else if (sample) {
1452 persson 1261 if (sample->pInfo->Name != name.raw()) {
1453     sample->pInfo->Name = name.raw();
1454     printf("sample name changed\n");
1455     file_changed();
1456     }
1457 schoenebeck 1225 }
1458     }
1459    
1460     void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
1461     const Gtk::TreeModel::iterator& iter) {
1462     if (!iter) return;
1463     Gtk::TreeModel::Row row = *iter;
1464     Glib::ustring name = row[m_Columns.m_col_name];
1465     gig::Instrument* instrument = row[m_Columns.m_col_instr];
1466 persson 1261 if (instrument && instrument->pInfo->Name != name.raw()) {
1467     instrument->pInfo->Name = name.raw();
1468     file_changed();
1469     }
1470 schoenebeck 1225 }
1471 schoenebeck 1322
1472 schoenebeck 1339 sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
1473 schoenebeck 1322 return file_structure_to_be_changed_signal;
1474     }
1475    
1476 schoenebeck 1339 sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_changed() {
1477 schoenebeck 1322 return file_structure_changed_signal;
1478     }
1479    
1480 schoenebeck 1339 sigc::signal<void, std::list<gig::Sample*> >& MainWindow::signal_samples_to_be_removed() {
1481 schoenebeck 1322 return samples_to_be_removed_signal;
1482     }
1483    
1484 schoenebeck 1339 sigc::signal<void>& MainWindow::signal_samples_removed() {
1485 schoenebeck 1322 return samples_removed_signal;
1486     }
1487    
1488 schoenebeck 1339 sigc::signal<void, gig::Region*>& MainWindow::signal_region_to_be_changed() {
1489 schoenebeck 1322 return region_to_be_changed_signal;
1490     }
1491    
1492 schoenebeck 1339 sigc::signal<void, gig::Region*>& MainWindow::signal_region_changed() {
1493 schoenebeck 1322 return region_changed_signal;
1494     }
1495    
1496 schoenebeck 1339 sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
1497 schoenebeck 1322 return sample_ref_changed_signal;
1498     }
1499    
1500 schoenebeck 1339 sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_to_be_changed() {
1501 schoenebeck 1322 return dimreg_to_be_changed_signal;
1502     }
1503    
1504 schoenebeck 1339 sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
1505 schoenebeck 1322 return dimreg_changed_signal;
1506     }

  ViewVC Help
Powered by ViewVC