/[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 1460 - (show annotations) (download)
Sat Oct 27 12:28:33 2007 UTC (16 years, 5 months ago) by persson
File size: 60265 byte(s)
* code refactoring: preparing for being able to edit multiple
  dimension regions simultaneously

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

  ViewVC Help
Powered by ViewVC