/[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 1415 - (show annotations) (download)
Sat Oct 13 13:14:10 2007 UTC (14 years, 1 month ago) by schoenebeck
File size: 59142 byte(s)
* statusbar can be hidden by menu

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.run();
790 #endif
791 }
792
793 PropDialog::PropDialog()
794 : table(2,1)
795 {
796 table.set_col_spacings(5);
797 const char* propLabels[] = {
798 "Name:",
799 "CreationDate:",
800 "Comments:", // TODO: multiline
801 "Product:",
802 "Copyright:",
803 "Artists:",
804 "Genre:",
805 "Keywords:",
806 "Engineer:",
807 "Technician:",
808 "Software:", // TODO: readonly
809 "Medium:",
810 "Source:",
811 "SourceForm:",
812 "Commissioned:",
813 "Subject:"
814 };
815 for (int i = 0 ; i < sizeof(propLabels) / sizeof(char*) ; i++) {
816 label[i].set_text(propLabels[i]);
817 label[i].set_alignment(Gtk::ALIGN_LEFT);
818 table.attach(label[i], 0, 1, i, i + 1, Gtk::FILL, Gtk::SHRINK);
819 table.attach(entry[i], 1, 2, i, i + 1, Gtk::FILL | Gtk::EXPAND,
820 Gtk::SHRINK);
821 }
822
823 add(table);
824 // add_button(Gtk::Stock::CANCEL, 0);
825 // add_button(Gtk::Stock::OK, 1);
826 show_all_children();
827 }
828
829 void PropDialog::set_info(DLS::Info* info)
830 {
831 entry[0].set_text(info->Name);
832 entry[1].set_text(info->CreationDate);
833 entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));
834 entry[3].set_text(info->Product);
835 entry[4].set_text(info->Copyright);
836 entry[5].set_text(info->Artists);
837 entry[6].set_text(info->Genre);
838 entry[7].set_text(info->Keywords);
839 entry[8].set_text(info->Engineer);
840 entry[9].set_text(info->Technician);
841 entry[10].set_text(info->Software);
842 entry[11].set_text(info->Medium);
843 entry[12].set_text(info->Source);
844 entry[13].set_text(info->SourceForm);
845 entry[14].set_text(info->Commissioned);
846 entry[15].set_text(info->Subject);
847 }
848
849 void InstrumentProps::add_prop(BoolEntry& boolentry)
850 {
851 table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
852 Gtk::FILL, Gtk::SHRINK);
853 rowno++;
854 boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
855 }
856
857 void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)
858 {
859 table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,
860 Gtk::FILL, Gtk::SHRINK);
861 rowno++;
862 boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());
863 }
864
865 void InstrumentProps::add_prop(LabelWidget& prop)
866 {
867 table.attach(prop.label, 0, 1, rowno, rowno + 1,
868 Gtk::FILL, Gtk::SHRINK);
869 table.attach(prop.widget, 1, 2, rowno, rowno + 1,
870 Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);
871 rowno++;
872 prop.signal_changed_by_user().connect(instrument_changed.make_slot());
873 }
874
875 InstrumentProps::InstrumentProps()
876 : table(2,1),
877 quitButton(Gtk::Stock::CLOSE),
878 eName("Name"),
879 eIsDrum("Is drum"),
880 eMIDIBank("MIDI bank", 0, 16383),
881 eMIDIProgram("MIDI program"),
882 eAttenuation("Attenuation", 0, 96, 0, 1),
883 eGainPlus6("Gain +6dB", eAttenuation, -6),
884 eEffectSend("Effect send", 0, 65535),
885 eFineTune("Fine tune", -8400, 8400),
886 ePitchbendRange("Pitchbend range", 0, 12),
887 ePianoReleaseMode("Piano release mode"),
888 eDimensionKeyRangeLow("Dimension key range low"),
889 eDimensionKeyRangeHigh("Dimension key range high")
890 {
891 set_title("Instrument properties");
892
893 rowno = 0;
894 table.set_col_spacings(5);
895
896 add_prop(eName);
897 add_prop(eIsDrum);
898 add_prop(eMIDIBank);
899 add_prop(eMIDIProgram);
900 add_prop(eAttenuation);
901 add_prop(eGainPlus6);
902 add_prop(eEffectSend);
903 add_prop(eFineTune);
904 add_prop(ePitchbendRange);
905 add_prop(ePianoReleaseMode);
906 add_prop(eDimensionKeyRangeLow);
907 add_prop(eDimensionKeyRangeHigh);
908
909 eDimensionKeyRangeLow.signal_changed_by_user().connect(
910 sigc::mem_fun(*this, &InstrumentProps::key_range_low_changed));
911 eDimensionKeyRangeHigh.signal_changed_by_user().connect(
912 sigc::mem_fun(*this, &InstrumentProps::key_range_high_changed));
913
914 add(vbox);
915 table.set_border_width(5);
916 vbox.pack_start(table);
917 table.show();
918 vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
919 buttonBox.set_layout(Gtk::BUTTONBOX_END);
920 buttonBox.set_border_width(5);
921 buttonBox.show();
922 buttonBox.pack_start(quitButton);
923 quitButton.set_flags(Gtk::CAN_DEFAULT);
924 quitButton.grab_focus();
925
926 quitButton.signal_clicked().connect(
927 sigc::mem_fun(*this, &InstrumentProps::hide));
928
929 quitButton.show();
930 vbox.show();
931 show_all_children();
932 }
933
934 void InstrumentProps::set_instrument(gig::Instrument* instrument)
935 {
936 eName.set_ptr(&instrument->pInfo->Name);
937 eIsDrum.set_ptr(&instrument->IsDrum);
938 eMIDIBank.set_ptr(&instrument->MIDIBank);
939 eMIDIProgram.set_ptr(&instrument->MIDIProgram);
940 eAttenuation.set_ptr(&instrument->Attenuation);
941 eGainPlus6.set_ptr(&instrument->Attenuation);
942 eEffectSend.set_ptr(&instrument->EffectSend);
943 eFineTune.set_ptr(&instrument->FineTune);
944 ePitchbendRange.set_ptr(&instrument->PitchbendRange);
945 ePianoReleaseMode.set_ptr(&instrument->PianoReleaseMode);
946 eDimensionKeyRangeLow.set_ptr(0);
947 eDimensionKeyRangeHigh.set_ptr(0);
948 eDimensionKeyRangeLow.set_ptr(&instrument->DimensionKeyRange.low);
949 eDimensionKeyRangeHigh.set_ptr(&instrument->DimensionKeyRange.high);
950 }
951
952 void InstrumentProps::key_range_low_changed()
953 {
954 double l = eDimensionKeyRangeLow.get_value();
955 double h = eDimensionKeyRangeHigh.get_value();
956 if (h < l) eDimensionKeyRangeHigh.set_value(l);
957 }
958
959 void InstrumentProps::key_range_high_changed()
960 {
961 double l = eDimensionKeyRangeLow.get_value();
962 double h = eDimensionKeyRangeHigh.get_value();
963 if (h < l) eDimensionKeyRangeLow.set_value(h);
964 }
965
966 sigc::signal<void>& InstrumentProps::signal_instrument_changed()
967 {
968 return instrument_changed;
969 }
970
971 void MainWindow::file_changed()
972 {
973 if (file && !file_is_changed) {
974 set_title("*" + get_title());
975 file_is_changed = true;
976 }
977 }
978
979 void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
980 {
981 file = 0;
982 set_file_is_shared(isSharedInstrument);
983
984 this->filename = filename ? filename : _("Unsaved Gig File");
985 set_title(Glib::filename_display_basename(this->filename));
986 file_has_name = filename;
987 file_is_changed = false;
988
989 propDialog.set_info(gig->pInfo);
990
991 Gtk::MenuItem* instrument_menu =
992 dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));
993
994 int instrument_index = 0;
995 Gtk::RadioMenuItem::Group instrument_group;
996 for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
997 instrument = gig->GetNextInstrument()) {
998 Gtk::TreeModel::iterator iter = m_refTreeModel->append();
999 Gtk::TreeModel::Row row = *iter;
1000 row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
1001 row[m_Columns.m_col_instr] = instrument;
1002 // create a menu item for this instrument
1003 Gtk::RadioMenuItem* item =
1004 new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());
1005 instrument_menu->get_submenu()->append(*item);
1006 item->signal_activate().connect(
1007 sigc::bind(
1008 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
1009 instrument_index
1010 )
1011 );
1012 instrument_index++;
1013 }
1014 instrument_menu->show();
1015 instrument_menu->get_submenu()->show_all_children();
1016
1017 for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1018 if (group->Name != "") {
1019 Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1020 Gtk::TreeModel::Row rowGroup = *iterGroup;
1021 rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
1022 rowGroup[m_SamplesModel.m_col_group] = group;
1023 rowGroup[m_SamplesModel.m_col_sample] = NULL;
1024 for (gig::Sample* sample = group->GetFirstSample();
1025 sample; sample = group->GetNextSample()) {
1026 Gtk::TreeModel::iterator iterSample =
1027 m_refSamplesTreeModel->append(rowGroup.children());
1028 Gtk::TreeModel::Row rowSample = *iterSample;
1029 rowSample[m_SamplesModel.m_col_name] = sample->pInfo->Name.c_str();
1030 rowSample[m_SamplesModel.m_col_sample] = sample;
1031 rowSample[m_SamplesModel.m_col_group] = NULL;
1032 }
1033 }
1034 }
1035
1036 file = gig;
1037
1038 // select the first instrument
1039 Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
1040 tree_sel_ref->select(Gtk::TreePath("0"));
1041 }
1042
1043 void MainWindow::show_instr_props()
1044 {
1045 Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();
1046 Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();
1047 if (it)
1048 {
1049 Gtk::TreeModel::Row row = *it;
1050 if (row[m_Columns.m_col_instr])
1051 {
1052 instrumentProps.set_instrument(row[m_Columns.m_col_instr]);
1053 instrumentProps.show();
1054 instrumentProps.deiconify();
1055 }
1056 }
1057 }
1058
1059 void MainWindow::on_action_view_status_bar() {
1060 Gtk::CheckMenuItem* item =
1061 dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
1062 if (!item) {
1063 std::cerr << "/MenuBar/MenuView/Statusbar == NULL\n";
1064 return;
1065 }
1066 if (item->get_active()) m_StatusBar.show();
1067 else m_StatusBar.hide();
1068 }
1069
1070 void MainWindow::on_button_release(GdkEventButton* button)
1071 {
1072 if (button->type == GDK_2BUTTON_PRESS) {
1073 show_instr_props();
1074 } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1075 popup_menu->popup(button->button, button->time);
1076 }
1077 }
1078
1079 void MainWindow::on_instrument_selection_change(int index) {
1080 m_RegionChooser.set_instrument(file->GetInstrument(index));
1081 }
1082
1083 void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
1084 if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1085 Gtk::Menu* sample_popup =
1086 dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
1087 // update enabled/disabled state of sample popup items
1088 Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1089 Gtk::TreeModel::iterator it = sel->get_selected();
1090 bool group_selected = false;
1091 bool sample_selected = false;
1092 if (it) {
1093 Gtk::TreeModel::Row row = *it;
1094 group_selected = row[m_SamplesModel.m_col_group];
1095 sample_selected = row[m_SamplesModel.m_col_sample];
1096 }
1097 dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
1098 set_sensitive(group_selected || sample_selected);
1099 dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
1100 set_sensitive(group_selected || sample_selected);
1101 dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
1102 set_sensitive(file);
1103 dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
1104 set_sensitive(group_selected || sample_selected);
1105 // show sample popup
1106 sample_popup->popup(button->button, button->time);
1107 }
1108 }
1109
1110 void MainWindow::on_action_add_instrument() {
1111 static int __instrument_indexer = 0;
1112 if (!file) return;
1113 gig::Instrument* instrument = file->AddInstrument();
1114 __instrument_indexer++;
1115 instrument->pInfo->Name =
1116 "Unnamed Instrument " + ToString(__instrument_indexer);
1117 // update instrument tree view
1118 Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
1119 Gtk::TreeModel::Row rowInstr = *iterInstr;
1120 rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();
1121 rowInstr[m_Columns.m_col_instr] = instrument;
1122 file_changed();
1123 }
1124
1125 void MainWindow::on_action_remove_instrument() {
1126 if (!file) return;
1127 if (file_is_shared) {
1128 Gtk::MessageDialog msg(
1129 *this,
1130 _("You cannot delete an instrument from this file, since it's "
1131 "currently used by the sampler."),
1132 false, Gtk::MESSAGE_INFO
1133 );
1134 msg.run();
1135 return;
1136 }
1137
1138 Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1139 Gtk::TreeModel::iterator it = sel->get_selected();
1140 if (it) {
1141 Gtk::TreeModel::Row row = *it;
1142 gig::Instrument* instr = row[m_Columns.m_col_instr];
1143 try {
1144 // remove instrument from the gig file
1145 if (instr) file->DeleteInstrument(instr);
1146 // remove respective row from instruments tree view
1147 m_refTreeModel->erase(it);
1148 file_changed();
1149 } catch (RIFF::Exception e) {
1150 Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1151 msg.run();
1152 }
1153 }
1154 }
1155
1156 void MainWindow::on_action_sample_properties() {
1157 //TODO: show a dialog where the selected sample's properties can be edited
1158 Gtk::MessageDialog msg(
1159 *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO
1160 );
1161 msg.run();
1162 }
1163
1164 void MainWindow::on_action_add_group() {
1165 static int __sample_indexer = 0;
1166 if (!file) return;
1167 gig::Group* group = file->AddGroup();
1168 group->Name = "Unnamed Group";
1169 if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
1170 __sample_indexer++;
1171 // update sample tree view
1172 Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1173 Gtk::TreeModel::Row rowGroup = *iterGroup;
1174 rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();
1175 rowGroup[m_SamplesModel.m_col_sample] = NULL;
1176 rowGroup[m_SamplesModel.m_col_group] = group;
1177 file_changed();
1178 }
1179
1180 void MainWindow::on_action_add_sample() {
1181 if (!file) return;
1182 // get selected group
1183 Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1184 Gtk::TreeModel::iterator it = sel->get_selected();
1185 if (!it) return;
1186 Gtk::TreeModel::Row row = *it;
1187 gig::Group* group = row[m_SamplesModel.m_col_group];
1188 if (!group) { // not a group, but a sample is selected (probably)
1189 gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1190 if (!sample) return;
1191 it = row.parent(); // resolve parent (that is the sample's group)
1192 if (!it) return;
1193 row = *it;
1194 group = row[m_SamplesModel.m_col_group];
1195 if (!group) return;
1196 }
1197 // show 'browse for file' dialog
1198 Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));
1199 dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1200 dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
1201 dialog.set_select_multiple(true);
1202 Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile
1203 const char* const supportedFileTypes[] = {
1204 "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
1205 "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
1206 "*.svx", "*.SVX", "*.sf", "*.SF", "*.voc", "*.VOC", "*.w64",
1207 "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
1208 "*.caf", "*.CAF", NULL
1209 };
1210 for (int i = 0; supportedFileTypes[i]; i++)
1211 soundfilter.add_pattern(supportedFileTypes[i]);
1212 soundfilter.set_name("Sound Files");
1213 Gtk::FileFilter allpassfilter; // matches every file
1214 allpassfilter.add_pattern("*.*");
1215 allpassfilter.set_name("All Files");
1216 dialog.add_filter(soundfilter);
1217 dialog.add_filter(allpassfilter);
1218 if (dialog.run() == Gtk::RESPONSE_OK) {
1219 Glib::ustring error_files;
1220 Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();
1221 for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();
1222 iter != filenames.end(); ++iter) {
1223 printf("Adding sample %s\n",(*iter).c_str());
1224 // use libsndfile to retrieve file informations
1225 SF_INFO info;
1226 info.format = 0;
1227 SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
1228 try {
1229 if (!hFile) throw std::string("could not open file");
1230 int bitdepth;
1231 switch (info.format & 0xff) {
1232 case SF_FORMAT_PCM_S8:
1233 case SF_FORMAT_PCM_16:
1234 case SF_FORMAT_PCM_U8:
1235 bitdepth = 16;
1236 break;
1237 case SF_FORMAT_PCM_24:
1238 case SF_FORMAT_PCM_32:
1239 case SF_FORMAT_FLOAT:
1240 case SF_FORMAT_DOUBLE:
1241 bitdepth = 24;
1242 break;
1243 default:
1244 sf_close(hFile); // close sound file
1245 throw std::string("format not supported"); // unsupported subformat (yet?)
1246 }
1247 // add a new sample to the .gig file
1248 gig::Sample* sample = file->AddSample();
1249 // file name without path
1250 Glib::ustring filename = Glib::filename_display_basename(*iter);
1251 // remove file extension if there is one
1252 for (int i = 0; supportedFileTypes[i]; i++) {
1253 if (Glib::str_has_suffix(filename, supportedFileTypes[i] + 1)) {
1254 filename.erase(filename.length() - strlen(supportedFileTypes[i] + 1));
1255 break;
1256 }
1257 }
1258 sample->pInfo->Name = filename;
1259 sample->Channels = info.channels;
1260 sample->BitDepth = bitdepth;
1261 sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
1262 sample->SamplesPerSecond = info.samplerate;
1263 sample->AverageBytesPerSecond = sample->FrameSize * sample->SamplesPerSecond;
1264 sample->BlockAlign = sample->FrameSize;
1265 sample->SamplesTotal = info.frames;
1266
1267 SF_INSTRUMENT instrument;
1268 if (sf_command(hFile, SFC_GET_INSTRUMENT,
1269 &instrument, sizeof(instrument)) != SF_FALSE)
1270 {
1271 sample->MIDIUnityNote = instrument.basenote;
1272
1273 #if HAVE_SF_INSTRUMENT_LOOPS
1274 if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
1275 sample->Loops = 1;
1276
1277 switch (instrument.loops[0].mode) {
1278 case SF_LOOP_FORWARD:
1279 sample->LoopType = gig::loop_type_normal;
1280 break;
1281 case SF_LOOP_BACKWARD:
1282 sample->LoopType = gig::loop_type_backward;
1283 break;
1284 case SF_LOOP_ALTERNATING:
1285 sample->LoopType = gig::loop_type_bidirectional;
1286 break;
1287 }
1288 sample->LoopStart = instrument.loops[0].start;
1289 sample->LoopEnd = instrument.loops[0].end;
1290 sample->LoopPlayCount = instrument.loops[0].count;
1291 sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
1292 }
1293 #endif
1294 }
1295
1296 // schedule resizing the sample (which will be done
1297 // physically when File::Save() is called)
1298 sample->Resize(info.frames);
1299 // make sure sample is part of the selected group
1300 group->AddSample(sample);
1301 // schedule that physical resize and sample import
1302 // (data copying), performed when "Save" is requested
1303 SampleImportItem sched_item;
1304 sched_item.gig_sample = sample;
1305 sched_item.sample_path = *iter;
1306 m_SampleImportQueue.push_back(sched_item);
1307 // add sample to the tree view
1308 Gtk::TreeModel::iterator iterSample =
1309 m_refSamplesTreeModel->append(row.children());
1310 Gtk::TreeModel::Row rowSample = *iterSample;
1311 rowSample[m_SamplesModel.m_col_name] = filename;
1312 rowSample[m_SamplesModel.m_col_sample] = sample;
1313 rowSample[m_SamplesModel.m_col_group] = NULL;
1314 // close sound file
1315 sf_close(hFile);
1316 file_changed();
1317 } catch (std::string what) { // remember the files that made trouble (and their cause)
1318 if (error_files.size()) error_files += "\n";
1319 error_files += *iter += " (" + what + ")";
1320 }
1321 }
1322 // show error message box when some file(s) could not be opened / added
1323 if (error_files.size()) {
1324 Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;
1325 Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1326 msg.run();
1327 }
1328 }
1329 }
1330
1331 void MainWindow::on_action_remove_sample() {
1332 if (!file) return;
1333 Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1334 Gtk::TreeModel::iterator it = sel->get_selected();
1335 if (it) {
1336 Gtk::TreeModel::Row row = *it;
1337 gig::Group* group = row[m_SamplesModel.m_col_group];
1338 gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1339 Glib::ustring name = row[m_SamplesModel.m_col_name];
1340 try {
1341 // remove group or sample from the gig file
1342 if (group) {
1343 // temporarily remember the samples that bolong to
1344 // that group (we need that to clean the queue)
1345 std::list<gig::Sample*> members;
1346 for (gig::Sample* pSample = group->GetFirstSample();
1347 pSample; pSample = group->GetNextSample()) {
1348 members.push_back(pSample);
1349 }
1350 // notify everybody that we're going to remove these samples
1351 samples_to_be_removed_signal.emit(members);
1352 // delete the group in the .gig file including the
1353 // samples that belong to the group
1354 file->DeleteGroup(group);
1355 // notify that we're done with removal
1356 samples_removed_signal.emit();
1357 // if sample(s) were just previously added, remove
1358 // them from the import queue
1359 for (std::list<gig::Sample*>::iterator member = members.begin();
1360 member != members.end(); ++member) {
1361 for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1362 iter != m_SampleImportQueue.end(); ++iter) {
1363 if ((*iter).gig_sample == *member) {
1364 printf("Removing previously added sample '%s' from group '%s'\n",
1365 (*iter).sample_path.c_str(), name.c_str());
1366 m_SampleImportQueue.erase(iter);
1367 break;
1368 }
1369 }
1370 }
1371 file_changed();
1372 } else if (sample) {
1373 // notify everybody that we're going to remove this sample
1374 std::list<gig::Sample*> lsamples;
1375 lsamples.push_back(sample);
1376 samples_to_be_removed_signal.emit(lsamples);
1377 // remove sample from the .gig file
1378 file->DeleteSample(sample);
1379 // notify that we're done with removal
1380 samples_removed_signal.emit();
1381 // if sample was just previously added, remove it from
1382 // the import queue
1383 for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1384 iter != m_SampleImportQueue.end(); ++iter) {
1385 if ((*iter).gig_sample == sample) {
1386 printf("Removing previously added sample '%s'\n",
1387 (*iter).sample_path.c_str());
1388 m_SampleImportQueue.erase(iter);
1389 break;
1390 }
1391 }
1392 dimreg_changed();
1393 file_changed();
1394 }
1395 // remove respective row(s) from samples tree view
1396 m_refSamplesTreeModel->erase(it);
1397 } catch (RIFF::Exception e) {
1398 // pretend we're done with removal (i.e. to avoid dead locks)
1399 samples_removed_signal.emit();
1400 // show error message
1401 Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1402 msg.run();
1403 }
1404 }
1405 }
1406
1407 // For some reason drag_data_get gets called two times for each
1408 // drag'n'drop (at least when target is an Entry). This work-around
1409 // makes sure the code in drag_data_get and drop_drag_data_received is
1410 // only executed once, as drag_begin only gets called once.
1411 void MainWindow::on_sample_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
1412 {
1413 first_call_to_drag_data_get = true;
1414 }
1415
1416 void MainWindow::on_sample_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
1417 Gtk::SelectionData& selection_data, guint, guint)
1418 {
1419 if (!first_call_to_drag_data_get) return;
1420 first_call_to_drag_data_get = false;
1421
1422 // get selected sample
1423 gig::Sample* sample = NULL;
1424 Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
1425 Gtk::TreeModel::iterator it = sel->get_selected();
1426 if (it) {
1427 Gtk::TreeModel::Row row = *it;
1428 sample = row[m_SamplesModel.m_col_sample];
1429 }
1430 // pass the gig::Sample as pointer
1431 selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&sample,
1432 sizeof(sample)/*length of data in bytes*/);
1433 }
1434
1435 void MainWindow::on_sample_label_drop_drag_data_received(
1436 const Glib::RefPtr<Gdk::DragContext>& context, int, int,
1437 const Gtk::SelectionData& selection_data, guint, guint time)
1438 {
1439 gig::Sample* sample = *((gig::Sample**) selection_data.get_data());
1440
1441 if (sample && selection_data.get_length() == sizeof(gig::Sample*)) {
1442 std::cout << "Drop received sample \"" <<
1443 sample->pInfo->Name << "\"" << std::endl;
1444 // drop success
1445 context->drop_reply(true, time);
1446
1447 //TODO: we should better move most of the following code to DimRegionEdit::set_sample()
1448
1449 // notify everybody that we're going to alter the region
1450 gig::Region* region = m_RegionChooser.get_region();
1451 region_to_be_changed_signal.emit(region);
1452
1453 // find the samplechannel dimension
1454 gig::dimension_def_t* stereo_dimension = 0;
1455 for (int i = 0 ; i < region->Dimensions ; i++) {
1456 if (region->pDimensionDefinitions[i].dimension ==
1457 gig::dimension_samplechannel) {
1458 stereo_dimension = &region->pDimensionDefinitions[i];
1459 break;
1460 }
1461 }
1462 bool channels_changed = false;
1463 if (sample->Channels == 1 && stereo_dimension) {
1464 // remove the samplechannel dimension
1465 region->DeleteDimension(stereo_dimension);
1466 channels_changed = true;
1467 region_changed();
1468 }
1469 dimreg_edit.set_sample(sample);
1470
1471 if (sample->Channels == 2 && !stereo_dimension) {
1472 // add samplechannel dimension
1473 gig::dimension_def_t dim;
1474 dim.dimension = gig::dimension_samplechannel;
1475 dim.bits = 1;
1476 dim.zones = 2;
1477 region->AddDimension(&dim);
1478 channels_changed = true;
1479 region_changed();
1480 }
1481 if (channels_changed) {
1482 // unmap all samples with wrong number of channels
1483 // TODO: maybe there should be a warning dialog for this
1484 for (int i = 0 ; i < region->DimensionRegions ; i++) {
1485 gig::DimensionRegion* d = region->pDimensionRegions[i];
1486 if (d->pSample && d->pSample->Channels != sample->Channels) {
1487 gig::Sample* oldref = d->pSample;
1488 d->pSample = NULL;
1489 sample_ref_changed_signal.emit(oldref, NULL);
1490 }
1491 }
1492 }
1493
1494 // notify we're done with altering
1495 region_changed_signal.emit(region);
1496
1497 return;
1498 }
1499 // drop failed
1500 context->drop_reply(false, time);
1501 }
1502
1503 void MainWindow::sample_name_changed(const Gtk::TreeModel::Path& path,
1504 const Gtk::TreeModel::iterator& iter) {
1505 if (!iter) return;
1506 Gtk::TreeModel::Row row = *iter;
1507 Glib::ustring name = row[m_SamplesModel.m_col_name];
1508 gig::Group* group = row[m_SamplesModel.m_col_group];
1509 gig::Sample* sample = row[m_SamplesModel.m_col_sample];
1510 if (group) {
1511 if (group->Name != name) {
1512 group->Name = name;
1513 printf("group name changed\n");
1514 file_changed();
1515 }
1516 } else if (sample) {
1517 if (sample->pInfo->Name != name.raw()) {
1518 sample->pInfo->Name = name.raw();
1519 printf("sample name changed\n");
1520 file_changed();
1521 }
1522 }
1523 }
1524
1525 void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
1526 const Gtk::TreeModel::iterator& iter) {
1527 if (!iter) return;
1528 Gtk::TreeModel::Row row = *iter;
1529 Glib::ustring name = row[m_Columns.m_col_name];
1530 gig::Instrument* instrument = row[m_Columns.m_col_instr];
1531 if (instrument && instrument->pInfo->Name != name.raw()) {
1532 instrument->pInfo->Name = name.raw();
1533 file_changed();
1534 }
1535 }
1536
1537 void MainWindow::set_file_is_shared(bool b) {
1538 this->file_is_shared = b;
1539
1540 if (file_is_shared) {
1541 m_AttachedStateLabel.set_label(_("live-mode"));
1542 m_AttachedStateImage.set(
1543 Gdk::Pixbuf::create_from_xpm_data(status_attached_xpm)
1544 );
1545 } else {
1546 m_AttachedStateLabel.set_label(_("stand-alone"));
1547 m_AttachedStateImage.set(
1548 Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
1549 );
1550 }
1551 }
1552
1553 sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
1554 return file_structure_to_be_changed_signal;
1555 }
1556
1557 sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_changed() {
1558 return file_structure_changed_signal;
1559 }
1560
1561 sigc::signal<void, std::list<gig::Sample*> >& MainWindow::signal_samples_to_be_removed() {
1562 return samples_to_be_removed_signal;
1563 }
1564
1565 sigc::signal<void>& MainWindow::signal_samples_removed() {
1566 return samples_removed_signal;
1567 }
1568
1569 sigc::signal<void, gig::Region*>& MainWindow::signal_region_to_be_changed() {
1570 return region_to_be_changed_signal;
1571 }
1572
1573 sigc::signal<void, gig::Region*>& MainWindow::signal_region_changed() {
1574 return region_changed_signal;
1575 }
1576
1577 sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
1578 return sample_ref_changed_signal;
1579 }
1580
1581 sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_to_be_changed() {
1582 return dimreg_to_be_changed_signal;
1583 }
1584
1585 sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
1586 return dimreg_changed_signal;
1587 }

  ViewVC Help
Powered by ViewVC