/[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 1261 by persson, Thu Jul 5 17:12:20 2007 UTC revision 2968 by schoenebeck, Mon Jul 18 11:25:13 2016 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006, 2007 Andreas Persson   * Copyright (C) 2006-2016 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 <glibmmconfig.h>
24    // threads.h must be included first to be able to build with
25    // G_DISABLE_DEPRECATED
26    #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION == 31 && GLIBMM_MICRO_VERSION >= 2) || \
27        (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION > 31) || GLIBMM_MAJOR_VERSION > 2
28    #include <glibmm/threads.h>
29    #endif
30    
31    #include <glibmm/convert.h>
32    #include <glibmm/dispatcher.h>
33    #include <glibmm/miscutils.h>
34    #include <glibmm/stringutils.h>
35    #include <gtkmm/aboutdialog.h>
36  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
37  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
 #include <gtkmm/stock.h>  
38  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
39  #include <gtkmm/main.h>  #include <gtkmm/main.h>
40    #include <gtkmm/toggleaction.h>
41  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  #if GTKMM_MAJOR_VERSION < 3
42  #define ABOUT_DIALOG  #include "wrapLabel.hh"
 #include <gtkmm/aboutdialog.h>  
43  #endif  #endif
44    
45    #include "global.h"
46    #include "compat.h"
47    
48  #include <stdio.h>  #include <stdio.h>
49  #include <sndfile.h>  #include <sndfile.h>
50    #include <assert.h>
51    
52  #include "mainwindow.h"  #include "mainwindow.h"
53    #include "Settings.h"
54    #include "CombineInstrumentsDialog.h"
55    #include "scripteditor.h"
56    #include "scriptslots.h"
57    #include "ReferencesView.h"
58    #include "../../gfx/status_attached.xpm"
59    #include "../../gfx/status_detached.xpm"
60    
 #define _(String) gettext(String)  
   
 template<class T> inline std::string ToString(T o) {  
     std::stringstream ss;  
     ss << o;  
     return ss.str();  
 }  
61    
62  MainWindow::MainWindow()  MainWindow::MainWindow() :
63        m_DimRegionChooser(*this),
64        dimreg_label(_("Changes apply to:")),
65        dimreg_all_regions(_("all regions")),
66        dimreg_all_dimregs(_("all dimension splits")),
67        dimreg_stereo(_("both channels"))
68  {  {
69  //    set_border_width(5);  //    set_border_width(5);
70  //    set_default_size(400, 200);  //    set_default_size(400, 200);
# Line 53  MainWindow::MainWindow() Line 73  MainWindow::MainWindow()
73      add(m_VBox);      add(m_VBox);
74    
75      // Handle selection      // Handle selection
76      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
77          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
78    
79      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
# Line 70  MainWindow::MainWindow() Line 89  MainWindow::MainWindow()
89      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
90      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
91    
92        m_ScrolledWindowScripts.add(m_TreeViewScripts);
93        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
94    
95    
96      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
97    
98      m_HPaned.add1(m_TreeViewNotebook);      m_HPaned.add1(m_TreeViewNotebook);
99      m_HPaned.add2(dimreg_edit);      dimreg_hbox.add(dimreg_label);
100        dimreg_hbox.add(dimreg_all_regions);
101        dimreg_hbox.add(dimreg_all_dimregs);
102      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");      dimreg_stereo.set_active();
103      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");      dimreg_hbox.add(dimreg_stereo);
104        dimreg_vbox.add(dimreg_edit);
105        dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
106        m_HPaned.add2(dimreg_vbox);
107    
108        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
109        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."));
110        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."));
111        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)."));
112    
113        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
114        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
115        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
116    
117      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
118    
119      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
120      actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),      actionGroup->add(Gtk::Action::create("New", _("_New")),
121                         Gtk::AccelKey("<control>n"),
122                       sigc::mem_fun(                       sigc::mem_fun(
123                           *this, &MainWindow::on_action_file_new));                           *this, &MainWindow::on_action_file_new));
124      Glib::RefPtr<Gtk::Action> action =      actionGroup->add(Gtk::Action::create("Open", _("_Open...")),
125          Gtk::Action::create("Open", Gtk::Stock::OPEN);                       Gtk::AccelKey("<control>o"),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
126                       sigc::mem_fun(                       sigc::mem_fun(
127                           *this, &MainWindow::on_action_file_open));                           *this, &MainWindow::on_action_file_open));
128      actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),      actionGroup->add(Gtk::Action::create("Save", _("_Save")),
129                         Gtk::AccelKey("<control>s"),
130                       sigc::mem_fun(                       sigc::mem_fun(
131                           *this, &MainWindow::on_action_file_save));                           *this, &MainWindow::on_action_file_save));
132      action = Gtk::Action::create("SaveAs", Gtk::Stock::SAVE_AS);      actionGroup->add(Gtk::Action::create("SaveAs", _("Save _As...")),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
133                       Gtk::AccelKey("<shift><control>s"),                       Gtk::AccelKey("<shift><control>s"),
134                       sigc::mem_fun(                       sigc::mem_fun(
135                           *this, &MainWindow::on_action_file_save_as));                           *this, &MainWindow::on_action_file_save_as));
136      actionGroup->add(Gtk::Action::create("Properties",      actionGroup->add(Gtk::Action::create("Properties",
137                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
138                       sigc::mem_fun(                       sigc::mem_fun(
139                           *this, &MainWindow::on_action_file_properties));                           *this, &MainWindow::on_action_file_properties));
140      actionGroup->add(Gtk::Action::create("InstrProperties",      actionGroup->add(Gtk::Action::create("InstrProperties",
141                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
142                       sigc::mem_fun(                       sigc::mem_fun(
143                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
144      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("MidiRules",
145                                             _("_Midi Rules...")),
146                         sigc::mem_fun(
147                             *this, &MainWindow::show_midi_rules));
148        actionGroup->add(Gtk::Action::create("ScriptSlots",
149                                             _("_Script Slots...")),
150                         sigc::mem_fun(
151                             *this, &MainWindow::show_script_slots));
152        actionGroup->add(Gtk::Action::create("Quit", _("_Quit")),
153                         Gtk::AccelKey("<control>q"),
154                       sigc::mem_fun(                       sigc::mem_fun(
155                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
156      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
157            Gtk::Action::create("MenuSample", _("_Sample")),
158            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
159        );
160        actionGroup->add(
161            Gtk::Action::create("MenuInstrument", _("_Instrument")),
162            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
163        );
164        actionGroup->add(
165            Gtk::Action::create("MenuScript", _("S_cript")),
166            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
167        );
168        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
169    
170        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
171    
172        Glib::RefPtr<Gtk::ToggleAction> toggle_action =
173            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
174        toggle_action->set_active(true);
175        actionGroup->add(toggle_action);
176    
177        toggle_action =
178            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
179        toggle_action->set_active(true);
180        actionGroup->add(toggle_action);
181    
182        toggle_action =
183            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
184        toggle_action->set_active(true);
185        actionGroup->add(toggle_action);
186    
187    
188        actionGroup->add(Gtk::Action::create("MenuView", _("_View")));
189        toggle_action =
190            Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
191        toggle_action->set_active(true);
192        actionGroup->add(toggle_action,
193                         sigc::mem_fun(
194                             *this, &MainWindow::on_action_view_status_bar));
195    
196        toggle_action =
197            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
198        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
199        actionGroup->add(toggle_action,
200                         sigc::mem_fun(
201                             *this, &MainWindow::on_auto_restore_win_dim));
202    
203        toggle_action =
204            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
205        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
206        actionGroup->add(toggle_action,
207                         sigc::mem_fun(
208                             *this, &MainWindow::on_save_with_temporary_file));
209    
210        actionGroup->add(
211            Gtk::Action::create("RefreshAll", _("_Refresh All")),
212            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
213        );                
214    
215      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
216      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("About", _("_About")),
                                          action->property_label()));  
 #ifdef ABOUT_DIALOG  
     actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),  
217                       sigc::mem_fun(                       sigc::mem_fun(
218                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
219      actionGroup->add(      actionGroup->add(
220          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
221          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
222      );      );
223      actionGroup->add(      actionGroup->add(
224          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
225            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
226        );
227        actionGroup->add(
228            Gtk::Action::create("RemoveInstrument", _("_Remove")),
229          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
230      );      );
231    
232    
233        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
234        
235        toggle_action =
236            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
237        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
238        actionGroup->add(
239            toggle_action,
240            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
241        );
242    
243        toggle_action =
244            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
245        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
246        actionGroup->add(
247            toggle_action,
248            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
249        );
250    
251        toggle_action =
252            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
253        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
254        actionGroup->add(
255            toggle_action,
256            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
257        );
258    
259    
260        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
261    
262        actionGroup->add(
263            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
264            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
265        );
266    
267        actionGroup->add(
268            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
269            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
270        );
271    
272    
273      // sample right-click popup actions      // sample right-click popup actions
274      actionGroup->add(      actionGroup->add(
275          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", _("_Properties")),
276          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
277      );      );
278      actionGroup->add(      actionGroup->add(
# Line 142  MainWindow::MainWindow() Line 280  MainWindow::MainWindow()
280          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
281      );      );
282      actionGroup->add(      actionGroup->add(
283          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
284          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
285      );      );
286      actionGroup->add(      actionGroup->add(
287          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", _("_Remove")),
288          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
289      );      );
290        actionGroup->add(
291            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
292            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
293        );
294        actionGroup->add(
295            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
296            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
297        );
298        actionGroup->add(
299            Gtk::Action::create("ReplaceSample",
300                                _("Replace Sample...")),
301            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
302        );
303        actionGroup->add(
304            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
305                                _("Replace All Samples in All Groups...")),
306            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
307        );
308        
309        // script right-click popup actions
310        actionGroup->add(
311            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
312            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
313        );
314        actionGroup->add(
315            Gtk::Action::create("AddScript", _("Add _Script")),
316            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
317        );
318        actionGroup->add(
319            Gtk::Action::create("EditScript", _("_Edit Script...")),
320            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
321        );
322        actionGroup->add(
323            Gtk::Action::create("RemoveScript", _("_Remove")),
324            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
325        );
326    
327      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
328      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 168  MainWindow::MainWindow() Line 342  MainWindow::MainWindow()
342          "      <separator/>"          "      <separator/>"
343          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
344          "    </menu>"          "    </menu>"
345            "    <menu action='MenuEdit'>"
346            "      <menuitem action='CopySampleUnity'/>"
347            "      <menuitem action='CopySampleTune'/>"
348            "      <menuitem action='CopySampleLoop'/>"
349            "    </menu>"
350            "    <menu action='MenuSample'>"
351            "      <menuitem action='SampleProperties'/>"
352            "      <menuitem action='AddGroup'/>"
353            "      <menuitem action='AddSample'/>"
354            "      <menuitem action='ShowSampleRefs'/>"
355            "      <menuitem action='ReplaceSample' />"
356            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
357            "      <separator/>"
358            "      <menuitem action='RemoveSample'/>"
359            "      <menuitem action='RemoveUnusedSamples'/>"
360            "    </menu>"
361          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
362            "      <menu action='AllInstruments'>"
363            "      </menu>"
364            "      <separator/>"
365            "      <menuitem action='InstrProperties'/>"
366            "      <menuitem action='MidiRules'/>"
367            "      <menuitem action='ScriptSlots'/>"
368            "      <menuitem action='AddInstrument'/>"
369            "      <menuitem action='DupInstrument'/>"
370            "      <separator/>"
371            "      <menuitem action='RemoveInstrument'/>"
372            "    </menu>"
373            "    <menu action='MenuScript'>"
374            "      <menuitem action='AddScriptGroup'/>"
375            "      <menuitem action='AddScript'/>"
376            "      <menuitem action='EditScript'/>"
377            "      <separator/>"
378            "      <menuitem action='RemoveScript'/>"
379            "    </menu>"
380            "    <menu action='MenuView'>"
381            "      <menuitem action='Statusbar'/>"
382            "      <menuitem action='AutoRestoreWinDim'/>"
383            "      <separator/>"
384            "      <menuitem action='RefreshAll'/>"
385            "    </menu>"
386            "    <menu action='MenuTools'>"
387            "      <menuitem action='CombineInstruments'/>"
388            "      <menuitem action='MergeFiles'/>"
389            "    </menu>"
390            "    <menu action='MenuSettings'>"
391            "      <menuitem action='WarnUserOnExtensions'/>"
392            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
393            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
394            "      <menuitem action='SaveWithTemporaryFile'/>"
395          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
396          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
397          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
398          "    </menu>"          "    </menu>"
 #endif  
399          "  </menubar>"          "  </menubar>"
400          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
401          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
402            "    <menuitem action='MidiRules'/>"
403            "    <menuitem action='ScriptSlots'/>"
404          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
405            "    <menuitem action='DupInstrument'/>"
406          "    <separator/>"          "    <separator/>"
407          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
408          "  </popup>"          "  </popup>"
# Line 186  MainWindow::MainWindow() Line 410  MainWindow::MainWindow()
410          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
411          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
412          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
413            "    <menuitem action='ShowSampleRefs'/>"
414            "    <menuitem action='ReplaceSample' />"
415            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
416          "    <separator/>"          "    <separator/>"
417          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
418            "    <menuitem action='RemoveUnusedSamples'/>"
419            "  </popup>"
420            "  <popup name='ScriptPopupMenu'>"
421            "    <menuitem action='AddScriptGroup'/>"
422            "    <menuitem action='AddScript'/>"
423            "    <menuitem action='EditScript'/>"
424            "    <separator/>"
425            "    <menuitem action='RemoveScript'/>"
426          "  </popup>"          "  </popup>"
427          "</ui>";          "</ui>";
428      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
429    
430      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
431        
432        // Set tooltips for menu items (for some reason, setting a tooltip on the
433        // respective Gtk::Action objects above will simply be ignored, no matter
434        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
435        // Gtk::Action::create()).
436        {
437            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
438                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
439            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."));
440        }
441        {
442            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
443                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
444            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."));
445        }
446        {
447            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
448                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
449            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."));
450        }
451        {
452            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
453                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
454            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."));
455        }
456        {
457            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
458                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
459            item->set_tooltip_text(_("If checked, the sampler's current instrument will automatically be switched whenever another instrument was selected in gigedit (only available in live-mode)."));
460        }
461        {
462            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
463                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
464            item->set_tooltip_text(_("If checked, and when a region is moved by dragging it around on the virtual keyboard, the keybord position dependent pitch will move exactly with the amount of semi tones the region was moved around."));
465        }
466        {
467            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
468                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
469            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
470            // copy tooltip to popup menu
471            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
472                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
473            item2->set_tooltip_text(item->get_tooltip_text());
474        }
475        {
476            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
477                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
478            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
479        }
480        {
481            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
482                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
483            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
484        }
485        {
486            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
487                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
488            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
489        }
490        {
491            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
492                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
493            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
494        }
495    
496    
497        instrument_menu = static_cast<Gtk::MenuItem*>(
498            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
499    
500      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
501      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
502      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
503      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
504        m_VBox.pack_start(m_RegionChooser.m_VirtKeybPropsBox, Gtk::PACK_SHRINK);
505      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
506        m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
507    
508        set_file_is_shared(false);
509    
510        // Status Bar:
511        m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
512        m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
513        m_StatusBar.show();
514    
515      m_RegionChooser.signal_region_selected().connect(      m_RegionChooser.signal_region_selected().connect(
516          sigc::mem_fun(*this, &MainWindow::region_changed) );          sigc::mem_fun(*this, &MainWindow::region_changed) );
# Line 209  MainWindow::MainWindow() Line 521  MainWindow::MainWindow()
521      // Create the Tree model:      // Create the Tree model:
522      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
523      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
524      m_refTreeModel->signal_row_changed().connect(      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
525        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
526          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
527      );      );
528    
529      // Add the TreeView's view columns:      // Add the TreeView's view columns:
530      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);
531      m_TreeView.set_headers_visible(false);      m_TreeView.set_headers_visible(false);
532        
533        // establish drag&drop within the instrument tree view, allowing to reorder
534        // the sequence of instruments within the gig file
535        {
536            std::vector<Gtk::TargetEntry> drag_target_instrument;
537            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
538            m_TreeView.drag_source_set(drag_target_instrument);
539            m_TreeView.drag_dest_set(drag_target_instrument);
540            m_TreeView.signal_drag_begin().connect(
541                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
542            );
543            m_TreeView.signal_drag_data_get().connect(
544                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
545            );
546            m_TreeView.signal_drag_data_received().connect(
547                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
548            );
549        }
550    
551      // create samples treeview (including its data model)      // create samples treeview (including its data model)
552      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
553      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
554        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."));
555      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
556      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
557      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
558        {
559            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
560            Gtk::CellRendererText* cellrenderer =
561                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
562            column->add_attribute(
563                cellrenderer->property_foreground(), m_SamplesModel.m_color
564            );
565        }
566        {
567            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
568            Gtk::CellRendererText* cellrenderer =
569                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
570            column->add_attribute(
571                cellrenderer->property_foreground(), m_SamplesModel.m_color
572            );
573        }
574        m_TreeViewSamples.set_headers_visible(true);
575      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
576          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
577      );      );
# Line 230  MainWindow::MainWindow() Line 579  MainWindow::MainWindow()
579          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
580      );      );
581    
582        // create scripts treeview (including its data model)
583        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
584        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
585        m_TreeViewScripts.set_tooltip_text(_(
586            "Use CTRL + double click for editing a script."
587            "\n\n"
588            "Note: instrument scripts are a LinuxSampler extension of the gig "
589            "format. This feature will not work with the GigaStudio software!"
590        ));
591        // m_TreeViewScripts.set_reorderable();
592        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
593        m_TreeViewScripts.set_headers_visible(false);
594        m_TreeViewScripts.signal_button_press_event().connect_notify(
595            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
596        );
597        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
598        m_TreeViewScripts.signal_row_activated().connect(
599            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
600        );
601        m_refScriptsTreeModel->signal_row_changed().connect(
602            sigc::mem_fun(*this, &MainWindow::script_name_changed)
603        );
604    
605        // establish drag&drop between scripts tree view and ScriptSlots window
606        std::vector<Gtk::TargetEntry> drag_target_gig_script;
607        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
608        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
609        m_TreeViewScripts.signal_drag_begin().connect(
610            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
611        );
612        m_TreeViewScripts.signal_drag_data_get().connect(
613            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
614        );
615    
616      // 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
617      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
618      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
619      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
620        m_TreeViewSamples.signal_drag_begin().connect(
621            sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
622        );
623      m_TreeViewSamples.signal_drag_data_get().connect(      m_TreeViewSamples.signal_drag_data_get().connect(
624          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_data_get)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_data_get)
625      );      );
# Line 242  MainWindow::MainWindow() Line 628  MainWindow::MainWindow()
628          sigc::mem_fun(*this, &MainWindow::on_sample_label_drop_drag_data_received)          sigc::mem_fun(*this, &MainWindow::on_sample_label_drop_drag_data_received)
629      );      );
630      dimreg_edit.signal_dimreg_changed().connect(      dimreg_edit.signal_dimreg_changed().connect(
631          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
632      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
633          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
634        m_RegionChooser.signal_instrument_changed().connect(
635            sigc::mem_fun(*this, &MainWindow::region_changed));
636      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
637          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
638      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
639            sigc::mem_fun(*this, &MainWindow::file_changed));
640        propDialog.signal_changed().connect(
641            sigc::mem_fun(*this, &MainWindow::file_changed));
642        midiRules.signal_changed().connect(
643          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
644    
645        dimreg_edit.signal_dimreg_to_be_changed().connect(
646            dimreg_to_be_changed_signal.make_slot());
647        dimreg_edit.signal_dimreg_changed().connect(
648            dimreg_changed_signal.make_slot());
649        dimreg_edit.signal_sample_ref_changed().connect(
650            sample_ref_changed_signal.make_slot());
651        sample_ref_changed_signal.connect(
652            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
653        );
654        samples_to_be_removed_signal.connect(
655            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
656        );
657    
658        dimreg_edit.signal_select_sample().connect(
659            sigc::mem_fun(*this, &MainWindow::select_sample)
660        );
661    
662        m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
663            sigc::hide(
664                sigc::bind(
665                    file_structure_to_be_changed_signal.make_slot(),
666                    sigc::ref(this->file)
667                )
668            )
669        );
670        m_RegionChooser.signal_instrument_struct_changed().connect(
671            sigc::hide(
672                sigc::bind(
673                    file_structure_changed_signal.make_slot(),
674                    sigc::ref(this->file)
675                )
676            )
677        );
678        m_RegionChooser.signal_region_to_be_changed().connect(
679            region_to_be_changed_signal.make_slot());
680        m_RegionChooser.signal_region_changed_signal().connect(
681            region_changed_signal.make_slot());
682    
683        note_on_signal.connect(
684            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_on_event));
685        note_off_signal.connect(
686            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_off_event));
687    
688        dimreg_all_regions.signal_toggled().connect(
689            sigc::mem_fun(*this, &MainWindow::update_dimregs));
690        dimreg_all_dimregs.signal_toggled().connect(
691            sigc::mem_fun(*this, &MainWindow::dimreg_all_dimregs_toggled));
692        dimreg_stereo.signal_toggled().connect(
693            sigc::mem_fun(*this, &MainWindow::update_dimregs));
694    
695      file = 0;      file = 0;
696      file_is_changed = false;      file_is_changed = false;
697    
698      show_all_children();      show_all_children();
699    
700        // start with a new gig file by default
701        on_action_file_new();
702    
703        // select 'Instruments' tab by default
704        // (gtk allows this only if the tab childs are visible, thats why it's here)
705        m_TreeViewNotebook.set_current_page(1);
706  }  }
707    
708  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 261  MainWindow::~MainWindow() Line 711  MainWindow::~MainWindow()
711    
712  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
713  {  {
714      return file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
715  }  }
716    
717  void MainWindow::on_action_quit()  void MainWindow::on_action_quit()
718  {  {
719      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
720      hide();      hide();
721  }  }
722    
# Line 275  void MainWindow::region_changed() Line 725  void MainWindow::region_changed()
725      m_DimRegionChooser.set_region(m_RegionChooser.get_region());      m_DimRegionChooser.set_region(m_RegionChooser.get_region());
726  }  }
727    
728    gig::Instrument* MainWindow::get_instrument()
729    {
730        gig::Instrument* instrument = 0;
731        Gtk::TreeModel::const_iterator it =
732            m_TreeView.get_selection()->get_selected();
733        if (it) {
734            Gtk::TreeModel::Row row = *it;
735            instrument = row[m_Columns.m_col_instr];
736        }
737        return instrument;
738    }
739    
740    void MainWindow::add_region_to_dimregs(gig::Region* region, bool stereo, bool all_dimregs)
741    {
742        if (all_dimregs) {
743            for (int i = 0 ; i < region->DimensionRegions ; i++) {
744                if (region->pDimensionRegions[i]) {
745                    dimreg_edit.dimregs.insert(region->pDimensionRegions[i]);
746                }
747            }
748        } else {
749            m_DimRegionChooser.get_dimregions(region, stereo, dimreg_edit.dimregs);
750        }
751    }
752    
753    void MainWindow::update_dimregs()
754    {
755        dimreg_edit.dimregs.clear();
756        bool all_regions = dimreg_all_regions.get_active();
757        bool stereo = dimreg_stereo.get_active();
758        bool all_dimregs = dimreg_all_dimregs.get_active();
759    
760        if (all_regions) {
761            gig::Instrument* instrument = get_instrument();
762            if (instrument) {
763                for (gig::Region* region = instrument->GetFirstRegion() ;
764                     region ;
765                     region = instrument->GetNextRegion()) {
766                    add_region_to_dimregs(region, stereo, all_dimregs);
767                }
768            }
769        } else {
770            gig::Region* region = m_RegionChooser.get_region();
771            if (region) {
772                add_region_to_dimregs(region, stereo, all_dimregs);
773            }
774        }
775    }
776    
777    void MainWindow::dimreg_all_dimregs_toggled()
778    {
779        dimreg_stereo.set_sensitive(!dimreg_all_dimregs.get_active());
780        update_dimregs();
781    }
782    
783  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
784  {  {
785      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      update_dimregs();
786        dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
787  }  }
788    
789  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
790  {  {
791      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      // select item in instrument menu
792        Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();
     Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();  
793      if (it) {      if (it) {
794          Gtk::TreeModel::Row row = *it;          Gtk::TreePath path(it);
795          std::cout << row[m_Columns.m_col_name] << std::endl;          int index = path[0];
796            const std::vector<Gtk::Widget*> children =
797                instrument_menu->get_children();
798            static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
799        }
800    
801          m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);      m_RegionChooser.set_instrument(get_instrument());
802      } else {  
803          m_RegionChooser.set_instrument(0);      if (Settings::singleton()->syncSamplerInstrumentSelection) {
804            switch_sampler_instrument_signal.emit(get_instrument());
805      }      }
806  }  }
807    
# Line 304  void loader_progress_callback(gig::progr Line 814  void loader_progress_callback(gig::progr
814  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
815  {  {
816      {      {
817          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
818          progress = fraction;          progress = fraction;
819      }      }
820      progress_dispatcher();      progress_dispatcher();
# Line 312  void Loader::progress_callback(float fra Line 822  void Loader::progress_callback(float fra
822    
823  void Loader::thread_function()  void Loader::thread_function()
824  {  {
825      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
826      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
827      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
828      gig = new gig::File(riff);      try {
829      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
830      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
831      progress.custom = this;          gig::progress_t progress;
832            progress.callback = loader_progress_callback;
833      gig->GetInstrument(0, &progress);          progress.custom = this;
834      printf("End\n");  
835      finished_dispatcher();          gig->GetInstrument(0, &progress);
836            printf("End\n");
837            finished_dispatcher();
838        } catch (RIFF::Exception e) {
839            error_message = e.Message;
840            error_dispatcher.emit();
841        } catch (...) {
842            error_message = _("Unknown exception occurred");
843            error_dispatcher.emit();
844        }
845  }  }
846    
847  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
848      : thread(0), filename(filename)      : filename(filename), gig(0), thread(0), progress(0.f)
849  {  {
850  }  }
851    
852  void Loader::launch()  void Loader::launch()
853  {  {
854    #ifdef OLD_THREADS
855      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
856      printf("launch thread=%x\n", thread);  #else
857        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
858    #endif
859        printf("launch thread=%p\n", static_cast<void*>(thread));
860  }  }
861    
862  float Loader::get_progress()  float Loader::get_progress()
863  {  {
864      float res;      float res;
865      {      {
866          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
867          res = progress;          res = progress;
868      }      }
869      return res;      return res;
# Line 356  Glib::Dispatcher& Loader::signal_finishe Line 879  Glib::Dispatcher& Loader::signal_finishe
879      return finished_dispatcher;      return finished_dispatcher;
880  }  }
881    
882  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
883    {
884        return error_dispatcher;
885    }
886    
887    void saver_progress_callback(gig::progress_t* progress)
888    {
889        Saver* saver = static_cast<Saver*>(progress->custom);
890        saver->progress_callback(progress->factor);
891    }
892    
893    void Saver::progress_callback(float fraction)
894    {
895        {
896            Glib::Threads::Mutex::Lock lock(progressMutex);
897            progress = fraction;
898        }
899        progress_dispatcher.emit();
900    }
901    
902    void Saver::thread_function()
903    {
904        printf("thread_function self=%p\n",
905               static_cast<void*>(Glib::Threads::Thread::self()));
906        printf("Start %s\n", filename.c_str());
907        try {
908            gig::progress_t progress;
909            progress.callback = saver_progress_callback;
910            progress.custom = this;
911    
912            // if no filename was provided, that means "save", if filename was provided means "save as"
913            if (filename.empty()) {
914                if (!Settings::singleton()->saveWithTemporaryFile) {
915                    // save directly over the existing .gig file
916                    // (requires less disk space than solution below
917                    // but may be slower)
918                    gig->Save(&progress);
919                } else {
920                    // save the file as separate temporary file first,
921                    // then move the saved file over the old file
922                    // (may result in performance speedup during save)
923                    String tmpname = filename + ".TMP";
924                    gig->Save(tmpname, &progress);
925                    #if defined(WIN32)
926                    if (!DeleteFile(filename.c_str())) {
927                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
928                    }
929                    #else // POSIX ...
930                    if (unlink(filename.c_str())) {
931                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
932                    }
933                    #endif
934                    if (rename(tmpname.c_str(), filename.c_str())) {
935                        #if defined(WIN32)
936                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
937                        #else
938                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
939                        #endif
940                    }
941                }
942            } else {
943                gig->Save(filename, &progress);
944            }
945    
946            printf("End\n");
947            finished_dispatcher.emit();
948        } catch (RIFF::Exception e) {
949            error_message = e.Message;
950            error_dispatcher.emit();
951        } catch (...) {
952            error_message = _("Unknown exception occurred");
953            error_dispatcher.emit();
954        }
955    }
956    
957    Saver::Saver(gig::File* file, Glib::ustring filename)
958        : gig(file), filename(filename), thread(0), progress(0.f)
959    {
960    }
961    
962    void Saver::launch()
963    {
964    #ifdef OLD_THREADS
965        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
966    #else
967        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
968    #endif
969        printf("launch thread=%p\n", static_cast<void*>(thread));
970    }
971    
972    float Saver::get_progress()
973    {
974        float res;
975        {
976            Glib::Threads::Mutex::Lock lock(progressMutex);
977            res = progress;
978        }
979        return res;
980    }
981    
982    Glib::Dispatcher& Saver::signal_progress()
983    {
984        return progress_dispatcher;
985    }
986    
987    Glib::Dispatcher& Saver::signal_finished()
988    {
989        return finished_dispatcher;
990    }
991    
992    Glib::Dispatcher& Saver::signal_error()
993    {
994        return error_dispatcher;
995    }
996    
997    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
998      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
999  {  {
1000      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1001      show_all_children();      show_all_children();
1002        resize(600,50);
1003  }  }
1004    
1005  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
1006  // 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.
1007  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();  
1008      // forget all samples that ought to be imported      // forget all samples that ought to be imported
1009      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
1010      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1011      m_refTreeModel->clear();      m_refTreeModel->clear();
1012      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1013        m_refScriptsTreeModel->clear();
1014        // remove all entries from "Instrument" menu
1015        while (!instrument_menu->get_children().empty()) {
1016            remove_instrument_from_menu(0);
1017        }
1018      // free libgig's gig::File instance      // free libgig's gig::File instance
1019      if (file) {      if (file && !file_is_shared) delete file;
1020          delete file;      file = NULL;
1021          file = NULL;      set_file_is_shared(false);
1022    }
1023    
1024    void MainWindow::__refreshEntireGUI() {
1025        // clear the samples and instruments tree views
1026        m_refTreeModel->clear();
1027        m_refSamplesTreeModel->clear();
1028        m_refScriptsTreeModel->clear();
1029        // remove all entries from "Instrument" menu
1030        while (!instrument_menu->get_children().empty()) {
1031            remove_instrument_from_menu(0);
1032      }      }
1033    
1034        if (!this->file) return;
1035    
1036        load_gig(
1037            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1038        );
1039  }  }
1040    
1041  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
1042  {  {
1043      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
1044    
1045        if (file_is_shared && !leaving_shared_mode_dialog()) return;
1046    
1047      // clear all GUI elements      // clear all GUI elements
1048      __clear();      __clear();
# Line 396  void MainWindow::on_action_file_new() Line 1050  void MainWindow::on_action_file_new()
1050      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
1051      // already add one new instrument by default      // already add one new instrument by default
1052      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
1053      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
1054      // update GUI with that new gig::File      // update GUI with that new gig::File
1055      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
1056  }  }
# Line 409  bool MainWindow::close_confirmation_dial Line 1063  bool MainWindow::close_confirmation_dial
1063      g_free(msg);      g_free(msg);
1064      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."));
1065      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1066      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1067      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);      dialog.add_button(file_has_name ? _("_Save") : _("Save _As"), Gtk::RESPONSE_YES);
1068      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1069      int response = dialog.run();      int response = dialog.run();
1070      if (response == Gtk::RESPONSE_YES) return file_save();      dialog.hide();
1071      return response != Gtk::RESPONSE_CANCEL;  
1072        // user decided to exit app without saving
1073        if (response == Gtk::RESPONSE_NO) return true;
1074    
1075        // user cancelled dialog, thus don't close app
1076        if (response == Gtk::RESPONSE_CANCEL) return false;
1077    
1078        // TODO: the following return valid is disabled and hard coded instead for
1079        // now, due to the fact that saving with progress bar is now implemented
1080        // asynchronously, as a result the app does not close automatically anymore
1081        // after saving the file has completed
1082        //
1083        //   if (response == Gtk::RESPONSE_YES) return file_save();
1084        //   return response != Gtk::RESPONSE_CANCEL;
1085        //
1086        if (response == Gtk::RESPONSE_YES) file_save();
1087        return false; // always prevent closing the app for now (see comment above)
1088    }
1089    
1090    bool MainWindow::leaving_shared_mode_dialog() {
1091        Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
1092        Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
1093        dialog.set_secondary_text(
1094            _("If you proceed to work on another instrument file, it won't be "
1095              "used by the sampler until you tell the sampler explicitly to "
1096              "load it."));
1097        dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1098        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1099        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1100        int response = dialog.run();
1101        dialog.hide();
1102        return response == Gtk::RESPONSE_YES;
1103  }  }
1104    
1105  void MainWindow::on_action_file_open()  void MainWindow::on_action_file_open()
1106  {  {
1107      if (file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
1108    
1109        if (file_is_shared && !leaving_shared_mode_dialog()) return;
1110    
1111      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1112      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1113      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1114      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1115    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1116      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1117      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1118    #else
1119        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1120        filter->add_pattern("*.gig");
1121    #endif
1122      dialog.set_filter(filter);      dialog.set_filter(filter);
1123      if (current_dir != "") {      if (current_gig_dir != "") {
1124          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1125      }      }
1126      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1127          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1128          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1129          __clear();          printf("on_action_file_open self=%p\n",
1130          printf("on_action_file_open self=%x\n", Glib::Thread::self());                 static_cast<void*>(Glib::Threads::Thread::self()));
1131          load_file(filename.c_str());          load_file(filename.c_str());
1132          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1133      }      }
1134  }  }
1135    
1136  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1137  {  {
1138      load_dialog = new LoadDialog("Loading...", *this);      __clear();
1139      load_dialog->show_all();  
1140      loader = new Loader(strdup(name));      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1141            _("Loading") +  Glib::ustring(" '") +
1142            Glib::filename_display_basename(name) + "' ...",
1143            *this
1144        );
1145        progress_dialog->show_all();
1146        loader = new Loader(name); //FIXME: memory leak!
1147      loader->signal_progress().connect(      loader->signal_progress().connect(
1148          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1149      loader->signal_finished().connect(      loader->signal_finished().connect(
1150          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1151        loader->signal_error().connect(
1152            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1153      loader->launch();      loader->launch();
1154  }  }
1155    
# Line 460  void MainWindow::load_instrument(gig::In Line 1160  void MainWindow::load_instrument(gig::In
1160          msg.run();          msg.run();
1161          Gtk::Main::quit();          Gtk::Main::quit();
1162      }      }
1163        // clear all GUI elements
1164        __clear();
1165        // load the instrument
1166      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1167      load_gig(pFile, 0 /*file name*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1168      //TODO: automatically select the given instrument      // automatically select the given instrument
1169        int i = 0;
1170        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1171             instrument = pFile->GetNextInstrument(), ++i)
1172        {
1173            if (instrument == instr) {
1174                // select item in "instruments" tree view
1175                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1176                // make sure the selected item in the "instruments" tree view is
1177                // visible (scroll to it)
1178                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1179                // select item in instrument menu
1180                {
1181                    const std::vector<Gtk::Widget*> children =
1182                        instrument_menu->get_children();
1183                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1184                }
1185                // update region chooser and dimension region chooser
1186                m_RegionChooser.set_instrument(instr);
1187                break;
1188            }
1189        }
1190  }  }
1191    
1192  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1193  {  {
1194      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1195  }  }
1196    
1197  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1198  {  {
1199      printf("Loader finished!\n");      printf("Loader finished!\n");
1200      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
1201      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1202      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1203        progress_dialog->hide();
1204    }
1205    
1206    void MainWindow::on_loader_error()
1207    {
1208        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1209        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1210        msg.run();
1211        progress_dialog->hide();
1212  }  }
1213    
1214  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 483  void MainWindow::on_action_file_save() Line 1216  void MainWindow::on_action_file_save()
1216      file_save();      file_save();
1217  }  }
1218    
1219  bool MainWindow::file_save()  bool MainWindow::check_if_savable()
1220  {  {
1221      if (!file) return false;      if (!file) return false;
     if (!file_has_name) return file_save_as();  
1222    
1223      std::cout << "Saving file\n" << std::flush;      if (!file->GetFirstSample()) {
1224      try {          Gtk::MessageDialog(*this, _("The file could not be saved "
1225          file->Save();                                      "because it contains no samples"),
1226          if (file_is_changed) {                             false, Gtk::MESSAGE_ERROR).run();
             set_title(get_title().substr(1));  
             file_is_changed = false;  
         }  
     } catch (RIFF::Exception e) {  
         Glib::ustring txt = "Could not save file: " + e.Message;  
         Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
         msg.run();  
1227          return false;          return false;
1228      }      }
1229      std::cout << "Saving file done\n" << std::flush;  
1230      __import_queued_samples();      for (gig::Instrument* instrument = file->GetFirstInstrument() ; instrument ;
1231             instrument = file->GetNextInstrument()) {
1232            if (!instrument->GetFirstRegion()) {
1233                Gtk::MessageDialog(*this, _("The file could not be saved "
1234                                            "because there are instruments "
1235                                            "that have no regions"),
1236                                   false, Gtk::MESSAGE_ERROR).run();
1237                return false;
1238            }
1239        }
1240        return true;
1241    }
1242    
1243    bool MainWindow::file_save()
1244    {
1245        if (!check_if_savable()) return false;
1246        if (!file_is_shared && !file_has_name) return file_save_as();
1247    
1248        std::cout << "Saving file\n" << std::flush;
1249        file_structure_to_be_changed_signal.emit(this->file);
1250    
1251        progress_dialog = new ProgressDialog( //FIXME: memory leak!
1252            _("Saving") +  Glib::ustring(" '") +
1253            Glib::filename_display_basename(this->filename) + "' ...",
1254            *this
1255        );
1256        progress_dialog->show_all();
1257        saver = new Saver(this->file); //FIXME: memory leak!
1258        saver->signal_progress().connect(
1259            sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1260        saver->signal_finished().connect(
1261            sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1262        saver->signal_error().connect(
1263            sigc::mem_fun(*this, &MainWindow::on_saver_error));
1264        saver->launch();
1265    
1266      return true;      return true;
1267  }  }
1268    
1269    void MainWindow::on_saver_progress()
1270    {
1271        progress_dialog->set_fraction(saver->get_progress());
1272    }
1273    
1274    void MainWindow::on_saver_error()
1275    {
1276        file_structure_changed_signal.emit(this->file);
1277        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1278        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1279        msg.run();
1280    }
1281    
1282    void MainWindow::on_saver_finished()
1283    {
1284        this->file = saver->gig;
1285        this->filename = saver->filename;
1286        current_gig_dir = Glib::path_get_dirname(filename);
1287        set_title(Glib::filename_display_basename(filename));
1288        file_has_name = true;
1289        file_is_changed = false;
1290        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1291        __import_queued_samples();
1292        std::cout << "Importing queued samples done.\n" << std::flush;
1293    
1294        file_structure_changed_signal.emit(this->file);
1295    
1296        __refreshEntireGUI();
1297        progress_dialog->hide();
1298    }
1299    
1300  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
1301  {  {
1302        if (!check_if_savable()) return;
1303      file_save_as();      file_save_as();
1304  }  }
1305    
1306  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1307  {  {
1308      if (!file) return false;      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1309      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1310      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
     dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);  
1311      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  
1312      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1313      // TODO: an overwrite dialog for gtkmm < 2.8  
1314  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1315      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1316      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1317    #else
1318        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1319        filter->add_pattern("*.gig");
1320    #endif
1321      dialog.set_filter(filter);      dialog.set_filter(filter);
1322    
1323      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1324          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1325      } else if (current_dir != "") {      {
1326          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1327            std::string dir = Glib::path_get_dirname(filename);
1328            basename = std::string(_("copy_of_")) + basename;
1329            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1330            if (Glib::path_is_absolute(filename)) {
1331                dialog.set_filename(copyFileName);
1332            } else {
1333                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1334            }
1335            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1336      }      }
1337      dialog.set_current_name(Glib::filename_display_basename(filename));  
1338        // show warning in the dialog
1339        Gtk::HBox descriptionArea;
1340        descriptionArea.set_spacing(15);
1341        Gtk::Image warningIcon;
1342        warningIcon.set_from_icon_name("dialog-warning",
1343                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1344        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1345    #if GTKMM_MAJOR_VERSION < 3
1346        view::WrapLabel description;
1347    #else
1348        Gtk::Label description;
1349        description.set_line_wrap();
1350    #endif
1351        description.set_markup(
1352            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1353              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1354              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1355              "to the same .gig file. Using "
1356              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1357              "same .gig file will end up in corrupted sample wave data!\n")
1358        );
1359        descriptionArea.pack_start(description);
1360        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1361        descriptionArea.show_all();
1362    
1363      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1364          try {          std::string filename = dialog.get_filename();
1365              std::string filename = dialog.get_filename();          if (!Glib::str_has_suffix(filename, ".gig")) {
1366              if (!Glib::str_has_suffix(filename, ".gig")) {              filename += ".gig";
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_dir = Glib::path_get_dirname(filename);  
             set_title(Glib::filename_display_basename(filename));  
             file_has_name = true;  
             file_is_changed = false;  
         } catch (RIFF::Exception e) {  
             Glib::ustring txt = "Could not save file: " + e.Message;  
             Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
             msg.run();  
             return false;  
1367          }          }
1368          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1369    
1370            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1371                _("Saving") +  Glib::ustring(" '") +
1372                Glib::filename_display_basename(filename) + "' ...",
1373                *this
1374            );
1375            progress_dialog->show_all();
1376    
1377            saver = new Saver(file, filename); //FIXME: memory leak!
1378            saver->signal_progress().connect(
1379                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1380            saver->signal_finished().connect(
1381                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1382            saver->signal_error().connect(
1383                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1384            saver->launch();
1385    
1386          return true;          return true;
1387      }      }
1388      return false;      return false;
# Line 563  bool MainWindow::file_save_as() Line 1392  bool MainWindow::file_save_as()
1392  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1393      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1394      Glib::ustring error_files;      Glib::ustring error_files;
1395      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1396      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1397           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1398          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",(*iter).sample_path.c_str());
1399          SF_INFO info;          SF_INFO info;
1400          info.format = 0;          info.format = 0;
1401          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
1402            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1403          try {          try {
1404              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1405              // determine sample's bit depth              // determine sample's bit depth
1406              int bitdepth;              int bitdepth;
1407              switch (info.format & 0xff) {              switch (info.format & 0xff) {
1408                  case SF_FORMAT_PCM_S8:                  case SF_FORMAT_PCM_S8:
                     bitdepth = 16; // we simply convert to 16 bit for now  
                     break;  
1409                  case SF_FORMAT_PCM_16:                  case SF_FORMAT_PCM_16:
1410                    case SF_FORMAT_PCM_U8:
1411                      bitdepth = 16;                      bitdepth = 16;
1412                      break;                      break;
1413                  case SF_FORMAT_PCM_24:                  case SF_FORMAT_PCM_24:
                     bitdepth = 32; // we simply convert to 32 bit for now  
                     break;  
1414                  case SF_FORMAT_PCM_32:                  case SF_FORMAT_PCM_32:
                     bitdepth = 32;  
                     break;  
                 case SF_FORMAT_PCM_U8:  
                     bitdepth = 16; // we simply convert to 16 bit for now  
                     break;  
1415                  case SF_FORMAT_FLOAT:                  case SF_FORMAT_FLOAT:
                     bitdepth = 32;  
                     break;  
1416                  case SF_FORMAT_DOUBLE:                  case SF_FORMAT_DOUBLE:
1417                      bitdepth = 32; // I guess we will always truncate this to 32 bit                      bitdepth = 24;
1418                      break;                      break;
1419                  default:                  default:
1420                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1421                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1422              }              }
1423              // allocate appropriate copy buffer (TODO: for now we copy  
1424              // it in one piece, might be tough for very long samples)              const int bufsize = 10000;
             // and copy sample data into buffer  
             int8_t* buffer = NULL;  
1425              switch (bitdepth) {              switch (bitdepth) {
1426                  case 16:                  case 16: {
1427                      buffer = new int8_t[2 * info.channels * info.frames];                      short* buffer = new short[bufsize * info.channels];
1428                      // libsndfile does the conversion for us (if needed)                      sf_count_t cnt = info.frames;
1429                      sf_readf_short(hFile, (short*) buffer, info.frames);                      while (cnt) {
1430                            // libsndfile does the conversion for us (if needed)
1431                            int n = sf_readf_short(hFile, buffer, bufsize);
1432                            // write from buffer directly (physically) into .gig file
1433                            iter->gig_sample->Write(buffer, n);
1434                            cnt -= n;
1435                        }
1436                        delete[] buffer;
1437                      break;                      break;
1438                  case 32:                  }
1439                      buffer = new int8_t[4 * info.channels * info.frames];                  case 24: {
1440                      // libsndfile does the conversion for us (if needed)                      int* srcbuf = new int[bufsize * info.channels];
1441                      sf_readf_int(hFile, (int*) buffer, info.frames);                      uint8_t* dstbuf = new uint8_t[bufsize * 3 * info.channels];
1442                        sf_count_t cnt = info.frames;
1443                        while (cnt) {
1444                            // libsndfile returns 32 bits, convert to 24
1445                            int n = sf_readf_int(hFile, srcbuf, bufsize);
1446                            int j = 0;
1447                            for (int i = 0 ; i < n * info.channels ; i++) {
1448                                dstbuf[j++] = srcbuf[i] >> 8;
1449                                dstbuf[j++] = srcbuf[i] >> 16;
1450                                dstbuf[j++] = srcbuf[i] >> 24;
1451                            }
1452                            // write from buffer directly (physically) into .gig file
1453                            iter->gig_sample->Write(dstbuf, n);
1454                            cnt -= n;
1455                        }
1456                        delete[] srcbuf;
1457                        delete[] dstbuf;
1458                      break;                      break;
1459                    }
1460              }              }
             // write from buffer directly (physically) into .gig file  
             (*iter).gig_sample->Write(buffer, info.frames);  
1461              // cleanup              // cleanup
1462              sf_close(hFile);              sf_close(hFile);
1463              delete[] buffer;              // let the sampler re-cache the sample if needed
1464                sample_changed_signal.emit(iter->gig_sample);
1465              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1466              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1467              std::list<SampleImportItem>::iterator cur = iter;              std::list<SampleImportItem>::iterator cur = iter;
# Line 628  void MainWindow::__import_queued_samples Line 1469  void MainWindow::__import_queued_samples
1469              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1470          } catch (std::string what) {          } catch (std::string what) {
1471              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1472              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1473              error_files += (*iter).sample_path += " (" + what + ")";              error_files += (*iter).sample_path += " (" + what + ")";
1474              ++iter;              ++iter;
1475          }          }
1476      }      }
1477      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1478      if (error_files.size()) {      if (!error_files.empty()) {
1479          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;
1480          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1481          msg.run();          msg.run();
1482      }      }
# Line 647  void MainWindow::on_action_file_properti Line 1488  void MainWindow::on_action_file_properti
1488      propDialog.deiconify();      propDialog.deiconify();
1489  }  }
1490    
1491    void MainWindow::on_action_warn_user_on_extensions() {
1492        Settings::singleton()->warnUserOnExtensions =
1493            !Settings::singleton()->warnUserOnExtensions;
1494    }
1495    
1496    void MainWindow::on_action_sync_sampler_instrument_selection() {
1497        Settings::singleton()->syncSamplerInstrumentSelection =
1498            !Settings::singleton()->syncSamplerInstrumentSelection;
1499    }
1500    
1501    void MainWindow::on_action_move_root_note_with_region_moved() {
1502        Settings::singleton()->moveRootNoteWithRegionMoved =
1503            !Settings::singleton()->moveRootNoteWithRegionMoved;
1504    }
1505    
1506  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1507  {  {
 #ifdef ABOUT_DIALOG  
1508      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1509    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1510        dialog.set_program_name("Gigedit");
1511    #else
1512        dialog.set_name("Gigedit");
1513    #endif
1514      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1515        dialog.set_copyright("Copyright (C) 2006-2016 Andreas Persson");
1516        const std::string sComment =
1517            _("Built " __DATE__ "\nUsing ") +
1518            ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1519            _(
1520                "Gigedit is released under the GNU General Public License.\n"
1521                "\n"
1522                "This program is distributed WITHOUT ANY WARRANTY; So better "
1523                "backup your Gigasampler/GigaStudio files before editing them with "
1524                "this application.\n"
1525                "\n"
1526                "Please report bugs to: http://bugs.linuxsampler.org"
1527            );
1528        dialog.set_comments(sComment.c_str());
1529        dialog.set_website("http://www.linuxsampler.org");
1530        dialog.set_website_label("http://www.linuxsampler.org");
1531      dialog.run();      dialog.run();
 #endif  
1532  }  }
1533    
1534  PropDialog::PropDialog()  PropDialog::PropDialog()
1535      : table(2,1)      : eFileFormat(_("File Format")),
1536  {        eName(_("Name")),
1537          eCreationDate(_("Creation date")),
1538          eComments(_("Comments")),
1539          eProduct(_("Product")),
1540          eCopyright(_("Copyright")),
1541          eArtists(_("Artists")),
1542          eGenre(_("Genre")),
1543          eKeywords(_("Keywords")),
1544          eEngineer(_("Engineer")),
1545          eTechnician(_("Technician")),
1546          eSoftware(_("Software")),
1547          eMedium(_("Medium")),
1548          eSource(_("Source")),
1549          eSourceForm(_("Source form")),
1550          eCommissioned(_("Commissioned")),
1551          eSubject(_("Subject")),
1552          quitButton(_("_Close"), true),
1553          table(2, 1),
1554          m_file(NULL)
1555    {
1556        set_title(_("File Properties"));
1557        eName.set_width_chars(50);
1558    
1559        connect(eName, &DLS::Info::Name);
1560        connect(eCreationDate, &DLS::Info::CreationDate);
1561        connect(eComments, &DLS::Info::Comments);
1562        connect(eProduct, &DLS::Info::Product);
1563        connect(eCopyright, &DLS::Info::Copyright);
1564        connect(eArtists, &DLS::Info::Artists);
1565        connect(eGenre, &DLS::Info::Genre);
1566        connect(eKeywords, &DLS::Info::Keywords);
1567        connect(eEngineer, &DLS::Info::Engineer);
1568        connect(eTechnician, &DLS::Info::Technician);
1569        connect(eSoftware, &DLS::Info::Software);
1570        connect(eMedium, &DLS::Info::Medium);
1571        connect(eSource, &DLS::Info::Source);
1572        connect(eSourceForm, &DLS::Info::SourceForm);
1573        connect(eCommissioned, &DLS::Info::Commissioned);
1574        connect(eSubject, &DLS::Info::Subject);
1575    
1576        table.add(eFileFormat);
1577        table.add(eName);
1578        table.add(eCreationDate);
1579        table.add(eComments);
1580        table.add(eProduct);
1581        table.add(eCopyright);
1582        table.add(eArtists);
1583        table.add(eGenre);
1584        table.add(eKeywords);
1585        table.add(eEngineer);
1586        table.add(eTechnician);
1587        table.add(eSoftware);
1588        table.add(eMedium);
1589        table.add(eSource);
1590        table.add(eSourceForm);
1591        table.add(eCommissioned);
1592        table.add(eSubject);
1593    
1594      table.set_col_spacings(5);      table.set_col_spacings(5);
1595      const char* propLabels[] = {      add(vbox);
1596          "Name:",      table.set_border_width(5);
1597          "CreationDate:",      vbox.add(table);
1598          "Comments:", // TODO: multiline      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
1599          "Product:",      buttonBox.set_layout(Gtk::BUTTONBOX_END);
1600          "Copyright:",      buttonBox.set_border_width(5);
1601          "Artists:",      buttonBox.show();
1602          "Genre:",      buttonBox.pack_start(quitButton);
1603          "Keywords:",      quitButton.set_can_default();
1604          "Engineer:",      quitButton.grab_focus();
1605          "Technician:",      quitButton.signal_clicked().connect(
1606          "Software:", // TODO: readonly          sigc::mem_fun(*this, &PropDialog::hide));
1607          "Medium:",      eFileFormat.signal_value_changed().connect(
1608          "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);  
     }  
1609    
1610      add(table);      quitButton.show();
1611      // add_button(Gtk::Stock::CANCEL, 0);      vbox.show();
     // add_button(Gtk::Stock::OK, 1);  
1612      show_all_children();      show_all_children();
1613  }  }
1614    
1615    void PropDialog::set_file(gig::File* file)
1616    {
1617        m_file = file;
1618    
1619        // update file format version combo box
1620        const std::string sGiga = "Gigasampler/GigaStudio v";
1621        const int major = file->pVersion->major;
1622        std::vector<std::string> txts;
1623        std::vector<int> values;
1624        txts.push_back(sGiga + "2"); values.push_back(2);
1625        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1626        if (major != 2 && major != 3) {
1627            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1628        }
1629        std::vector<const char*> texts;
1630        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1631        texts.push_back(NULL); values.push_back(0);
1632        eFileFormat.set_choices(&texts[0], &values[0]);
1633        eFileFormat.set_value(major);
1634    }
1635    
1636    void PropDialog::onFileFormatChanged() {
1637        const int major = eFileFormat.get_value();
1638        if (m_file) m_file->pVersion->major = major;
1639    }
1640    
1641  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_info(DLS::Info* info)
1642  {  {
1643      entry[0].set_text(info->Name);      update(info);
1644      entry[1].set_text(info->CreationDate);  }
1645      entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));  
1646      entry[3].set_text(info->Product);  
1647      entry[4].set_text(info->Copyright);  void InstrumentProps::set_Name(const gig::String& name)
1648      entry[5].set_text(info->Artists);  {
1649      entry[6].set_text(info->Genre);      m->pInfo->Name = name;
1650      entry[7].set_text(info->Keywords);  }
1651      entry[8].set_text(info->Engineer);  
1652      entry[9].set_text(info->Technician);  void InstrumentProps::update_name()
1653      entry[10].set_text(info->Software);  {
1654      entry[11].set_text(info->Medium);      update_model++;
1655      entry[12].set_text(info->Source);      eName.set_value(m->pInfo->Name);
1656      entry[13].set_text(info->SourceForm);      update_model--;
1657      entry[14].set_text(info->Commissioned);  }
1658      entry[15].set_text(info->Subject);  
1659  }  void InstrumentProps::set_IsDrum(bool value)
1660    {
1661  void InstrumentProps::add_prop(LabelWidget& prop)      m->IsDrum = value;
1662  {  }
1663      table.attach(prop.label, 0, 1, rowno, rowno + 1,  
1664                   Gtk::FILL, Gtk::SHRINK);  void InstrumentProps::set_MIDIBank(uint16_t value)
1665      table.attach(prop.widget, 1, 2, rowno, rowno + 1,  {
1666                   Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);      m->MIDIBank = value;
1667      rowno++;  }
1668      prop.signal_changed_by_user().connect(instrument_changed.make_slot());  
1669  }  void InstrumentProps::set_MIDIProgram(uint32_t value)
   
 InstrumentProps::InstrumentProps()  
     : table(2,1),  
       quitButton(Gtk::Stock::CLOSE),  
       eName("Name"),  
       eIsDrum("IsDrum"),  
       eMIDIBank("MIDIBank", 0, 16383),  
       eMIDIProgram("MIDIProgram"),  
       eAttenuation("Attenuation", 0, 96, 0, 1),  
       eGainPlus6("Gain +6dB", eAttenuation, -6),  
       eEffectSend("EffectSend", 0, 65535),  
       eFineTune("FineTune", -8400, 8400),  
       ePitchbendRange("PitchbendRange", 0, 12),  
       ePianoReleaseMode("PianoReleaseMode"),  
       eDimensionKeyRangeLow("DimensionKeyRangeLow"),  
       eDimensionKeyRangeHigh("DimensionKeyRangeHigh")  
1670  {  {
1671      set_title("Instrument properties");      m->MIDIProgram = value;
1672    }
1673    
1674    InstrumentProps::InstrumentProps() :
1675        quitButton(_("_Close"), true),
1676        table(2,1),
1677        eName(_("Name")),
1678        eIsDrum(_("Is drum")),
1679        eMIDIBank(_("MIDI bank"), 0, 16383),
1680        eMIDIProgram(_("MIDI program")),
1681        eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1682        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1683        eEffectSend(_("Effect send"), 0, 65535),
1684        eFineTune(_("Fine tune"), -8400, 8400),
1685        ePitchbendRange(_("Pitchbend range"), 0, 12),
1686        ePianoReleaseMode(_("Piano release mode")),
1687        eDimensionKeyRangeLow(_("Keyswitching range low")),
1688        eDimensionKeyRangeHigh(_("Keyswitching range high"))
1689    {
1690        set_title(_("Instrument Properties"));
1691    
1692        eDimensionKeyRangeLow.set_tip(
1693            _("start of the keyboard area which should switch the "
1694              "\"keyswitching\" dimension")
1695        );
1696        eDimensionKeyRangeHigh.set_tip(
1697            _("end of the keyboard area which should switch the "
1698              "\"keyswitching\" dimension")
1699        );
1700    
1701        connect(eName, &InstrumentProps::set_Name);
1702        connect(eIsDrum, &InstrumentProps::set_IsDrum);
1703        connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1704        connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
1705        connect(eAttenuation, &gig::Instrument::Attenuation);
1706        connect(eGainPlus6, &gig::Instrument::Attenuation);
1707        connect(eEffectSend, &gig::Instrument::EffectSend);
1708        connect(eFineTune, &gig::Instrument::FineTune);
1709        connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1710        connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1711        connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1712                &gig::Instrument::DimensionKeyRange);
1713    
1714        eName.signal_value_changed().connect(sig_name_changed.make_slot());
1715    
     rowno = 0;  
1716      table.set_col_spacings(5);      table.set_col_spacings(5);
1717    
1718      add_prop(eName);      table.add(eName);
1719      add_prop(eIsDrum);      table.add(eIsDrum);
1720      add_prop(eMIDIBank);      table.add(eMIDIBank);
1721      add_prop(eMIDIProgram);      table.add(eMIDIProgram);
1722      add_prop(eAttenuation);      table.add(eAttenuation);
1723      add_prop(eGainPlus6);      table.add(eGainPlus6);
1724      add_prop(eEffectSend);      table.add(eEffectSend);
1725      add_prop(eFineTune);      table.add(eFineTune);
1726      add_prop(ePitchbendRange);      table.add(ePitchbendRange);
1727      add_prop(ePianoReleaseMode);      table.add(ePianoReleaseMode);
1728      add_prop(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
1729      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));  
1730    
1731      add(vbox);      add(vbox);
1732      table.set_border_width(5);      table.set_border_width(5);
# Line 770  InstrumentProps::InstrumentProps() Line 1737  InstrumentProps::InstrumentProps()
1737      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1738      buttonBox.show();      buttonBox.show();
1739      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1740      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1741      quitButton.grab_focus();      quitButton.grab_focus();
1742    
1743      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 783  InstrumentProps::InstrumentProps() Line 1750  InstrumentProps::InstrumentProps()
1750    
1751  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1752  {  {
1753      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);  
 }  
1754    
1755  void InstrumentProps::key_range_low_changed()      update_model++;
1756  {      eName.set_value(instrument->pInfo->Name);
1757      double l = eDimensionKeyRangeLow.get_value();      eIsDrum.set_value(instrument->IsDrum);
1758      double h = eDimensionKeyRangeHigh.get_value();      eMIDIBank.set_value(instrument->MIDIBank);
1759      if (h < l) eDimensionKeyRangeHigh.set_value(l);      eMIDIProgram.set_value(instrument->MIDIProgram);
1760        update_model--;
1761  }  }
1762    
 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;  
 }  
1763    
1764  void MainWindow::file_changed()  void MainWindow::file_changed()
1765  {  {
# Line 826  void MainWindow::file_changed() Line 1769  void MainWindow::file_changed()
1769      }      }
1770  }  }
1771    
1772  void MainWindow::load_gig(gig::File* gig, const char* filename)  void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1773        sample_ref_count.clear();
1774        
1775        if (!gig) return;
1776    
1777        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1778             instrument = gig->GetNextInstrument())
1779        {
1780            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1781                 rgn = instrument->GetNextRegion())
1782            {
1783                for (int i = 0; i < 256; ++i) {
1784                    if (!rgn->pDimensionRegions[i]) continue;
1785                    if (rgn->pDimensionRegions[i]->pSample) {
1786                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1787                    }
1788                }
1789            }
1790        }
1791    }
1792    
1793    void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1794  {  {
1795      file = 0;      file = 0;
1796        set_file_is_shared(isSharedInstrument);
1797    
1798      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
1799            (filename && strlen(filename) > 0) ?
1800                filename : (!gig->GetFileName().empty()) ?
1801                    gig->GetFileName() : _("Unsaved Gig File");
1802      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1803      file_has_name = filename;      file_has_name = filename;
1804      file_is_changed = false;      file_is_changed = false;
1805    
1806        propDialog.set_file(gig);
1807      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1808    
1809      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;  
1810      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1811           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument()) {
1812            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1813    
1814          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1815          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1816          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_name] = name;
1817          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1818          // create a menu item for this instrument  
1819          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++;  
1820      }      }
1821      instrument_menu->show();      instrument_name_connection.unblock();
1822      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1823    
1824        updateSampleRefCountMap(gig);
1825    
1826      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1827          if (group->Name != "") {          if (group->Name != "") {
1828              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1829              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1830              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1831              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1832              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1833              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 875  void MainWindow::load_gig(gig::File* gig Line 1835  void MainWindow::load_gig(gig::File* gig
1835                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1836                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1837                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1838                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1839                        gig_to_utf8(sample->pInfo->Name);
1840                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1841                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1842                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1843                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1844                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1845              }              }
1846          }          }
1847      }      }
1848        
1849        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1850            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1851    
1852            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1853            Gtk::TreeModel::Row rowGroup = *iterGroup;
1854            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1855            rowGroup[m_ScriptsModel.m_col_group]  = group;
1856            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1857            for (int s = 0; group->GetScript(s); ++s) {
1858                gig::Script* script = group->GetScript(s);
1859    
1860                Gtk::TreeModel::iterator iterScript =
1861                    m_refScriptsTreeModel->append(rowGroup.children());
1862                Gtk::TreeModel::Row rowScript = *iterScript;
1863                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1864                rowScript[m_ScriptsModel.m_col_script] = script;
1865                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1866            }
1867        }
1868        // unfold all sample groups & script groups by default
1869        m_TreeViewSamples.expand_all();
1870        m_TreeViewScripts.expand_all();
1871    
1872      file = gig;      file = gig;
1873    
1874      // select the first instrument      // select the first instrument
1875      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1876      tree_sel_ref->select(Gtk::TreePath("0"));  
1877        instr_props_set_instrument();
1878        gig::Instrument* instrument = get_instrument();
1879        if (instrument) {
1880            midiRules.set_instrument(instrument);
1881        }
1882    }
1883    
1884    bool MainWindow::instr_props_set_instrument()
1885    {
1886        instrumentProps.signal_name_changed().clear();
1887    
1888        Gtk::TreeModel::const_iterator it =
1889            m_TreeView.get_selection()->get_selected();
1890        if (it) {
1891            Gtk::TreeModel::Row row = *it;
1892            gig::Instrument* instrument = row[m_Columns.m_col_instr];
1893    
1894            instrumentProps.set_instrument(instrument);
1895    
1896            // make sure instrument tree is updated when user changes the
1897            // instrument name in instrument properties window
1898            instrumentProps.signal_name_changed().connect(
1899                sigc::bind(
1900                    sigc::mem_fun(*this,
1901                                  &MainWindow::instr_name_changed_by_instr_props),
1902                    it));
1903        } else {
1904            instrumentProps.hide();
1905        }
1906        return it;
1907  }  }
1908    
1909  void MainWindow::show_instr_props()  void MainWindow::show_instr_props()
1910  {  {
1911      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (instr_props_set_instrument()) {
1912      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();          instrumentProps.show();
1913      if (it)          instrumentProps.deiconify();
1914        }
1915    }
1916    
1917    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
1918    {
1919        Gtk::TreeModel::Row row = *it;
1920        Glib::ustring name = row[m_Columns.m_col_name];
1921    
1922        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1923        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
1924        if (gigname != name) {
1925            row[m_Columns.m_col_name] = gigname;
1926        }
1927    }
1928    
1929    void MainWindow::show_midi_rules()
1930    {
1931        if (gig::Instrument* instrument = get_instrument())
1932      {      {
1933          Gtk::TreeModel::Row row = *it;          midiRules.set_instrument(instrument);
1934          if (row[m_Columns.m_col_instr])          midiRules.show();
1935          {          midiRules.deiconify();
1936              instrumentProps.set_instrument(row[m_Columns.m_col_instr]);      }
1937              instrumentProps.show();  }
1938              instrumentProps.deiconify();  
1939          }  void MainWindow::show_script_slots() {
1940        if (!file) return;
1941        // get selected instrument
1942        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
1943        Gtk::TreeModel::iterator it = sel->get_selected();
1944        if (!it) return;
1945        Gtk::TreeModel::Row row = *it;
1946        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1947        if (!instrument) return;
1948    
1949        ScriptSlots* window = new ScriptSlots;
1950        window->setInstrument(instrument);
1951        //window->reparent(*this);
1952        window->show();
1953    }
1954    
1955    void MainWindow::on_action_refresh_all() {
1956        __refreshEntireGUI();
1957    }
1958    
1959    void MainWindow::on_action_view_status_bar() {
1960        Gtk::CheckMenuItem* item =
1961            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
1962        if (!item) {
1963            std::cerr << "/MenuBar/MenuView/Statusbar == NULL\n";
1964            return;
1965        }
1966        if (item->get_active()) m_StatusBar.show();
1967        else                    m_StatusBar.hide();
1968    }
1969    
1970    void MainWindow::on_auto_restore_win_dim() {
1971        Gtk::CheckMenuItem* item =
1972            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
1973        if (!item) {
1974            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
1975            return;
1976        }
1977        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
1978    }
1979    
1980    void MainWindow::on_save_with_temporary_file() {
1981        Gtk::CheckMenuItem* item =
1982            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
1983        if (!item) {
1984            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
1985            return;
1986        }
1987        Settings::singleton()->saveWithTemporaryFile = item->get_active();
1988    }
1989    
1990    bool MainWindow::is_copy_samples_unity_note_enabled() const {
1991        Gtk::CheckMenuItem* item =
1992            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1993        if (!item) {
1994            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
1995            return true;
1996        }
1997        return item->get_active();
1998    }
1999    
2000    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
2001        Gtk::CheckMenuItem* item =
2002            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
2003        if (!item) {
2004            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
2005            return true;
2006      }      }
2007        return item->get_active();
2008    }
2009    
2010    bool MainWindow::is_copy_samples_loop_enabled() const {
2011        Gtk::CheckMenuItem* item =
2012            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
2013        if (!item) {
2014            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
2015            return true;
2016        }
2017        return item->get_active();
2018  }  }
2019    
2020  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
# Line 910  void MainWindow::on_button_release(GdkEv Line 2022  void MainWindow::on_button_release(GdkEv
2022      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2023          show_instr_props();          show_instr_props();
2024      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2025            // gig v2 files have no midi rules
2026            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2027            static_cast<Gtk::MenuItem*>(
2028                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2029                    bEnabled
2030                );
2031            static_cast<Gtk::MenuItem*>(
2032                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2033                    bEnabled
2034                );
2035          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2036      }      }
2037  }  }
2038    
2039  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
2040      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
2041            const std::vector<Gtk::Widget*> children =
2042                instrument_menu->get_children();
2043            std::vector<Gtk::Widget*>::const_iterator it =
2044                find(children.begin(), children.end(), item);
2045            if (it != children.end()) {
2046                int index = it - children.begin();
2047                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
2048    
2049                m_RegionChooser.set_instrument(file->GetInstrument(index));
2050            }
2051        }
2052    }
2053    
2054    void MainWindow::select_instrument(gig::Instrument* instrument) {
2055        if (!instrument) return;
2056    
2057        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2058        for (int i = 0; i < model->children().size(); ++i) {
2059            Gtk::TreeModel::Row row = model->children()[i];
2060            if (row[m_Columns.m_col_instr] == instrument) {
2061                // select and show the respective instrument in the list view
2062                show_intruments_tab();
2063                m_TreeView.get_selection()->select(model->children()[i]);
2064                Gtk::TreePath path(
2065                    m_TreeView.get_selection()->get_selected()
2066                );
2067                m_TreeView.scroll_to_row(path);
2068                on_sel_change(); // the regular instrument selection change callback
2069            }
2070        }
2071    }
2072    
2073    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2074    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2075        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2076        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2077    
2078        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2079        for (int i = 0; i < model->children().size(); ++i) {
2080            Gtk::TreeModel::Row row = model->children()[i];
2081            if (row[m_Columns.m_col_instr] == pInstrument) {
2082                // select and show the respective instrument in the list view
2083                show_intruments_tab();
2084                m_TreeView.get_selection()->select(model->children()[i]);
2085                Gtk::TreePath path(
2086                    m_TreeView.get_selection()->get_selected()
2087                );
2088                m_TreeView.scroll_to_row(path);
2089                on_sel_change(); // the regular instrument selection change callback
2090    
2091                // select respective region in the region selector
2092                m_RegionChooser.set_region(pRegion);
2093    
2094                // select and show the respective dimension region in the editor
2095                //update_dimregs();
2096                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2097                //dimreg_edit.set_dim_region(dimRgn);
2098    
2099                return true;
2100            }
2101        }
2102    
2103        return false;
2104    }
2105    
2106    void MainWindow::select_sample(gig::Sample* sample) {
2107        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2108        for (int g = 0; g < model->children().size(); ++g) {
2109            Gtk::TreeModel::Row rowGroup = model->children()[g];
2110            for (int s = 0; s < rowGroup.children().size(); ++s) {
2111                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2112                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2113                    show_samples_tab();
2114                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2115                    Gtk::TreePath path(
2116                        m_TreeViewSamples.get_selection()->get_selected()
2117                    );
2118                    m_TreeViewSamples.scroll_to_row(path);
2119                    return;
2120                }
2121            }
2122        }
2123  }  }
2124    
2125  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
# Line 932  void MainWindow::on_sample_treeview_butt Line 2136  void MainWindow::on_sample_treeview_butt
2136              group_selected  = row[m_SamplesModel.m_col_group];              group_selected  = row[m_SamplesModel.m_col_group];
2137              sample_selected = row[m_SamplesModel.m_col_sample];              sample_selected = row[m_SamplesModel.m_col_sample];
2138          }          }
2139            
2140                
2141          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2142              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
2143          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2144              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
2145          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2146              set_sensitive(file);              set_sensitive(file);
2147            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2148                set_sensitive(sample_selected);
2149          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2150              set_sensitive(group_selected || sample_selected);              set_sensitive(group_selected || sample_selected);
2151          // show sample popup          // show sample popup
2152          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2153    
2154            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2155                set_sensitive(group_selected || sample_selected);
2156            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2157                set_sensitive(group_selected || sample_selected);
2158            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2159                set_sensitive(file);
2160            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2161                set_sensitive(sample_selected);
2162            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2163                set_sensitive(group_selected || sample_selected);
2164      }      }
2165  }  }
2166    
2167  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2168      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2169      if (!file) return;          Gtk::Menu* script_popup =
2170      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2171      __instrument_indexer++;          // update enabled/disabled state of sample popup items
2172      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2173          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
2174            bool group_selected  = false;
2175            bool script_selected = false;
2176            if (it) {
2177                Gtk::TreeModel::Row row = *it;
2178                group_selected  = row[m_ScriptsModel.m_col_group];
2179                script_selected = row[m_ScriptsModel.m_col_script];
2180            }
2181            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2182                set_sensitive(group_selected || script_selected);
2183            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2184                set_sensitive(file);
2185            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2186                set_sensitive(script_selected);    
2187            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2188                set_sensitive(group_selected || script_selected);
2189            // show sample popup
2190            script_popup->popup(button->button, button->time);
2191    
2192            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2193                set_sensitive(group_selected || script_selected);
2194            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2195                set_sensitive(file);
2196            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2197                set_sensitive(script_selected);    
2198            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2199                set_sensitive(group_selected || script_selected);
2200        }
2201    }
2202    
2203    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2204        const Glib::ustring& name, int position) {
2205    
2206        Gtk::RadioMenuItem::Group instrument_group;
2207        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2208        if (!children.empty()) {
2209            instrument_group =
2210                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2211        }
2212        Gtk::RadioMenuItem* item =
2213            new Gtk::RadioMenuItem(instrument_group, name);
2214        if (position < 0) {
2215            instrument_menu->append(*item);
2216        } else {
2217            instrument_menu->insert(*item, position);
2218        }
2219        item->show();
2220        item->signal_activate().connect(
2221            sigc::bind(
2222                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2223                item));
2224        return item;
2225    }
2226    
2227    void MainWindow::remove_instrument_from_menu(int index) {
2228        const std::vector<Gtk::Widget*> children =
2229            instrument_menu->get_children();
2230        Gtk::Widget* child = children[index];
2231        instrument_menu->remove(*child);
2232        delete child;
2233    }
2234    
2235    void MainWindow::add_instrument(gig::Instrument* instrument) {
2236        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2237    
2238      // update instrument tree view      // update instrument tree view
2239        instrument_name_connection.block();
2240      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2241      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2242      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_name] = name;
2243      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2244        instrument_name_connection.unblock();
2245    
2246        add_instrument_to_menu(name);
2247    
2248        m_TreeView.get_selection()->select(iterInstr);
2249    
2250      file_changed();      file_changed();
2251  }  }
2252    
2253    void MainWindow::on_action_add_instrument() {
2254        static int __instrument_indexer = 0;
2255        if (!file) return;
2256        gig::Instrument* instrument = file->AddInstrument();
2257        __instrument_indexer++;
2258        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2259                                                ToString(__instrument_indexer));
2260    
2261        add_instrument(instrument);
2262    }
2263    
2264    void MainWindow::on_action_duplicate_instrument() {
2265        if (!file) return;
2266    
2267        // retrieve the currently selected instrument
2268        // (being the original instrument to be duplicated)
2269        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2270        Gtk::TreeModel::iterator itSelection = sel->get_selected();
2271        if (!itSelection) return;
2272        Gtk::TreeModel::Row row = *itSelection;
2273        gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2274        if (!instrOrig) return;
2275    
2276        // duplicate the orginal instrument
2277        gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2278        instrNew->pInfo->Name =
2279            instrOrig->pInfo->Name +
2280            gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2281    
2282        add_instrument(instrNew);
2283    }
2284    
2285  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2286      if (!file) return;      if (!file) return;
2287        if (file_is_shared) {
2288            Gtk::MessageDialog msg(
2289                *this,
2290                 _("You cannot delete an instrument from this file, since it's "
2291                   "currently used by the sampler."),
2292                 false, Gtk::MESSAGE_INFO
2293            );
2294            msg.run();
2295            return;
2296        }
2297    
2298      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2299      Gtk::TreeModel::iterator it = sel->get_selected();      Gtk::TreeModel::iterator it = sel->get_selected();
2300      if (it) {      if (it) {
2301          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2302          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2303          try {          try {
2304                Gtk::TreePath path(it);
2305                int index = path[0];
2306    
2307              // remove instrument from the gig file              // remove instrument from the gig file
2308              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2309              file_changed();              file_changed();
2310    
2311                remove_instrument_from_menu(index);
2312    
2313                // remove row from instruments tree view
2314                m_refTreeModel->erase(it);
2315    
2316    #if GTKMM_MAJOR_VERSION < 3
2317                // select another instrument (in gtk3 this is done
2318                // automatically)
2319                if (!m_refTreeModel->children().empty()) {
2320                    if (index == m_refTreeModel->children().size()) {
2321                        index--;
2322                    }
2323                    m_TreeView.get_selection()->select(
2324                        Gtk::TreePath(ToString(index)));
2325                }
2326    #endif
2327                instr_props_set_instrument();
2328                instr = get_instrument();
2329                if (instr) {
2330                    midiRules.set_instrument(instr);
2331                } else {
2332                    midiRules.hide();
2333                }
2334          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2335              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2336              msg.run();              msg.run();
# Line 983  void MainWindow::on_action_remove_instru Line 2341  void MainWindow::on_action_remove_instru
2341  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2342      //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
2343      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2344          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2345      );      );
2346      msg.run();      msg.run();
2347  }  }
2348    
2349    void MainWindow::on_action_add_script_group() {
2350        static int __script_indexer = 0;
2351        if (!file) return;
2352        gig::ScriptGroup* group = file->AddScriptGroup();
2353        group->Name = gig_from_utf8(_("Unnamed Group"));
2354        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2355        __script_indexer++;
2356        // update sample tree view
2357        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2358        Gtk::TreeModel::Row rowGroup = *iterGroup;
2359        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2360        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2361        rowGroup[m_ScriptsModel.m_col_group] = group;
2362        file_changed();
2363    }
2364    
2365    void MainWindow::on_action_add_script() {
2366        if (!file) return;
2367        // get selected group
2368        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2369        Gtk::TreeModel::iterator it = sel->get_selected();
2370        if (!it) return;
2371        Gtk::TreeModel::Row row = *it;
2372        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2373        if (!group) { // not a group, but a script is selected (probably)
2374            gig::Script* script = row[m_ScriptsModel.m_col_script];
2375            if (!script) return;
2376            it = row.parent(); // resolve parent (that is the script's group)
2377            if (!it) return;
2378            row = *it;
2379            group = row[m_ScriptsModel.m_col_group];
2380            if (!group) return;
2381        }
2382    
2383        // add a new script to the .gig file
2384        gig::Script* script = group->AddScript();    
2385        Glib::ustring name = _("Unnamed Script");
2386        script->Name = gig_from_utf8(name);
2387    
2388        // add script to the tree view
2389        Gtk::TreeModel::iterator iterScript =
2390            m_refScriptsTreeModel->append(row.children());
2391        Gtk::TreeModel::Row rowScript = *iterScript;
2392        rowScript[m_ScriptsModel.m_col_name] = name;
2393        rowScript[m_ScriptsModel.m_col_script] = script;
2394        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2395    
2396        // unfold group of new script item in treeview
2397        Gtk::TreeModel::Path path(iterScript);
2398        m_TreeViewScripts.expand_to_path(path);
2399    }
2400    
2401    void MainWindow::on_action_edit_script() {
2402        if (!file) return;
2403        // get selected script
2404        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2405        Gtk::TreeModel::iterator it = sel->get_selected();
2406        if (!it) return;
2407        Gtk::TreeModel::Row row = *it;
2408        gig::Script* script = row[m_ScriptsModel.m_col_script];
2409        if (!script) return;
2410    
2411        ScriptEditor* editor = new ScriptEditor;
2412        editor->signal_script_to_be_changed.connect(
2413            signal_script_to_be_changed.make_slot()
2414        );
2415        editor->signal_script_changed.connect(
2416            signal_script_changed.make_slot()
2417        );
2418        editor->setScript(script);
2419        //editor->reparent(*this);
2420        editor->show();
2421    }
2422    
2423    void MainWindow::on_action_remove_script() {
2424        if (!file) return;
2425        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2426        Gtk::TreeModel::iterator it = sel->get_selected();
2427        if (it) {
2428            Gtk::TreeModel::Row row = *it;
2429            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2430            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2431            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2432            try {
2433                // remove script group or script from the gig file
2434                if (group) {
2435                    // notify everybody that we're going to remove these samples
2436    //TODO:         scripts_to_be_removed_signal.emit(members);
2437                    // delete the group in the .gig file including the
2438                    // samples that belong to the group
2439                    file->DeleteScriptGroup(group);
2440                    // notify that we're done with removal
2441    //TODO:         scripts_removed_signal.emit();
2442                    file_changed();
2443                } else if (script) {
2444                    // notify everybody that we're going to remove this sample
2445    //TODO:         std::list<gig::Script*> lscripts;
2446    //TODO:         lscripts.push_back(script);
2447    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2448                    // remove sample from the .gig file
2449                    script->GetGroup()->DeleteScript(script);
2450                    // notify that we're done with removal
2451    //TODO:         scripts_removed_signal.emit();
2452                    dimreg_changed();
2453                    file_changed();
2454                }
2455                // remove respective row(s) from samples tree view
2456                m_refScriptsTreeModel->erase(it);
2457            } catch (RIFF::Exception e) {
2458                // pretend we're done with removal (i.e. to avoid dead locks)
2459    //TODO:     scripts_removed_signal.emit();
2460                // show error message
2461                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2462                msg.run();
2463            }
2464        }
2465    }
2466    
2467  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2468      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2469      if (!file) return;      if (!file) return;
2470      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2471      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2472      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2473      __sample_indexer++;      __sample_indexer++;
2474      // update sample tree view      // update sample tree view
2475      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2476      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2477      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2478      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2479      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2480      file_changed();      file_changed();
2481  }  }
2482    
2483    void MainWindow::on_action_replace_sample() {
2484        add_or_replace_sample(true);
2485    }
2486    
2487  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2488        add_or_replace_sample(false);
2489    }
2490    
2491    void MainWindow::add_or_replace_sample(bool replace) {
2492      if (!file) return;      if (!file) return;
2493      // get selected group  
2494        // get selected group (and probably selected sample)
2495      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2496      Gtk::TreeModel::iterator it = sel->get_selected();      Gtk::TreeModel::iterator it = sel->get_selected();
2497      if (!it) return;      if (!it) return;
2498      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2499        gig::Sample* sample = NULL;
2500      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2501      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2502          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2503          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2504          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2505          if (!it) return;          if (!it) return;
2506          row = *it;          if (!replace) row = *it;
2507          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2508          if (!group) return;          if (!group) return;
2509      }      }
2510        if (replace && !sample) return;
2511    
2512      // show 'browse for file' dialog      // show 'browse for file' dialog
2513      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2514      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2515      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2516      dialog.set_select_multiple(true);      dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
2517      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2518      const char* supportedFileTypes[] = {      // matches all file types supported by libsndfile
2519    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2520        Gtk::FileFilter soundfilter;
2521    #else
2522        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2523    #endif
2524        const char* const supportedFileTypes[] = {
2525          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2526          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
2527          "*.svx", "*.SVX", "*.sf", "*.SF", "*.voc", "*.VOC", "*.w64",          "*.svx", "*.SVX", "*.sf", "*.SF", "*.voc", "*.VOC", "*.w64",
2528          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2529          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2530      };      };
2531        const char* soundfiles = _("Sound Files");
2532        const char* allfiles = _("All Files");
2533    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2534      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2535          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2536      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2537      Gtk::FileFilter allpassfilter; // matches every file  
2538        // matches every file
2539        Gtk::FileFilter allpassfilter;
2540      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2541      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2542    #else
2543        for (int i = 0; supportedFileTypes[i]; i++)
2544            soundfilter->add_pattern(supportedFileTypes[i]);
2545        soundfilter->set_name(soundfiles);
2546    
2547        // matches every file
2548        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2549        allpassfilter->add_pattern("*.*");
2550        allpassfilter->set_name(allfiles);
2551    #endif
2552      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2553      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2554        if (current_sample_dir != "") {
2555            dialog.set_current_folder(current_sample_dir);
2556        }
2557      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2558            current_sample_dir = dialog.get_current_folder();
2559          Glib::ustring error_files;          Glib::ustring error_files;
2560          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2561          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2562               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2563              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2564              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1053  void MainWindow::on_action_add_sample() Line 2566  void MainWindow::on_action_add_sample()
2566              info.format = 0;              info.format = 0;
2567              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2568              try {              try {
2569                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2570                  int bitdepth;                  int bitdepth;
2571                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2572                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
                         bitdepth = 16; // we simply convert to 16 bit for now  
                         break;  
2573                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
2574                        case SF_FORMAT_PCM_U8:
2575                          bitdepth = 16;                          bitdepth = 16;
2576                          break;                          break;
2577                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
                         bitdepth = 32; // we simply convert to 32 bit for now  
                         break;  
2578                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
                         bitdepth = 32;  
                         break;  
                     case SF_FORMAT_PCM_U8:  
                         bitdepth = 16; // we simply convert to 16 bit for now  
                         break;  
2579                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
                         bitdepth = 32;  
                         break;  
2580                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
2581                          bitdepth = 32; // I guess we will always truncate this to 32 bit                          bitdepth = 24;
2582                          break;                          break;
2583                      default:                      default:
2584                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2585                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2586                  }                  }
2587                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2588                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2589                  // file name without path                  // file name without path
2590                  sample->pInfo->Name = (*iter).substr((*iter).rfind('/') + 1).raw();                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2591                    // remove file extension if there is one
2592                    for (int i = 0; supportedFileTypes[i]; i++) {
2593                        if (Glib::str_has_suffix(filename, supportedFileTypes[i] + 1)) {
2594                            filename.erase(filename.length() - strlen(supportedFileTypes[i] + 1));
2595                            break;
2596                        }
2597                    }
2598                    sample->pInfo->Name = gig_from_utf8(filename);
2599                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2600                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2601                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
2602                  sample->SamplesPerSecond = info.samplerate;                  sample->SamplesPerSecond = info.samplerate;
2603                    sample->AverageBytesPerSecond = sample->FrameSize * sample->SamplesPerSecond;
2604                    sample->BlockAlign = sample->FrameSize;
2605                    sample->SamplesTotal = info.frames;
2606    
2607                    SF_INSTRUMENT instrument;
2608                    if (sf_command(hFile, SFC_GET_INSTRUMENT,
2609                                   &instrument, sizeof(instrument)) != SF_FALSE)
2610                    {
2611                        sample->MIDIUnityNote = instrument.basenote;
2612                        sample->FineTune      = instrument.detune;
2613    
2614                        if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2615                            sample->Loops = 1;
2616    
2617                            switch (instrument.loops[0].mode) {
2618                            case SF_LOOP_FORWARD:
2619                                sample->LoopType = gig::loop_type_normal;
2620                                break;
2621                            case SF_LOOP_BACKWARD:
2622                                sample->LoopType = gig::loop_type_backward;
2623                                break;
2624                            case SF_LOOP_ALTERNATING:
2625                                sample->LoopType = gig::loop_type_bidirectional;
2626                                break;
2627                            }
2628                            sample->LoopStart = instrument.loops[0].start;
2629                            sample->LoopEnd = instrument.loops[0].end;
2630                            sample->LoopPlayCount = instrument.loops[0].count;
2631                            sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2632                        }
2633                    }
2634    
2635                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
2636                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2637                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2638                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2639                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2640                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2641                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2642                  SampleImportItem sched_item;                  SampleImportItem sched_item;
# Line 1101  void MainWindow::on_action_add_sample() Line 2644  void MainWindow::on_action_add_sample()
2644                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2645                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue.push_back(sched_item);
2646                  // add sample to the tree view                  // add sample to the tree view
2647                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2648                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2649                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2650                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                      Gtk::TreeModel::iterator iterSample =
2651                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
2652                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
2653                        rowSample[m_SamplesModel.m_col_name] =
2654                            gig_to_utf8(sample->pInfo->Name);
2655                        rowSample[m_SamplesModel.m_col_sample] = sample;
2656                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2657                    }
2658                  // close sound file                  // close sound file
2659                  sf_close(hFile);                  sf_close(hFile);
2660                  file_changed();                  file_changed();
2661              } 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)
2662                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2663                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2664              }              }
2665          }          }
2666          // 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
2667          if (error_files.size()) {          if (!error_files.empty()) {
2668              Glib::ustring txt = "Could not add the following sample(s):\n" + error_files;              Glib::ustring txt =
2669                    (replace
2670                        ? _("Failed to replace sample with:\n")
2671                        : _("Could not add the following sample(s):\n"))
2672                    + error_files;
2673                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2674                msg.run();
2675            }
2676        }
2677    }
2678    
2679    void MainWindow::on_action_replace_all_samples_in_all_groups()
2680    {
2681        if (!file) return;
2682        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2683                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2684        const char* str =
2685            _("This is a very specific function. It tries to replace all samples "
2686              "in the current gig file by samples located in the chosen "
2687              "directory.\n\n"
2688              "It works like this: For each sample in the gig file, it tries to "
2689              "find a sample file in the selected directory with the same name as "
2690              "the sample in the gig file. Optionally, you can add a filename "
2691              "extension below, which will be added to the filename expected to be "
2692              "found. That is, assume you have a gig file with a sample called "
2693              "'Snare', if you enter '.wav' below (like it's done by default), it "
2694              "expects to find a sample file called 'Snare.wav' and will replace "
2695              "the sample in the gig file accordingly. If you don't need an "
2696              "extension, blank the field below. Any gig sample where no "
2697              "appropriate sample file could be found will be reported and left "
2698              "untouched.\n");
2699    #if GTKMM_MAJOR_VERSION < 3
2700        view::WrapLabel description(str);
2701    #else
2702        Gtk::Label description(str);
2703        description.set_line_wrap();
2704    #endif
2705        Gtk::HBox entryArea;
2706        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2707        Gtk::Entry postfixEntryBox;
2708        postfixEntryBox.set_text(".wav");
2709        entryArea.pack_start(entryLabel);
2710        entryArea.pack_start(postfixEntryBox);
2711        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2712        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2713        description.show();
2714        entryArea.show_all();
2715        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2716        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2717        dialog.set_select_multiple(false);
2718        if (current_sample_dir != "") {
2719            dialog.set_current_folder(current_sample_dir);
2720        }
2721        if (dialog.run() == Gtk::RESPONSE_OK)
2722        {
2723            current_sample_dir = dialog.get_current_folder();
2724            Glib::ustring error_files;
2725            std::string folder = dialog.get_filename();
2726            for (gig::Sample* sample = file->GetFirstSample();
2727                 sample; sample = file->GetNextSample())
2728            {
2729                std::string filename =
2730                    folder + G_DIR_SEPARATOR_S +
2731                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2732                                             postfixEntryBox.get_text());
2733                SF_INFO info;
2734                info.format = 0;
2735                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2736                try
2737                {
2738                    if (!hFile) throw std::string(_("could not open file"));
2739                    switch (info.format & 0xff) {
2740                        case SF_FORMAT_PCM_S8:
2741                        case SF_FORMAT_PCM_16:
2742                        case SF_FORMAT_PCM_U8:
2743                        case SF_FORMAT_PCM_24:
2744                        case SF_FORMAT_PCM_32:
2745                        case SF_FORMAT_FLOAT:
2746                        case SF_FORMAT_DOUBLE:
2747                            break;
2748                        default:
2749                            sf_close(hFile);
2750                            throw std::string(_("format not supported"));
2751                    }
2752                    SampleImportItem sched_item;
2753                    sched_item.gig_sample  = sample;
2754                    sched_item.sample_path = filename;
2755                    m_SampleImportQueue.push_back(sched_item);
2756                    sf_close(hFile);
2757                    file_changed();
2758                }
2759                catch (std::string what)
2760                {
2761                    if (!error_files.empty()) error_files += "\n";
2762                    error_files += Glib::filename_to_utf8(filename) +
2763                        " (" + what + ")";
2764                }
2765            }
2766            // show error message box when some file(s) could not be opened / added
2767            if (!error_files.empty()) {
2768                Glib::ustring txt =
2769                    _("Could not replace the following sample(s):\n") + error_files;
2770              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2771              msg.run();              msg.run();
2772          }          }
# Line 1136  void MainWindow::on_action_remove_sample Line 2785  void MainWindow::on_action_remove_sample
2785          try {          try {
2786              // remove group or sample from the gig file              // remove group or sample from the gig file
2787              if (group) {              if (group) {
2788                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2789                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2790                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2791                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
2792                       pSample; pSample = group->GetNextSample()) {                       pSample; pSample = group->GetNextSample()) {
2793                      members.push_back(pSample);                      members.push_back(pSample);
2794                  }                  }
2795                    // notify everybody that we're going to remove these samples
2796                    samples_to_be_removed_signal.emit(members);
2797                  // delete the group in the .gig file including the                  // delete the group in the .gig file including the
2798                  // samples that belong to the group                  // samples that belong to the group
2799                  file->DeleteGroup(group);                  file->DeleteGroup(group);
2800                    // notify that we're done with removal
2801                    samples_removed_signal.emit();
2802                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
2803                  // them from the import queue                  // them from the import queue
2804                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
# Line 1162  void MainWindow::on_action_remove_sample Line 2815  void MainWindow::on_action_remove_sample
2815                  }                  }
2816                  file_changed();                  file_changed();
2817              } else if (sample) {              } else if (sample) {
2818                    // notify everybody that we're going to remove this sample
2819                    std::list<gig::Sample*> lsamples;
2820                    lsamples.push_back(sample);
2821                    samples_to_be_removed_signal.emit(lsamples);
2822                  // remove sample from the .gig file                  // remove sample from the .gig file
2823                  file->DeleteSample(sample);                  file->DeleteSample(sample);
2824                    // notify that we're done with removal
2825                    samples_removed_signal.emit();
2826                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
2827                  // the import queue                  // the import queue
2828                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
# Line 1175  void MainWindow::on_action_remove_sample Line 2834  void MainWindow::on_action_remove_sample
2834                          break;                          break;
2835                      }                      }
2836                  }                  }
2837                    dimreg_changed();
2838                  file_changed();                  file_changed();
2839              }              }
2840              // remove respective row(s) from samples tree view              // remove respective row(s) from samples tree view
2841              m_refSamplesTreeModel->erase(it);              m_refSamplesTreeModel->erase(it);
2842          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2843                // pretend we're done with removal (i.e. to avoid dead locks)
2844                samples_removed_signal.emit();
2845                // show error message
2846              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2847              msg.run();              msg.run();
2848          }          }
2849      }      }
2850  }  }
2851    
2852    void MainWindow::on_action_remove_unused_samples() {
2853        if (!file) return;
2854    
2855        // collect all samples that are not referenced by any instrument
2856        std::list<gig::Sample*> lsamples;
2857        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
2858            gig::Sample* sample = file->GetSample(iSample);
2859            bool isUsed = false;
2860            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
2861                                  instrument = file->GetNextInstrument())
2862            {
2863                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2864                                  rgn = instrument->GetNextRegion())
2865                {
2866                    for (int i = 0; i < 256; ++i) {
2867                        if (!rgn->pDimensionRegions[i]) continue;
2868                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
2869                        isUsed = true;
2870                        goto endOfRefSearch;
2871                    }
2872                }
2873            }
2874            endOfRefSearch:
2875            if (!isUsed) lsamples.push_back(sample);
2876        }
2877    
2878        if (lsamples.empty()) return;
2879    
2880        // notify everybody that we're going to remove these samples
2881        samples_to_be_removed_signal.emit(lsamples);
2882    
2883        // remove collected samples
2884        try {
2885            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
2886                 itSample != lsamples.end(); ++itSample)
2887            {
2888                gig::Sample* sample = *itSample;
2889                // remove sample from the .gig file
2890                file->DeleteSample(sample);
2891                // if sample was just previously added, remove it fro the import queue
2892                for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2893                     iter != m_SampleImportQueue.end(); ++iter)
2894                {
2895                    if ((*iter).gig_sample == sample) {
2896                        printf("Removing previously added sample '%s'\n",
2897                               (*iter).sample_path.c_str());
2898                        m_SampleImportQueue.erase(iter);
2899                        break;
2900                    }
2901                }
2902            }
2903        } catch (RIFF::Exception e) {
2904            // show error message
2905            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2906            msg.run();
2907        }
2908    
2909        // notify everybody that we're done with removal
2910        samples_removed_signal.emit();
2911    
2912        dimreg_changed();
2913        file_changed();
2914        __refreshEntireGUI();
2915    }
2916    
2917    // see comment on on_sample_treeview_drag_begin()
2918    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
2919    {
2920        first_call_to_drag_data_get = true;
2921    }
2922    
2923    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
2924                                                       Gtk::SelectionData& selection_data, guint, guint)
2925    {
2926        if (!first_call_to_drag_data_get) return;
2927        first_call_to_drag_data_get = false;
2928    
2929        // get selected script
2930        gig::Script* script = NULL;
2931        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2932        Gtk::TreeModel::iterator it = sel->get_selected();
2933        if (it) {
2934            Gtk::TreeModel::Row row = *it;
2935            script = row[m_ScriptsModel.m_col_script];
2936        }
2937        // pass the gig::Script as pointer
2938        selection_data.set(selection_data.get_target(), 0/*unused*/,
2939                           (const guchar*)&script,
2940                           sizeof(script)/*length of data in bytes*/);
2941    }
2942    
2943    // see comment on on_sample_treeview_drag_begin()
2944    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
2945    {
2946        first_call_to_drag_data_get = true;
2947    }
2948    
2949    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
2950                                                           Gtk::SelectionData& selection_data, guint, guint)
2951    {
2952        if (!first_call_to_drag_data_get) return;
2953        first_call_to_drag_data_get = false;
2954    
2955        // get selected source instrument
2956        gig::Instrument* src = NULL;
2957        {
2958            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2959            Gtk::TreeModel::iterator it = sel->get_selected();
2960            if (it) {
2961                Gtk::TreeModel::Row row = *it;
2962                src = row[m_Columns.m_col_instr];
2963            }
2964        }
2965        if (!src) return;
2966    
2967        // pass the source gig::Instrument as pointer
2968        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
2969                           sizeof(src)/*length of data in bytes*/);
2970    }
2971    
2972    void MainWindow::on_instruments_treeview_drop_drag_data_received(
2973        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
2974        const Gtk::SelectionData& selection_data, guint, guint time)
2975    {
2976        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
2977        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
2978            return;
2979    
2980        gig::Instrument* dst = NULL;
2981        {
2982            Gtk::TreeModel::Path path;
2983            const bool found = m_TreeView.get_path_at_pos(x, y, path);
2984            if (!found) return;
2985    
2986            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
2987            if (!iter) return;
2988            Gtk::TreeModel::Row row = *iter;
2989            dst = row[m_Columns.m_col_instr];
2990        }
2991        if (!dst) return;
2992    
2993        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
2994        src->MoveTo(dst);
2995        __refreshEntireGUI();
2996        select_instrument(src);
2997    }
2998    
2999    // For some reason drag_data_get gets called two times for each
3000    // drag'n'drop (at least when target is an Entry). This work-around
3001    // makes sure the code in drag_data_get and drop_drag_data_received is
3002    // only executed once, as drag_begin only gets called once.
3003    void MainWindow::on_sample_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3004    {
3005        first_call_to_drag_data_get = true;
3006    }
3007    
3008  void MainWindow::on_sample_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,  void MainWindow::on_sample_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3009                                                    Gtk::SelectionData& selection_data, guint, guint)                                                    Gtk::SelectionData& selection_data, guint, guint)
3010  {  {
3011        if (!first_call_to_drag_data_get) return;
3012        first_call_to_drag_data_get = false;
3013    
3014      // get selected sample      // get selected sample
3015      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3016      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
# Line 1206  void MainWindow::on_sample_label_drop_dr Line 3028  void MainWindow::on_sample_label_drop_dr
3028      const Glib::RefPtr<Gdk::DragContext>& context, int, int,      const Glib::RefPtr<Gdk::DragContext>& context, int, int,
3029      const Gtk::SelectionData& selection_data, guint, guint time)      const Gtk::SelectionData& selection_data, guint, guint time)
3030  {  {
     gig::DimensionRegion* dimregion = m_DimRegionChooser.get_dimregion();  
3031      gig::Sample* sample = *((gig::Sample**) selection_data.get_data());      gig::Sample* sample = *((gig::Sample**) selection_data.get_data());
3032    
3033      if (sample && dimregion && selection_data.get_length() == sizeof(gig::Sample*)) {      if (sample && selection_data.get_length() == sizeof(gig::Sample*)) {
3034          if (sample != dimregion->pSample) {          std::cout << "Drop received sample \"" <<
3035              dimregion->pSample = sample;              sample->pInfo->Name << "\"" << std::endl;
3036              dimreg_edit.wSample->set_text(dimregion->pSample->pInfo->Name.c_str());          // drop success
3037              std::cout << "Drop received sample \"" <<          context->drop_reply(true, time);
3038                  dimregion->pSample->pInfo->Name.c_str() << "\"" << std::endl;  
3039              // drop success          //TODO: we should better move most of the following code to DimRegionEdit::set_sample()
3040              context->drop_reply(true, time);  
3041              file_changed();          // notify everybody that we're going to alter the region
3042              return;          gig::Region* region = m_RegionChooser.get_region();
3043            region_to_be_changed_signal.emit(region);
3044    
3045            // find the samplechannel dimension
3046            gig::dimension_def_t* stereo_dimension = 0;
3047            for (int i = 0 ; i < region->Dimensions ; i++) {
3048                if (region->pDimensionDefinitions[i].dimension ==
3049                    gig::dimension_samplechannel) {
3050                    stereo_dimension = &region->pDimensionDefinitions[i];
3051                    break;
3052                }
3053            }
3054            bool channels_changed = false;
3055            if (sample->Channels == 1 && stereo_dimension) {
3056                // remove the samplechannel dimension
3057    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3058                region->DeleteDimension(stereo_dimension);
3059                channels_changed = true;
3060                region_changed();
3061    */
3062            }
3063            dimreg_edit.set_sample(
3064                sample,
3065                is_copy_samples_unity_note_enabled(),
3066                is_copy_samples_fine_tune_enabled(),
3067                is_copy_samples_loop_enabled()
3068            );
3069    
3070            if (sample->Channels == 2 && !stereo_dimension) {
3071                // add samplechannel dimension
3072                gig::dimension_def_t dim;
3073                dim.dimension = gig::dimension_samplechannel;
3074                dim.bits = 1;
3075                dim.zones = 2;
3076                region->AddDimension(&dim);
3077                channels_changed = true;
3078                region_changed();
3079            }
3080            if (channels_changed) {
3081                // unmap all samples with wrong number of channels
3082                // TODO: maybe there should be a warning dialog for this
3083                for (int i = 0 ; i < region->DimensionRegions ; i++) {
3084                    gig::DimensionRegion* d = region->pDimensionRegions[i];
3085                    if (d->pSample && d->pSample->Channels != sample->Channels) {
3086                        gig::Sample* oldref = d->pSample;
3087                        d->pSample = NULL;
3088                        sample_ref_changed_signal.emit(oldref, NULL);
3089                    }
3090                }
3091          }          }
3092    
3093            // notify we're done with altering
3094            region_changed_signal.emit(region);
3095    
3096            file_changed();
3097    
3098            return;
3099      }      }
3100      // drop failed      // drop failed
3101      context->drop_reply(false, time);      context->drop_reply(false, time);
# Line 1232  void MainWindow::sample_name_changed(con Line 3108  void MainWindow::sample_name_changed(con
3108      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
3109      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
3110      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3111        gig::String gigname(gig_from_utf8(name));
3112      if (group) {      if (group) {
3113          if (group->Name != name) {          if (group->Name != gigname) {
3114              group->Name = name;              group->Name = gigname;
3115              printf("group name changed\n");              printf("group name changed\n");
3116              file_changed();              file_changed();
3117          }          }
3118      } else if (sample) {      } else if (sample) {
3119          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
3120              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
3121              printf("sample name changed\n");              printf("sample name changed\n");
3122              file_changed();              file_changed();
3123          }          }
3124      }      }
3125  }  }
3126    
3127    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3128                                         const Gtk::TreeModel::iterator& iter) {
3129        if (!iter) return;
3130        Gtk::TreeModel::Row row = *iter;
3131        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3132        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3133        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3134        gig::String gigname(gig_from_utf8(name));
3135        if (group) {
3136            if (group->Name != gigname) {
3137                group->Name = gigname;
3138                printf("script group name changed\n");
3139                file_changed();
3140            }
3141        } else if (script) {
3142            if (script->Name != gigname) {
3143                script->Name = gigname;
3144                printf("script name changed\n");
3145                file_changed();
3146            }
3147        }
3148    }
3149    
3150    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3151                                           Gtk::TreeViewColumn* column)
3152    {
3153        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3154        if (!iter) return;
3155        Gtk::TreeModel::Row row = *iter;
3156        gig::Script* script = row[m_ScriptsModel.m_col_script];
3157        if (!script) return;
3158    
3159        ScriptEditor* editor = new ScriptEditor;
3160        editor->signal_script_to_be_changed.connect(
3161            signal_script_to_be_changed.make_slot()
3162        );
3163        editor->signal_script_changed.connect(
3164            signal_script_changed.make_slot()
3165        );
3166        editor->setScript(script);
3167        //editor->reparent(*this);
3168        editor->show();
3169    }
3170    
3171  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3172                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3173      if (!iter) return;      if (!iter) return;
3174      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
3175      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
3176    
3177        // change name in instrument menu
3178        int index = path[0];
3179        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3180        if (index < children.size()) {
3181    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
3182            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
3183    #else
3184            remove_instrument_from_menu(index);
3185            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
3186            item->set_active();
3187    #endif
3188        }
3189    
3190        // change name in gig
3191      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
3192      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
3193          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
3194            instrument->pInfo->Name = gigname;
3195    
3196            // change name in the instrument properties window
3197            if (instrumentProps.get_instrument() == instrument) {
3198                instrumentProps.update_name();
3199            }
3200    
3201          file_changed();          file_changed();
3202      }      }
3203  }  }
3204    
3205    void MainWindow::on_action_combine_instruments() {
3206        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3207        d->show_all();
3208        d->resize(500, 400);
3209        d->run();
3210        if (d->fileWasChanged()) {
3211            // update GUI with new instrument just created
3212            add_instrument(d->newCombinedInstrument());
3213        }
3214        delete d;
3215    }
3216    
3217    void MainWindow::on_action_view_references() {
3218        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3219        Gtk::TreeModel::iterator it = sel->get_selected();
3220        if (!it) return;
3221        Gtk::TreeModel::Row row = *it;
3222        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3223        if (!sample) return;
3224    
3225        ReferencesView* d = new ReferencesView(*this);
3226        d->setSample(sample);
3227        d->dimension_region_selected.connect(
3228            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3229        );
3230        d->show_all();
3231        d->resize(500, 400);
3232        d->run();
3233        delete d;
3234    }
3235    
3236    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3237        struct _Source {
3238            std::vector<RIFF::File*> riffs;
3239            std::vector<gig::File*> gigs;
3240            
3241            ~_Source() {
3242                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3243                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3244                riffs.clear();
3245                gigs.clear();
3246            }
3247        } sources;
3248    
3249        if (filenames.empty())
3250            throw RIFF::Exception(_("No files selected, so nothing done."));
3251    
3252        // first open all input files (to avoid output file corruption)
3253        int i;
3254        try {
3255            for (i = 0; i < filenames.size(); ++i) {
3256                const std::string& filename = filenames[i];
3257                printf("opening file=%s\n", filename.c_str());
3258    
3259                RIFF::File* riff = new RIFF::File(filename);
3260                sources.riffs.push_back(riff);
3261    
3262                gig::File* gig = new gig::File(riff);
3263                sources.gigs.push_back(gig);
3264            }
3265        } catch (RIFF::Exception e) {
3266            throw RIFF::Exception(
3267                _("Error occurred while opening '") +
3268                filenames[i] +
3269                "': " +
3270                e.Message
3271            );
3272        } catch (...) {
3273            throw RIFF::Exception(
3274                _("Unknown exception occurred while opening '") +
3275                filenames[i] + "'"
3276            );
3277        }
3278    
3279        // now merge the opened .gig files to the main .gig file currently being
3280        // open in gigedit
3281        try {
3282            for (i = 0; i < filenames.size(); ++i) {
3283                const std::string& filename = filenames[i];
3284                printf("merging file=%s\n", filename.c_str());
3285                assert(i < sources.gigs.size());
3286    
3287                this->file->AddContentOf(sources.gigs[i]);
3288            }
3289        } catch (RIFF::Exception e) {
3290            throw RIFF::Exception(
3291                _("Error occurred while merging '") +
3292                filenames[i] +
3293                "': " +
3294                e.Message
3295            );
3296        } catch (...) {
3297            throw RIFF::Exception(
3298                _("Unknown exception occurred while merging '") +
3299                filenames[i] + "'"
3300            );
3301        }
3302    
3303        // Finally save gig file persistently to disk ...
3304        //NOTE: requires that this gig file already has a filename !
3305        {
3306            std::cout << "Saving file\n" << std::flush;
3307            file_structure_to_be_changed_signal.emit(this->file);
3308    
3309            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3310                _("Saving") +  Glib::ustring(" '") +
3311                Glib::filename_display_basename(this->filename) + "' ...",
3312                *this
3313            );
3314            progress_dialog->show_all();
3315            saver = new Saver(this->file); //FIXME: memory leak!
3316            saver->signal_progress().connect(
3317                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3318            saver->signal_finished().connect(
3319                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3320            saver->signal_error().connect(
3321                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3322            saver->launch();
3323        }
3324    }
3325    
3326    void MainWindow::on_action_merge_files() {
3327        if (this->file->GetFileName().empty()) {
3328            Glib::ustring txt = _(
3329                "You seem to have a new .gig file open that has not been saved "
3330                "yet. You must save it somewhere before starting to merge it with "
3331                "other .gig files though, because during the merge operation the "
3332                "other files' sample data must be written on file level to the "
3333                "target .gig file."
3334            );
3335            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3336            msg.run();
3337            return;
3338        }
3339    
3340        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3341        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3342        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3343        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3344    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3345        Gtk::FileFilter filter;
3346        filter.add_pattern("*.gig");
3347    #else
3348        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3349        filter->add_pattern("*.gig");
3350    #endif
3351        dialog.set_filter(filter);
3352        if (current_gig_dir != "") {
3353            dialog.set_current_folder(current_gig_dir);
3354        }
3355        dialog.set_select_multiple(true);
3356    
3357        // show warning in the file picker dialog
3358        Gtk::HBox descriptionArea;
3359        descriptionArea.set_spacing(15);
3360        Gtk::Image warningIcon;
3361        warningIcon.set_from_icon_name("dialog-warning",
3362                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3363        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3364    #if GTKMM_MAJOR_VERSION < 3
3365        view::WrapLabel description;
3366    #else
3367        Gtk::Label description;
3368        description.set_line_wrap();
3369    #endif
3370        description.set_markup(_(
3371            "\nSelect at least one .gig file that shall be merged to the .gig file "
3372            "currently being open in gigedit.\n\n"
3373            "<b>Please Note:</b> Merging with other files will modify your "
3374            "currently open .gig file on file level! And be aware that the current "
3375            "merge algorithm does not detect duplicate samples yet. So if you are "
3376            "merging files which are using equivalent sample data, those "
3377            "equivalent samples will currently be treated as separate samples and "
3378            "will accordingly be stored separately in the target .gig file!"
3379        ));
3380        descriptionArea.pack_start(description);
3381        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3382        descriptionArea.show_all();
3383    
3384        if (dialog.run() == Gtk::RESPONSE_OK) {
3385            printf("on_action_merge_files self=%p\n",
3386                   static_cast<void*>(Glib::Threads::Thread::self()));
3387            std::vector<std::string> filenames = dialog.get_filenames();
3388    
3389            // merge the selected files to the currently open .gig file
3390            try {
3391                mergeFiles(filenames);
3392            } catch (RIFF::Exception e) {
3393                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3394                msg.run();
3395            }
3396    
3397            // update GUI
3398            __refreshEntireGUI();
3399        }
3400    }
3401    
3402    void MainWindow::set_file_is_shared(bool b) {
3403        this->file_is_shared = b;
3404    
3405        if (file_is_shared) {
3406            m_AttachedStateLabel.set_label(_("live-mode"));
3407            m_AttachedStateImage.set(
3408                Gdk::Pixbuf::create_from_xpm_data(status_attached_xpm)
3409            );
3410        } else {
3411            m_AttachedStateLabel.set_label(_("stand-alone"));
3412            m_AttachedStateImage.set(
3413                Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3414            );
3415        }
3416    
3417        {
3418            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3419                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3420            if (item) item->set_sensitive(b);
3421        }
3422    }
3423    
3424    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3425        if (!sample) return;
3426        sample_ref_count[sample] += offset;
3427        const int refcount = sample_ref_count[sample];
3428    
3429        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3430        for (int g = 0; g < model->children().size(); ++g) {
3431            Gtk::TreeModel::Row rowGroup = model->children()[g];
3432            for (int s = 0; s < rowGroup.children().size(); ++s) {
3433                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3434                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3435                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3436                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3437            }
3438        }
3439    }
3440    
3441    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3442        on_sample_ref_count_incremented(oldSample, -1);
3443        on_sample_ref_count_incremented(newSample, +1);
3444    }
3445    
3446    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3447        // just in case a new sample is added later with exactly the same memory
3448        // address, which would lead to incorrect refcount if not deleted here
3449        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3450             it != samples.end(); ++it)
3451        {
3452            sample_ref_count.erase(*it);
3453        }
3454    }
3455    
3456    void MainWindow::show_samples_tab() {
3457        m_TreeViewNotebook.set_current_page(0);
3458    }
3459    
3460    void MainWindow::show_intruments_tab() {
3461        m_TreeViewNotebook.set_current_page(1);
3462    }
3463    
3464    void MainWindow::show_scripts_tab() {
3465        m_TreeViewNotebook.set_current_page(2);
3466    }
3467    
3468    sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
3469        return file_structure_to_be_changed_signal;
3470    }
3471    
3472    sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_changed() {
3473        return file_structure_changed_signal;
3474    }
3475    
3476    sigc::signal<void, std::list<gig::Sample*> >& MainWindow::signal_samples_to_be_removed() {
3477        return samples_to_be_removed_signal;
3478    }
3479    
3480    sigc::signal<void>& MainWindow::signal_samples_removed() {
3481        return samples_removed_signal;
3482    }
3483    
3484    sigc::signal<void, gig::Region*>& MainWindow::signal_region_to_be_changed() {
3485        return region_to_be_changed_signal;
3486    }
3487    
3488    sigc::signal<void, gig::Region*>& MainWindow::signal_region_changed() {
3489        return region_changed_signal;
3490    }
3491    
3492    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3493        return sample_changed_signal;
3494    }
3495    
3496    sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
3497        return sample_ref_changed_signal;
3498    }
3499    
3500    sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_to_be_changed() {
3501        return dimreg_to_be_changed_signal;
3502    }
3503    
3504    sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
3505        return dimreg_changed_signal;
3506    }
3507    
3508    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_on() {
3509        return note_on_signal;
3510    }
3511    
3512    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
3513        return note_off_signal;
3514    }
3515    
3516    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
3517        return m_RegionChooser.signal_keyboard_key_hit();
3518    }
3519    
3520    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3521        return m_RegionChooser.signal_keyboard_key_released();
3522    }
3523    
3524    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3525        return switch_sampler_instrument_signal;
3526    }

Legend:
Removed from v.1261  
changed lines
  Added in v.2968

  ViewVC Help
Powered by ViewVC