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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1396 - (show annotations) (download)
Wed Oct 10 15:48:54 2007 UTC (16 years, 5 months ago) by schoenebeck
File size: 57471 byte(s)
* gettext is now an optional dependency
* added Dev-C++ project files for Windows

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

  ViewVC Help
Powered by ViewVC