/[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 1303 - (hide annotations) (download)
Sun Aug 26 09:29:52 2007 UTC (16 years, 7 months ago) by persson
File size: 52333 byte(s)
* make sure samplechannel dimension gets created for stereo samples
* allow building with older versions of gtk and libsndfile
* remember selected dimension when switching regions
* fix for loop parameters for unmapped dimregions
* check if file is savable before trying to save

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     sigc::mem_fun(*this, &MainWindow::file_changed));
261     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 1225 file = 0;
268 persson 1261 file_is_changed = false;
269 schoenebeck 1225
270     show_all_children();
271 schoenebeck 1300
272     // start with a new gig file by default
273     on_action_file_new();
274 schoenebeck 1225 }
275    
276     MainWindow::~MainWindow()
277     {
278     }
279    
280 persson 1261 bool MainWindow::on_delete_event(GdkEventAny* event)
281     {
282     return file_is_changed && !close_confirmation_dialog();
283     }
284    
285     void MainWindow::on_action_quit()
286     {
287     if (file_is_changed && !close_confirmation_dialog()) return;
288     hide();
289     }
290    
291 schoenebeck 1225 void MainWindow::region_changed()
292     {
293     m_DimRegionChooser.set_region(m_RegionChooser.get_region());
294     }
295    
296     void MainWindow::dimreg_changed()
297     {
298     dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());
299     }
300    
301     void MainWindow::on_sel_change()
302     {
303     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
304    
305     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();
306     if (it) {
307     Gtk::TreeModel::Row row = *it;
308     std::cout << row[m_Columns.m_col_name] << std::endl;
309    
310     m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);
311     } else {
312     m_RegionChooser.set_instrument(0);
313     }
314     }
315    
316     void loader_progress_callback(gig::progress_t* progress)
317     {
318     Loader* loader = static_cast<Loader*>(progress->custom);
319     loader->progress_callback(progress->factor);
320     }
321    
322     void Loader::progress_callback(float fraction)
323     {
324     {
325     Glib::Mutex::Lock lock(progressMutex);
326     progress = fraction;
327     }
328     progress_dispatcher();
329     }
330    
331     void Loader::thread_function()
332     {
333     printf("thread_function self=%x\n", Glib::Thread::self());
334     printf("Start %s\n", filename);
335     RIFF::File* riff = new RIFF::File(filename);
336     gig = new gig::File(riff);
337     gig::progress_t progress;
338     progress.callback = loader_progress_callback;
339     progress.custom = this;
340    
341     gig->GetInstrument(0, &progress);
342     printf("End\n");
343     finished_dispatcher();
344     }
345    
346     Loader::Loader(const char* filename)
347     : thread(0), filename(filename)
348     {
349     }
350    
351     void Loader::launch()
352     {
353     thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
354     printf("launch thread=%x\n", thread);
355     }
356    
357     float Loader::get_progress()
358     {
359     float res;
360     {
361     Glib::Mutex::Lock lock(progressMutex);
362     res = progress;
363     }
364     return res;
365     }
366    
367     Glib::Dispatcher& Loader::signal_progress()
368     {
369     return progress_dispatcher;
370     }
371    
372     Glib::Dispatcher& Loader::signal_finished()
373     {
374     return finished_dispatcher;
375     }
376    
377     LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)
378     : Gtk::Dialog(title, parent, true)
379     {
380     get_vbox()->pack_start(progressBar);
381     show_all_children();
382     }
383    
384     // Clear all GUI elements / controls. This method is typically called
385     // before a new .gig file is to be created or to be loaded.
386     void MainWindow::__clear() {
387     // remove all entries from "Instrument" menu
388     Gtk::MenuItem* instrument_menu =
389     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));
390     instrument_menu->hide();
391     for (int i = 0; i < instrument_menu->get_submenu()->items().size(); i++) {
392     delete &instrument_menu->get_submenu()->items()[i];
393     }
394     instrument_menu->get_submenu()->items().clear();
395     // forget all samples that ought to be imported
396     m_SampleImportQueue.clear();
397     // clear the samples and instruments tree views
398     m_refTreeModel->clear();
399     m_refSamplesTreeModel->clear();
400     // free libgig's gig::File instance
401     if (file) {
402     delete file;
403     file = NULL;
404     }
405     }
406    
407     void MainWindow::on_action_file_new()
408     {
409 persson 1261 if (file_is_changed && !close_confirmation_dialog()) return;
410    
411 schoenebeck 1225 // clear all GUI elements
412     __clear();
413     // create a new .gig file (virtually yet)
414     gig::File* pFile = new gig::File;
415     // already add one new instrument by default
416     gig::Instrument* pInstrument = pFile->AddInstrument();
417     pInstrument->pInfo->Name = "Unnamed Instrument";
418     // update GUI with that new gig::File
419 persson 1261 load_gig(pFile, 0 /*no file name yet*/);
420 schoenebeck 1225 }
421    
422 persson 1261 bool MainWindow::close_confirmation_dialog()
423     {
424     gchar* msg = g_strdup_printf(_("Save changes to \"%s\" before closing?"),
425     Glib::filename_display_basename(filename).c_str());
426     Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
427     g_free(msg);
428 persson 1303 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2
429 persson 1261 dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
430 persson 1303 #endif
431 persson 1261 dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
432     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
433     dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);
434     dialog.set_default_response(Gtk::RESPONSE_YES);
435     int response = dialog.run();
436 persson 1303 dialog.hide();
437 persson 1261 if (response == Gtk::RESPONSE_YES) return file_save();
438     return response != Gtk::RESPONSE_CANCEL;
439     }
440    
441 schoenebeck 1225 void MainWindow::on_action_file_open()
442     {
443 persson 1261 if (file_is_changed && !close_confirmation_dialog()) return;
444    
445 schoenebeck 1225 Gtk::FileChooserDialog dialog(*this, _("Open file"));
446     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
447     dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
448 persson 1261 dialog.set_default_response(Gtk::RESPONSE_OK);
449 schoenebeck 1225 Gtk::FileFilter filter;
450     filter.add_pattern("*.gig");
451     dialog.set_filter(filter);
452 persson 1261 if (current_dir != "") {
453     dialog.set_current_folder(current_dir);
454     }
455 schoenebeck 1225 if (dialog.run() == Gtk::RESPONSE_OK) {
456 persson 1261 std::string filename = dialog.get_filename();
457     printf("filename=%s\n", filename.c_str());
458 schoenebeck 1225 printf("on_action_file_open self=%x\n", Glib::Thread::self());
459 persson 1261 load_file(filename.c_str());
460     current_dir = Glib::path_get_dirname(filename);
461 schoenebeck 1225 }
462     }
463    
464     void MainWindow::load_file(const char* name)
465     {
466 persson 1303 __clear();
467 schoenebeck 1225 load_dialog = new LoadDialog("Loading...", *this);
468     load_dialog->show_all();
469     loader = new Loader(strdup(name));
470     loader->signal_progress().connect(
471     sigc::mem_fun(*this, &MainWindow::on_loader_progress));
472     loader->signal_finished().connect(
473     sigc::mem_fun(*this, &MainWindow::on_loader_finished));
474     loader->launch();
475     }
476    
477     void MainWindow::load_instrument(gig::Instrument* instr) {
478     if (!instr) {
479     Glib::ustring txt = "Provided instrument is NULL!\n";
480     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
481     msg.run();
482     Gtk::Main::quit();
483     }
484     gig::File* pFile = (gig::File*) instr->GetParent();
485 persson 1261 load_gig(pFile, 0 /*file name*/);
486 schoenebeck 1225 //TODO: automatically select the given instrument
487     }
488    
489     void MainWindow::on_loader_progress()
490     {
491     load_dialog->set_fraction(loader->get_progress());
492     }
493    
494     void MainWindow::on_loader_finished()
495     {
496     printf("Loader finished!\n");
497     printf("on_loader_finished self=%x\n", Glib::Thread::self());
498     load_gig(loader->gig, loader->filename);
499     load_dialog->hide();
500     }
501    
502     void MainWindow::on_action_file_save()
503     {
504 persson 1261 file_save();
505     }
506    
507 persson 1303 bool MainWindow::check_if_savable()
508     {
509     if (!file) return false;
510    
511     if (!file->GetFirstSample()) {
512     Gtk::MessageDialog(*this, _("The file could not be saved "
513     "because it contains no samples"),
514     false, Gtk::MESSAGE_ERROR).run();
515     return false;
516     }
517    
518     for (gig::Instrument* instrument = file->GetFirstInstrument() ; instrument ;
519     instrument = file->GetNextInstrument()) {
520     if (!instrument->GetFirstRegion()) {
521     Gtk::MessageDialog(*this, _("The file could not be saved "
522     "because there are instruments "
523     "that have no regions"),
524     false, Gtk::MESSAGE_ERROR).run();
525     return false;
526     }
527     }
528     return true;
529     }
530    
531 persson 1261 bool MainWindow::file_save()
532     {
533 persson 1303 if (!check_if_savable()) return false;
534 persson 1261 if (!file_has_name) return file_save_as();
535    
536 schoenebeck 1225 std::cout << "Saving file\n" << std::flush;
537     try {
538     file->Save();
539 persson 1261 if (file_is_changed) {
540     set_title(get_title().substr(1));
541     file_is_changed = false;
542     }
543 schoenebeck 1225 } catch (RIFF::Exception e) {
544     Glib::ustring txt = "Could not save file: " + e.Message;
545     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
546     msg.run();
547 persson 1261 return false;
548 schoenebeck 1225 }
549     std::cout << "Saving file done\n" << std::flush;
550     __import_queued_samples();
551 persson 1261 return true;
552 schoenebeck 1225 }
553    
554     void MainWindow::on_action_file_save_as()
555     {
556 persson 1303 if (!check_if_savable()) return;
557 persson 1261 file_save_as();
558     }
559    
560     bool MainWindow::file_save_as()
561     {
562     Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
563 schoenebeck 1225 dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
564     dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
565 persson 1261 dialog.set_default_response(Gtk::RESPONSE_OK);
566    
567     #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 2
568     dialog.set_do_overwrite_confirmation();
569     // TODO: an overwrite dialog for gtkmm < 2.8
570     #endif
571 schoenebeck 1225 Gtk::FileFilter filter;
572     filter.add_pattern("*.gig");
573     dialog.set_filter(filter);
574 persson 1261
575     if (Glib::path_is_absolute(filename)) {
576     dialog.set_filename(filename);
577     } else if (current_dir != "") {
578     dialog.set_current_folder(current_dir);
579     }
580     dialog.set_current_name(Glib::filename_display_basename(filename));
581    
582 schoenebeck 1225 if (dialog.run() == Gtk::RESPONSE_OK) {
583     try {
584 persson 1261 std::string filename = dialog.get_filename();
585     if (!Glib::str_has_suffix(filename, ".gig")) {
586     filename += ".gig";
587     }
588     printf("filename=%s\n", filename.c_str());
589     file->Save(filename);
590     this->filename = filename;
591     current_dir = Glib::path_get_dirname(filename);
592     set_title(Glib::filename_display_basename(filename));
593     file_has_name = true;
594     file_is_changed = false;
595 schoenebeck 1225 } catch (RIFF::Exception e) {
596     Glib::ustring txt = "Could not save file: " + e.Message;
597     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
598     msg.run();
599 persson 1261 return false;
600 schoenebeck 1225 }
601     __import_queued_samples();
602 persson 1261 return true;
603 schoenebeck 1225 }
604 persson 1261 return false;
605 schoenebeck 1225 }
606    
607     // actually write the sample(s)' data to the gig file
608     void MainWindow::__import_queued_samples() {
609     std::cout << "Starting sample import\n" << std::flush;
610     Glib::ustring error_files;
611     printf("Samples to import: %d\n", m_SampleImportQueue.size());
612     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
613     iter != m_SampleImportQueue.end(); ) {
614     printf("Importing sample %s\n",(*iter).sample_path.c_str());
615     SF_INFO info;
616     info.format = 0;
617     SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
618     try {
619     if (!hFile) throw std::string("could not open file");
620     // determine sample's bit depth
621     int bitdepth;
622     switch (info.format & 0xff) {
623     case SF_FORMAT_PCM_S8:
624     case SF_FORMAT_PCM_16:
625 persson 1265 case SF_FORMAT_PCM_U8:
626 schoenebeck 1225 bitdepth = 16;
627     break;
628     case SF_FORMAT_PCM_24:
629     case SF_FORMAT_PCM_32:
630     case SF_FORMAT_FLOAT:
631     case SF_FORMAT_DOUBLE:
632 persson 1265 bitdepth = 24;
633 schoenebeck 1225 break;
634     default:
635     sf_close(hFile); // close sound file
636     throw std::string("format not supported"); // unsupported subformat (yet?)
637     }
638 persson 1265
639     const int bufsize = 10000;
640 schoenebeck 1225 switch (bitdepth) {
641 persson 1265 case 16: {
642     short* buffer = new short[bufsize * info.channels];
643     sf_count_t cnt = info.frames;
644     while (cnt) {
645     // libsndfile does the conversion for us (if needed)
646     int n = sf_readf_short(hFile, buffer, bufsize);
647     // write from buffer directly (physically) into .gig file
648     iter->gig_sample->Write(buffer, n);
649     cnt -= n;
650     }
651     delete[] buffer;
652 schoenebeck 1225 break;
653 persson 1265 }
654     case 24: {
655     int* srcbuf = new int[bufsize * info.channels];
656     uint8_t* dstbuf = new uint8_t[bufsize * 3 * info.channels];
657     sf_count_t cnt = info.frames;
658     while (cnt) {
659     // libsndfile returns 32 bits, convert to 24
660     int n = sf_readf_int(hFile, srcbuf, bufsize);
661     int j = 0;
662     for (int i = 0 ; i < n * info.channels ; i++) {
663     dstbuf[j++] = srcbuf[i] >> 8;
664     dstbuf[j++] = srcbuf[i] >> 16;
665     dstbuf[j++] = srcbuf[i] >> 24;
666     }
667     // write from buffer directly (physically) into .gig file
668     iter->gig_sample->Write(dstbuf, n);
669     cnt -= n;
670     }
671     delete[] srcbuf;
672     delete[] dstbuf;
673 schoenebeck 1225 break;
674 persson 1265 }
675 schoenebeck 1225 }
676     // cleanup
677     sf_close(hFile);
678     // on success we remove the sample from the import queue,
679     // otherwise keep it, maybe it works the next time ?
680     std::list<SampleImportItem>::iterator cur = iter;
681     ++iter;
682     m_SampleImportQueue.erase(cur);
683     } catch (std::string what) {
684     // remember the files that made trouble (and their cause)
685     if (error_files.size()) error_files += "\n";
686     error_files += (*iter).sample_path += " (" + what + ")";
687     ++iter;
688     }
689     }
690     // show error message box when some sample(s) could not be imported
691     if (error_files.size()) {
692     Glib::ustring txt = "Could not import the following sample(s):\n" + error_files;
693     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
694     msg.run();
695     }
696     }
697    
698     void MainWindow::on_action_file_properties()
699     {
700     propDialog.show();
701     propDialog.deiconify();
702     }
703    
704     void MainWindow::on_action_help_about()
705     {
706     #ifdef ABOUT_DIALOG
707     Gtk::AboutDialog dialog;
708     dialog.set_version(VERSION);
709     dialog.run();
710     #endif
711     }
712    
713     PropDialog::PropDialog()
714     : table(2,1)
715     {
716     table.set_col_spacings(5);
717     const char* propLabels[] = {
718     "Name:",
719     "CreationDate:",
720     "Comments:", // TODO: multiline
721     "Product:",
722     "Copyright:",
723     "Artists:",
724     "Genre:",
725     "Keywords:",
726     "Engineer:",
727     "Technician:",
728     "Software:", // TODO: readonly
729     "Medium:",
730     "Source:",
731     "SourceForm:",
732     "Commissioned:",
733     "Subject:"
734     };
735     for (int i = 0 ; i < sizeof(propLabels) / sizeof(char*) ; i++) {
736     label[i].set_text(propLabels[i]);
737     label[i].set_alignment(Gtk::ALIGN_LEFT);
738     table.attach(label[i], 0, 1, i, i + 1, Gtk::FILL, Gtk::SHRINK);
739     table.attach(entry[i], 1, 2, i, i + 1, Gtk::FILL | Gtk::EXPAND,
740     Gtk::SHRINK);
741     }
742    
743     add(table);
744     // add_button(Gtk::Stock::CANCEL, 0);
745     // add_button(Gtk::Stock::OK, 1);
746     show_all_children();
747     }
748    
749     void PropDialog::set_info(DLS::Info* info)
750     {
751     entry[0].set_text(info->Name);
752     entry[1].set_text(info->CreationDate);
753     entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));
754     entry[3].set_text(info->Product);
755     entry[4].set_text(info->Copyright);
756     entry[5].set_text(info->Artists);
757     entry[6].set_text(info->Genre);
758     entry[7].set_text(info->Keywords);
759     entry[8].set_text(info->Engineer);
760     entry[9].set_text(info->Technician);
761     entry[10].set_text(info->Software);
762     entry[11].set_text(info->Medium);
763     entry[12].set_text(info->Source);
764     entry[13].set_text(info->SourceForm);
765     entry[14].set_text(info->Commissioned);
766     entry[15].set_text(info->Subject);
767     }
768    
769 persson 1262 void InstrumentProps::add_prop(BoolEntry& boolentry)
770     {
771     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
772     Gtk::FILL, Gtk::SHRINK);
773     rowno++;
774     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
775     }
776    
777     void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)
778     {
779     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
780     Gtk::FILL, Gtk::SHRINK);
781     rowno++;
782     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
783     }
784    
785 schoenebeck 1225 void InstrumentProps::add_prop(LabelWidget& prop)
786     {
787     table.attach(prop.label, 0, 1, rowno, rowno + 1,
788     Gtk::FILL, Gtk::SHRINK);
789     table.attach(prop.widget, 1, 2, rowno, rowno + 1,
790     Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);
791     rowno++;
792 persson 1261 prop.signal_changed_by_user().connect(instrument_changed.make_slot());
793 schoenebeck 1225 }
794    
795     InstrumentProps::InstrumentProps()
796     : table(2,1),
797     quitButton(Gtk::Stock::CLOSE),
798     eName("Name"),
799 persson 1262 eIsDrum("Is drum"),
800     eMIDIBank("MIDI bank", 0, 16383),
801     eMIDIProgram("MIDI program"),
802 schoenebeck 1225 eAttenuation("Attenuation", 0, 96, 0, 1),
803     eGainPlus6("Gain +6dB", eAttenuation, -6),
804 persson 1262 eEffectSend("Effect send", 0, 65535),
805     eFineTune("Fine tune", -8400, 8400),
806     ePitchbendRange("Pitchbend range", 0, 12),
807     ePianoReleaseMode("Piano release mode"),
808     eDimensionKeyRangeLow("Dimension key range low"),
809     eDimensionKeyRangeHigh("Dimension key range high")
810 schoenebeck 1225 {
811     set_title("Instrument properties");
812    
813     rowno = 0;
814     table.set_col_spacings(5);
815    
816     add_prop(eName);
817     add_prop(eIsDrum);
818     add_prop(eMIDIBank);
819     add_prop(eMIDIProgram);
820     add_prop(eAttenuation);
821     add_prop(eGainPlus6);
822     add_prop(eEffectSend);
823     add_prop(eFineTune);
824     add_prop(ePitchbendRange);
825     add_prop(ePianoReleaseMode);
826     add_prop(eDimensionKeyRangeLow);
827     add_prop(eDimensionKeyRangeHigh);
828    
829 persson 1261 eDimensionKeyRangeLow.signal_changed_by_user().connect(
830 schoenebeck 1225 sigc::mem_fun(*this, &InstrumentProps::key_range_low_changed));
831 persson 1261 eDimensionKeyRangeHigh.signal_changed_by_user().connect(
832 schoenebeck 1225 sigc::mem_fun(*this, &InstrumentProps::key_range_high_changed));
833    
834     add(vbox);
835     table.set_border_width(5);
836     vbox.pack_start(table);
837     table.show();
838     vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
839     buttonBox.set_layout(Gtk::BUTTONBOX_END);
840     buttonBox.set_border_width(5);
841     buttonBox.show();
842     buttonBox.pack_start(quitButton);
843     quitButton.set_flags(Gtk::CAN_DEFAULT);
844     quitButton.grab_focus();
845    
846     quitButton.signal_clicked().connect(
847     sigc::mem_fun(*this, &InstrumentProps::hide));
848    
849     quitButton.show();
850     vbox.show();
851     show_all_children();
852     }
853    
854     void InstrumentProps::set_instrument(gig::Instrument* instrument)
855     {
856     eName.set_ptr(&instrument->pInfo->Name);
857     eIsDrum.set_ptr(&instrument->IsDrum);
858     eMIDIBank.set_ptr(&instrument->MIDIBank);
859     eMIDIProgram.set_ptr(&instrument->MIDIProgram);
860     eAttenuation.set_ptr(&instrument->Attenuation);
861     eGainPlus6.set_ptr(&instrument->Attenuation);
862     eEffectSend.set_ptr(&instrument->EffectSend);
863     eFineTune.set_ptr(&instrument->FineTune);
864     ePitchbendRange.set_ptr(&instrument->PitchbendRange);
865     ePianoReleaseMode.set_ptr(&instrument->PianoReleaseMode);
866 persson 1261 eDimensionKeyRangeLow.set_ptr(0);
867     eDimensionKeyRangeHigh.set_ptr(0);
868 schoenebeck 1225 eDimensionKeyRangeLow.set_ptr(&instrument->DimensionKeyRange.low);
869     eDimensionKeyRangeHigh.set_ptr(&instrument->DimensionKeyRange.high);
870     }
871    
872     void InstrumentProps::key_range_low_changed()
873     {
874     double l = eDimensionKeyRangeLow.get_value();
875     double h = eDimensionKeyRangeHigh.get_value();
876     if (h < l) eDimensionKeyRangeHigh.set_value(l);
877     }
878    
879     void InstrumentProps::key_range_high_changed()
880     {
881     double l = eDimensionKeyRangeLow.get_value();
882     double h = eDimensionKeyRangeHigh.get_value();
883     if (h < l) eDimensionKeyRangeLow.set_value(h);
884     }
885    
886 persson 1261 sigc::signal<void> InstrumentProps::signal_instrument_changed()
887 schoenebeck 1225 {
888 persson 1261 return instrument_changed;
889     }
890 schoenebeck 1225
891 persson 1261 void MainWindow::file_changed()
892     {
893     if (file && !file_is_changed) {
894     set_title("*" + get_title());
895     file_is_changed = true;
896 schoenebeck 1225 }
897 persson 1261 }
898 schoenebeck 1225
899 persson 1261 void MainWindow::load_gig(gig::File* gig, const char* filename)
900     {
901     file = 0;
902    
903     this->filename = filename ? filename : _("Unsaved Gig File");
904     set_title(Glib::filename_display_basename(this->filename));
905     file_has_name = filename;
906     file_is_changed = false;
907    
908 schoenebeck 1225 propDialog.set_info(gig->pInfo);
909    
910     Gtk::MenuItem* instrument_menu =
911     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));
912    
913     int instrument_index = 0;
914     Gtk::RadioMenuItem::Group instrument_group;
915     for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
916     instrument = gig->GetNextInstrument()) {
917     Gtk::TreeModel::iterator iter = m_refTreeModel->append();
918     Gtk::TreeModel::Row row = *iter;
919     row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
920     row[m_Columns.m_col_instr] = instrument;
921     // create a menu item for this instrument
922     Gtk::RadioMenuItem* item =
923     new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());
924     instrument_menu->get_submenu()->append(*item);
925     item->signal_activate().connect(
926     sigc::bind(
927     sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
928     instrument_index
929     )
930     );
931     instrument_index++;
932     }
933     instrument_menu->show();
934     instrument_menu->get_submenu()->show_all_children();
935    
936     for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
937     if (group->Name != "") {
938     Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
939     Gtk::TreeModel::Row rowGroup = *iterGroup;
940     rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
941     rowGroup[m_SamplesModel.m_col_group] = group;
942     rowGroup[m_SamplesModel.m_col_sample] = NULL;
943     for (gig::Sample* sample = group->GetFirstSample();
944     sample; sample = group->GetNextSample()) {
945     Gtk::TreeModel::iterator iterSample =
946     m_refSamplesTreeModel->append(rowGroup.children());
947     Gtk::TreeModel::Row rowSample = *iterSample;
948     rowSample[m_SamplesModel.m_col_name] = sample->pInfo->Name.c_str();
949     rowSample[m_SamplesModel.m_col_sample] = sample;
950     rowSample[m_SamplesModel.m_col_group] = NULL;
951     }
952     }
953     }
954    
955 persson 1261 file = gig;
956    
957 schoenebeck 1225 // select the first instrument
958     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
959     tree_sel_ref->select(Gtk::TreePath("0"));
960     }
961    
962     void MainWindow::show_instr_props()
963     {
964     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
965     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();
966     if (it)
967     {
968     Gtk::TreeModel::Row row = *it;
969     if (row[m_Columns.m_col_instr])
970     {
971     instrumentProps.set_instrument(row[m_Columns.m_col_instr]);
972     instrumentProps.show();
973     instrumentProps.deiconify();
974     }
975     }
976     }
977    
978     void MainWindow::on_button_release(GdkEventButton* button)
979     {
980     if (button->type == GDK_2BUTTON_PRESS) {
981     show_instr_props();
982     } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
983     popup_menu->popup(button->button, button->time);
984     }
985     }
986    
987     void MainWindow::on_instrument_selection_change(int index) {
988     m_RegionChooser.set_instrument(file->GetInstrument(index));
989     }
990    
991     void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
992     if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
993     Gtk::Menu* sample_popup =
994     dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
995     // update enabled/disabled state of sample popup items
996     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
997     Gtk::TreeModel::iterator it = sel->get_selected();
998     bool group_selected = false;
999     bool sample_selected = false;
1000     if (it) {
1001     Gtk::TreeModel::Row row = *it;
1002     group_selected = row[m_SamplesModel.m_col_group];
1003     sample_selected = row[m_SamplesModel.m_col_sample];
1004     }
1005     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
1006     set_sensitive(group_selected || sample_selected);
1007     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
1008     set_sensitive(group_selected || sample_selected);
1009     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
1010     set_sensitive(file);
1011     dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
1012     set_sensitive(group_selected || sample_selected);
1013     // show sample popup
1014     sample_popup->popup(button->button, button->time);
1015     }
1016     }
1017    
1018     void MainWindow::on_action_add_instrument() {
1019     static int __instrument_indexer = 0;
1020     if (!file) return;
1021     gig::Instrument* instrument = file->AddInstrument();
1022     __instrument_indexer++;
1023     instrument->pInfo->Name =
1024     "Unnamed Instrument " + ToString(__instrument_indexer);
1025     // update instrument tree view
1026     Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
1027     Gtk::TreeModel::Row rowInstr = *iterInstr;
1028     rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
1029     rowInstr[m_Columns.m_col_instr] = instrument;
1030 persson 1261 file_changed();
1031 schoenebeck 1225 }
1032    
1033     void MainWindow::on_action_remove_instrument() {
1034     if (!file) return;
1035     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1036     Gtk::TreeModel::iterator it = sel->get_selected();
1037     if (it) {
1038     Gtk::TreeModel::Row row = *it;
1039     gig::Instrument* instr = row[m_Columns.m_col_instr];
1040     try {
1041     // remove instrument from the gig file
1042     if (instr) file->DeleteInstrument(instr);
1043     // remove respective row from instruments tree view
1044     m_refTreeModel->erase(it);
1045 persson 1261 file_changed();
1046 schoenebeck 1225 } catch (RIFF::Exception e) {
1047     Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1048     msg.run();
1049     }
1050     }
1051     }
1052    
1053     void MainWindow::on_action_sample_properties() {
1054     //TODO: show a dialog where the selected sample's properties can be edited
1055     Gtk::MessageDialog msg(
1056     *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO
1057     );
1058     msg.run();
1059     }
1060    
1061     void MainWindow::on_action_add_group() {
1062     static int __sample_indexer = 0;
1063     if (!file) return;
1064     gig::Group* group = file->AddGroup();
1065     group->Name = "Unnamed Group";
1066     if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
1067     __sample_indexer++;
1068     // update sample tree view
1069     Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1070     Gtk::TreeModel::Row rowGroup = *iterGroup;
1071     rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
1072     rowGroup[m_SamplesModel.m_col_sample] = NULL;
1073     rowGroup[m_SamplesModel.m_col_group] = group;
1074 persson 1261 file_changed();
1075 schoenebeck 1225 }
1076    
1077     void MainWindow::on_action_add_sample() {
1078     if (!file) return;
1079     // get selected group
1080     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1081     Gtk::TreeModel::iterator it = sel->get_selected();
1082     if (!it) return;
1083     Gtk::TreeModel::Row row = *it;
1084     gig::Group* group = row[m_SamplesModel.m_col_group];
1085     if (!group) { // not a group, but a sample is selected (probably)
1086     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1087     if (!sample) return;
1088     it = row.parent(); // resolve parent (that is the sample's group)
1089     if (!it) return;
1090     row = *it;
1091     group = row[m_SamplesModel.m_col_group];
1092     if (!group) return;
1093     }
1094     // show 'browse for file' dialog
1095     Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));
1096     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1097     dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
1098     dialog.set_select_multiple(true);
1099     Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile
1100 persson 1262 const char* const supportedFileTypes[] = {
1101 schoenebeck 1225 "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
1102     "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
1103     "*.svx", "*.SVX", "*.sf", "*.SF", "*.voc", "*.VOC", "*.w64",
1104     "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
1105     "*.caf", "*.CAF", NULL
1106     };
1107     for (int i = 0; supportedFileTypes[i]; i++)
1108     soundfilter.add_pattern(supportedFileTypes[i]);
1109     soundfilter.set_name("Sound Files");
1110     Gtk::FileFilter allpassfilter; // matches every file
1111     allpassfilter.add_pattern("*.*");
1112     allpassfilter.set_name("All Files");
1113     dialog.add_filter(soundfilter);
1114     dialog.add_filter(allpassfilter);
1115     if (dialog.run() == Gtk::RESPONSE_OK) {
1116     Glib::ustring error_files;
1117     Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();
1118     for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();
1119     iter != filenames.end(); ++iter) {
1120     printf("Adding sample %s\n",(*iter).c_str());
1121     // use libsndfile to retrieve file informations
1122     SF_INFO info;
1123     info.format = 0;
1124     SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
1125     try {
1126     if (!hFile) throw std::string("could not open file");
1127     int bitdepth;
1128     switch (info.format & 0xff) {
1129     case SF_FORMAT_PCM_S8:
1130     case SF_FORMAT_PCM_16:
1131 persson 1265 case SF_FORMAT_PCM_U8:
1132 schoenebeck 1225 bitdepth = 16;
1133     break;
1134     case SF_FORMAT_PCM_24:
1135     case SF_FORMAT_PCM_32:
1136     case SF_FORMAT_FLOAT:
1137     case SF_FORMAT_DOUBLE:
1138 persson 1265 bitdepth = 24;
1139 schoenebeck 1225 break;
1140     default:
1141     sf_close(hFile); // close sound file
1142     throw std::string("format not supported"); // unsupported subformat (yet?)
1143     }
1144     // add a new sample to the .gig file
1145     gig::Sample* sample = file->AddSample();
1146     // file name without path
1147 persson 1262 Glib::ustring filename = Glib::filename_display_basename(*iter);
1148     // remove file extension if there is one
1149     for (int i = 0; supportedFileTypes[i]; i++) {
1150     if (Glib::str_has_suffix(filename, supportedFileTypes[i] + 1)) {
1151     filename.erase(filename.length() - strlen(supportedFileTypes[i] + 1));
1152     break;
1153     }
1154     }
1155     sample->pInfo->Name = filename;
1156 schoenebeck 1225 sample->Channels = info.channels;
1157     sample->BitDepth = bitdepth;
1158     sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
1159     sample->SamplesPerSecond = info.samplerate;
1160 persson 1265 sample->AverageBytesPerSecond = sample->FrameSize * sample->SamplesPerSecond;
1161     sample->BlockAlign = sample->FrameSize;
1162     sample->SamplesTotal = info.frames;
1163    
1164     SF_INSTRUMENT instrument;
1165     if (sf_command(hFile, SFC_GET_INSTRUMENT,
1166     &instrument, sizeof(instrument)) != SF_FALSE)
1167     {
1168     sample->MIDIUnityNote = instrument.basenote;
1169    
1170 persson 1303 #if HAVE_SF_INSTRUMENT_LOOPS
1171 persson 1265 if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
1172     sample->Loops = 1;
1173    
1174     switch (instrument.loops[0].mode) {
1175     case SF_LOOP_FORWARD:
1176     sample->LoopType = gig::loop_type_normal;
1177     break;
1178     case SF_LOOP_BACKWARD:
1179     sample->LoopType = gig::loop_type_backward;
1180     break;
1181     case SF_LOOP_ALTERNATING:
1182     sample->LoopType = gig::loop_type_bidirectional;
1183     break;
1184     }
1185     sample->LoopStart = instrument.loops[0].start;
1186     sample->LoopEnd = instrument.loops[0].end;
1187     sample->LoopPlayCount = instrument.loops[0].count;
1188     sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
1189     }
1190 persson 1303 #endif
1191 persson 1265 }
1192    
1193 schoenebeck 1225 // schedule resizing the sample (which will be done
1194     // physically when File::Save() is called)
1195     sample->Resize(info.frames);
1196     // make sure sample is part of the selected group
1197     group->AddSample(sample);
1198     // schedule that physical resize and sample import
1199     // (data copying), performed when "Save" is requested
1200     SampleImportItem sched_item;
1201     sched_item.gig_sample = sample;
1202     sched_item.sample_path = *iter;
1203     m_SampleImportQueue.push_back(sched_item);
1204     // add sample to the tree view
1205     Gtk::TreeModel::iterator iterSample =
1206     m_refSamplesTreeModel->append(row.children());
1207     Gtk::TreeModel::Row rowSample = *iterSample;
1208 persson 1262 rowSample[m_SamplesModel.m_col_name] = filename;
1209 schoenebeck 1225 rowSample[m_SamplesModel.m_col_sample] = sample;
1210     rowSample[m_SamplesModel.m_col_group] = NULL;
1211     // close sound file
1212     sf_close(hFile);
1213 persson 1261 file_changed();
1214 schoenebeck 1225 } catch (std::string what) { // remember the files that made trouble (and their cause)
1215     if (error_files.size()) error_files += "\n";
1216     error_files += *iter += " (" + what + ")";
1217     }
1218     }
1219     // show error message box when some file(s) could not be opened / added
1220     if (error_files.size()) {
1221     Glib::ustring txt = "Could not add the following sample(s):\n" + error_files;
1222     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1223     msg.run();
1224     }
1225     }
1226     }
1227    
1228     void MainWindow::on_action_remove_sample() {
1229     if (!file) return;
1230     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1231     Gtk::TreeModel::iterator it = sel->get_selected();
1232     if (it) {
1233     Gtk::TreeModel::Row row = *it;
1234     gig::Group* group = row[m_SamplesModel.m_col_group];
1235     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1236     Glib::ustring name = row[m_SamplesModel.m_col_name];
1237     try {
1238     // remove group or sample from the gig file
1239     if (group) {
1240     // temporarily remember the samples that bolong to
1241     // that group (we need that to clean the queue)
1242     std::list<gig::Sample*> members;
1243     for (gig::Sample* pSample = group->GetFirstSample();
1244     pSample; pSample = group->GetNextSample()) {
1245     members.push_back(pSample);
1246     }
1247     // delete the group in the .gig file including the
1248     // samples that belong to the group
1249     file->DeleteGroup(group);
1250     // if sample(s) were just previously added, remove
1251     // them from the import queue
1252     for (std::list<gig::Sample*>::iterator member = members.begin();
1253     member != members.end(); ++member) {
1254     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1255     iter != m_SampleImportQueue.end(); ++iter) {
1256     if ((*iter).gig_sample == *member) {
1257     printf("Removing previously added sample '%s' from group '%s'\n",
1258     (*iter).sample_path.c_str(), name.c_str());
1259     m_SampleImportQueue.erase(iter);
1260     break;
1261     }
1262     }
1263     }
1264 persson 1261 file_changed();
1265 schoenebeck 1225 } else if (sample) {
1266     // remove sample from the .gig file
1267     file->DeleteSample(sample);
1268     // if sample was just previously added, remove it from
1269     // the import queue
1270     for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1271     iter != m_SampleImportQueue.end(); ++iter) {
1272     if ((*iter).gig_sample == sample) {
1273     printf("Removing previously added sample '%s'\n",
1274     (*iter).sample_path.c_str());
1275     m_SampleImportQueue.erase(iter);
1276     break;
1277     }
1278     }
1279 persson 1303 dimreg_changed();
1280 persson 1261 file_changed();
1281 schoenebeck 1225 }
1282     // remove respective row(s) from samples tree view
1283     m_refSamplesTreeModel->erase(it);
1284     } catch (RIFF::Exception e) {
1285     Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1286     msg.run();
1287     }
1288     }
1289     }
1290    
1291 persson 1303 // For some reason drag_data_get gets called two times for each
1292     // drag'n'drop (at least when target is an Entry). This work-around
1293     // makes sure the code in drag_data_get and drop_drag_data_received is
1294     // only executed once, as drag_begin only gets called once.
1295     void MainWindow::on_sample_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
1296     {
1297     first_call_to_drag_data_get = true;
1298     }
1299    
1300 schoenebeck 1225 void MainWindow::on_sample_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
1301     Gtk::SelectionData& selection_data, guint, guint)
1302     {
1303 persson 1303 if (!first_call_to_drag_data_get) return;
1304     first_call_to_drag_data_get = false;
1305    
1306 schoenebeck 1225 // get selected sample
1307     gig::Sample* sample = NULL;
1308     Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1309     Gtk::TreeModel::iterator it = sel->get_selected();
1310     if (it) {
1311     Gtk::TreeModel::Row row = *it;
1312     sample = row[m_SamplesModel.m_col_sample];
1313     }
1314     // pass the gig::Sample as pointer
1315     selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&sample,
1316     sizeof(sample)/*length of data in bytes*/);
1317     }
1318    
1319     void MainWindow::on_sample_label_drop_drag_data_received(
1320     const Glib::RefPtr<Gdk::DragContext>& context, int, int,
1321     const Gtk::SelectionData& selection_data, guint, guint time)
1322     {
1323     gig::Sample* sample = *((gig::Sample**) selection_data.get_data());
1324    
1325 persson 1265 if (sample && selection_data.get_length() == sizeof(gig::Sample*)) {
1326 persson 1303 std::cout << "Drop received sample \"" <<
1327     sample->pInfo->Name << "\"" << std::endl;
1328     // drop success
1329     context->drop_reply(true, time);
1330    
1331     // find the samplechannel dimension
1332     gig::Region* region = m_RegionChooser.get_region();
1333     gig::dimension_def_t* stereo_dimension = 0;
1334     for (int i = 0 ; i < region->Dimensions ; i++) {
1335     if (region->pDimensionDefinitions[i].dimension ==
1336     gig::dimension_samplechannel) {
1337     stereo_dimension = &region->pDimensionDefinitions[i];
1338     break;
1339     }
1340 schoenebeck 1225 }
1341 persson 1303 bool channels_changed = false;
1342     if (sample->Channels == 1 && stereo_dimension) {
1343     // remove the samplechannel dimension
1344     region->DeleteDimension(stereo_dimension);
1345     channels_changed = true;
1346     region_changed();
1347     }
1348     dimreg_edit.set_sample(sample);
1349    
1350     if (sample->Channels == 2 && !stereo_dimension) {
1351     // add samplechannel dimension
1352     gig::dimension_def_t dim;
1353     dim.dimension = gig::dimension_samplechannel;
1354     dim.bits = 1;
1355     dim.zones = 2;
1356     region->AddDimension(&dim);
1357     channels_changed = true;
1358     region_changed();
1359     }
1360     if (channels_changed) {
1361     // unmap all samples with wrong number of channels
1362     // TODO: maybe there should be a warning dialog for this
1363     for (int i = 0 ; i < region->DimensionRegions ; i++) {
1364     gig::DimensionRegion* d = region->pDimensionRegions[i];
1365     if (d->pSample && d->pSample->Channels != sample->Channels) {
1366     d->pSample = 0;
1367     }
1368     }
1369     }
1370    
1371     return;
1372 schoenebeck 1225 }
1373     // drop failed
1374     context->drop_reply(false, time);
1375     }
1376    
1377     void MainWindow::sample_name_changed(const Gtk::TreeModel::Path& path,
1378     const Gtk::TreeModel::iterator& iter) {
1379     if (!iter) return;
1380     Gtk::TreeModel::Row row = *iter;
1381     Glib::ustring name = row[m_SamplesModel.m_col_name];
1382     gig::Group* group = row[m_SamplesModel.m_col_group];
1383     gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1384     if (group) {
1385 persson 1261 if (group->Name != name) {
1386     group->Name = name;
1387     printf("group name changed\n");
1388     file_changed();
1389     }
1390 schoenebeck 1225 } else if (sample) {
1391 persson 1261 if (sample->pInfo->Name != name.raw()) {
1392     sample->pInfo->Name = name.raw();
1393     printf("sample name changed\n");
1394     file_changed();
1395     }
1396 schoenebeck 1225 }
1397     }
1398    
1399     void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
1400     const Gtk::TreeModel::iterator& iter) {
1401     if (!iter) return;
1402     Gtk::TreeModel::Row row = *iter;
1403     Glib::ustring name = row[m_Columns.m_col_name];
1404     gig::Instrument* instrument = row[m_Columns.m_col_instr];
1405 persson 1261 if (instrument && instrument->pInfo->Name != name.raw()) {
1406     instrument->pInfo->Name = name.raw();
1407     file_changed();
1408     }
1409 schoenebeck 1225 }

  ViewVC Help
Powered by ViewVC