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

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

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1460 by persson, Sat Oct 27 12:28:33 2007 UTC revision 2695 by schoenebeck, Tue Jan 6 18:11:27 2015 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006, 2007 Andreas Persson   * Copyright (C) 2006-2015 Andreas Persson
3   *   *
4   * This program is free software; you can redistribute it and/or   * This program is free software; you can redistribute it and/or
5   * modify it under the terms of the GNU General Public License as   * modify it under the terms of the GNU General Public License as
# Line 18  Line 18 
18   */   */
19    
20  #include <iostream>  #include <iostream>
21    #include <cstring>
22    
23    #include <glibmm/convert.h>
24    #include <glibmm/dispatcher.h>
25    #include <glibmm/miscutils.h>
26    #include <glibmm/stringutils.h>
27    #include <gtkmm/aboutdialog.h>
28  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
29  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
30  #include <gtkmm/stock.h>  #include <gtkmm/stock.h>
31  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
32  #include <gtkmm/main.h>  #include <gtkmm/main.h>
33  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
34    #if GTKMM_MAJOR_VERSION < 3
35  #include "global.h"  #include "wrapLabel.hh"
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
 #define ABOUT_DIALOG  
 #include <gtkmm/aboutdialog.h>  
36  #endif  #endif
37    
38  #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2  #include "global.h"
39  namespace Glib {  #include "compat.h"
 Glib::ustring filename_display_basename(const std::string& filename)  
 {  
     gchar* gstr = g_path_get_basename(filename.c_str());  
     Glib::ustring str(gstr);  
     g_free(gstr);  
     return Glib::filename_to_utf8(str);  
 }  
 }  
 #endif  
40    
41  #include <stdio.h>  #include <stdio.h>
42  #include <sndfile.h>  #include <sndfile.h>
43    #include <assert.h>
44    
45  #include "mainwindow.h"  #include "mainwindow.h"
46    #include "Settings.h"
47    #include "CombineInstrumentsDialog.h"
48    #include "scripteditor.h"
49    #include "scriptslots.h"
50    #include "ReferencesView.h"
51  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
52  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
53    
 template<class T> inline std::string ToString(T o) {  
     std::stringstream ss;  
     ss << o;  
     return ss.str();  
 }  
54    
55  MainWindow::MainWindow()  MainWindow::MainWindow() :
56        m_DimRegionChooser(*this),
57        dimreg_label(_("Changes apply to:")),
58        dimreg_all_regions(_("all regions")),
59        dimreg_all_dimregs(_("all dimension splits")),
60        dimreg_stereo(_("both channels"))
61  {  {
62  //    set_border_width(5);  //    set_border_width(5);
63  //    set_default_size(400, 200);  //    set_default_size(400, 200);
# Line 68  MainWindow::MainWindow() Line 66  MainWindow::MainWindow()
66      add(m_VBox);      add(m_VBox);
67    
68      // Handle selection      // Handle selection
69      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
70          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
71    
72      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
# Line 85  MainWindow::MainWindow() Line 82  MainWindow::MainWindow()
82      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
83      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
84    
85        m_ScrolledWindowScripts.add(m_TreeViewScripts);
86        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
87    
88    
89      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
90    
91      m_HPaned.add1(m_TreeViewNotebook);      m_HPaned.add1(m_TreeViewNotebook);
92      m_HPaned.add2(dimreg_edit);      dimreg_hbox.add(dimreg_label);
93        dimreg_hbox.add(dimreg_all_regions);
94        dimreg_hbox.add(dimreg_all_dimregs);
95      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");      dimreg_stereo.set_active();
96      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");      dimreg_hbox.add(dimreg_stereo);
97        dimreg_vbox.add(dimreg_edit);
98        dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
99        m_HPaned.add2(dimreg_vbox);
100    
101        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
102        dimreg_all_regions.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied to all regions of this instrument as well."));
103        dimreg_all_dimregs.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied as well to all dimension splits of the region selected below."));
104        dimreg_stereo.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied to both audio channel splits (only if a \"stereo\" dimension is defined below)."));
105    
106        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
107        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
108        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
109    
110      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
111    
# Line 125  MainWindow::MainWindow() Line 136  MainWindow::MainWindow()
136                                           Gtk::Stock::PROPERTIES),                                           Gtk::Stock::PROPERTIES),
137                       sigc::mem_fun(                       sigc::mem_fun(
138                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
139        actionGroup->add(Gtk::Action::create("MidiRules",
140                                             _("_Midi Rules...")),
141                         sigc::mem_fun(
142                             *this, &MainWindow::show_midi_rules));
143        actionGroup->add(Gtk::Action::create("ScriptSlots",
144                                             _("_Script Slots...")),
145                         sigc::mem_fun(
146                             *this, &MainWindow::show_script_slots));
147      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
148                       sigc::mem_fun(                       sigc::mem_fun(
149                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
150      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
151            Gtk::Action::create("MenuSample", _("_Sample")),
152            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
153        );
154        actionGroup->add(
155            Gtk::Action::create("MenuInstrument", _("_Instrument")),
156            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
157        );
158        actionGroup->add(
159            Gtk::Action::create("MenuScript", _("S_cript")),
160            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
161        );
162        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
163    
164        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
165    
     actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  
166      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
167            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
168        toggle_action->set_active(true);
169        actionGroup->add(toggle_action);
170    
171        toggle_action =
172            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
173        toggle_action->set_active(true);
174        actionGroup->add(toggle_action);
175    
176        toggle_action =
177            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
178        toggle_action->set_active(true);
179        actionGroup->add(toggle_action);
180    
181    
182        actionGroup->add(Gtk::Action::create("MenuView", _("_View")));
183        toggle_action =
184          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
185      toggle_action->set_active(true);      toggle_action->set_active(true);
186      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
# Line 141  MainWindow::MainWindow() Line 190  MainWindow::MainWindow()
190      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
191      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
192                                           action->property_label()));                                           action->property_label()));
 #ifdef ABOUT_DIALOG  
193      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),
194                       sigc::mem_fun(                       sigc::mem_fun(
195                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
196      actionGroup->add(      actionGroup->add(
197          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
198          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
199      );      );
200      actionGroup->add(      actionGroup->add(
201            Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
202            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
203        );
204        actionGroup->add(
205          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
206          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
207      );      );
208    
209    
210        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
211        
212        toggle_action =
213            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
214        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
215        actionGroup->add(
216            toggle_action,
217            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
218        );
219    
220        toggle_action =
221            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
222        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
223        actionGroup->add(
224            toggle_action,
225            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
226        );
227    
228    
229        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
230    
231        actionGroup->add(
232            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
233            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
234        );
235    
236        actionGroup->add(
237            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
238            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
239        );
240    
241    
242      // sample right-click popup actions      // sample right-click popup actions
243      actionGroup->add(      actionGroup->add(
244          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
# Line 165  MainWindow::MainWindow() Line 249  MainWindow::MainWindow()
249          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
250      );      );
251      actionGroup->add(      actionGroup->add(
252          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
253          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
254      );      );
255      actionGroup->add(      actionGroup->add(
256          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),
257          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
258      );      );
259        actionGroup->add(
260            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
261            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
262        );
263        actionGroup->add(
264            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
265                                _("Replace All Samples in All Groups...")),
266            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
267        );
268        
269        // script right-click popup actions
270        actionGroup->add(
271            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
272            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
273        );
274        actionGroup->add(
275            Gtk::Action::create("AddScript", _("Add _Script")),
276            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
277        );
278        actionGroup->add(
279            Gtk::Action::create("EditScript", _("_Edit Script...")),
280            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
281        );
282        actionGroup->add(
283            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
284            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
285        );
286    
287      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
288      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 191  MainWindow::MainWindow() Line 302  MainWindow::MainWindow()
302          "      <separator/>"          "      <separator/>"
303          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
304          "    </menu>"          "    </menu>"
305            "    <menu action='MenuEdit'>"
306            "      <menuitem action='CopySampleUnity'/>"
307            "      <menuitem action='CopySampleTune'/>"
308            "      <menuitem action='CopySampleLoop'/>"
309            "    </menu>"
310            "    <menu action='MenuSample'>"
311            "      <menuitem action='SampleProperties'/>"
312            "      <menuitem action='AddGroup'/>"
313            "      <menuitem action='AddSample'/>"
314            "      <menuitem action='ShowSampleRefs'/>"
315            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
316            "      <separator/>"
317            "      <menuitem action='RemoveSample'/>"
318            "    </menu>"
319          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
320            "      <menu action='AllInstruments'>"
321            "      </menu>"
322            "      <separator/>"
323            "      <menuitem action='InstrProperties'/>"
324            "      <menuitem action='MidiRules'/>"
325            "      <menuitem action='ScriptSlots'/>"
326            "      <menuitem action='AddInstrument'/>"
327            "      <menuitem action='DupInstrument'/>"
328            "      <separator/>"
329            "      <menuitem action='RemoveInstrument'/>"
330            "    </menu>"
331            "    <menu action='MenuScript'>"
332            "      <menuitem action='AddScriptGroup'/>"
333            "      <menuitem action='AddScript'/>"
334            "      <menuitem action='EditScript'/>"
335            "      <separator/>"
336            "      <menuitem action='RemoveScript'/>"
337          "    </menu>"          "    </menu>"
338          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
339          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
340          "    </menu>"          "    </menu>"
341  #ifdef ABOUT_DIALOG          "    <menu action='MenuTools'>"
342            "      <menuitem action='CombineInstruments'/>"
343            "      <menuitem action='MergeFiles'/>"
344            "    </menu>"
345            "    <menu action='MenuSettings'>"
346            "      <menuitem action='WarnUserOnExtensions'/>"
347            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
348            "    </menu>"
349          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
350          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
351          "    </menu>"          "    </menu>"
 #endif  
352          "  </menubar>"          "  </menubar>"
353          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
354          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
355            "    <menuitem action='MidiRules'/>"
356            "    <menuitem action='ScriptSlots'/>"
357          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
358            "    <menuitem action='DupInstrument'/>"
359          "    <separator/>"          "    <separator/>"
360          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
361          "  </popup>"          "  </popup>"
# Line 212  MainWindow::MainWindow() Line 363  MainWindow::MainWindow()
363          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
364          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
365          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
366            "    <menuitem action='ShowSampleRefs'/>"
367            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
368          "    <separator/>"          "    <separator/>"
369          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
370          "  </popup>"          "  </popup>"
371            "  <popup name='ScriptPopupMenu'>"
372            "    <menuitem action='AddScriptGroup'/>"
373            "    <menuitem action='AddScript'/>"
374            "    <menuitem action='EditScript'/>"
375            "    <separator/>"
376            "    <menuitem action='RemoveScript'/>"
377            "  </popup>"
378          "</ui>";          "</ui>";
379      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
380    
381      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
382        
383        // Set tooltips for menu items (for some reason, setting a tooltip on the
384        // respective Gtk::Action objects above will simply be ignored, no matter
385        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
386        // Gtk::Action::create()).
387        {
388            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
389                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
390            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current unity note setting will be altered by this action."));
391        }
392        {
393            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
394                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
395            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current sample playback tuning will be altered by this action."));
396        }
397        {
398            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
399                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
400            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current loop informations to be altered by this action."));
401        }
402        {
403            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
404                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
405            item->set_tooltip_text(_("If checked, a warning will be shown whenever you try to use a feature which is based on a LinuxSampler extension ontop of the original gig format, which would not work with the Gigasampler/GigaStudio application."));
406        }
407        {
408            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
409                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
410            item->set_tooltip_text(_("If checked, the sampler's current instrument will automatically be switched whenever another instrument was selected in gigedit (only available in live-mode)."));
411        }
412        {
413            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
414                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
415            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
416        }
417        {
418            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
419                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
420            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
421        }
422    
423    
424        instrument_menu = static_cast<Gtk::MenuItem*>(
425            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
426    
427      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
428      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
429      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
430      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
431        m_VBox.pack_start(m_RegionChooser.m_VirtKeybPropsBox, Gtk::PACK_SHRINK);
432      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
433      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
434    
435        set_file_is_shared(false);
436    
437      // Status Bar:      // Status Bar:
438      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
439      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
# Line 241  MainWindow::MainWindow() Line 448  MainWindow::MainWindow()
448      // Create the Tree model:      // Create the Tree model:
449      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
450      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
451      m_refTreeModel->signal_row_changed().connect(      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules."));
452        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
453          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
454      );      );
455    
# Line 252  MainWindow::MainWindow() Line 460  MainWindow::MainWindow()
460      // create samples treeview (including its data model)      // create samples treeview (including its data model)
461      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
462      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
463        m_TreeViewSamples.set_tooltip_text(_("To actually use a sample, drag it from this list view to \"Sample\" -> \"Sample:\" on the region's settings pane on the right.\n\nRight click here for more actions on samples."));
464      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
465      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
466      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
467        {
468            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
469            Gtk::CellRendererText* cellrenderer =
470                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
471            column->add_attribute(
472                cellrenderer->property_foreground(), m_SamplesModel.m_color
473            );
474        }
475        {
476            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
477            Gtk::CellRendererText* cellrenderer =
478                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
479            column->add_attribute(
480                cellrenderer->property_foreground(), m_SamplesModel.m_color
481            );
482        }
483        m_TreeViewSamples.set_headers_visible(true);
484      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
485          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
486      );      );
# Line 262  MainWindow::MainWindow() Line 488  MainWindow::MainWindow()
488          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
489      );      );
490    
491        // create scripts treeview (including its data model)
492        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
493        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
494        m_TreeViewScripts.set_tooltip_text(_(
495            "Use CTRL + double click for editing a script."
496            "\n\n"
497            "Note: instrument scripts are a LinuxSampler extension of the gig "
498            "format. This feature will not work with the GigaStudio software!"
499        ));
500        // m_TreeViewScripts.set_reorderable();
501        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
502        m_TreeViewScripts.set_headers_visible(false);
503        m_TreeViewScripts.signal_button_press_event().connect_notify(
504            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
505        );
506        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
507        m_TreeViewScripts.signal_row_activated().connect(
508            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
509        );
510        m_refScriptsTreeModel->signal_row_changed().connect(
511            sigc::mem_fun(*this, &MainWindow::script_name_changed)
512        );
513    
514        // establish drag&drop between scripts tree view and ScriptSlots window
515        std::vector<Gtk::TargetEntry> drag_target_gig_script;
516        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
517        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
518        m_TreeViewScripts.signal_drag_begin().connect(
519            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
520        );
521        m_TreeViewScripts.signal_drag_data_get().connect(
522            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
523        );
524    
525      // establish drag&drop between samples tree view and dimension region 'Sample' text entry      // establish drag&drop between samples tree view and dimension region 'Sample' text entry
526      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
527      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
528      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
529      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
530          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 282  MainWindow::MainWindow() Line 542  MainWindow::MainWindow()
542          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
543      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
544          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
545      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
546            sigc::mem_fun(*this, &MainWindow::file_changed));
547        propDialog.signal_changed().connect(
548            sigc::mem_fun(*this, &MainWindow::file_changed));
549        midiRules.signal_changed().connect(
550          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
551    
552      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 291  MainWindow::MainWindow() Line 555  MainWindow::MainWindow()
555          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
556      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
557          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
558        sample_ref_changed_signal.connect(
559            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
560        );
561        samples_to_be_removed_signal.connect(
562            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
563        );
564    
565        dimreg_edit.signal_select_sample().connect(
566            sigc::mem_fun(*this, &MainWindow::select_sample)
567        );
568    
569      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
570          sigc::hide(          sigc::hide(
# Line 313  MainWindow::MainWindow() Line 587  MainWindow::MainWindow()
587      m_RegionChooser.signal_region_changed_signal().connect(      m_RegionChooser.signal_region_changed_signal().connect(
588          region_changed_signal.make_slot());          region_changed_signal.make_slot());
589    
590        note_on_signal.connect(
591            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_on_event));
592        note_off_signal.connect(
593            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_off_event));
594    
595        dimreg_all_regions.signal_toggled().connect(
596            sigc::mem_fun(*this, &MainWindow::update_dimregs));
597        dimreg_all_dimregs.signal_toggled().connect(
598            sigc::mem_fun(*this, &MainWindow::dimreg_all_dimregs_toggled));
599        dimreg_stereo.signal_toggled().connect(
600            sigc::mem_fun(*this, &MainWindow::update_dimregs));
601    
602      file = 0;      file = 0;
603      file_is_changed = false;      file_is_changed = false;
     set_file_is_shared(false);  
604    
605      show_all_children();      show_all_children();
606    
607      // start with a new gig file by default      // start with a new gig file by default
608      on_action_file_new();      on_action_file_new();
609    
610        // select 'Instruments' tab by default
611        // (gtk allows this only if the tab childs are visible, thats why it's here)
612        m_TreeViewNotebook.set_current_page(1);
613  }  }
614    
615  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 343  void MainWindow::region_changed() Line 632  void MainWindow::region_changed()
632      m_DimRegionChooser.set_region(m_RegionChooser.get_region());      m_DimRegionChooser.set_region(m_RegionChooser.get_region());
633  }  }
634    
635    gig::Instrument* MainWindow::get_instrument()
636    {
637        gig::Instrument* instrument = 0;
638        Gtk::TreeModel::const_iterator it =
639            m_TreeView.get_selection()->get_selected();
640        if (it) {
641            Gtk::TreeModel::Row row = *it;
642            instrument = row[m_Columns.m_col_instr];
643        }
644        return instrument;
645    }
646    
647    void MainWindow::add_region_to_dimregs(gig::Region* region, bool stereo, bool all_dimregs)
648    {
649        if (all_dimregs) {
650            for (int i = 0 ; i < region->DimensionRegions ; i++) {
651                if (region->pDimensionRegions[i]) {
652                    dimreg_edit.dimregs.insert(region->pDimensionRegions[i]);
653                }
654            }
655        } else {
656            m_DimRegionChooser.get_dimregions(region, stereo, dimreg_edit.dimregs);
657        }
658    }
659    
660    void MainWindow::update_dimregs()
661    {
662        dimreg_edit.dimregs.clear();
663        bool all_regions = dimreg_all_regions.get_active();
664        bool stereo = dimreg_stereo.get_active();
665        bool all_dimregs = dimreg_all_dimregs.get_active();
666    
667        if (all_regions) {
668            gig::Instrument* instrument = get_instrument();
669            if (instrument) {
670                for (gig::Region* region = instrument->GetFirstRegion() ;
671                     region ;
672                     region = instrument->GetNextRegion()) {
673                    add_region_to_dimregs(region, stereo, all_dimregs);
674                }
675            }
676        } else {
677            gig::Region* region = m_RegionChooser.get_region();
678            if (region) {
679                add_region_to_dimregs(region, stereo, all_dimregs);
680            }
681        }
682    }
683    
684    void MainWindow::dimreg_all_dimregs_toggled()
685    {
686        dimreg_stereo.set_sensitive(!dimreg_all_dimregs.get_active());
687        update_dimregs();
688    }
689    
690  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
691  {  {
692      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      update_dimregs();
693        dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
694  }  }
695    
696  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
697  {  {
698      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      // select item in instrument menu
699        Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();
     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();  
700      if (it) {      if (it) {
701          Gtk::TreeModel::Row row = *it;          Gtk::TreePath path(it);
702          std::cout << row[m_Columns.m_col_name] << std::endl;          int index = path[0];
703            const std::vector<Gtk::Widget*> children =
704                instrument_menu->get_children();
705            static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
706        }
707    
708          m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);      m_RegionChooser.set_instrument(get_instrument());
709      } else {  
710          m_RegionChooser.set_instrument(0);      if (Settings::singleton()->syncSamplerInstrumentSelection) {
711            switch_sampler_instrument_signal.emit(get_instrument());
712      }      }
713  }  }
714    
# Line 372  void loader_progress_callback(gig::progr Line 721  void loader_progress_callback(gig::progr
721  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
722  {  {
723      {      {
724          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
725          progress = fraction;          progress = fraction;
726      }      }
727      progress_dispatcher();      progress_dispatcher();
# Line 380  void Loader::progress_callback(float fra Line 729  void Loader::progress_callback(float fra
729    
730  void Loader::thread_function()  void Loader::thread_function()
731  {  {
732      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%x\n", Glib::Threads::Thread::self());
733      printf("Start %s\n", filename);      printf("Start %s\n", filename.c_str());
734      RIFF::File* riff = new RIFF::File(filename);      try {
735      gig = new gig::File(riff);          RIFF::File* riff = new RIFF::File(filename);
736      gig::progress_t progress;          gig = new gig::File(riff);
737      progress.callback = loader_progress_callback;          gig::progress_t progress;
738      progress.custom = this;          progress.callback = loader_progress_callback;
739            progress.custom = this;
740      gig->GetInstrument(0, &progress);  
741      printf("End\n");          gig->GetInstrument(0, &progress);
742      finished_dispatcher();          printf("End\n");
743            finished_dispatcher();
744        } catch (RIFF::Exception e) {
745            error_message = e.Message;
746            error_dispatcher.emit();
747        } catch (...) {
748            error_message = _("Unknown exception occurred");
749            error_dispatcher.emit();
750        }
751  }  }
752    
753  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
754      : thread(0), filename(filename)      : filename(filename), thread(0), progress(0.f)
755  {  {
756  }  }
757    
758  void Loader::launch()  void Loader::launch()
759  {  {
760    #ifdef OLD_THREADS
761      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
762    #else
763        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
764    #endif
765      printf("launch thread=%x\n", thread);      printf("launch thread=%x\n", thread);
766  }  }
767    
# Line 408  float Loader::get_progress() Line 769  float Loader::get_progress()
769  {  {
770      float res;      float res;
771      {      {
772          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
773          res = progress;          res = progress;
774      }      }
775      return res;      return res;
# Line 424  Glib::Dispatcher& Loader::signal_finishe Line 785  Glib::Dispatcher& Loader::signal_finishe
785      return finished_dispatcher;      return finished_dispatcher;
786  }  }
787    
788  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
789    {
790        return error_dispatcher;
791    }
792    
793    void saver_progress_callback(gig::progress_t* progress)
794    {
795        Saver* saver = static_cast<Saver*>(progress->custom);
796        saver->progress_callback(progress->factor);
797    }
798    
799    void Saver::progress_callback(float fraction)
800    {
801        {
802            Glib::Threads::Mutex::Lock lock(progressMutex);
803            progress = fraction;
804        }
805        progress_dispatcher.emit();
806    }
807    
808    void Saver::thread_function()
809    {
810        printf("thread_function self=%x\n", Glib::Threads::Thread::self());
811        printf("Start %s\n", filename.c_str());
812        try {
813            gig::progress_t progress;
814            progress.callback = saver_progress_callback;
815            progress.custom = this;
816    
817            // if no filename was provided, that means "save", if filename was provided means "save as"
818            if (filename.empty()) {
819                gig->Save(&progress);
820            } else {
821                gig->Save(filename, &progress);
822            }
823    
824            printf("End\n");
825            finished_dispatcher.emit();
826        } catch (RIFF::Exception e) {
827            error_message = e.Message;
828            error_dispatcher.emit();
829        } catch (...) {
830            error_message = _("Unknown exception occurred");
831            error_dispatcher.emit();
832        }
833    }
834    
835    Saver::Saver(gig::File* file, Glib::ustring filename)
836        : gig(file), filename(filename), thread(0), progress(0.f)
837    {
838    }
839    
840    void Saver::launch()
841    {
842    #ifdef OLD_THREADS
843        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
844    #else
845        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
846    #endif
847        printf("launch thread=%x\n", thread);
848    }
849    
850    float Saver::get_progress()
851    {
852        float res;
853        {
854            Glib::Threads::Mutex::Lock lock(progressMutex);
855            res = progress;
856        }
857        return res;
858    }
859    
860    Glib::Dispatcher& Saver::signal_progress()
861    {
862        return progress_dispatcher;
863    }
864    
865    Glib::Dispatcher& Saver::signal_finished()
866    {
867        return finished_dispatcher;
868    }
869    
870    Glib::Dispatcher& Saver::signal_error()
871    {
872        return error_dispatcher;
873    }
874    
875    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
876      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
877  {  {
878      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
879      show_all_children();      show_all_children();
880        resize(600,50);
881  }  }
882    
883  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
884  // before a new .gig file is to be created or to be loaded.  // before a new .gig file is to be created or to be loaded.
885  void MainWindow::__clear() {  void MainWindow::__clear() {
     // remove all entries from "Instrument" menu  
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
     instrument_menu->hide();  
     for (int i = 0; i < instrument_menu->get_submenu()->items().size(); i++) {  
         delete &instrument_menu->get_submenu()->items()[i];  
     }  
     instrument_menu->get_submenu()->items().clear();  
886      // forget all samples that ought to be imported      // forget all samples that ought to be imported
887      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
888      // clear the samples and instruments tree views      // clear the samples and instruments tree views
889      m_refTreeModel->clear();      m_refTreeModel->clear();
890      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
891        m_refScriptsTreeModel->clear();
892        // remove all entries from "Instrument" menu
893        while (!instrument_menu->get_children().empty()) {
894            remove_instrument_from_menu(0);
895        }
896      // free libgig's gig::File instance      // free libgig's gig::File instance
897      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
898      file = NULL;      file = NULL;
899      set_file_is_shared(false);      set_file_is_shared(false);
900  }  }
901    
902    void MainWindow::__refreshEntireGUI() {
903        // clear the samples and instruments tree views
904        m_refTreeModel->clear();
905        m_refSamplesTreeModel->clear();
906        m_refScriptsTreeModel->clear();
907        // remove all entries from "Instrument" menu
908        while (!instrument_menu->get_children().empty()) {
909            remove_instrument_from_menu(0);
910        }
911    
912        if (!this->file) return;
913    
914        load_gig(
915            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
916        );
917    }
918    
919  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
920  {  {
921      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 465  void MainWindow::on_action_file_new() Line 928  void MainWindow::on_action_file_new()
928      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
929      // already add one new instrument by default      // already add one new instrument by default
930      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
931      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
932      // update GUI with that new gig::File      // update GUI with that new gig::File
933      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
934  }  }
# Line 476  bool MainWindow::close_confirmation_dial Line 939  bool MainWindow::close_confirmation_dial
939                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
940      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
941      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
942      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
 #endif  
943      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
944      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
945      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);
946      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
947      int response = dialog.run();      int response = dialog.run();
948      dialog.hide();      dialog.hide();
949      if (response == Gtk::RESPONSE_YES) return file_save();  
950      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
951        if (response == Gtk::RESPONSE_NO) return true;
952    
953        // user cancelled dialog, thus don't close app
954        if (response == Gtk::RESPONSE_CANCEL) return false;
955    
956        // TODO: the following return valid is disabled and hard coded instead for
957        // now, due to the fact that saving with progress bar is now implemented
958        // asynchronously, as a result the app does not close automatically anymore
959        // after saving the file has completed
960        //
961        //   if (response == Gtk::RESPONSE_YES) return file_save();
962        //   return response != Gtk::RESPONSE_CANCEL;
963        //
964        if (response == Gtk::RESPONSE_YES) file_save();
965        return false; // always prevent closing the app for now (see comment above)
966  }  }
967    
968  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
969      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
970      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
971      dialog.set_secondary_text(      dialog.set_secondary_text(
972          _("If you proceed to work on another instrument file, it won't be "          _("If you proceed to work on another instrument file, it won't be "
973            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
974            "load it.")            "load it."));
    );  
 #endif  
975      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
976      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
977      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
# Line 517  void MainWindow::on_action_file_open() Line 990  void MainWindow::on_action_file_open()
990      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
991      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
992      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
993    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
994      Gtk::FileFilter filter;      Gtk::FileFilter filter;
995      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
996    #else
997        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
998        filter->add_pattern("*.gig");
999    #endif
1000      dialog.set_filter(filter);      dialog.set_filter(filter);
1001      if (current_dir != "") {      if (current_gig_dir != "") {
1002          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1003      }      }
1004      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1005          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1006          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1007          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());
1008          load_file(filename.c_str());          load_file(filename.c_str());
1009          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1010      }      }
1011  }  }
1012    
1013  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1014  {  {
1015      __clear();      __clear();
1016      load_dialog = new LoadDialog("Loading...", *this);  
1017      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1018      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1019            Glib::filename_display_basename(name) + "' ...",
1020            *this
1021        );
1022        progress_dialog->show_all();
1023        loader = new Loader(name); //FIXME: memory leak!
1024      loader->signal_progress().connect(      loader->signal_progress().connect(
1025          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1026      loader->signal_finished().connect(      loader->signal_finished().connect(
1027          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1028        loader->signal_error().connect(
1029            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1030      loader->launch();      loader->launch();
1031  }  }
1032    
# Line 557  void MainWindow::load_instrument(gig::In Line 1042  void MainWindow::load_instrument(gig::In
1042      // load the instrument      // load the instrument
1043      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1044      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1045      //TODO: automatically select the given instrument      // automatically select the given instrument
1046        int i = 0;
1047        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1048             instrument = pFile->GetNextInstrument(), ++i)
1049        {
1050            if (instrument == instr) {
1051                // select item in "instruments" tree view
1052                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1053                // make sure the selected item in the "instruments" tree view is
1054                // visible (scroll to it)
1055                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1056                // select item in instrument menu
1057                {
1058                    const std::vector<Gtk::Widget*> children =
1059                        instrument_menu->get_children();
1060                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1061                }
1062                // update region chooser and dimension region chooser
1063                m_RegionChooser.set_instrument(instr);
1064                break;
1065            }
1066        }
1067  }  }
1068    
1069  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1070  {  {
1071      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1072  }  }
1073    
1074  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1075  {  {
1076      printf("Loader finished!\n");      printf("Loader finished!\n");
1077      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());
1078      load_gig(loader->gig, loader->filename);      load_gig(loader->gig, loader->filename.c_str());
1079      load_dialog->hide();      progress_dialog->hide();
1080    }
1081    
1082    void MainWindow::on_loader_error()
1083    {
1084        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1085        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1086        msg.run();
1087        progress_dialog->hide();
1088  }  }
1089    
1090  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 609  bool MainWindow::file_save() Line 1123  bool MainWindow::file_save()
1123    
1124      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1125      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1126      try {  
1127          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1128          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1129              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1130              file_is_changed = false;          *this
1131          }      );
1132      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1133          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1134          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1135          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1136          msg.run();      saver->signal_finished().connect(
1137          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1138      }      saver->signal_error().connect(
1139      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1140        saver->launch();
1141    
1142        return true;
1143    }
1144    
1145    void MainWindow::on_saver_progress()
1146    {
1147        progress_dialog->set_fraction(saver->get_progress());
1148    }
1149    
1150    void MainWindow::on_saver_error()
1151    {
1152        file_structure_changed_signal.emit(this->file);
1153        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1154        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1155        msg.run();
1156    }
1157    
1158    void MainWindow::on_saver_finished()
1159    {
1160        this->file = saver->gig;
1161        this->filename = saver->filename;
1162        current_gig_dir = Glib::path_get_dirname(filename);
1163        set_title(Glib::filename_display_basename(filename));
1164        file_has_name = true;
1165        file_is_changed = false;
1166        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1167      __import_queued_samples();      __import_queued_samples();
1168        std::cout << "Importing queued samples done.\n" << std::flush;
1169    
1170      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1171      return true;  
1172        load_gig(this->file, this->filename.c_str());
1173        progress_dialog->hide();
1174  }  }
1175    
1176  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 640  bool MainWindow::file_save_as() Line 1185  bool MainWindow::file_save_as()
1185      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1186      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
1187      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 2  
1188      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1189      // TODO: an overwrite dialog for gtkmm < 2.8  
1190  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1191      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1192      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1193    #else
1194        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1195        filter->add_pattern("*.gig");
1196    #endif
1197      dialog.set_filter(filter);      dialog.set_filter(filter);
1198    
1199      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1200          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1201      } else if (current_dir != "") {      {
1202          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1203            std::string dir = Glib::path_get_dirname(filename);
1204            basename = std::string(_("copy_of_")) + basename;
1205            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1206            if (Glib::path_is_absolute(filename)) {
1207                dialog.set_filename(copyFileName);
1208            } else {
1209                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1210            }
1211            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1212      }      }
1213      dialog.set_current_name(Glib::filename_display_basename(filename));  
1214        // show warning in the dialog
1215        Gtk::HBox descriptionArea;
1216        descriptionArea.set_spacing(15);
1217        Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1218        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1219    #if GTKMM_MAJOR_VERSION < 3
1220        view::WrapLabel description;
1221    #else
1222        Gtk::Label description;
1223        description.set_line_wrap();
1224    #endif
1225        description.set_markup(
1226            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1227              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1228              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1229              "to the same .gig file. Using "
1230              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1231              "same .gig file will end up in corrupted sample wave data!\n")
1232        );
1233        descriptionArea.pack_start(description);
1234        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1235        descriptionArea.show_all();
1236    
1237      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1238          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1239          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1240              std::string filename = dialog.get_filename();              filename += ".gig";
             if (!Glib::str_has_suffix(filename, ".gig")) {  
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_dir = Glib::path_get_dirname(filename);  
             set_title(Glib::filename_display_basename(filename));  
             file_has_name = true;  
             file_is_changed = false;  
         } catch (RIFF::Exception e) {  
             file_structure_changed_signal.emit(this->file);  
             Glib::ustring txt = _("Could not save file: ") + e.Message;  
             Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
             msg.run();  
             return false;  
1241          }          }
1242          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1243          file_structure_changed_signal.emit(this->file);  
1244            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1245                _("Saving") +  Glib::ustring(" '") +
1246                Glib::filename_display_basename(filename) + "' ...",
1247                *this
1248            );
1249            progress_dialog->show_all();
1250    
1251            saver = new Saver(file, filename); //FIXME: memory leak!
1252            saver->signal_progress().connect(
1253                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1254            saver->signal_finished().connect(
1255                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1256            saver->signal_error().connect(
1257                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1258            saver->launch();
1259    
1260          return true;          return true;
1261      }      }
1262      return false;      return false;
# Line 695  void MainWindow::__import_queued_samples Line 1273  void MainWindow::__import_queued_samples
1273          SF_INFO info;          SF_INFO info;
1274          info.format = 0;          info.format = 0;
1275          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
1276            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1277          try {          try {
1278              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1279              // determine sample's bit depth              // determine sample's bit depth
1280              int bitdepth;              int bitdepth;
1281              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 713  void MainWindow::__import_queued_samples Line 1292  void MainWindow::__import_queued_samples
1292                      break;                      break;
1293                  default:                  default:
1294                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1295                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1296              }              }
1297    
1298              const int bufsize = 10000;              const int bufsize = 10000;
# Line 755  void MainWindow::__import_queued_samples Line 1334  void MainWindow::__import_queued_samples
1334              }              }
1335              // cleanup              // cleanup
1336              sf_close(hFile);              sf_close(hFile);
1337                // let the sampler re-cache the sample if needed
1338                sample_changed_signal.emit(iter->gig_sample);
1339              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1340              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1341              std::list<SampleImportItem>::iterator cur = iter;              std::list<SampleImportItem>::iterator cur = iter;
# Line 762  void MainWindow::__import_queued_samples Line 1343  void MainWindow::__import_queued_samples
1343              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1344          } catch (std::string what) {          } catch (std::string what) {
1345              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1346              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1347              error_files += (*iter).sample_path += " (" + what + ")";              error_files += (*iter).sample_path += " (" + what + ")";
1348              ++iter;              ++iter;
1349          }          }
1350      }      }
1351      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1352      if (error_files.size()) {      if (!error_files.empty()) {
1353          Glib::ustring txt = _("Could not import the following sample(s):\n") + error_files;          Glib::ustring txt = _("Could not import the following sample(s):\n") + error_files;
1354          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1355          msg.run();          msg.run();
# Line 781  void MainWindow::on_action_file_properti Line 1362  void MainWindow::on_action_file_properti
1362      propDialog.deiconify();      propDialog.deiconify();
1363  }  }
1364    
1365    void MainWindow::on_action_warn_user_on_extensions() {
1366        Settings::singleton()->warnUserOnExtensions =
1367            !Settings::singleton()->warnUserOnExtensions;
1368    }
1369    
1370    void MainWindow::on_action_sync_sampler_instrument_selection() {
1371        Settings::singleton()->syncSamplerInstrumentSelection =
1372            !Settings::singleton()->syncSamplerInstrumentSelection;
1373    }
1374    
1375  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1376  {  {
 #ifdef ABOUT_DIALOG  
1377      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1378    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1379        dialog.set_program_name("Gigedit");
1380    #else
1381        dialog.set_name("Gigedit");
1382    #endif
1383      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1384      dialog.set_copyright("Copyright (C) 2006,2007 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2015 Andreas Persson");
1385      dialog.set_comments(      const std::string sComment =
1386          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
1387          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1388          "Please notice that this is still a very young instrument editor. "          _(
1389          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
1390          "this application.\n"              "\n"
1391          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
1392          "Please report bugs to: http://bugs.linuxsampler.org"              "backup your Gigasampler/GigaStudio files before editing them with "
1393      );              "this application.\n"
1394                "\n"
1395                "Please report bugs to: http://bugs.linuxsampler.org"
1396            );
1397        dialog.set_comments(sComment.c_str());
1398      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1399      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1400      dialog.run();      dialog.run();
 #endif  
1401  }  }
1402    
1403  PropDialog::PropDialog()  PropDialog::PropDialog()
1404      : table(2,1)      : eFileFormat(_("File Format")),
1405          eName(_("Name")),
1406          eCreationDate(_("Creation date")),
1407          eComments(_("Comments")),
1408          eProduct(_("Product")),
1409          eCopyright(_("Copyright")),
1410          eArtists(_("Artists")),
1411          eGenre(_("Genre")),
1412          eKeywords(_("Keywords")),
1413          eEngineer(_("Engineer")),
1414          eTechnician(_("Technician")),
1415          eSoftware(_("Software")),
1416          eMedium(_("Medium")),
1417          eSource(_("Source")),
1418          eSourceForm(_("Source form")),
1419          eCommissioned(_("Commissioned")),
1420          eSubject(_("Subject")),
1421          quitButton(Gtk::Stock::CLOSE),
1422          table(2, 1),
1423          m_file(NULL)
1424  {  {
1425        set_title(_("File Properties"));
1426        eName.set_width_chars(50);
1427    
1428        connect(eName, &DLS::Info::Name);
1429        connect(eCreationDate, &DLS::Info::CreationDate);
1430        connect(eComments, &DLS::Info::Comments);
1431        connect(eProduct, &DLS::Info::Product);
1432        connect(eCopyright, &DLS::Info::Copyright);
1433        connect(eArtists, &DLS::Info::Artists);
1434        connect(eGenre, &DLS::Info::Genre);
1435        connect(eKeywords, &DLS::Info::Keywords);
1436        connect(eEngineer, &DLS::Info::Engineer);
1437        connect(eTechnician, &DLS::Info::Technician);
1438        connect(eSoftware, &DLS::Info::Software);
1439        connect(eMedium, &DLS::Info::Medium);
1440        connect(eSource, &DLS::Info::Source);
1441        connect(eSourceForm, &DLS::Info::SourceForm);
1442        connect(eCommissioned, &DLS::Info::Commissioned);
1443        connect(eSubject, &DLS::Info::Subject);
1444    
1445        table.add(eFileFormat);
1446        table.add(eName);
1447        table.add(eCreationDate);
1448        table.add(eComments);
1449        table.add(eProduct);
1450        table.add(eCopyright);
1451        table.add(eArtists);
1452        table.add(eGenre);
1453        table.add(eKeywords);
1454        table.add(eEngineer);
1455        table.add(eTechnician);
1456        table.add(eSoftware);
1457        table.add(eMedium);
1458        table.add(eSource);
1459        table.add(eSourceForm);
1460        table.add(eCommissioned);
1461        table.add(eSubject);
1462    
1463      table.set_col_spacings(5);      table.set_col_spacings(5);
1464      const char* propLabels[] = {      add(vbox);
1465          "Name:",      table.set_border_width(5);
1466          "CreationDate:",      vbox.add(table);
1467          "Comments:", // TODO: multiline      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
1468          "Product:",      buttonBox.set_layout(Gtk::BUTTONBOX_END);
1469          "Copyright:",      buttonBox.set_border_width(5);
1470          "Artists:",      buttonBox.show();
1471          "Genre:",      buttonBox.pack_start(quitButton);
1472          "Keywords:",      quitButton.set_can_default();
1473          "Engineer:",      quitButton.grab_focus();
1474          "Technician:",      quitButton.signal_clicked().connect(
1475          "Software:", // TODO: readonly          sigc::mem_fun(*this, &PropDialog::hide));
1476          "Medium:",      eFileFormat.signal_value_changed().connect(
1477          "Source:",          sigc::mem_fun(*this, &PropDialog::onFileFormatChanged));
         "SourceForm:",  
         "Commissioned:",  
         "Subject:"  
     };  
     for (int i = 0 ; i < sizeof(propLabels) / sizeof(char*) ; i++) {  
         label[i].set_text(propLabels[i]);  
         label[i].set_alignment(Gtk::ALIGN_LEFT);  
         table.attach(label[i], 0, 1, i, i + 1, Gtk::FILL, Gtk::SHRINK);  
         table.attach(entry[i], 1, 2, i, i + 1, Gtk::FILL | Gtk::EXPAND,  
                      Gtk::SHRINK);  
     }  
1478    
1479      add(table);      quitButton.show();
1480      // add_button(Gtk::Stock::CANCEL, 0);      vbox.show();
     // add_button(Gtk::Stock::OK, 1);  
1481      show_all_children();      show_all_children();
1482  }  }
1483    
1484  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_file(gig::File* file)
1485  {  {
1486      entry[0].set_text(info->Name);      m_file = file;
     entry[1].set_text(info->CreationDate);  
     entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));  
     entry[3].set_text(info->Product);  
     entry[4].set_text(info->Copyright);  
     entry[5].set_text(info->Artists);  
     entry[6].set_text(info->Genre);  
     entry[7].set_text(info->Keywords);  
     entry[8].set_text(info->Engineer);  
     entry[9].set_text(info->Technician);  
     entry[10].set_text(info->Software);  
     entry[11].set_text(info->Medium);  
     entry[12].set_text(info->Source);  
     entry[13].set_text(info->SourceForm);  
     entry[14].set_text(info->Commissioned);  
     entry[15].set_text(info->Subject);  
 }  
1487    
1488  void InstrumentProps::set_IsDrum(bool value)      // update file format version combo box
1489  {      const std::string sGiga = "Gigasampler/GigaStudio v";
1490      instrument->IsDrum = value;      const int major = file->pVersion->major;
1491        std::vector<std::string> txts;
1492        std::vector<int> values;
1493        txts.push_back(sGiga + "2"); values.push_back(2);
1494        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1495        if (major != 2 && major != 3) {
1496            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1497        }
1498        std::vector<const char*> texts;
1499        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1500        texts.push_back(NULL); values.push_back(0);
1501        eFileFormat.set_choices(&texts[0], &values[0]);
1502        eFileFormat.set_value(major);
1503    }
1504    
1505    void PropDialog::onFileFormatChanged() {
1506        const int major = eFileFormat.get_value();
1507        if (m_file) m_file->pVersion->major = major;
1508  }  }
1509    
1510  void InstrumentProps::set_MIDIBank(uint16_t value)  void PropDialog::set_info(DLS::Info* info)
1511  {  {
1512      instrument->MIDIBank = value;      update(info);
1513  }  }
1514    
 void InstrumentProps::set_MIDIProgram(uint32_t value)  
 {  
     instrument->MIDIProgram = value;  
 }  
1515    
1516  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_Name(const gig::String& name)
1517  {  {
1518      instrument->DimensionKeyRange.low = value;      m->pInfo->Name = name;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
1519  }  }
1520    
1521  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::update_name()
1522  {  {
1523      instrument->DimensionKeyRange.high = value;      update_model++;
1524      if (value < instrument->DimensionKeyRange.low) {      eName.set_value(m->pInfo->Name);
1525          eDimensionKeyRangeLow.set_value(value);      update_model--;
     }  
1526  }  }
1527    
1528  void InstrumentProps::add_prop(BoolEntry& boolentry)  void InstrumentProps::set_IsDrum(bool value)
1529  {  {
1530      table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,      m->IsDrum = value;
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
1531  }  }
1532    
1533  void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)  void InstrumentProps::set_MIDIBank(uint16_t value)
1534  {  {
1535      table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,      m->MIDIBank = value;
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
1536  }  }
1537    
1538  void InstrumentProps::add_prop(LabelWidget& prop)  void InstrumentProps::set_MIDIProgram(uint32_t value)
1539  {  {
1540      table.attach(prop.label, 0, 1, rowno, rowno + 1,      m->MIDIProgram = value;
                  Gtk::FILL, Gtk::SHRINK);  
     table.attach(prop.widget, 1, 2, rowno, rowno + 1,  
                  Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);  
     rowno++;  
1541  }  }
1542    
1543  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
1544      : table(2,1),      quitButton(Gtk::Stock::CLOSE),
1545        quitButton(Gtk::Stock::CLOSE),      table(2,1),
1546        eName("Name"),      eName(_("Name")),
1547        eIsDrum("Is drum"),      eIsDrum(_("Is drum")),
1548        eMIDIBank("MIDI bank", 0, 16383),      eMIDIBank(_("MIDI bank"), 0, 16383),
1549        eMIDIProgram("MIDI program"),      eMIDIProgram(_("MIDI program")),
1550        eAttenuation("Attenuation", 0, 96, 0, 1),      eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1551        eGainPlus6("Gain +6dB", eAttenuation, -6),      eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1552        eEffectSend("Effect send", 0, 65535),      eEffectSend(_("Effect send"), 0, 65535),
1553        eFineTune("Fine tune", -8400, 8400),      eFineTune(_("Fine tune"), -8400, 8400),
1554        ePitchbendRange("Pitchbend range", 0, 12),      ePitchbendRange(_("Pitchbend range"), 0, 12),
1555        ePianoReleaseMode("Piano release mode"),      ePianoReleaseMode(_("Piano release mode")),
1556        eDimensionKeyRangeLow("Dimension key range low"),      eDimensionKeyRangeLow(_("Keyswitching range low")),
1557        eDimensionKeyRangeHigh("Dimension key range high"),      eDimensionKeyRangeHigh(_("Keyswitching range high"))
1558        update_model(0)  {
1559  {      set_title(_("Instrument Properties"));
1560      set_title("Instrument properties");  
1561        eDimensionKeyRangeLow.set_tip(
1562            _("start of the keyboard area which should switch the "
1563              "\"keyswitching\" dimension")
1564        );
1565        eDimensionKeyRangeHigh.set_tip(
1566            _("end of the keyboard area which should switch the "
1567              "\"keyswitching\" dimension")
1568        );
1569    
1570        connect(eName, &InstrumentProps::set_Name);
1571      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
1572      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1573      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
# Line 940  InstrumentProps::InstrumentProps() Line 1577  InstrumentProps::InstrumentProps()
1577      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
1578      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1579      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1580      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1581              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
1582      connect(eDimensionKeyRangeHigh,  
1583              &InstrumentProps::set_DimensionKeyRange_high);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
1584    
     rowno = 0;  
1585      table.set_col_spacings(5);      table.set_col_spacings(5);
1586    
1587      add_prop(eName);      table.add(eName);
1588      add_prop(eIsDrum);      table.add(eIsDrum);
1589      add_prop(eMIDIBank);      table.add(eMIDIBank);
1590      add_prop(eMIDIProgram);      table.add(eMIDIProgram);
1591      add_prop(eAttenuation);      table.add(eAttenuation);
1592      add_prop(eGainPlus6);      table.add(eGainPlus6);
1593      add_prop(eEffectSend);      table.add(eEffectSend);
1594      add_prop(eFineTune);      table.add(eFineTune);
1595      add_prop(ePitchbendRange);      table.add(ePitchbendRange);
1596      add_prop(ePianoReleaseMode);      table.add(ePianoReleaseMode);
1597      add_prop(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
1598      add_prop(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
1599    
1600      add(vbox);      add(vbox);
1601      table.set_border_width(5);      table.set_border_width(5);
# Line 970  InstrumentProps::InstrumentProps() Line 1606  InstrumentProps::InstrumentProps()
1606      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1607      buttonBox.show();      buttonBox.show();
1608      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1609      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1610      quitButton.grab_focus();      quitButton.grab_focus();
1611    
1612      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 983  InstrumentProps::InstrumentProps() Line 1619  InstrumentProps::InstrumentProps()
1619    
1620  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1621  {  {
1622      this->instrument = instrument;      update(instrument);
1623    
1624      update_model++;      update_model++;
1625      eName.set_ptr(&instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
1626      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
1627      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
1628      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
     eAttenuation.set_value(instrument->Attenuation);  
     eGainPlus6.set_value(instrument->Attenuation);  
     eEffectSend.set_value(instrument->EffectSend);  
     eFineTune.set_value(instrument->FineTune);  
     ePitchbendRange.set_value(instrument->PitchbendRange);  
     ePianoReleaseMode.set_value(instrument->PianoReleaseMode);  
     eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);  
     eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);  
1629      update_model--;      update_model--;
1630  }  }
1631    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
1632    
1633  void MainWindow::file_changed()  void MainWindow::file_changed()
1634  {  {
# Line 1014  void MainWindow::file_changed() Line 1638  void MainWindow::file_changed()
1638      }      }
1639  }  }
1640    
1641    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1642        sample_ref_count.clear();
1643        
1644        if (!gig) return;
1645    
1646        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1647             instrument = gig->GetNextInstrument())
1648        {
1649            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1650                 rgn = instrument->GetNextRegion())
1651            {
1652                for (int i = 0; i < 256; ++i) {
1653                    if (!rgn->pDimensionRegions[i]) continue;
1654                    if (rgn->pDimensionRegions[i]->pSample) {
1655                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1656                    }
1657                }
1658            }
1659        }
1660    }
1661    
1662  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1663  {  {
1664      file = 0;      file = 0;
# Line 1024  void MainWindow::load_gig(gig::File* gig Line 1669  void MainWindow::load_gig(gig::File* gig
1669      file_has_name = filename;      file_has_name = filename;
1670      file_is_changed = false;      file_is_changed = false;
1671    
1672        propDialog.set_file(gig);
1673      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1674    
1675      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
1676      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1677           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument()) {
1678            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1679    
1680          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1681          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1682          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_name] = name;
1683          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1684          // create a menu item for this instrument  
1685          Gtk::RadioMenuItem* item =          add_instrument_to_menu(name);
             new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());  
         instrument_menu->get_submenu()->append(*item);  
         item->signal_activate().connect(  
             sigc::bind(  
                 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  
                 instrument_index  
             )  
         );  
         instrument_index++;  
1686      }      }
1687      instrument_menu->show();      instrument_name_connection.unblock();
1688      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1689    
1690        updateSampleRefCountMap(gig);
1691    
1692      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1693          if (group->Name != "") {          if (group->Name != "") {
1694              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1695              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1696              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1697              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1698              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1699              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1064  void MainWindow::load_gig(gig::File* gig Line 1701  void MainWindow::load_gig(gig::File* gig
1701                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1702                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1703                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1704                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1705                        gig_to_utf8(sample->pInfo->Name);
1706                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1707                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1708                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1709                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1710                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1711              }              }
1712          }          }
1713      }      }
1714        
1715        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1716            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1717    
1718            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1719            Gtk::TreeModel::Row rowGroup = *iterGroup;
1720            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1721            rowGroup[m_ScriptsModel.m_col_group]  = group;
1722            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1723            for (int s = 0; group->GetScript(s); ++s) {
1724                gig::Script* script = group->GetScript(s);
1725    
1726                Gtk::TreeModel::iterator iterScript =
1727                    m_refScriptsTreeModel->append(rowGroup.children());
1728                Gtk::TreeModel::Row rowScript = *iterScript;
1729                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1730                rowScript[m_ScriptsModel.m_col_script] = script;
1731                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1732            }
1733        }
1734        // unfold all sample groups & script groups by default
1735        m_TreeViewSamples.expand_all();
1736        m_TreeViewScripts.expand_all();
1737    
1738      file = gig;      file = gig;
1739    
1740      // select the first instrument      // select the first instrument
1741      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1742      tree_sel_ref->select(Gtk::TreePath("0"));  
1743        instr_props_set_instrument();
1744        gig::Instrument* instrument = get_instrument();
1745        if (instrument) {
1746            midiRules.set_instrument(instrument);
1747        }
1748    }
1749    
1750    bool MainWindow::instr_props_set_instrument()
1751    {
1752        instrumentProps.signal_name_changed().clear();
1753    
1754        Gtk::TreeModel::const_iterator it =
1755            m_TreeView.get_selection()->get_selected();
1756        if (it) {
1757            Gtk::TreeModel::Row row = *it;
1758            gig::Instrument* instrument = row[m_Columns.m_col_instr];
1759    
1760            instrumentProps.set_instrument(instrument);
1761    
1762            // make sure instrument tree is updated when user changes the
1763            // instrument name in instrument properties window
1764            instrumentProps.signal_name_changed().connect(
1765                sigc::bind(
1766                    sigc::mem_fun(*this,
1767                                  &MainWindow::instr_name_changed_by_instr_props),
1768                    it));
1769        } else {
1770            instrumentProps.hide();
1771        }
1772        return it;
1773  }  }
1774    
1775  void MainWindow::show_instr_props()  void MainWindow::show_instr_props()
1776  {  {
1777      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (instr_props_set_instrument()) {
1778      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();          instrumentProps.show();
1779      if (it)          instrumentProps.deiconify();
1780        }
1781    }
1782    
1783    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
1784    {
1785        Gtk::TreeModel::Row row = *it;
1786        Glib::ustring name = row[m_Columns.m_col_name];
1787    
1788        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1789        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
1790        if (gigname != name) {
1791            row[m_Columns.m_col_name] = gigname;
1792        }
1793    }
1794    
1795    void MainWindow::show_midi_rules()
1796    {
1797        if (gig::Instrument* instrument = get_instrument())
1798      {      {
1799          Gtk::TreeModel::Row row = *it;          midiRules.set_instrument(instrument);
1800          if (row[m_Columns.m_col_instr])          midiRules.show();
1801          {          midiRules.deiconify();
             instrumentProps.set_instrument(row[m_Columns.m_col_instr]);  
             instrumentProps.show();  
             instrumentProps.deiconify();  
         }  
1802      }      }
1803  }  }
1804    
1805    void MainWindow::show_script_slots() {
1806        if (!file) return;
1807        // get selected instrument
1808        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1809        Gtk::TreeModel::iterator it = sel->get_selected();
1810        if (!it) return;
1811        Gtk::TreeModel::Row row = *it;
1812        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1813        if (!instrument) return;
1814    
1815        ScriptSlots* window = new ScriptSlots;
1816        window->setInstrument(instrument);
1817        //window->reparent(*this);
1818        window->show();
1819    }
1820    
1821  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
1822      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
1823          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1105  void MainWindow::on_action_view_status_b Line 1829  void MainWindow::on_action_view_status_b
1829      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
1830  }  }
1831    
1832    bool MainWindow::is_copy_samples_unity_note_enabled() const {
1833        Gtk::CheckMenuItem* item =
1834            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1835        if (!item) {
1836            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
1837            return true;
1838        }
1839        return item->get_active();
1840    }
1841    
1842    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
1843        Gtk::CheckMenuItem* item =
1844            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
1845        if (!item) {
1846            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
1847            return true;
1848        }
1849        return item->get_active();
1850    }
1851    
1852    bool MainWindow::is_copy_samples_loop_enabled() const {
1853        Gtk::CheckMenuItem* item =
1854            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
1855        if (!item) {
1856            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
1857            return true;
1858        }
1859        return item->get_active();
1860    }
1861    
1862  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
1863  {  {
1864      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
1865          show_instr_props();          show_instr_props();
1866      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1867            // gig v2 files have no midi rules
1868            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
1869            static_cast<Gtk::MenuItem*>(
1870                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
1871                    bEnabled
1872                );
1873            static_cast<Gtk::MenuItem*>(
1874                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
1875                    bEnabled
1876                );
1877          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
1878      }      }
1879  }  }
1880    
1881  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
1882      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
1883            const std::vector<Gtk::Widget*> children =
1884                instrument_menu->get_children();
1885            std::vector<Gtk::Widget*>::const_iterator it =
1886                find(children.begin(), children.end(), item);
1887            if (it != children.end()) {
1888                int index = it - children.begin();
1889                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
1890    
1891                m_RegionChooser.set_instrument(file->GetInstrument(index));
1892            }
1893        }
1894    }
1895    
1896    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
1897    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
1898        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
1899        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
1900    
1901        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
1902        for (int i = 0; i < model->children().size(); ++i) {
1903            Gtk::TreeModel::Row row = model->children()[i];
1904            if (row[m_Columns.m_col_instr] == pInstrument) {
1905                // select and show the respective instrument in the list view
1906                show_intruments_tab();
1907                m_TreeView.get_selection()->select(model->children()[i]);
1908                Gtk::TreePath path(
1909                    m_TreeView.get_selection()->get_selected()
1910                );
1911                m_TreeView.scroll_to_row(path);
1912                on_sel_change(); // the regular instrument selection change callback
1913    
1914                // select respective region in the region selector
1915                m_RegionChooser.set_region(pRegion);
1916    
1917                // select and show the respective dimension region in the editor
1918                //update_dimregs();
1919                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
1920                //dimreg_edit.set_dim_region(dimRgn);
1921    
1922                return true;
1923            }
1924        }
1925    
1926        return false;
1927    }
1928    
1929    void MainWindow::select_sample(gig::Sample* sample) {
1930        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
1931        for (int g = 0; g < model->children().size(); ++g) {
1932            Gtk::TreeModel::Row rowGroup = model->children()[g];
1933            for (int s = 0; s < rowGroup.children().size(); ++s) {
1934                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
1935                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
1936                    show_samples_tab();
1937                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
1938                    Gtk::TreePath path(
1939                        m_TreeViewSamples.get_selection()->get_selected()
1940                    );
1941                    m_TreeViewSamples.scroll_to_row(path);
1942                    return;
1943                }
1944            }
1945        }
1946  }  }
1947    
1948  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
# Line 1132  void MainWindow::on_sample_treeview_butt Line 1959  void MainWindow::on_sample_treeview_butt
1959              group_selected  = row[m_SamplesModel.m_col_group];              group_selected  = row[m_SamplesModel.m_col_group];
1960              sample_selected = row[m_SamplesModel.m_col_sample];              sample_selected = row[m_SamplesModel.m_col_sample];
1961          }          }
1962            
1963                
1964          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
1965              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1966          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
1967              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1968          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
1969              set_sensitive(file);              set_sensitive(file);
1970            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
1971                set_sensitive(sample_selected);
1972          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
1973              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1974          // show sample popup          // show sample popup
1975          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
1976    
1977            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
1978                set_sensitive(group_selected || sample_selected);
1979            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
1980                set_sensitive(group_selected || sample_selected);
1981            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
1982                set_sensitive(file);
1983            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
1984                set_sensitive(sample_selected);
1985            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
1986                set_sensitive(group_selected || sample_selected);
1987      }      }
1988  }  }
1989    
1990  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
1991      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1992      if (!file) return;          Gtk::Menu* script_popup =
1993      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
1994      __instrument_indexer++;          // update enabled/disabled state of sample popup items
1995      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
1996          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
1997            bool group_selected  = false;
1998            bool script_selected = false;
1999            if (it) {
2000                Gtk::TreeModel::Row row = *it;
2001                group_selected  = row[m_ScriptsModel.m_col_group];
2002                script_selected = row[m_ScriptsModel.m_col_script];
2003            }
2004            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2005                set_sensitive(group_selected || script_selected);
2006            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2007                set_sensitive(file);
2008            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2009                set_sensitive(script_selected);    
2010            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2011                set_sensitive(group_selected || script_selected);
2012            // show sample popup
2013            script_popup->popup(button->button, button->time);
2014    
2015            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2016                set_sensitive(group_selected || script_selected);
2017            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2018                set_sensitive(file);
2019            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2020                set_sensitive(script_selected);    
2021            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2022                set_sensitive(group_selected || script_selected);
2023        }
2024    }
2025    
2026    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2027        const Glib::ustring& name, int position) {
2028    
2029        Gtk::RadioMenuItem::Group instrument_group;
2030        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2031        if (!children.empty()) {
2032            instrument_group =
2033                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2034        }
2035        Gtk::RadioMenuItem* item =
2036            new Gtk::RadioMenuItem(instrument_group, name);
2037        if (position < 0) {
2038            instrument_menu->append(*item);
2039        } else {
2040            instrument_menu->insert(*item, position);
2041        }
2042        item->show();
2043        item->signal_activate().connect(
2044            sigc::bind(
2045                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2046                item));
2047        return item;
2048    }
2049    
2050    void MainWindow::remove_instrument_from_menu(int index) {
2051        const std::vector<Gtk::Widget*> children =
2052            instrument_menu->get_children();
2053        Gtk::Widget* child = children[index];
2054        instrument_menu->remove(*child);
2055        delete child;
2056    }
2057    
2058    void MainWindow::add_instrument(gig::Instrument* instrument) {
2059        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2060    
2061      // update instrument tree view      // update instrument tree view
2062        instrument_name_connection.block();
2063      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2064      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2065      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_name] = name;
2066      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2067        instrument_name_connection.unblock();
2068    
2069        add_instrument_to_menu(name);
2070    
2071        m_TreeView.get_selection()->select(iterInstr);
2072    
2073      file_changed();      file_changed();
2074  }  }
2075    
2076    void MainWindow::on_action_add_instrument() {
2077        static int __instrument_indexer = 0;
2078        if (!file) return;
2079        gig::Instrument* instrument = file->AddInstrument();
2080        __instrument_indexer++;
2081        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2082                                                ToString(__instrument_indexer));
2083    
2084        add_instrument(instrument);
2085    }
2086    
2087    void MainWindow::on_action_duplicate_instrument() {
2088        if (!file) return;
2089    
2090        // retrieve the currently selected instrument
2091        // (being the original instrument to be duplicated)
2092        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2093        Gtk::TreeModel::iterator itSelection = sel->get_selected();
2094        if (!itSelection) return;
2095        Gtk::TreeModel::Row row = *itSelection;
2096        gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2097        if (!instrOrig) return;
2098    
2099        // duplicate the orginal instrument
2100        gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2101        instrNew->pInfo->Name =
2102            instrOrig->pInfo->Name +
2103            gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2104    
2105        add_instrument(instrNew);
2106    }
2107    
2108  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2109      if (!file) return;      if (!file) return;
2110      if (file_is_shared) {      if (file_is_shared) {
# Line 1179  void MainWindow::on_action_remove_instru Line 2124  void MainWindow::on_action_remove_instru
2124          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2125          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2126          try {          try {
2127                Gtk::TreePath path(it);
2128                int index = path[0];
2129    
2130              // remove instrument from the gig file              // remove instrument from the gig file
2131              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2132              file_changed();              file_changed();
2133    
2134                remove_instrument_from_menu(index);
2135    
2136                // remove row from instruments tree view
2137                m_refTreeModel->erase(it);
2138    
2139    #if GTKMM_MAJOR_VERSION < 3
2140                // select another instrument (in gtk3 this is done
2141                // automatically)
2142                if (!m_refTreeModel->children().empty()) {
2143                    if (index == m_refTreeModel->children().size()) {
2144                        index--;
2145                    }
2146                    m_TreeView.get_selection()->select(
2147                        Gtk::TreePath(ToString(index)));
2148                }
2149    #endif
2150                instr_props_set_instrument();
2151                instr = get_instrument();
2152                if (instr) {
2153                    midiRules.set_instrument(instr);
2154                } else {
2155                    midiRules.hide();
2156                }
2157          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2158              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2159              msg.run();              msg.run();
# Line 1194  void MainWindow::on_action_remove_instru Line 2164  void MainWindow::on_action_remove_instru
2164  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2165      //TODO: show a dialog where the selected sample's properties can be edited      //TODO: show a dialog where the selected sample's properties can be edited
2166      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2167          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2168      );      );
2169      msg.run();      msg.run();
2170  }  }
2171    
2172    void MainWindow::on_action_add_script_group() {
2173        static int __script_indexer = 0;
2174        if (!file) return;
2175        gig::ScriptGroup* group = file->AddScriptGroup();
2176        group->Name = gig_from_utf8(_("Unnamed Group"));
2177        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2178        __script_indexer++;
2179        // update sample tree view
2180        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2181        Gtk::TreeModel::Row rowGroup = *iterGroup;
2182        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2183        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2184        rowGroup[m_ScriptsModel.m_col_group] = group;
2185        file_changed();
2186    }
2187    
2188    void MainWindow::on_action_add_script() {
2189        if (!file) return;
2190        // get selected group
2191        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2192        Gtk::TreeModel::iterator it = sel->get_selected();
2193        if (!it) return;
2194        Gtk::TreeModel::Row row = *it;
2195        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2196        if (!group) { // not a group, but a script is selected (probably)
2197            gig::Script* script = row[m_ScriptsModel.m_col_script];
2198            if (!script) return;
2199            it = row.parent(); // resolve parent (that is the script's group)
2200            if (!it) return;
2201            row = *it;
2202            group = row[m_ScriptsModel.m_col_group];
2203            if (!group) return;
2204        }
2205    
2206        // add a new script to the .gig file
2207        gig::Script* script = group->AddScript();    
2208        Glib::ustring name = _("Unnamed Script");
2209        script->Name = gig_from_utf8(name);
2210    
2211        // add script to the tree view
2212        Gtk::TreeModel::iterator iterScript =
2213            m_refScriptsTreeModel->append(row.children());
2214        Gtk::TreeModel::Row rowScript = *iterScript;
2215        rowScript[m_ScriptsModel.m_col_name] = name;
2216        rowScript[m_ScriptsModel.m_col_script] = script;
2217        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2218    
2219        // unfold group of new script item in treeview
2220        Gtk::TreeModel::Path path(iterScript);
2221        m_TreeViewScripts.expand_to_path(path);
2222    }
2223    
2224    void MainWindow::on_action_edit_script() {
2225        if (!file) return;
2226        // get selected script
2227        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2228        Gtk::TreeModel::iterator it = sel->get_selected();
2229        if (!it) return;
2230        Gtk::TreeModel::Row row = *it;
2231        gig::Script* script = row[m_ScriptsModel.m_col_script];
2232        if (!script) return;
2233    
2234        ScriptEditor* editor = new ScriptEditor;
2235        editor->setScript(script);
2236        //editor->reparent(*this);
2237        editor->show();
2238    }
2239    
2240    void MainWindow::on_action_remove_script() {
2241        if (!file) return;
2242        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2243        Gtk::TreeModel::iterator it = sel->get_selected();
2244        if (it) {
2245            Gtk::TreeModel::Row row = *it;
2246            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2247            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2248            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2249            try {
2250                // remove script group or script from the gig file
2251                if (group) {
2252                    // notify everybody that we're going to remove these samples
2253    //TODO:         scripts_to_be_removed_signal.emit(members);
2254                    // delete the group in the .gig file including the
2255                    // samples that belong to the group
2256                    file->DeleteScriptGroup(group);
2257                    // notify that we're done with removal
2258    //TODO:         scripts_removed_signal.emit();
2259                    file_changed();
2260                } else if (script) {
2261                    // notify everybody that we're going to remove this sample
2262    //TODO:         std::list<gig::Script*> lscripts;
2263    //TODO:         lscripts.push_back(script);
2264    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2265                    // remove sample from the .gig file
2266                    script->GetGroup()->DeleteScript(script);
2267                    // notify that we're done with removal
2268    //TODO:         scripts_removed_signal.emit();
2269                    dimreg_changed();
2270                    file_changed();
2271                }
2272                // remove respective row(s) from samples tree view
2273                m_refScriptsTreeModel->erase(it);
2274            } catch (RIFF::Exception e) {
2275                // pretend we're done with removal (i.e. to avoid dead locks)
2276    //TODO:     scripts_removed_signal.emit();
2277                // show error message
2278                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2279                msg.run();
2280            }
2281        }
2282    }
2283    
2284  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2285      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2286      if (!file) return;      if (!file) return;
2287      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2288      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2289      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2290      __sample_indexer++;      __sample_indexer++;
2291      // update sample tree view      // update sample tree view
2292      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2293      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2294      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2295      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2296      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2297      file_changed();      file_changed();
# Line 1237  void MainWindow::on_action_add_sample() Line 2319  void MainWindow::on_action_add_sample()
2319      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2320      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2321      dialog.set_select_multiple(true);      dialog.set_select_multiple(true);
2322      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2323        // matches all file types supported by libsndfile
2324    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2325        Gtk::FileFilter soundfilter;
2326    #else
2327        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2328    #endif
2329      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2330          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2331          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1245  void MainWindow::on_action_add_sample() Line 2333  void MainWindow::on_action_add_sample()
2333          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2334          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2335      };      };
2336        const char* soundfiles = _("Sound Files");
2337        const char* allfiles = _("All Files");
2338    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2339      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2340          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2341      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2342      Gtk::FileFilter allpassfilter; // matches every file  
2343        // matches every file
2344        Gtk::FileFilter allpassfilter;
2345      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2346      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2347    #else
2348        for (int i = 0; supportedFileTypes[i]; i++)
2349            soundfilter->add_pattern(supportedFileTypes[i]);
2350        soundfilter->set_name(soundfiles);
2351    
2352        // matches every file
2353        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2354        allpassfilter->add_pattern("*.*");
2355        allpassfilter->set_name(allfiles);
2356    #endif
2357      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2358      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2359        if (current_sample_dir != "") {
2360            dialog.set_current_folder(current_sample_dir);
2361        }
2362      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2363            current_sample_dir = dialog.get_current_folder();
2364          Glib::ustring error_files;          Glib::ustring error_files;
2365          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2366          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2367               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2368              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2369              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1264  void MainWindow::on_action_add_sample() Line 2371  void MainWindow::on_action_add_sample()
2371              info.format = 0;              info.format = 0;
2372              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2373              try {              try {
2374                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2375                  int bitdepth;                  int bitdepth;
2376                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2377                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1280  void MainWindow::on_action_add_sample() Line 2387  void MainWindow::on_action_add_sample()
2387                          break;                          break;
2388                      default:                      default:
2389                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2390                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2391                  }                  }
2392                  // add a new sample to the .gig file                  // add a new sample to the .gig file
2393                  gig::Sample* sample = file->AddSample();                  gig::Sample* sample = file->AddSample();
# Line 1293  void MainWindow::on_action_add_sample() Line 2400  void MainWindow::on_action_add_sample()
2400                          break;                          break;
2401                      }                      }
2402                  }                  }
2403                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2404                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2405                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2406                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1307  void MainWindow::on_action_add_sample() Line 2414  void MainWindow::on_action_add_sample()
2414                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2415                  {                  {
2416                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2417                        sample->FineTune      = instrument.detune;
2418    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2419                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2420                          sample->Loops = 1;                          sample->Loops = 1;
2421    
# Line 1328  void MainWindow::on_action_add_sample() Line 2435  void MainWindow::on_action_add_sample()
2435                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2436                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2437                      }                      }
 #endif  
2438                  }                  }
2439    
2440                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
# Line 1346  void MainWindow::on_action_add_sample() Line 2452  void MainWindow::on_action_add_sample()
2452                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
2453                      m_refSamplesTreeModel->append(row.children());                      m_refSamplesTreeModel->append(row.children());
2454                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
2455                  rowSample[m_SamplesModel.m_col_name]   = filename;                  rowSample[m_SamplesModel.m_col_name] =
2456                        gig_to_utf8(sample->pInfo->Name);
2457                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2458                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2459                  // close sound file                  // close sound file
2460                  sf_close(hFile);                  sf_close(hFile);
2461                  file_changed();                  file_changed();
2462              } catch (std::string what) { // remember the files that made trouble (and their cause)              } catch (std::string what) { // remember the files that made trouble (and their cause)
2463                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2464                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2465              }              }
2466          }          }
2467          // show error message box when some file(s) could not be opened / added          // show error message box when some file(s) could not be opened / added
2468          if (error_files.size()) {          if (!error_files.empty()) {
2469              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;
2470              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2471              msg.run();              msg.run();
# Line 1366  void MainWindow::on_action_add_sample() Line 2473  void MainWindow::on_action_add_sample()
2473      }      }
2474  }  }
2475    
2476    void MainWindow::on_action_replace_all_samples_in_all_groups()
2477    {
2478        if (!file) return;
2479        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2480                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2481        const char* str =
2482            _("This is a very specific function. It tries to replace all samples "
2483              "in the current gig file by samples located in the chosen "
2484              "directory.\n\n"
2485              "It works like this: For each sample in the gig file, it tries to "
2486              "find a sample file in the selected directory with the same name as "
2487              "the sample in the gig file. Optionally, you can add a filename "
2488              "extension below, which will be added to the filename expected to be "
2489              "found. That is, assume you have a gig file with a sample called "
2490              "'Snare', if you enter '.wav' below (like it's done by default), it "
2491              "expects to find a sample file called 'Snare.wav' and will replace "
2492              "the sample in the gig file accordingly. If you don't need an "
2493              "extension, blank the field below. Any gig sample where no "
2494              "appropriate sample file could be found will be reported and left "
2495              "untouched.\n");
2496    #if GTKMM_MAJOR_VERSION < 3
2497        view::WrapLabel description(str);
2498    #else
2499        Gtk::Label description(str);
2500        description.set_line_wrap();
2501    #endif
2502        Gtk::HBox entryArea;
2503        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2504        Gtk::Entry postfixEntryBox;
2505        postfixEntryBox.set_text(".wav");
2506        entryArea.pack_start(entryLabel);
2507        entryArea.pack_start(postfixEntryBox);
2508        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2509        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2510        description.show();
2511        entryArea.show_all();
2512        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2513        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2514        dialog.set_select_multiple(false);
2515        if (current_sample_dir != "") {
2516            dialog.set_current_folder(current_sample_dir);
2517        }
2518        if (dialog.run() == Gtk::RESPONSE_OK)
2519        {
2520            current_sample_dir = dialog.get_current_folder();
2521            Glib::ustring error_files;
2522            std::string folder = dialog.get_filename();
2523            for (gig::Sample* sample = file->GetFirstSample();
2524                 sample; sample = file->GetNextSample())
2525            {
2526                std::string filename =
2527                    folder + G_DIR_SEPARATOR_S +
2528                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2529                                             postfixEntryBox.get_text());
2530                SF_INFO info;
2531                info.format = 0;
2532                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2533                try
2534                {
2535                    if (!hFile) throw std::string(_("could not open file"));
2536                    int bitdepth;
2537                    switch (info.format & 0xff) {
2538                        case SF_FORMAT_PCM_S8:
2539                        case SF_FORMAT_PCM_16:
2540                        case SF_FORMAT_PCM_U8:
2541                            bitdepth = 16;
2542                            break;
2543                        case SF_FORMAT_PCM_24:
2544                        case SF_FORMAT_PCM_32:
2545                        case SF_FORMAT_FLOAT:
2546                        case SF_FORMAT_DOUBLE:
2547                            bitdepth = 24;
2548                            break;
2549                        default:
2550                            sf_close(hFile);
2551                            throw std::string(_("format not supported"));
2552                    }
2553                    SampleImportItem sched_item;
2554                    sched_item.gig_sample  = sample;
2555                    sched_item.sample_path = filename;
2556                    m_SampleImportQueue.push_back(sched_item);
2557                    sf_close(hFile);
2558                    file_changed();
2559                }
2560                catch (std::string what)
2561                {
2562                    if (!error_files.empty()) error_files += "\n";
2563                    error_files += Glib::filename_to_utf8(filename) +
2564                        " (" + what + ")";
2565                }
2566            }
2567            // show error message box when some file(s) could not be opened / added
2568            if (!error_files.empty()) {
2569                Glib::ustring txt =
2570                    _("Could not replace the following sample(s):\n") + error_files;
2571                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2572                msg.run();
2573            }
2574        }
2575    }
2576    
2577  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
2578      if (!file) return;      if (!file) return;
2579      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
# Line 1378  void MainWindow::on_action_remove_sample Line 2586  void MainWindow::on_action_remove_sample
2586          try {          try {
2587              // remove group or sample from the gig file              // remove group or sample from the gig file
2588              if (group) {              if (group) {
2589                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2590                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2591                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2592                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1442  void MainWindow::on_action_remove_sample Line 2650  void MainWindow::on_action_remove_sample
2650      }      }
2651  }  }
2652    
2653    // see comment on on_sample_treeview_drag_begin()
2654    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
2655    {
2656        first_call_to_drag_data_get = true;
2657    }
2658    
2659    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
2660                                                       Gtk::SelectionData& selection_data, guint, guint)
2661    {
2662        if (!first_call_to_drag_data_get) return;
2663        first_call_to_drag_data_get = false;
2664    
2665        // get selected script
2666        gig::Script* script = NULL;
2667        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2668        Gtk::TreeModel::iterator it = sel->get_selected();
2669        if (it) {
2670            Gtk::TreeModel::Row row = *it;
2671            script = row[m_ScriptsModel.m_col_script];
2672        }
2673        // pass the gig::Script as pointer
2674        selection_data.set(selection_data.get_target(), 0/*unused*/,
2675                           (const guchar*)&script,
2676                           sizeof(script)/*length of data in bytes*/);
2677    }
2678    
2679  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
2680  // drag'n'drop (at least when target is an Entry). This work-around  // drag'n'drop (at least when target is an Entry). This work-around
2681  // makes sure the code in drag_data_get and drop_drag_data_received is  // makes sure the code in drag_data_get and drop_drag_data_received is
# Line 1500  void MainWindow::on_sample_label_drop_dr Line 2734  void MainWindow::on_sample_label_drop_dr
2734          bool channels_changed = false;          bool channels_changed = false;
2735          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
2736              // remove the samplechannel dimension              // remove the samplechannel dimension
2737    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
2738              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
2739              channels_changed = true;              channels_changed = true;
2740              region_changed();              region_changed();
2741    */
2742          }          }
2743          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
2744                sample,
2745                is_copy_samples_unity_note_enabled(),
2746                is_copy_samples_fine_tune_enabled(),
2747                is_copy_samples_loop_enabled()
2748            );
2749    
2750          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
2751              // add samplechannel dimension              // add samplechannel dimension
# Line 1547  void MainWindow::sample_name_changed(con Line 2788  void MainWindow::sample_name_changed(con
2788      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
2789      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
2790      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
2791        gig::String gigname(gig_from_utf8(name));
2792      if (group) {      if (group) {
2793          if (group->Name != name) {          if (group->Name != gigname) {
2794              group->Name = name;              group->Name = gigname;
2795              printf("group name changed\n");              printf("group name changed\n");
2796              file_changed();              file_changed();
2797          }          }
2798      } else if (sample) {      } else if (sample) {
2799          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
2800              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
2801              printf("sample name changed\n");              printf("sample name changed\n");
2802              file_changed();              file_changed();
2803          }          }
2804      }      }
2805  }  }
2806    
2807    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
2808                                         const Gtk::TreeModel::iterator& iter) {
2809        if (!iter) return;
2810        Gtk::TreeModel::Row row = *iter;
2811        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2812        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2813        gig::Script* script     = row[m_ScriptsModel.m_col_script];
2814        gig::String gigname(gig_from_utf8(name));
2815        if (group) {
2816            if (group->Name != gigname) {
2817                group->Name = gigname;
2818                printf("script group name changed\n");
2819                file_changed();
2820            }
2821        } else if (script) {
2822            if (script->Name != gigname) {
2823                script->Name = gigname;
2824                printf("script name changed\n");
2825                file_changed();
2826            }
2827        }
2828    }
2829    
2830    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
2831                                           Gtk::TreeViewColumn* column)
2832    {
2833        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
2834        if (!iter) return;
2835        Gtk::TreeModel::Row row = *iter;
2836        gig::Script* script = row[m_ScriptsModel.m_col_script];
2837        if (!script) return;
2838    
2839        ScriptEditor* editor = new ScriptEditor;
2840        editor->setScript(script);
2841        //editor->reparent(*this);
2842        editor->show();
2843    }
2844    
2845  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
2846                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
2847      if (!iter) return;      if (!iter) return;
2848      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
2849      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
2850    
2851        // change name in instrument menu
2852        int index = path[0];
2853        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2854        if (index < children.size()) {
2855    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
2856            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
2857    #else
2858            remove_instrument_from_menu(index);
2859            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
2860            item->set_active();
2861    #endif
2862        }
2863    
2864        // change name in gig
2865      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
2866      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
2867          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
2868            instrument->pInfo->Name = gigname;
2869    
2870            // change name in the instrument properties window
2871            if (instrumentProps.get_instrument() == instrument) {
2872                instrumentProps.update_name();
2873            }
2874    
2875          file_changed();          file_changed();
2876      }      }
2877  }  }
2878    
2879    void MainWindow::on_action_combine_instruments() {
2880        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
2881        d->show_all();
2882        d->resize(500, 400);
2883        d->run();
2884        if (d->fileWasChanged()) {
2885            // update GUI with new instrument just created
2886            add_instrument(d->newCombinedInstrument());
2887        }
2888        delete d;
2889    }
2890    
2891    void MainWindow::on_action_view_references() {
2892        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2893        Gtk::TreeModel::iterator it = sel->get_selected();
2894        if (!it) return;
2895        Gtk::TreeModel::Row row = *it;
2896        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
2897        if (!sample) return;
2898    
2899        ReferencesView* d = new ReferencesView(*this);
2900        d->setSample(sample);
2901        d->dimension_region_selected.connect(
2902            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
2903        );
2904        d->show_all();
2905        d->resize(500, 400);
2906        d->run();
2907        delete d;
2908    }
2909    
2910    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
2911        struct _Source {
2912            std::vector<RIFF::File*> riffs;
2913            std::vector<gig::File*> gigs;
2914            
2915            ~_Source() {
2916                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
2917                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
2918                riffs.clear();
2919                gigs.clear();
2920            }
2921        } sources;
2922    
2923        if (filenames.empty())
2924            throw RIFF::Exception(_("No files selected, so nothing done."));
2925    
2926        // first open all input files (to avoid output file corruption)
2927        int i;
2928        try {
2929            for (i = 0; i < filenames.size(); ++i) {
2930                const std::string& filename = filenames[i];
2931                printf("opening file=%s\n", filename.c_str());
2932    
2933                RIFF::File* riff = new RIFF::File(filename);
2934                sources.riffs.push_back(riff);
2935    
2936                gig::File* gig = new gig::File(riff);
2937                sources.gigs.push_back(gig);
2938            }
2939        } catch (RIFF::Exception e) {
2940            throw RIFF::Exception(
2941                _("Error occurred while opening '") +
2942                filenames[i] +
2943                "': " +
2944                e.Message
2945            );
2946        } catch (...) {
2947            throw RIFF::Exception(
2948                _("Unknown exception occurred while opening '") +
2949                filenames[i] + "'"
2950            );
2951        }
2952    
2953        // now merge the opened .gig files to the main .gig file currently being
2954        // open in gigedit
2955        try {
2956            for (i = 0; i < filenames.size(); ++i) {
2957                const std::string& filename = filenames[i];
2958                printf("merging file=%s\n", filename.c_str());
2959                assert(i < sources.gigs.size());
2960    
2961                this->file->AddContentOf(sources.gigs[i]);
2962            }
2963        } catch (RIFF::Exception e) {
2964            throw RIFF::Exception(
2965                _("Error occurred while merging '") +
2966                filenames[i] +
2967                "': " +
2968                e.Message
2969            );
2970        } catch (...) {
2971            throw RIFF::Exception(
2972                _("Unknown exception occurred while merging '") +
2973                filenames[i] + "'"
2974            );
2975        }
2976    
2977        // Finally save gig file persistently to disk ...
2978        //NOTE: requires that this gig file already has a filename !
2979        {
2980            std::cout << "Saving file\n" << std::flush;
2981            file_structure_to_be_changed_signal.emit(this->file);
2982    
2983            progress_dialog = new ProgressDialog( //FIXME: memory leak!
2984                _("Saving") +  Glib::ustring(" '") +
2985                Glib::filename_display_basename(this->filename) + "' ...",
2986                *this
2987            );
2988            progress_dialog->show_all();
2989            saver = new Saver(this->file); //FIXME: memory leak!
2990            saver->signal_progress().connect(
2991                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2992            saver->signal_finished().connect(
2993                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2994            saver->signal_error().connect(
2995                sigc::mem_fun(*this, &MainWindow::on_saver_error));
2996            saver->launch();
2997        }
2998    }
2999    
3000    void MainWindow::on_action_merge_files() {
3001        if (this->file->GetFileName().empty()) {
3002            Glib::ustring txt = _(
3003                "You seem to have a new .gig file open that has not been saved "
3004                "yet. You must save it somewhere before starting to merge it with "
3005                "other .gig files though, because during the merge operation the "
3006                "other files' sample data must be written on file level to the "
3007                "target .gig file."
3008            );
3009            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3010            msg.run();
3011            return;
3012        }
3013    
3014        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3015        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3016        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3017        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3018    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3019        Gtk::FileFilter filter;
3020        filter.add_pattern("*.gig");
3021    #else
3022        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3023        filter->add_pattern("*.gig");
3024    #endif
3025        dialog.set_filter(filter);
3026        if (current_gig_dir != "") {
3027            dialog.set_current_folder(current_gig_dir);
3028        }
3029        dialog.set_select_multiple(true);
3030    
3031        // show warning in the file picker dialog
3032        Gtk::HBox descriptionArea;
3033        descriptionArea.set_spacing(15);
3034        Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3035        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3036    #if GTKMM_MAJOR_VERSION < 3
3037        view::WrapLabel description;
3038    #else
3039        Gtk::Label description;
3040        description.set_line_wrap();
3041    #endif
3042        description.set_markup(_(
3043            "\nSelect at least one .gig file that shall be merged to the .gig file "
3044            "currently being open in gigedit.\n\n"
3045            "<b>Please Note:</b> Merging with other files will modify your "
3046            "currently open .gig file on file level! And be aware that the current "
3047            "merge algorithm does not detect duplicate samples yet. So if you are "
3048            "merging files which are using equivalent sample data, those "
3049            "equivalent samples will currently be treated as separate samples and "
3050            "will accordingly be stored separately in the target .gig file!"
3051        ));
3052        descriptionArea.pack_start(description);
3053        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3054        descriptionArea.show_all();
3055    
3056        if (dialog.run() == Gtk::RESPONSE_OK) {
3057            printf("on_action_merge_files self=%x\n", Glib::Threads::Thread::self());
3058            std::vector<std::string> filenames = dialog.get_filenames();
3059    
3060            // merge the selected files to the currently open .gig file
3061            try {
3062                mergeFiles(filenames);
3063            } catch (RIFF::Exception e) {
3064                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3065                msg.run();
3066            }
3067    
3068            // update GUI
3069            __refreshEntireGUI();        
3070        }
3071    }
3072    
3073  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
3074      this->file_is_shared = b;      this->file_is_shared = b;
3075    
# Line 1588  void MainWindow::set_file_is_shared(bool Line 3084  void MainWindow::set_file_is_shared(bool
3084              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3085          );          );
3086      }      }
3087    
3088        {
3089            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3090                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3091            if (item) item->set_sensitive(b);
3092        }
3093    }
3094    
3095    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3096        if (!sample) return;
3097        sample_ref_count[sample] += offset;
3098        const int refcount = sample_ref_count[sample];
3099    
3100        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3101        for (int g = 0; g < model->children().size(); ++g) {
3102            Gtk::TreeModel::Row rowGroup = model->children()[g];
3103            for (int s = 0; s < rowGroup.children().size(); ++s) {
3104                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3105                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3106                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3107                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3108            }
3109        }
3110    }
3111    
3112    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3113        on_sample_ref_count_incremented(oldSample, -1);
3114        on_sample_ref_count_incremented(newSample, +1);
3115    }
3116    
3117    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3118        // just in case a new sample is added later with exactly the same memory
3119        // address, which would lead to incorrect refcount if not deleted here
3120        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3121             it != samples.end(); ++it)
3122        {
3123            sample_ref_count.erase(*it);
3124        }
3125    }
3126    
3127    void MainWindow::show_samples_tab() {
3128        m_TreeViewNotebook.set_current_page(0);
3129    }
3130    
3131    void MainWindow::show_intruments_tab() {
3132        m_TreeViewNotebook.set_current_page(1);
3133    }
3134    
3135    void MainWindow::show_scripts_tab() {
3136        m_TreeViewNotebook.set_current_page(2);
3137  }  }
3138    
3139  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
# Line 1614  sigc::signal<void, gig::Region*>& MainWi Line 3160  sigc::signal<void, gig::Region*>& MainWi
3160      return region_changed_signal;      return region_changed_signal;
3161  }  }
3162    
3163    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3164        return sample_changed_signal;
3165    }
3166    
3167  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
3168      return sample_ref_changed_signal;      return sample_ref_changed_signal;
3169  }  }
# Line 1625  sigc::signal<void, gig::DimensionRegion* Line 3175  sigc::signal<void, gig::DimensionRegion*
3175  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
3176      return dimreg_changed_signal;      return dimreg_changed_signal;
3177  }  }
3178    
3179    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_on() {
3180        return note_on_signal;
3181    }
3182    
3183    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
3184        return note_off_signal;
3185    }
3186    
3187    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
3188        return m_RegionChooser.signal_keyboard_key_hit();
3189    }
3190    
3191    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3192        return m_RegionChooser.signal_keyboard_key_released();
3193    }
3194    
3195    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3196        return switch_sampler_instrument_signal;
3197    }

Legend:
Removed from v.1460  
changed lines
  Added in v.2695

  ViewVC Help
Powered by ViewVC