/[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 1328 by schoenebeck, Fri Sep 7 21:18:31 2007 UTC revision 2664 by schoenebeck, Sat Jul 5 19:43:14 2014 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006, 2007 Andreas Persson   * Copyright (C) 2006-2014 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 17  Line 17 
17   * 02110-1301 USA.   * 02110-1301 USA.
18   */   */
19    
 #include <libintl.h>  
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>
34  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  #if GTKMM_MAJOR_VERSION < 3
35  #define ABOUT_DIALOG  #include "wrapLabel.hh"
 #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"
52    #include "../../gfx/status_detached.xpm"
53    
 #define _(String) gettext(String)  
   
 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 65  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 82  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 122  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    
166        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"));
185        toggle_action->set_active(true);
186        actionGroup->add(toggle_action,
187                         sigc::mem_fun(
188                             *this, &MainWindow::on_action_view_status_bar));
189    
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    
221        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
222    
223        actionGroup->add(
224            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
225            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
226        );
227    
228        actionGroup->add(
229            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
230            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
231        );
232    
233    
234      // sample right-click popup actions      // sample right-click popup actions
235      actionGroup->add(      actionGroup->add(
236          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
# Line 154  MainWindow::MainWindow() Line 241  MainWindow::MainWindow()
241          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
242      );      );
243      actionGroup->add(      actionGroup->add(
244          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
245          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
246      );      );
247      actionGroup->add(      actionGroup->add(
248          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),
249          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
250      );      );
251        actionGroup->add(
252            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
253            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
254        );
255        actionGroup->add(
256            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
257                                _("Replace All Samples in All Groups...")),
258            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
259        );
260        
261        // script right-click popup actions
262        actionGroup->add(
263            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
264            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
265        );
266        actionGroup->add(
267            Gtk::Action::create("AddScript", _("Add _Script")),
268            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
269        );
270        actionGroup->add(
271            Gtk::Action::create("EditScript", _("_Edit Script...")),
272            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
273        );
274        actionGroup->add(
275            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
276            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
277        );
278    
279      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
280      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 180  MainWindow::MainWindow() Line 294  MainWindow::MainWindow()
294          "      <separator/>"          "      <separator/>"
295          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
296          "    </menu>"          "    </menu>"
297            "    <menu action='MenuEdit'>"
298            "      <menuitem action='CopySampleUnity'/>"
299            "      <menuitem action='CopySampleTune'/>"
300            "      <menuitem action='CopySampleLoop'/>"
301            "    </menu>"
302            "    <menu action='MenuSample'>"
303            "      <menuitem action='SampleProperties'/>"
304            "      <menuitem action='AddGroup'/>"
305            "      <menuitem action='AddSample'/>"
306            "      <menuitem action='ShowSampleRefs'/>"
307            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
308            "      <separator/>"
309            "      <menuitem action='RemoveSample'/>"
310            "    </menu>"
311          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
312            "      <menu action='AllInstruments'>"
313            "      </menu>"
314            "      <separator/>"
315            "      <menuitem action='InstrProperties'/>"
316            "      <menuitem action='MidiRules'/>"
317            "      <menuitem action='ScriptSlots'/>"
318            "      <menuitem action='AddInstrument'/>"
319            "      <menuitem action='DupInstrument'/>"
320            "      <separator/>"
321            "      <menuitem action='RemoveInstrument'/>"
322            "    </menu>"
323            "    <menu action='MenuScript'>"
324            "      <menuitem action='AddScriptGroup'/>"
325            "      <menuitem action='AddScript'/>"
326            "      <menuitem action='EditScript'/>"
327            "      <separator/>"
328            "      <menuitem action='RemoveScript'/>"
329            "    </menu>"
330            "    <menu action='MenuView'>"
331            "      <menuitem action='Statusbar'/>"
332            "    </menu>"
333            "    <menu action='MenuTools'>"
334            "      <menuitem action='CombineInstruments'/>"
335            "      <menuitem action='MergeFiles'/>"
336            "    </menu>"
337            "    <menu action='MenuSettings'>"
338            "      <menuitem action='WarnUserOnExtensions'/>"
339          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
340          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
341          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
342          "    </menu>"          "    </menu>"
 #endif  
343          "  </menubar>"          "  </menubar>"
344          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
345          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
346            "    <menuitem action='MidiRules'/>"
347            "    <menuitem action='ScriptSlots'/>"
348          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
349            "    <menuitem action='DupInstrument'/>"
350          "    <separator/>"          "    <separator/>"
351          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
352          "  </popup>"          "  </popup>"
# Line 198  MainWindow::MainWindow() Line 354  MainWindow::MainWindow()
354          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
355          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
356          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
357            "    <menuitem action='ShowSampleRefs'/>"
358            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
359          "    <separator/>"          "    <separator/>"
360          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
361          "  </popup>"          "  </popup>"
362            "  <popup name='ScriptPopupMenu'>"
363            "    <menuitem action='AddScriptGroup'/>"
364            "    <menuitem action='AddScript'/>"
365            "    <menuitem action='EditScript'/>"
366            "    <separator/>"
367            "    <menuitem action='RemoveScript'/>"
368            "  </popup>"
369          "</ui>";          "</ui>";
370      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
371    
372      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
373        
374        // Set tooltips for menu items (for some reason, setting a tooltip on the
375        // respective Gtk::Action objects above will simply be ignored, no matter
376        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
377        // Gtk::Action::create()).
378        {
379            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
380                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
381            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."));
382        }
383        {
384            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
385                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
386            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."));
387        }
388        {
389            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
390                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
391            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."));
392        }
393        {
394            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
395                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
396            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."));
397        }
398        {
399            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
400                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
401            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
402        }
403        {
404            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
405                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
406            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
407        }
408    
409    
410        instrument_menu = static_cast<Gtk::MenuItem*>(
411            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
412    
413      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
414      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
415      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
416      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
417        m_VBox.pack_start(m_RegionChooser.m_VirtKeybPropsBox, Gtk::PACK_SHRINK);
418      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
419        m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
420    
421        set_file_is_shared(false);
422    
423        // Status Bar:
424        m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
425        m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
426        m_StatusBar.show();
427    
428      m_RegionChooser.signal_region_selected().connect(      m_RegionChooser.signal_region_selected().connect(
429          sigc::mem_fun(*this, &MainWindow::region_changed) );          sigc::mem_fun(*this, &MainWindow::region_changed) );
# Line 221  MainWindow::MainWindow() Line 434  MainWindow::MainWindow()
434      // Create the Tree model:      // Create the Tree model:
435      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
436      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
437      m_refTreeModel->signal_row_changed().connect(      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules."));
438        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
439          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
440      );      );
441    
# Line 232  MainWindow::MainWindow() Line 446  MainWindow::MainWindow()
446      // create samples treeview (including its data model)      // create samples treeview (including its data model)
447      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
448      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
449        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."));
450      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
451      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
452      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
453        {
454            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
455            Gtk::CellRendererText* cellrenderer =
456                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
457            column->add_attribute(
458                cellrenderer->property_foreground(), m_SamplesModel.m_color
459            );
460        }
461        {
462            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
463            Gtk::CellRendererText* cellrenderer =
464                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
465            column->add_attribute(
466                cellrenderer->property_foreground(), m_SamplesModel.m_color
467            );
468        }
469        m_TreeViewSamples.set_headers_visible(true);
470      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
471          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
472      );      );
# Line 242  MainWindow::MainWindow() Line 474  MainWindow::MainWindow()
474          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
475      );      );
476    
477        // create scripts treeview (including its data model)
478        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
479        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
480        m_TreeViewScripts.set_tooltip_text(_(
481            "Use CTRL + double click for editing a script."
482            "\n\n"
483            "Note: instrument scripts are a LinuxSampler extension of the gig "
484            "format. This feature will not work with the GigaStudio software!"
485        ));
486        // m_TreeViewScripts.set_reorderable();
487        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
488        m_TreeViewScripts.set_headers_visible(false);
489        m_TreeViewScripts.signal_button_press_event().connect_notify(
490            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
491        );
492        //FIXME: why the heck does this double click signal_row_activated() only fired while CTRL key is pressed ?
493        m_TreeViewScripts.signal_row_activated().connect(
494            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
495        );
496        m_refScriptsTreeModel->signal_row_changed().connect(
497            sigc::mem_fun(*this, &MainWindow::script_name_changed)
498        );
499    
500        // establish drag&drop between scripts tree view and ScriptSlots window
501        std::vector<Gtk::TargetEntry> drag_target_gig_script;
502        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
503        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
504        m_TreeViewScripts.signal_drag_begin().connect(
505            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
506        );
507        m_TreeViewScripts.signal_drag_data_get().connect(
508            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
509        );
510    
511      // 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
512      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
513      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
514      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
515      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
516          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 262  MainWindow::MainWindow() Line 528  MainWindow::MainWindow()
528          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
529      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
530          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
531      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
532            sigc::mem_fun(*this, &MainWindow::file_changed));
533        propDialog.signal_changed().connect(
534            sigc::mem_fun(*this, &MainWindow::file_changed));
535        midiRules.signal_changed().connect(
536          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
537    
538      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 271  MainWindow::MainWindow() Line 541  MainWindow::MainWindow()
541          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
542      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
543          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
544        sample_ref_changed_signal.connect(
545            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
546        );
547        samples_to_be_removed_signal.connect(
548            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
549        );
550    
551      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
552          sigc::hide(          sigc::hide(
# Line 293  MainWindow::MainWindow() Line 569  MainWindow::MainWindow()
569      m_RegionChooser.signal_region_changed_signal().connect(      m_RegionChooser.signal_region_changed_signal().connect(
570          region_changed_signal.make_slot());          region_changed_signal.make_slot());
571    
572        note_on_signal.connect(
573            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_on_event));
574        note_off_signal.connect(
575            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_off_event));
576    
577        dimreg_all_regions.signal_toggled().connect(
578            sigc::mem_fun(*this, &MainWindow::update_dimregs));
579        dimreg_all_dimregs.signal_toggled().connect(
580            sigc::mem_fun(*this, &MainWindow::dimreg_all_dimregs_toggled));
581        dimreg_stereo.signal_toggled().connect(
582            sigc::mem_fun(*this, &MainWindow::update_dimregs));
583    
584      file = 0;      file = 0;
585      file_is_changed = false;      file_is_changed = false;
586    
# Line 300  MainWindow::MainWindow() Line 588  MainWindow::MainWindow()
588    
589      // start with a new gig file by default      // start with a new gig file by default
590      on_action_file_new();      on_action_file_new();
591    
592        // select 'Instruments' tab by default
593        // (gtk allows this only if the tab childs are visible, thats why it's here)
594        m_TreeViewNotebook.set_current_page(1);
595  }  }
596    
597  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 308  MainWindow::~MainWindow() Line 600  MainWindow::~MainWindow()
600    
601  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
602  {  {
603      return file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
604  }  }
605    
606  void MainWindow::on_action_quit()  void MainWindow::on_action_quit()
607  {  {
608      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
609      hide();      hide();
610  }  }
611    
# Line 322  void MainWindow::region_changed() Line 614  void MainWindow::region_changed()
614      m_DimRegionChooser.set_region(m_RegionChooser.get_region());      m_DimRegionChooser.set_region(m_RegionChooser.get_region());
615  }  }
616    
617  void MainWindow::dimreg_changed()  gig::Instrument* MainWindow::get_instrument()
618  {  {
619      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      gig::Instrument* instrument = 0;
620        Gtk::TreeModel::const_iterator it =
621            m_TreeView.get_selection()->get_selected();
622        if (it) {
623            Gtk::TreeModel::Row row = *it;
624            instrument = row[m_Columns.m_col_instr];
625        }
626        return instrument;
627  }  }
628    
629  void MainWindow::on_sel_change()  void MainWindow::add_region_to_dimregs(gig::Region* region, bool stereo, bool all_dimregs)
630  {  {
631      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (all_dimregs) {
632            for (int i = 0 ; i < region->DimensionRegions ; i++) {
633                if (region->pDimensionRegions[i]) {
634                    dimreg_edit.dimregs.insert(region->pDimensionRegions[i]);
635                }
636            }
637        } else {
638            m_DimRegionChooser.get_dimregions(region, stereo, dimreg_edit.dimregs);
639        }
640    }
641    
642      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();  void MainWindow::update_dimregs()
643      if (it) {  {
644          Gtk::TreeModel::Row row = *it;      dimreg_edit.dimregs.clear();
645          std::cout << row[m_Columns.m_col_name] << std::endl;      bool all_regions = dimreg_all_regions.get_active();
646        bool stereo = dimreg_stereo.get_active();
647        bool all_dimregs = dimreg_all_dimregs.get_active();
648    
649          m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);      if (all_regions) {
650            gig::Instrument* instrument = get_instrument();
651            if (instrument) {
652                for (gig::Region* region = instrument->GetFirstRegion() ;
653                     region ;
654                     region = instrument->GetNextRegion()) {
655                    add_region_to_dimregs(region, stereo, all_dimregs);
656                }
657            }
658      } else {      } else {
659          m_RegionChooser.set_instrument(0);          gig::Region* region = m_RegionChooser.get_region();
660            if (region) {
661                add_region_to_dimregs(region, stereo, all_dimregs);
662            }
663      }      }
664  }  }
665    
666    void MainWindow::dimreg_all_dimregs_toggled()
667    {
668        dimreg_stereo.set_sensitive(!dimreg_all_dimregs.get_active());
669        update_dimregs();
670    }
671    
672    void MainWindow::dimreg_changed()
673    {
674        update_dimregs();
675        dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
676    }
677    
678    void MainWindow::on_sel_change()
679    {
680        // select item in instrument menu
681        Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();
682        if (it) {
683            Gtk::TreePath path(it);
684            int index = path[0];
685            const std::vector<Gtk::Widget*> children =
686                instrument_menu->get_children();
687            static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
688        }
689    
690        m_RegionChooser.set_instrument(get_instrument());
691    }
692    
693  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
694  {  {
695      Loader* loader = static_cast<Loader*>(progress->custom);      Loader* loader = static_cast<Loader*>(progress->custom);
# Line 351  void loader_progress_callback(gig::progr Line 699  void loader_progress_callback(gig::progr
699  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
700  {  {
701      {      {
702          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
703          progress = fraction;          progress = fraction;
704      }      }
705      progress_dispatcher();      progress_dispatcher();
# Line 359  void Loader::progress_callback(float fra Line 707  void Loader::progress_callback(float fra
707    
708  void Loader::thread_function()  void Loader::thread_function()
709  {  {
710      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%x\n", Glib::Threads::Thread::self());
711      printf("Start %s\n", filename);      printf("Start %s\n", filename);
712      RIFF::File* riff = new RIFF::File(filename);      RIFF::File* riff = new RIFF::File(filename);
713      gig = new gig::File(riff);      gig = new gig::File(riff);
# Line 373  void Loader::thread_function() Line 721  void Loader::thread_function()
721  }  }
722    
723  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
724      : thread(0), filename(filename)      : filename(filename), thread(0)
725  {  {
726  }  }
727    
728  void Loader::launch()  void Loader::launch()
729  {  {
730    #ifdef OLD_THREADS
731      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
732    #else
733        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
734    #endif
735      printf("launch thread=%x\n", thread);      printf("launch thread=%x\n", thread);
736  }  }
737    
# Line 387  float Loader::get_progress() Line 739  float Loader::get_progress()
739  {  {
740      float res;      float res;
741      {      {
742          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
743          res = progress;          res = progress;
744      }      }
745      return res;      return res;
# Line 413  LoadDialog::LoadDialog(const Glib::ustri Line 765  LoadDialog::LoadDialog(const Glib::ustri
765  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
766  // 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.
767  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();  
768      // forget all samples that ought to be imported      // forget all samples that ought to be imported
769      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
770      // clear the samples and instruments tree views      // clear the samples and instruments tree views
771      m_refTreeModel->clear();      m_refTreeModel->clear();
772      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
773        m_refScriptsTreeModel->clear();
774        // remove all entries from "Instrument" menu
775        while (!instrument_menu->get_children().empty()) {
776            remove_instrument_from_menu(0);
777        }
778      // free libgig's gig::File instance      // free libgig's gig::File instance
779      if (file) {      if (file && !file_is_shared) delete file;
780          delete file;      file = NULL;
781          file = NULL;      set_file_is_shared(false);
782    }
783    
784    void MainWindow::__refreshEntireGUI() {
785        // clear the samples and instruments tree views
786        m_refTreeModel->clear();
787        m_refSamplesTreeModel->clear();
788        m_refScriptsTreeModel->clear();
789        // remove all entries from "Instrument" menu
790        while (!instrument_menu->get_children().empty()) {
791            remove_instrument_from_menu(0);
792      }      }
793    
794        if (!this->file) return;
795    
796        load_gig(
797            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
798        );
799  }  }
800    
801  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
802  {  {
803      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
804    
805        if (file_is_shared && !leaving_shared_mode_dialog()) return;
806    
807      // clear all GUI elements      // clear all GUI elements
808      __clear();      __clear();
# Line 443  void MainWindow::on_action_file_new() Line 810  void MainWindow::on_action_file_new()
810      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
811      // already add one new instrument by default      // already add one new instrument by default
812      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
813      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
814      // update GUI with that new gig::File      // update GUI with that new gig::File
815      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
816  }  }
# Line 454  bool MainWindow::close_confirmation_dial Line 821  bool MainWindow::close_confirmation_dial
821                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
822      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
823      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
824      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  
825      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
826      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
827      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);
# Line 467  bool MainWindow::close_confirmation_dial Line 832  bool MainWindow::close_confirmation_dial
832      return response != Gtk::RESPONSE_CANCEL;      return response != Gtk::RESPONSE_CANCEL;
833  }  }
834    
835    bool MainWindow::leaving_shared_mode_dialog() {
836        Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
837        Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
838        dialog.set_secondary_text(
839            _("If you proceed to work on another instrument file, it won't be "
840              "used by the sampler until you tell the sampler explicitly to "
841              "load it."));
842        dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
843        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
844        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
845        int response = dialog.run();
846        dialog.hide();
847        return response == Gtk::RESPONSE_YES;
848    }
849    
850  void MainWindow::on_action_file_open()  void MainWindow::on_action_file_open()
851  {  {
852      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
853    
854        if (file_is_shared && !leaving_shared_mode_dialog()) return;
855    
856      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
857      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
858      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
859      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
860    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
861      Gtk::FileFilter filter;      Gtk::FileFilter filter;
862      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
863    #else
864        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
865        filter->add_pattern("*.gig");
866    #endif
867      dialog.set_filter(filter);      dialog.set_filter(filter);
868      if (current_dir != "") {      if (current_gig_dir != "") {
869          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
870      }      }
871      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
872          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
873          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
874          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());
875          load_file(filename.c_str());          load_file(filename.c_str());
876          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
877      }      }
878  }  }
879    
880  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
881  {  {
882      __clear();      __clear();
883      load_dialog = new LoadDialog("Loading...", *this);      load_dialog = new LoadDialog(_("Loading..."), *this);
884      load_dialog->show_all();      load_dialog->show_all();
885      loader = new Loader(strdup(name));      loader = new Loader(strdup(name));
886      loader->signal_progress().connect(      loader->signal_progress().connect(
# Line 514  void MainWindow::load_instrument(gig::In Line 901  void MainWindow::load_instrument(gig::In
901      __clear();      __clear();
902      // load the instrument      // load the instrument
903      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
904      load_gig(pFile, 0 /*file name*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
905      //TODO: automatically select the given instrument      // automatically select the given instrument
906        int i = 0;
907        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
908             instrument = pFile->GetNextInstrument(), ++i)
909        {
910            if (instrument == instr) {
911                // select item in "instruments" tree view
912                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
913                // make sure the selected item in the "instruments" tree view is
914                // visible (scroll to it)
915                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
916                // select item in instrument menu
917                {
918                    const std::vector<Gtk::Widget*> children =
919                        instrument_menu->get_children();
920                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
921                }
922                // update region chooser and dimension region chooser
923                m_RegionChooser.set_instrument(instr);
924                break;
925            }
926        }
927  }  }
928    
929  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
# Line 526  void MainWindow::on_loader_progress() Line 934  void MainWindow::on_loader_progress()
934  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
935  {  {
936      printf("Loader finished!\n");      printf("Loader finished!\n");
937      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());
938      load_gig(loader->gig, loader->filename);      load_gig(loader->gig, loader->filename);
939      load_dialog->hide();      load_dialog->hide();
940  }  }
# Line 563  bool MainWindow::check_if_savable() Line 971  bool MainWindow::check_if_savable()
971  bool MainWindow::file_save()  bool MainWindow::file_save()
972  {  {
973      if (!check_if_savable()) return false;      if (!check_if_savable()) return false;
974      if (!file_has_name) return file_save_as();      if (!file_is_shared && !file_has_name) return file_save_as();
975    
976      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
977      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
# Line 575  bool MainWindow::file_save() Line 983  bool MainWindow::file_save()
983          }          }
984      } catch (RIFF::Exception e) {      } catch (RIFF::Exception e) {
985          file_structure_changed_signal.emit(this->file);          file_structure_changed_signal.emit(this->file);
986          Glib::ustring txt = "Could not save file: " + e.Message;          Glib::ustring txt = _("Could not save file: ") + e.Message;
987          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
988          msg.run();          msg.run();
989          return false;          return false;
# Line 598  bool MainWindow::file_save_as() Line 1006  bool MainWindow::file_save_as()
1006      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1007      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
1008      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  
1009      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1010      // TODO: an overwrite dialog for gtkmm < 2.8  
1011  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1012      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1013      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1014    #else
1015        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1016        filter->add_pattern("*.gig");
1017    #endif
1018      dialog.set_filter(filter);      dialog.set_filter(filter);
1019    
1020      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1021          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1022      } else if (current_dir != "") {      {
1023          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1024            std::string dir = Glib::path_get_dirname(filename);
1025            basename = std::string(_("copy_of_")) + basename;
1026            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1027            if (Glib::path_is_absolute(filename)) {
1028                dialog.set_filename(copyFileName);
1029            } else {
1030                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1031            }
1032            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1033      }      }
1034      dialog.set_current_name(Glib::filename_display_basename(filename));  
1035        // show warning in the dialog
1036        Gtk::HBox descriptionArea;
1037        descriptionArea.set_spacing(15);
1038        Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1039        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1040    #if GTKMM_MAJOR_VERSION < 3
1041        view::WrapLabel description;
1042    #else
1043        Gtk::Label description;
1044        description.set_line_wrap();
1045    #endif
1046        description.set_markup(
1047            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1048              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1049              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1050              "to the same .gig file. Using "
1051              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1052              "same .gig file will end up in corrupted sample wave data!\n")
1053        );
1054        descriptionArea.pack_start(description);
1055        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1056        descriptionArea.show_all();
1057    
1058      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1059          file_structure_to_be_changed_signal.emit(this->file);          file_structure_to_be_changed_signal.emit(this->file);
# Line 624  bool MainWindow::file_save_as() Line 1065  bool MainWindow::file_save_as()
1065              printf("filename=%s\n", filename.c_str());              printf("filename=%s\n", filename.c_str());
1066              file->Save(filename);              file->Save(filename);
1067              this->filename = filename;              this->filename = filename;
1068              current_dir = Glib::path_get_dirname(filename);              current_gig_dir = Glib::path_get_dirname(filename);
1069              set_title(Glib::filename_display_basename(filename));              set_title(Glib::filename_display_basename(filename));
1070              file_has_name = true;              file_has_name = true;
1071              file_is_changed = false;              file_is_changed = false;
1072          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
1073              file_structure_changed_signal.emit(this->file);              file_structure_changed_signal.emit(this->file);
1074              Glib::ustring txt = "Could not save file: " + e.Message;              Glib::ustring txt = _("Could not save file: ") + e.Message;
1075              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1076              msg.run();              msg.run();
1077              return false;              return false;
# Line 653  void MainWindow::__import_queued_samples Line 1094  void MainWindow::__import_queued_samples
1094          SF_INFO info;          SF_INFO info;
1095          info.format = 0;          info.format = 0;
1096          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
1097            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1098          try {          try {
1099              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1100              // determine sample's bit depth              // determine sample's bit depth
1101              int bitdepth;              int bitdepth;
1102              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 671  void MainWindow::__import_queued_samples Line 1113  void MainWindow::__import_queued_samples
1113                      break;                      break;
1114                  default:                  default:
1115                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1116                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1117              }              }
1118    
1119              const int bufsize = 10000;              const int bufsize = 10000;
# Line 713  void MainWindow::__import_queued_samples Line 1155  void MainWindow::__import_queued_samples
1155              }              }
1156              // cleanup              // cleanup
1157              sf_close(hFile);              sf_close(hFile);
1158                // let the sampler re-cache the sample if needed
1159                sample_changed_signal.emit(iter->gig_sample);
1160              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1161              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1162              std::list<SampleImportItem>::iterator cur = iter;              std::list<SampleImportItem>::iterator cur = iter;
# Line 720  void MainWindow::__import_queued_samples Line 1164  void MainWindow::__import_queued_samples
1164              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1165          } catch (std::string what) {          } catch (std::string what) {
1166              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1167              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1168              error_files += (*iter).sample_path += " (" + what + ")";              error_files += (*iter).sample_path += " (" + what + ")";
1169              ++iter;              ++iter;
1170          }          }
1171      }      }
1172      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1173      if (error_files.size()) {      if (!error_files.empty()) {
1174          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;
1175          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1176          msg.run();          msg.run();
1177      }      }
# Line 739  void MainWindow::on_action_file_properti Line 1183  void MainWindow::on_action_file_properti
1183      propDialog.deiconify();      propDialog.deiconify();
1184  }  }
1185    
1186    void MainWindow::on_action_warn_user_on_extensions() {
1187        Settings::singleton()->warnUserOnExtensions =
1188            !Settings::singleton()->warnUserOnExtensions;
1189    }
1190    
1191  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1192  {  {
 #ifdef ABOUT_DIALOG  
1193      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1194    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1195        dialog.set_program_name("Gigedit");
1196    #else
1197        dialog.set_name("Gigedit");
1198    #endif
1199      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1200        dialog.set_copyright("Copyright (C) 2006-2014 Andreas Persson");
1201        const std::string sComment =
1202            _("Built " __DATE__ "\nUsing ") +
1203            ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1204            _(
1205                "Gigedit is released under the GNU General Public License.\n"
1206                "\n"
1207                "This program is distributed WITHOUT ANY WARRANTY; So better "
1208                "backup your Gigasampler/GigaStudio files before editing them with "
1209                "this application.\n"
1210                "\n"
1211                "Please report bugs to: http://bugs.linuxsampler.org"
1212            );
1213        dialog.set_comments(sComment.c_str());
1214        dialog.set_website("http://www.linuxsampler.org");
1215        dialog.set_website_label("http://www.linuxsampler.org");
1216      dialog.run();      dialog.run();
 #endif  
1217  }  }
1218    
1219  PropDialog::PropDialog()  PropDialog::PropDialog()
1220      : table(2,1)      : eFileFormat(_("File Format")),
1221          eName(_("Name")),
1222          eCreationDate(_("Creation date")),
1223          eComments(_("Comments")),
1224          eProduct(_("Product")),
1225          eCopyright(_("Copyright")),
1226          eArtists(_("Artists")),
1227          eGenre(_("Genre")),
1228          eKeywords(_("Keywords")),
1229          eEngineer(_("Engineer")),
1230          eTechnician(_("Technician")),
1231          eSoftware(_("Software")),
1232          eMedium(_("Medium")),
1233          eSource(_("Source")),
1234          eSourceForm(_("Source form")),
1235          eCommissioned(_("Commissioned")),
1236          eSubject(_("Subject")),
1237          quitButton(Gtk::Stock::CLOSE),
1238          table(2, 1),
1239          m_file(NULL)
1240  {  {
1241        set_title(_("File Properties"));
1242        eName.set_width_chars(50);
1243    
1244        connect(eName, &DLS::Info::Name);
1245        connect(eCreationDate, &DLS::Info::CreationDate);
1246        connect(eComments, &DLS::Info::Comments);
1247        connect(eProduct, &DLS::Info::Product);
1248        connect(eCopyright, &DLS::Info::Copyright);
1249        connect(eArtists, &DLS::Info::Artists);
1250        connect(eGenre, &DLS::Info::Genre);
1251        connect(eKeywords, &DLS::Info::Keywords);
1252        connect(eEngineer, &DLS::Info::Engineer);
1253        connect(eTechnician, &DLS::Info::Technician);
1254        connect(eSoftware, &DLS::Info::Software);
1255        connect(eMedium, &DLS::Info::Medium);
1256        connect(eSource, &DLS::Info::Source);
1257        connect(eSourceForm, &DLS::Info::SourceForm);
1258        connect(eCommissioned, &DLS::Info::Commissioned);
1259        connect(eSubject, &DLS::Info::Subject);
1260    
1261        table.add(eFileFormat);
1262        table.add(eName);
1263        table.add(eCreationDate);
1264        table.add(eComments);
1265        table.add(eProduct);
1266        table.add(eCopyright);
1267        table.add(eArtists);
1268        table.add(eGenre);
1269        table.add(eKeywords);
1270        table.add(eEngineer);
1271        table.add(eTechnician);
1272        table.add(eSoftware);
1273        table.add(eMedium);
1274        table.add(eSource);
1275        table.add(eSourceForm);
1276        table.add(eCommissioned);
1277        table.add(eSubject);
1278    
1279      table.set_col_spacings(5);      table.set_col_spacings(5);
1280      const char* propLabels[] = {      add(vbox);
1281          "Name:",      table.set_border_width(5);
1282          "CreationDate:",      vbox.add(table);
1283          "Comments:", // TODO: multiline      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
1284          "Product:",      buttonBox.set_layout(Gtk::BUTTONBOX_END);
1285          "Copyright:",      buttonBox.set_border_width(5);
1286          "Artists:",      buttonBox.show();
1287          "Genre:",      buttonBox.pack_start(quitButton);
1288          "Keywords:",      quitButton.set_can_default();
1289          "Engineer:",      quitButton.grab_focus();
1290          "Technician:",      quitButton.signal_clicked().connect(
1291          "Software:", // TODO: readonly          sigc::mem_fun(*this, &PropDialog::hide));
1292          "Medium:",      eFileFormat.signal_value_changed().connect(
1293          "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);  
     }  
1294    
1295      add(table);      quitButton.show();
1296      // add_button(Gtk::Stock::CANCEL, 0);      vbox.show();
     // add_button(Gtk::Stock::OK, 1);  
1297      show_all_children();      show_all_children();
1298  }  }
1299    
1300    void PropDialog::set_file(gig::File* file)
1301    {
1302        m_file = file;
1303    
1304        // update file format version combo box
1305        const std::string sGiga = "Gigasampler/GigaStudio v";
1306        const int major = file->pVersion->major;
1307        std::vector<std::string> txts;
1308        std::vector<int> values;
1309        txts.push_back(sGiga + "2"); values.push_back(2);
1310        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1311        if (major != 2 && major != 3) {
1312            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1313        }
1314        std::vector<const char*> texts;
1315        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1316        texts.push_back(NULL); values.push_back(0);
1317        eFileFormat.set_choices(&texts[0], &values[0]);
1318        eFileFormat.set_value(major);
1319    }
1320    
1321    void PropDialog::onFileFormatChanged() {
1322        const int major = eFileFormat.get_value();
1323        if (m_file) m_file->pVersion->major = major;
1324    }
1325    
1326  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_info(DLS::Info* info)
1327  {  {
1328      entry[0].set_text(info->Name);      update(info);
     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);  
 }  
   
 void InstrumentProps::add_prop(BoolEntry& boolentry)  
 {  
     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)  
 {  
     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 void InstrumentProps::add_prop(LabelWidget& prop)  
 {  
     table.attach(prop.label, 0, 1, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     table.attach(prop.widget, 1, 2, rowno, rowno + 1,  
                  Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);  
     rowno++;  
     prop.signal_changed_by_user().connect(instrument_changed.make_slot());  
1329  }  }
1330    
1331  InstrumentProps::InstrumentProps()  
1332      : table(2,1),  void InstrumentProps::set_Name(const gig::String& name)
       quitButton(Gtk::Stock::CLOSE),  
       eName("Name"),  
       eIsDrum("Is drum"),  
       eMIDIBank("MIDI bank", 0, 16383),  
       eMIDIProgram("MIDI program"),  
       eAttenuation("Attenuation", 0, 96, 0, 1),  
       eGainPlus6("Gain +6dB", eAttenuation, -6),  
       eEffectSend("Effect send", 0, 65535),  
       eFineTune("Fine tune", -8400, 8400),  
       ePitchbendRange("Pitchbend range", 0, 12),  
       ePianoReleaseMode("Piano release mode"),  
       eDimensionKeyRangeLow("Dimension key range low"),  
       eDimensionKeyRangeHigh("Dimension key range high")  
1333  {  {
1334      set_title("Instrument properties");      m->pInfo->Name = name;
1335    }
1336    
1337    void InstrumentProps::update_name()
1338    {
1339        update_model++;
1340        eName.set_value(m->pInfo->Name);
1341        update_model--;
1342    }
1343    
1344    void InstrumentProps::set_IsDrum(bool value)
1345    {
1346        m->IsDrum = value;
1347    }
1348    
1349    void InstrumentProps::set_MIDIBank(uint16_t value)
1350    {
1351        m->MIDIBank = value;
1352    }
1353    
1354    void InstrumentProps::set_MIDIProgram(uint32_t value)
1355    {
1356        m->MIDIProgram = value;
1357    }
1358    
1359    InstrumentProps::InstrumentProps() :
1360        quitButton(Gtk::Stock::CLOSE),
1361        table(2,1),
1362        eName(_("Name")),
1363        eIsDrum(_("Is drum")),
1364        eMIDIBank(_("MIDI bank"), 0, 16383),
1365        eMIDIProgram(_("MIDI program")),
1366        eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1367        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1368        eEffectSend(_("Effect send"), 0, 65535),
1369        eFineTune(_("Fine tune"), -8400, 8400),
1370        ePitchbendRange(_("Pitchbend range"), 0, 12),
1371        ePianoReleaseMode(_("Piano release mode")),
1372        eDimensionKeyRangeLow(_("Keyswitching range low")),
1373        eDimensionKeyRangeHigh(_("Keyswitching range high"))
1374    {
1375        set_title(_("Instrument Properties"));
1376    
1377        eDimensionKeyRangeLow.set_tip(
1378            _("start of the keyboard area which should switch the "
1379              "\"keyswitching\" dimension")
1380        );
1381        eDimensionKeyRangeHigh.set_tip(
1382            _("end of the keyboard area which should switch the "
1383              "\"keyswitching\" dimension")
1384        );
1385    
1386        connect(eName, &InstrumentProps::set_Name);
1387        connect(eIsDrum, &InstrumentProps::set_IsDrum);
1388        connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1389        connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
1390        connect(eAttenuation, &gig::Instrument::Attenuation);
1391        connect(eGainPlus6, &gig::Instrument::Attenuation);
1392        connect(eEffectSend, &gig::Instrument::EffectSend);
1393        connect(eFineTune, &gig::Instrument::FineTune);
1394        connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1395        connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1396        connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1397                &gig::Instrument::DimensionKeyRange);
1398    
1399        eName.signal_value_changed().connect(sig_name_changed.make_slot());
1400    
     rowno = 0;  
1401      table.set_col_spacings(5);      table.set_col_spacings(5);
1402    
1403      add_prop(eName);      table.add(eName);
1404      add_prop(eIsDrum);      table.add(eIsDrum);
1405      add_prop(eMIDIBank);      table.add(eMIDIBank);
1406      add_prop(eMIDIProgram);      table.add(eMIDIProgram);
1407      add_prop(eAttenuation);      table.add(eAttenuation);
1408      add_prop(eGainPlus6);      table.add(eGainPlus6);
1409      add_prop(eEffectSend);      table.add(eEffectSend);
1410      add_prop(eFineTune);      table.add(eFineTune);
1411      add_prop(ePitchbendRange);      table.add(ePitchbendRange);
1412      add_prop(ePianoReleaseMode);      table.add(ePianoReleaseMode);
1413      add_prop(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
1414      add_prop(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
   
     eDimensionKeyRangeLow.signal_changed_by_user().connect(  
         sigc::mem_fun(*this, &InstrumentProps::key_range_low_changed));  
     eDimensionKeyRangeHigh.signal_changed_by_user().connect(  
         sigc::mem_fun(*this, &InstrumentProps::key_range_high_changed));  
1415    
1416      add(vbox);      add(vbox);
1417      table.set_border_width(5);      table.set_border_width(5);
# Line 878  InstrumentProps::InstrumentProps() Line 1422  InstrumentProps::InstrumentProps()
1422      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1423      buttonBox.show();      buttonBox.show();
1424      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1425      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1426      quitButton.grab_focus();      quitButton.grab_focus();
1427    
1428      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 891  InstrumentProps::InstrumentProps() Line 1435  InstrumentProps::InstrumentProps()
1435    
1436  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1437  {  {
1438      eName.set_ptr(&instrument->pInfo->Name);      update(instrument);
     eIsDrum.set_ptr(&instrument->IsDrum);  
     eMIDIBank.set_ptr(&instrument->MIDIBank);  
     eMIDIProgram.set_ptr(&instrument->MIDIProgram);  
     eAttenuation.set_ptr(&instrument->Attenuation);  
     eGainPlus6.set_ptr(&instrument->Attenuation);  
     eEffectSend.set_ptr(&instrument->EffectSend);  
     eFineTune.set_ptr(&instrument->FineTune);  
     ePitchbendRange.set_ptr(&instrument->PitchbendRange);  
     ePianoReleaseMode.set_ptr(&instrument->PianoReleaseMode);  
     eDimensionKeyRangeLow.set_ptr(0);  
     eDimensionKeyRangeHigh.set_ptr(0);  
     eDimensionKeyRangeLow.set_ptr(&instrument->DimensionKeyRange.low);  
     eDimensionKeyRangeHigh.set_ptr(&instrument->DimensionKeyRange.high);  
 }  
1439    
1440  void InstrumentProps::key_range_low_changed()      update_model++;
1441  {      eName.set_value(instrument->pInfo->Name);
1442      double l = eDimensionKeyRangeLow.get_value();      eIsDrum.set_value(instrument->IsDrum);
1443      double h = eDimensionKeyRangeHigh.get_value();      eMIDIBank.set_value(instrument->MIDIBank);
1444      if (h < l) eDimensionKeyRangeHigh.set_value(l);      eMIDIProgram.set_value(instrument->MIDIProgram);
1445        update_model--;
1446  }  }
1447    
 void InstrumentProps::key_range_high_changed()  
 {  
     double l = eDimensionKeyRangeLow.get_value();  
     double h = eDimensionKeyRangeHigh.get_value();  
     if (h < l) eDimensionKeyRangeLow.set_value(h);  
 }  
   
 sigc::signal<void> InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
1448    
1449  void MainWindow::file_changed()  void MainWindow::file_changed()
1450  {  {
# Line 934  void MainWindow::file_changed() Line 1454  void MainWindow::file_changed()
1454      }      }
1455  }  }
1456    
1457  void MainWindow::load_gig(gig::File* gig, const char* filename)  void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1458        sample_ref_count.clear();
1459        
1460        if (!gig) return;
1461    
1462        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1463             instrument = gig->GetNextInstrument())
1464        {
1465            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1466                 rgn = instrument->GetNextRegion())
1467            {
1468                for (int i = 0; i < 256; ++i) {
1469                    if (!rgn->pDimensionRegions[i]) continue;
1470                    if (rgn->pDimensionRegions[i]->pSample) {
1471                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1472                    }
1473                }
1474            }
1475        }
1476    }
1477    
1478    void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1479  {  {
1480      file = 0;      file = 0;
1481        set_file_is_shared(isSharedInstrument);
1482    
1483      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename = filename ? filename : _("Unsaved Gig File");
1484      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1485      file_has_name = filename;      file_has_name = filename;
1486      file_is_changed = false;      file_is_changed = false;
1487    
1488        propDialog.set_file(gig);
1489      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1490    
1491      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;  
1492      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1493           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument()) {
1494            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1495    
1496          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1497          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1498          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_name] = name;
1499          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1500          // create a menu item for this instrument  
1501          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++;  
1502      }      }
1503      instrument_menu->show();      instrument_name_connection.unblock();
1504      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1505    
1506        updateSampleRefCountMap(gig);
1507    
1508      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1509          if (group->Name != "") {          if (group->Name != "") {
1510              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1511              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1512              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1513              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1514              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1515              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 983  void MainWindow::load_gig(gig::File* gig Line 1517  void MainWindow::load_gig(gig::File* gig
1517                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1518                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1519                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1520                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1521                        gig_to_utf8(sample->pInfo->Name);
1522                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1523                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1524                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1525                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1526                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1527              }              }
1528          }          }
1529      }      }
1530        
1531        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1532            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1533    
1534            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1535            Gtk::TreeModel::Row rowGroup = *iterGroup;
1536            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1537            rowGroup[m_ScriptsModel.m_col_group]  = group;
1538            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1539            for (int s = 0; group->GetScript(s); ++s) {
1540                gig::Script* script = group->GetScript(s);
1541    
1542                Gtk::TreeModel::iterator iterScript =
1543                    m_refScriptsTreeModel->append(rowGroup.children());
1544                Gtk::TreeModel::Row rowScript = *iterScript;
1545                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1546                rowScript[m_ScriptsModel.m_col_script] = script;
1547                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1548            }
1549        }
1550        // unfold all sample groups & script groups by default
1551        m_TreeViewSamples.expand_all();
1552        m_TreeViewScripts.expand_all();
1553    
1554      file = gig;      file = gig;
1555    
1556      // select the first instrument      // select the first instrument
1557      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1558      tree_sel_ref->select(Gtk::TreePath("0"));  
1559        instr_props_set_instrument();
1560        gig::Instrument* instrument = get_instrument();
1561        if (instrument) {
1562            midiRules.set_instrument(instrument);
1563        }
1564    }
1565    
1566    bool MainWindow::instr_props_set_instrument()
1567    {
1568        instrumentProps.signal_name_changed().clear();
1569    
1570        Gtk::TreeModel::const_iterator it =
1571            m_TreeView.get_selection()->get_selected();
1572        if (it) {
1573            Gtk::TreeModel::Row row = *it;
1574            gig::Instrument* instrument = row[m_Columns.m_col_instr];
1575    
1576            instrumentProps.set_instrument(instrument);
1577    
1578            // make sure instrument tree is updated when user changes the
1579            // instrument name in instrument properties window
1580            instrumentProps.signal_name_changed().connect(
1581                sigc::bind(
1582                    sigc::mem_fun(*this,
1583                                  &MainWindow::instr_name_changed_by_instr_props),
1584                    it));
1585        } else {
1586            instrumentProps.hide();
1587        }
1588        return it;
1589  }  }
1590    
1591  void MainWindow::show_instr_props()  void MainWindow::show_instr_props()
1592  {  {
1593      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (instr_props_set_instrument()) {
1594      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();          instrumentProps.show();
1595      if (it)          instrumentProps.deiconify();
1596        }
1597    }
1598    
1599    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
1600    {
1601        Gtk::TreeModel::Row row = *it;
1602        Glib::ustring name = row[m_Columns.m_col_name];
1603    
1604        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1605        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
1606        if (gigname != name) {
1607            row[m_Columns.m_col_name] = gigname;
1608        }
1609    }
1610    
1611    void MainWindow::show_midi_rules()
1612    {
1613        if (gig::Instrument* instrument = get_instrument())
1614      {      {
1615          Gtk::TreeModel::Row row = *it;          midiRules.set_instrument(instrument);
1616          if (row[m_Columns.m_col_instr])          midiRules.show();
1617          {          midiRules.deiconify();
1618              instrumentProps.set_instrument(row[m_Columns.m_col_instr]);      }
1619              instrumentProps.show();  }
1620              instrumentProps.deiconify();  
1621          }  void MainWindow::show_script_slots() {
1622        if (!file) return;
1623        // get selected instrument
1624        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1625        Gtk::TreeModel::iterator it = sel->get_selected();
1626        if (!it) return;
1627        Gtk::TreeModel::Row row = *it;
1628        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1629        if (!instrument) return;
1630    
1631        ScriptSlots* window = new ScriptSlots;
1632        window->setInstrument(instrument);
1633        //window->reparent(*this);
1634        window->show();
1635    }
1636    
1637    void MainWindow::on_action_view_status_bar() {
1638        Gtk::CheckMenuItem* item =
1639            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
1640        if (!item) {
1641            std::cerr << "/MenuBar/MenuView/Statusbar == NULL\n";
1642            return;
1643        }
1644        if (item->get_active()) m_StatusBar.show();
1645        else                    m_StatusBar.hide();
1646    }
1647    
1648    bool MainWindow::is_copy_samples_unity_note_enabled() const {
1649        Gtk::CheckMenuItem* item =
1650            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1651        if (!item) {
1652            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
1653            return true;
1654        }
1655        return item->get_active();
1656    }
1657    
1658    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
1659        Gtk::CheckMenuItem* item =
1660            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
1661        if (!item) {
1662            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
1663            return true;
1664      }      }
1665        return item->get_active();
1666    }
1667    
1668    bool MainWindow::is_copy_samples_loop_enabled() const {
1669        Gtk::CheckMenuItem* item =
1670            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
1671        if (!item) {
1672            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
1673            return true;
1674        }
1675        return item->get_active();
1676  }  }
1677    
1678  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
# Line 1018  void MainWindow::on_button_release(GdkEv Line 1680  void MainWindow::on_button_release(GdkEv
1680      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
1681          show_instr_props();          show_instr_props();
1682      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1683            // gig v2 files have no midi rules
1684            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
1685            static_cast<Gtk::MenuItem*>(
1686                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
1687                    bEnabled
1688                );
1689            static_cast<Gtk::MenuItem*>(
1690                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
1691                    bEnabled
1692                );
1693          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
1694      }      }
1695  }  }
1696    
1697  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
1698      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
1699            const std::vector<Gtk::Widget*> children =
1700                instrument_menu->get_children();
1701            std::vector<Gtk::Widget*>::const_iterator it =
1702                find(children.begin(), children.end(), item);
1703            if (it != children.end()) {
1704                int index = it - children.begin();
1705                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
1706    
1707                m_RegionChooser.set_instrument(file->GetInstrument(index));
1708            }
1709        }
1710  }  }
1711    
1712  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
# Line 1040  void MainWindow::on_sample_treeview_butt Line 1723  void MainWindow::on_sample_treeview_butt
1723              group_selected  = row[m_SamplesModel.m_col_group];              group_selected  = row[m_SamplesModel.m_col_group];
1724              sample_selected = row[m_SamplesModel.m_col_sample];              sample_selected = row[m_SamplesModel.m_col_sample];
1725          }          }
1726            
1727                
1728          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
1729              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1730          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
1731              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1732          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
1733              set_sensitive(file);              set_sensitive(file);
1734            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
1735                set_sensitive(sample_selected);
1736          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
1737              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
1738          // show sample popup          // show sample popup
1739          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
1740    
1741            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
1742                set_sensitive(group_selected || sample_selected);
1743            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
1744                set_sensitive(group_selected || sample_selected);
1745            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
1746                set_sensitive(file);
1747            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
1748                set_sensitive(sample_selected);
1749            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
1750                set_sensitive(group_selected || sample_selected);
1751      }      }
1752  }  }
1753    
1754  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
1755      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
1756      if (!file) return;          Gtk::Menu* script_popup =
1757      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
1758      __instrument_indexer++;          // update enabled/disabled state of sample popup items
1759      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
1760          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
1761            bool group_selected  = false;
1762            bool script_selected = false;
1763            if (it) {
1764                Gtk::TreeModel::Row row = *it;
1765                group_selected  = row[m_ScriptsModel.m_col_group];
1766                script_selected = row[m_ScriptsModel.m_col_script];
1767            }
1768            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
1769                set_sensitive(group_selected || script_selected);
1770            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
1771                set_sensitive(file);
1772            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
1773                set_sensitive(script_selected);    
1774            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
1775                set_sensitive(group_selected || script_selected);
1776            // show sample popup
1777            script_popup->popup(button->button, button->time);
1778    
1779            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
1780                set_sensitive(group_selected || script_selected);
1781            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
1782                set_sensitive(file);
1783            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
1784                set_sensitive(script_selected);    
1785            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
1786                set_sensitive(group_selected || script_selected);
1787        }
1788    }
1789    
1790    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
1791        const Glib::ustring& name, int position) {
1792    
1793        Gtk::RadioMenuItem::Group instrument_group;
1794        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
1795        if (!children.empty()) {
1796            instrument_group =
1797                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
1798        }
1799        Gtk::RadioMenuItem* item =
1800            new Gtk::RadioMenuItem(instrument_group, name);
1801        if (position < 0) {
1802            instrument_menu->append(*item);
1803        } else {
1804            instrument_menu->insert(*item, position);
1805        }
1806        item->show();
1807        item->signal_activate().connect(
1808            sigc::bind(
1809                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
1810                item));
1811        return item;
1812    }
1813    
1814    void MainWindow::remove_instrument_from_menu(int index) {
1815        const std::vector<Gtk::Widget*> children =
1816            instrument_menu->get_children();
1817        Gtk::Widget* child = children[index];
1818        instrument_menu->remove(*child);
1819        delete child;
1820    }
1821    
1822    void MainWindow::add_instrument(gig::Instrument* instrument) {
1823        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1824    
1825      // update instrument tree view      // update instrument tree view
1826        instrument_name_connection.block();
1827      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
1828      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
1829      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_name] = name;
1830      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
1831        instrument_name_connection.unblock();
1832    
1833        add_instrument_to_menu(name);
1834    
1835        m_TreeView.get_selection()->select(iterInstr);
1836    
1837      file_changed();      file_changed();
1838  }  }
1839    
1840    void MainWindow::on_action_add_instrument() {
1841        static int __instrument_indexer = 0;
1842        if (!file) return;
1843        gig::Instrument* instrument = file->AddInstrument();
1844        __instrument_indexer++;
1845        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
1846                                                ToString(__instrument_indexer));
1847    
1848        add_instrument(instrument);
1849    }
1850    
1851    void MainWindow::on_action_duplicate_instrument() {
1852        if (!file) return;
1853    
1854        // retrieve the currently selected instrument
1855        // (being the original instrument to be duplicated)
1856        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1857        Gtk::TreeModel::iterator itSelection = sel->get_selected();
1858        if (!itSelection) return;
1859        Gtk::TreeModel::Row row = *itSelection;
1860        gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
1861        if (!instrOrig) return;
1862    
1863        // duplicate the orginal instrument
1864        gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
1865        instrNew->pInfo->Name =
1866            instrOrig->pInfo->Name +
1867            gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
1868    
1869        add_instrument(instrNew);
1870    }
1871    
1872  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
1873      if (!file) return;      if (!file) return;
1874        if (file_is_shared) {
1875            Gtk::MessageDialog msg(
1876                *this,
1877                 _("You cannot delete an instrument from this file, since it's "
1878                   "currently used by the sampler."),
1879                 false, Gtk::MESSAGE_INFO
1880            );
1881            msg.run();
1882            return;
1883        }
1884    
1885      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1886      Gtk::TreeModel::iterator it = sel->get_selected();      Gtk::TreeModel::iterator it = sel->get_selected();
1887      if (it) {      if (it) {
1888          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1889          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
1890          try {          try {
1891                Gtk::TreePath path(it);
1892                int index = path[0];
1893    
1894              // remove instrument from the gig file              // remove instrument from the gig file
1895              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
1896              file_changed();              file_changed();
1897    
1898                remove_instrument_from_menu(index);
1899    
1900                // remove row from instruments tree view
1901                m_refTreeModel->erase(it);
1902    
1903    #if GTKMM_MAJOR_VERSION < 3
1904                // select another instrument (in gtk3 this is done
1905                // automatically)
1906                if (!m_refTreeModel->children().empty()) {
1907                    if (index == m_refTreeModel->children().size()) {
1908                        index--;
1909                    }
1910                    m_TreeView.get_selection()->select(
1911                        Gtk::TreePath(ToString(index)));
1912                }
1913    #endif
1914                instr_props_set_instrument();
1915                instr = get_instrument();
1916                if (instr) {
1917                    midiRules.set_instrument(instr);
1918                } else {
1919                    midiRules.hide();
1920                }
1921          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
1922              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
1923              msg.run();              msg.run();
# Line 1091  void MainWindow::on_action_remove_instru Line 1928  void MainWindow::on_action_remove_instru
1928  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
1929      //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
1930      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
1931          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
1932      );      );
1933      msg.run();      msg.run();
1934  }  }
1935    
1936    void MainWindow::on_action_add_script_group() {
1937        static int __script_indexer = 0;
1938        if (!file) return;
1939        gig::ScriptGroup* group = file->AddScriptGroup();
1940        group->Name = gig_from_utf8(_("Unnamed Group"));
1941        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
1942        __script_indexer++;
1943        // update sample tree view
1944        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1945        Gtk::TreeModel::Row rowGroup = *iterGroup;
1946        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
1947        rowGroup[m_ScriptsModel.m_col_script] = NULL;
1948        rowGroup[m_ScriptsModel.m_col_group] = group;
1949        file_changed();
1950    }
1951    
1952    void MainWindow::on_action_add_script() {
1953        if (!file) return;
1954        // get selected group
1955        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
1956        Gtk::TreeModel::iterator it = sel->get_selected();
1957        if (!it) return;
1958        Gtk::TreeModel::Row row = *it;
1959        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
1960        if (!group) { // not a group, but a script is selected (probably)
1961            gig::Script* script = row[m_ScriptsModel.m_col_script];
1962            if (!script) return;
1963            it = row.parent(); // resolve parent (that is the script's group)
1964            if (!it) return;
1965            row = *it;
1966            group = row[m_ScriptsModel.m_col_group];
1967            if (!group) return;
1968        }
1969    
1970        // add a new script to the .gig file
1971        gig::Script* script = group->AddScript();    
1972        Glib::ustring name = _("Unnamed Script");
1973        script->Name = gig_from_utf8(name);
1974    
1975        // add script to the tree view
1976        Gtk::TreeModel::iterator iterScript =
1977            m_refScriptsTreeModel->append(row.children());
1978        Gtk::TreeModel::Row rowScript = *iterScript;
1979        rowScript[m_ScriptsModel.m_col_name] = name;
1980        rowScript[m_ScriptsModel.m_col_script] = script;
1981        rowScript[m_ScriptsModel.m_col_group]  = NULL;
1982    
1983        // unfold group of new script item in treeview
1984        Gtk::TreeModel::Path path(iterScript);
1985        m_TreeViewScripts.expand_to_path(path);
1986    }
1987    
1988    void MainWindow::on_action_edit_script() {
1989        if (!file) return;
1990        // get selected script
1991        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
1992        Gtk::TreeModel::iterator it = sel->get_selected();
1993        if (!it) return;
1994        Gtk::TreeModel::Row row = *it;
1995        gig::Script* script = row[m_ScriptsModel.m_col_script];
1996        if (!script) return;
1997    
1998        ScriptEditor* editor = new ScriptEditor;
1999        editor->setScript(script);
2000        //editor->reparent(*this);
2001        editor->show();
2002    }
2003    
2004    void MainWindow::on_action_remove_script() {
2005        if (!file) return;
2006        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2007        Gtk::TreeModel::iterator it = sel->get_selected();
2008        if (it) {
2009            Gtk::TreeModel::Row row = *it;
2010            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2011            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2012            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2013            try {
2014                // remove script group or script from the gig file
2015                if (group) {
2016                    // notify everybody that we're going to remove these samples
2017    //TODO:         scripts_to_be_removed_signal.emit(members);
2018                    // delete the group in the .gig file including the
2019                    // samples that belong to the group
2020                    file->DeleteScriptGroup(group);
2021                    // notify that we're done with removal
2022    //TODO:         scripts_removed_signal.emit();
2023                    file_changed();
2024                } else if (script) {
2025                    // notify everybody that we're going to remove this sample
2026    //TODO:         std::list<gig::Script*> lscripts;
2027    //TODO:         lscripts.push_back(script);
2028    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2029                    // remove sample from the .gig file
2030                    script->GetGroup()->DeleteScript(script);
2031                    // notify that we're done with removal
2032    //TODO:         scripts_removed_signal.emit();
2033                    dimreg_changed();
2034                    file_changed();
2035                }
2036                // remove respective row(s) from samples tree view
2037                m_refScriptsTreeModel->erase(it);
2038            } catch (RIFF::Exception e) {
2039                // pretend we're done with removal (i.e. to avoid dead locks)
2040    //TODO:     scripts_removed_signal.emit();
2041                // show error message
2042                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2043                msg.run();
2044            }
2045        }
2046    }
2047    
2048  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2049      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2050      if (!file) return;      if (!file) return;
2051      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2052      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2053      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2054      __sample_indexer++;      __sample_indexer++;
2055      // update sample tree view      // update sample tree view
2056      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2057      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2058      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2059      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2060      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2061      file_changed();      file_changed();
# Line 1134  void MainWindow::on_action_add_sample() Line 2083  void MainWindow::on_action_add_sample()
2083      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2084      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2085      dialog.set_select_multiple(true);      dialog.set_select_multiple(true);
2086      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2087        // matches all file types supported by libsndfile
2088    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2089        Gtk::FileFilter soundfilter;
2090    #else
2091        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2092    #endif
2093      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2094          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2095          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1142  void MainWindow::on_action_add_sample() Line 2097  void MainWindow::on_action_add_sample()
2097          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2098          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2099      };      };
2100        const char* soundfiles = _("Sound Files");
2101        const char* allfiles = _("All Files");
2102    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2103      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2104          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2105      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2106      Gtk::FileFilter allpassfilter; // matches every file  
2107        // matches every file
2108        Gtk::FileFilter allpassfilter;
2109      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2110      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2111    #else
2112        for (int i = 0; supportedFileTypes[i]; i++)
2113            soundfilter->add_pattern(supportedFileTypes[i]);
2114        soundfilter->set_name(soundfiles);
2115    
2116        // matches every file
2117        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2118        allpassfilter->add_pattern("*.*");
2119        allpassfilter->set_name(allfiles);
2120    #endif
2121      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2122      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2123        if (current_sample_dir != "") {
2124            dialog.set_current_folder(current_sample_dir);
2125        }
2126      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2127            current_sample_dir = dialog.get_current_folder();
2128          Glib::ustring error_files;          Glib::ustring error_files;
2129          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2130          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2131               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2132              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2133              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1161  void MainWindow::on_action_add_sample() Line 2135  void MainWindow::on_action_add_sample()
2135              info.format = 0;              info.format = 0;
2136              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2137              try {              try {
2138                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2139                  int bitdepth;                  int bitdepth;
2140                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2141                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1177  void MainWindow::on_action_add_sample() Line 2151  void MainWindow::on_action_add_sample()
2151                          break;                          break;
2152                      default:                      default:
2153                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2154                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2155                  }                  }
2156                  // add a new sample to the .gig file                  // add a new sample to the .gig file
2157                  gig::Sample* sample = file->AddSample();                  gig::Sample* sample = file->AddSample();
# Line 1190  void MainWindow::on_action_add_sample() Line 2164  void MainWindow::on_action_add_sample()
2164                          break;                          break;
2165                      }                      }
2166                  }                  }
2167                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2168                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2169                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2170                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1204  void MainWindow::on_action_add_sample() Line 2178  void MainWindow::on_action_add_sample()
2178                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2179                  {                  {
2180                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2181                        sample->FineTune      = instrument.detune;
2182    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2183                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2184                          sample->Loops = 1;                          sample->Loops = 1;
2185    
# Line 1225  void MainWindow::on_action_add_sample() Line 2199  void MainWindow::on_action_add_sample()
2199                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2200                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2201                      }                      }
 #endif  
2202                  }                  }
2203    
2204                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
# Line 1243  void MainWindow::on_action_add_sample() Line 2216  void MainWindow::on_action_add_sample()
2216                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
2217                      m_refSamplesTreeModel->append(row.children());                      m_refSamplesTreeModel->append(row.children());
2218                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
2219                  rowSample[m_SamplesModel.m_col_name]   = filename;                  rowSample[m_SamplesModel.m_col_name] =
2220                        gig_to_utf8(sample->pInfo->Name);
2221                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2222                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2223                  // close sound file                  // close sound file
2224                  sf_close(hFile);                  sf_close(hFile);
2225                  file_changed();                  file_changed();
2226              } 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)
2227                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2228                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2229              }              }
2230          }          }
2231          // 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
2232          if (error_files.size()) {          if (!error_files.empty()) {
2233              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;
2234                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2235                msg.run();
2236            }
2237        }
2238    }
2239    
2240    void MainWindow::on_action_replace_all_samples_in_all_groups()
2241    {
2242        if (!file) return;
2243        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2244                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2245        const char* str =
2246            _("This is a very specific function. It tries to replace all samples "
2247              "in the current gig file by samples located in the chosen "
2248              "directory.\n\n"
2249              "It works like this: For each sample in the gig file, it tries to "
2250              "find a sample file in the selected directory with the same name as "
2251              "the sample in the gig file. Optionally, you can add a filename "
2252              "extension below, which will be added to the filename expected to be "
2253              "found. That is, assume you have a gig file with a sample called "
2254              "'Snare', if you enter '.wav' below (like it's done by default), it "
2255              "expects to find a sample file called 'Snare.wav' and will replace "
2256              "the sample in the gig file accordingly. If you don't need an "
2257              "extension, blank the field below. Any gig sample where no "
2258              "appropriate sample file could be found will be reported and left "
2259              "untouched.\n");
2260    #if GTKMM_MAJOR_VERSION < 3
2261        view::WrapLabel description(str);
2262    #else
2263        Gtk::Label description(str);
2264        description.set_line_wrap();
2265    #endif
2266        Gtk::HBox entryArea;
2267        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2268        Gtk::Entry postfixEntryBox;
2269        postfixEntryBox.set_text(".wav");
2270        entryArea.pack_start(entryLabel);
2271        entryArea.pack_start(postfixEntryBox);
2272        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2273        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2274        description.show();
2275        entryArea.show_all();
2276        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2277        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2278        dialog.set_select_multiple(false);
2279        if (current_sample_dir != "") {
2280            dialog.set_current_folder(current_sample_dir);
2281        }
2282        if (dialog.run() == Gtk::RESPONSE_OK)
2283        {
2284            current_sample_dir = dialog.get_current_folder();
2285            Glib::ustring error_files;
2286            std::string folder = dialog.get_filename();
2287            for (gig::Sample* sample = file->GetFirstSample();
2288                 sample; sample = file->GetNextSample())
2289            {
2290                std::string filename =
2291                    folder + G_DIR_SEPARATOR_S +
2292                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2293                                             postfixEntryBox.get_text());
2294                SF_INFO info;
2295                info.format = 0;
2296                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2297                try
2298                {
2299                    if (!hFile) throw std::string(_("could not open file"));
2300                    int bitdepth;
2301                    switch (info.format & 0xff) {
2302                        case SF_FORMAT_PCM_S8:
2303                        case SF_FORMAT_PCM_16:
2304                        case SF_FORMAT_PCM_U8:
2305                            bitdepth = 16;
2306                            break;
2307                        case SF_FORMAT_PCM_24:
2308                        case SF_FORMAT_PCM_32:
2309                        case SF_FORMAT_FLOAT:
2310                        case SF_FORMAT_DOUBLE:
2311                            bitdepth = 24;
2312                            break;
2313                        default:
2314                            sf_close(hFile);
2315                            throw std::string(_("format not supported"));
2316                    }
2317                    SampleImportItem sched_item;
2318                    sched_item.gig_sample  = sample;
2319                    sched_item.sample_path = filename;
2320                    m_SampleImportQueue.push_back(sched_item);
2321                    sf_close(hFile);
2322                    file_changed();
2323                }
2324                catch (std::string what)
2325                {
2326                    if (!error_files.empty()) error_files += "\n";
2327                    error_files += Glib::filename_to_utf8(filename) +
2328                        " (" + what + ")";
2329                }
2330            }
2331            // show error message box when some file(s) could not be opened / added
2332            if (!error_files.empty()) {
2333                Glib::ustring txt =
2334                    _("Could not replace the following sample(s):\n") + error_files;
2335              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2336              msg.run();              msg.run();
2337          }          }
# Line 1275  void MainWindow::on_action_remove_sample Line 2350  void MainWindow::on_action_remove_sample
2350          try {          try {
2351              // remove group or sample from the gig file              // remove group or sample from the gig file
2352              if (group) {              if (group) {
2353                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2354                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2355                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2356                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1339  void MainWindow::on_action_remove_sample Line 2414  void MainWindow::on_action_remove_sample
2414      }      }
2415  }  }
2416    
2417    // see comment on on_sample_treeview_drag_begin()
2418    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
2419    {
2420        first_call_to_drag_data_get = true;
2421    }
2422    
2423    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
2424                                                       Gtk::SelectionData& selection_data, guint, guint)
2425    {
2426        if (!first_call_to_drag_data_get) return;
2427        first_call_to_drag_data_get = false;
2428    
2429        // get selected script
2430        gig::Script* script = NULL;
2431        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2432        Gtk::TreeModel::iterator it = sel->get_selected();
2433        if (it) {
2434            Gtk::TreeModel::Row row = *it;
2435            script = row[m_ScriptsModel.m_col_script];
2436        }
2437        // pass the gig::Script as pointer
2438        selection_data.set(selection_data.get_target(), 0/*unused*/,
2439                           (const guchar*)&script,
2440                           sizeof(script)/*length of data in bytes*/);
2441    }
2442    
2443  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
2444  // 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
2445  // 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 1397  void MainWindow::on_sample_label_drop_dr Line 2498  void MainWindow::on_sample_label_drop_dr
2498          bool channels_changed = false;          bool channels_changed = false;
2499          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
2500              // remove the samplechannel dimension              // remove the samplechannel dimension
2501    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
2502              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
2503              channels_changed = true;              channels_changed = true;
2504              region_changed();              region_changed();
2505    */
2506          }          }
2507          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
2508                sample,
2509                is_copy_samples_unity_note_enabled(),
2510                is_copy_samples_fine_tune_enabled(),
2511                is_copy_samples_loop_enabled()
2512            );
2513    
2514          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
2515              // add samplechannel dimension              // add samplechannel dimension
# Line 1429  void MainWindow::on_sample_label_drop_dr Line 2537  void MainWindow::on_sample_label_drop_dr
2537          // notify we're done with altering          // notify we're done with altering
2538          region_changed_signal.emit(region);          region_changed_signal.emit(region);
2539    
2540            file_changed();
2541    
2542          return;          return;
2543      }      }
2544      // drop failed      // drop failed
# Line 1442  void MainWindow::sample_name_changed(con Line 2552  void MainWindow::sample_name_changed(con
2552      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
2553      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
2554      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
2555        gig::String gigname(gig_from_utf8(name));
2556      if (group) {      if (group) {
2557          if (group->Name != name) {          if (group->Name != gigname) {
2558              group->Name = name;              group->Name = gigname;
2559              printf("group name changed\n");              printf("group name changed\n");
2560              file_changed();              file_changed();
2561          }          }
2562      } else if (sample) {      } else if (sample) {
2563          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
2564              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
2565              printf("sample name changed\n");              printf("sample name changed\n");
2566              file_changed();              file_changed();
2567          }          }
2568      }      }
2569  }  }
2570    
2571    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
2572                                         const Gtk::TreeModel::iterator& iter) {
2573        if (!iter) return;
2574        Gtk::TreeModel::Row row = *iter;
2575        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2576        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2577        gig::Script* script     = row[m_ScriptsModel.m_col_script];
2578        gig::String gigname(gig_from_utf8(name));
2579        if (group) {
2580            if (group->Name != gigname) {
2581                group->Name = gigname;
2582                printf("script group name changed\n");
2583                file_changed();
2584            }
2585        } else if (script) {
2586            if (script->Name != gigname) {
2587                script->Name = gigname;
2588                printf("script name changed\n");
2589                file_changed();
2590            }
2591        }
2592    }
2593    
2594    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
2595                                           Gtk::TreeViewColumn* column)
2596    {
2597        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
2598        if (!iter) return;
2599        Gtk::TreeModel::Row row = *iter;
2600        gig::Script* script = row[m_ScriptsModel.m_col_script];
2601        if (!script) return;
2602    
2603        ScriptEditor* editor = new ScriptEditor;
2604        editor->setScript(script);
2605        //editor->reparent(*this);
2606        editor->show();
2607    }
2608    
2609  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
2610                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
2611      if (!iter) return;      if (!iter) return;
2612      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
2613      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
2614    
2615        // change name in instrument menu
2616        int index = path[0];
2617        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2618        if (index < children.size()) {
2619    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
2620            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
2621    #else
2622            remove_instrument_from_menu(index);
2623            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
2624            item->set_active();
2625    #endif
2626        }
2627    
2628        // change name in gig
2629      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
2630      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
2631          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
2632            instrument->pInfo->Name = gigname;
2633    
2634            // change name in the instrument properties window
2635            if (instrumentProps.get_instrument() == instrument) {
2636                instrumentProps.update_name();
2637            }
2638    
2639          file_changed();          file_changed();
2640      }      }
2641  }  }
2642    
2643  sigc::signal<void, gig::File*> MainWindow::signal_file_structure_to_be_changed() {  void MainWindow::on_action_combine_instruments() {
2644        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
2645        d->show_all();
2646        d->resize(500, 400);
2647        d->run();
2648        if (d->fileWasChanged()) {
2649            // update GUI with new instrument just created
2650            add_instrument(d->newCombinedInstrument());
2651        }
2652        delete d;
2653    }
2654    
2655    void MainWindow::on_action_view_references() {
2656        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2657        Gtk::TreeModel::iterator it = sel->get_selected();
2658        if (!it) return;
2659        Gtk::TreeModel::Row row = *it;
2660        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
2661        if (!sample) return;
2662    
2663        ReferencesView* d = new ReferencesView(*this);
2664        d->setSample(sample);
2665        d->show_all();
2666        d->resize(500, 400);
2667        d->run();
2668        delete d;
2669    }
2670    
2671    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
2672        struct _Source {
2673            std::vector<RIFF::File*> riffs;
2674            std::vector<gig::File*> gigs;
2675            
2676            ~_Source() {
2677                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
2678                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
2679                riffs.clear();
2680                gigs.clear();
2681            }
2682        } sources;
2683    
2684        if (filenames.empty())
2685            throw RIFF::Exception(_("No files selected, so nothing done."));
2686    
2687        // first open all input files (to avoid output file corruption)
2688        int i;
2689        try {
2690            for (i = 0; i < filenames.size(); ++i) {
2691                const std::string& filename = filenames[i];
2692                printf("opening file=%s\n", filename.c_str());
2693    
2694                RIFF::File* riff = new RIFF::File(filename);
2695                sources.riffs.push_back(riff);
2696    
2697                gig::File* gig = new gig::File(riff);
2698                sources.gigs.push_back(gig);
2699            }
2700        } catch (RIFF::Exception e) {
2701            throw RIFF::Exception(
2702                _("Error occurred while opening '") +
2703                filenames[i] +
2704                "': " +
2705                e.Message
2706            );
2707        } catch (...) {
2708            throw RIFF::Exception(
2709                _("Unknown exception occurred while opening '") +
2710                filenames[i] + "'"
2711            );
2712        }
2713    
2714        // now merge the opened .gig files to the main .gig file currently being
2715        // open in gigedit
2716        try {
2717            for (i = 0; i < filenames.size(); ++i) {
2718                const std::string& filename = filenames[i];
2719                printf("merging file=%s\n", filename.c_str());
2720                assert(i < sources.gigs.size());
2721    
2722                this->file->AddContentOf(sources.gigs[i]);
2723            }
2724        } catch (RIFF::Exception e) {
2725            throw RIFF::Exception(
2726                _("Error occurred while merging '") +
2727                filenames[i] +
2728                "': " +
2729                e.Message
2730            );
2731        } catch (...) {
2732            throw RIFF::Exception(
2733                _("Unknown exception occurred while merging '") +
2734                filenames[i] + "'"
2735            );
2736        }
2737    
2738        // Note: requires that this file already has a filename !
2739        this->file->Save();
2740    }
2741    
2742    void MainWindow::on_action_merge_files() {
2743        if (this->file->GetFileName().empty()) {
2744            Glib::ustring txt = _(
2745                "You seem to have a new .gig file open that has not been saved "
2746                "yet. You must save it somewhere before starting to merge it with "
2747                "other .gig files though, because during the merge operation the "
2748                "other files' sample data must be written on file level to the "
2749                "target .gig file."
2750            );
2751            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2752            msg.run();
2753            return;
2754        }
2755    
2756        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
2757        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2758        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
2759        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
2760    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2761        Gtk::FileFilter filter;
2762        filter.add_pattern("*.gig");
2763    #else
2764        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
2765        filter->add_pattern("*.gig");
2766    #endif
2767        dialog.set_filter(filter);
2768        if (current_gig_dir != "") {
2769            dialog.set_current_folder(current_gig_dir);
2770        }
2771        dialog.set_select_multiple(true);
2772    
2773        // show warning in the file picker dialog
2774        Gtk::HBox descriptionArea;
2775        descriptionArea.set_spacing(15);
2776        Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
2777        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
2778    #if GTKMM_MAJOR_VERSION < 3
2779        view::WrapLabel description;
2780    #else
2781        Gtk::Label description;
2782        description.set_line_wrap();
2783    #endif
2784        description.set_markup(_(
2785            "\nSelect at least one .gig file that shall be merged to the .gig file "
2786            "currently being open in gigedit.\n\n"
2787            "<b>Please Note:</b> Merging with other files will modify your "
2788            "currently open .gig file on file level! And be aware that the current "
2789            "merge algorithm does not detect duplicate samples yet. So if you are "
2790            "merging files which are using equivalent sample data, those "
2791            "equivalent samples will currently be treated as separate samples and "
2792            "will accordingly be stored separately in the target .gig file!"
2793        ));
2794        descriptionArea.pack_start(description);
2795        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2796        descriptionArea.show_all();
2797    
2798        if (dialog.run() == Gtk::RESPONSE_OK) {
2799            printf("on_action_merge_files self=%x\n", Glib::Threads::Thread::self());
2800            std::vector<std::string> filenames = dialog.get_filenames();
2801    
2802            // merge the selected files to the currently open .gig file
2803            try {
2804                mergeFiles(filenames);
2805            } catch (RIFF::Exception e) {
2806                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
2807                msg.run();
2808            }
2809    
2810            // update GUI
2811            __refreshEntireGUI();        
2812        }
2813    }
2814    
2815    void MainWindow::set_file_is_shared(bool b) {
2816        this->file_is_shared = b;
2817    
2818        if (file_is_shared) {
2819            m_AttachedStateLabel.set_label(_("live-mode"));
2820            m_AttachedStateImage.set(
2821                Gdk::Pixbuf::create_from_xpm_data(status_attached_xpm)
2822            );
2823        } else {
2824            m_AttachedStateLabel.set_label(_("stand-alone"));
2825            m_AttachedStateImage.set(
2826                Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
2827            );
2828        }
2829    }
2830    
2831    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
2832        if (!sample) return;
2833        sample_ref_count[sample] += offset;
2834        const int refcount = sample_ref_count[sample];
2835    
2836        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2837        for (int g = 0; g < model->children().size(); ++g) {
2838            Gtk::TreeModel::Row rowGroup = model->children()[g];
2839            for (int s = 0; s < rowGroup.children().size(); ++s) {
2840                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2841                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
2842                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
2843                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
2844            }
2845        }
2846    }
2847    
2848    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
2849        on_sample_ref_count_incremented(oldSample, -1);
2850        on_sample_ref_count_incremented(newSample, +1);
2851    }
2852    
2853    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
2854        // just in case a new sample is added later with exactly the same memory
2855        // address, which would lead to incorrect refcount if not deleted here
2856        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
2857             it != samples.end(); it != samples.end())
2858        {
2859            sample_ref_count.erase(*it);
2860        }
2861    }
2862    
2863    void MainWindow::show_samples_tab() {
2864        m_TreeViewNotebook.set_current_page(0);
2865    }
2866    
2867    void MainWindow::show_intruments_tab() {
2868        m_TreeViewNotebook.set_current_page(1);
2869    }
2870    
2871    void MainWindow::show_scripts_tab() {
2872        m_TreeViewNotebook.set_current_page(2);
2873    }
2874    
2875    sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
2876      return file_structure_to_be_changed_signal;      return file_structure_to_be_changed_signal;
2877  }  }
2878    
2879  sigc::signal<void, gig::File*> MainWindow::signal_file_structure_changed() {  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_changed() {
2880      return file_structure_changed_signal;      return file_structure_changed_signal;
2881  }  }
2882    
2883  sigc::signal<void, std::list<gig::Sample*> > MainWindow::signal_samples_to_be_removed() {  sigc::signal<void, std::list<gig::Sample*> >& MainWindow::signal_samples_to_be_removed() {
2884      return samples_to_be_removed_signal;      return samples_to_be_removed_signal;
2885  }  }
2886    
2887  sigc::signal<void> MainWindow::signal_samples_removed() {  sigc::signal<void>& MainWindow::signal_samples_removed() {
2888      return samples_removed_signal;      return samples_removed_signal;
2889  }  }
2890    
2891  sigc::signal<void, gig::Region*> MainWindow::signal_region_to_be_changed() {  sigc::signal<void, gig::Region*>& MainWindow::signal_region_to_be_changed() {
2892      return region_to_be_changed_signal;      return region_to_be_changed_signal;
2893  }  }
2894    
2895  sigc::signal<void, gig::Region*> MainWindow::signal_region_changed() {  sigc::signal<void, gig::Region*>& MainWindow::signal_region_changed() {
2896      return region_changed_signal;      return region_changed_signal;
2897  }  }
2898    
2899  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/> MainWindow::signal_sample_ref_changed() {  sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
2900        return sample_changed_signal;
2901    }
2902    
2903    sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
2904      return sample_ref_changed_signal;      return sample_ref_changed_signal;
2905  }  }
2906    
2907  sigc::signal<void, gig::DimensionRegion*> MainWindow::signal_dimreg_to_be_changed() {  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_to_be_changed() {
2908      return dimreg_to_be_changed_signal;      return dimreg_to_be_changed_signal;
2909  }  }
2910    
2911  sigc::signal<void, gig::DimensionRegion*> MainWindow::signal_dimreg_changed() {  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
2912      return dimreg_changed_signal;      return dimreg_changed_signal;
2913  }  }
2914    
2915    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_on() {
2916        return note_on_signal;
2917    }
2918    
2919    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
2920        return note_off_signal;
2921    }
2922    
2923    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
2924        return m_RegionChooser.signal_keyboard_key_hit();
2925    }
2926    
2927    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
2928        return m_RegionChooser.signal_keyboard_key_released();
2929    }

Legend:
Removed from v.1328  
changed lines
  Added in v.2664

  ViewVC Help
Powered by ViewVC