/[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 1382 by schoenebeck, Thu Oct 4 23:29:22 2007 UTC revision 3089 by schoenebeck, Sun Jan 15 19:18:39 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006, 2007 Andreas Persson   * Copyright (C) 2006-2017 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  #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2  #include "global.h"
46  namespace Glib {  #include "compat.h"
 Glib::ustring filename_display_basename(const std::string& filename)  
 {  
     gchar* gstr = g_path_get_basename(filename.c_str());  
     Glib::ustring str(gstr);  
     g_free(gstr);  
     return Glib::filename_to_utf8(str);  
 }  
 }  
 #endif  
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 65  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 82  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      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      toggle_action =
204      actionGroup->add(Gtk::Action::create("MenuHelp",          Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
205                                           action->property_label()));      toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
206  #ifdef ABOUT_DIALOG      actionGroup->add(toggle_action,
207      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),                       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        actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
216        actionGroup->add(Gtk::Action::create("About", _("_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 154  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 180  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 198  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 221  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.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
525        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
526        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
527          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
528      );      );
529    
530      // Add the TreeView's view columns:      // Add the TreeView's view columns:
531      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
532      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
533        m_TreeView.set_headers_visible(true);
534        
535        // establish drag&drop within the instrument tree view, allowing to reorder
536        // the sequence of instruments within the gig file
537        {
538            std::vector<Gtk::TargetEntry> drag_target_instrument;
539            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
540            m_TreeView.drag_source_set(drag_target_instrument);
541            m_TreeView.drag_dest_set(drag_target_instrument);
542            m_TreeView.signal_drag_begin().connect(
543                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
544            );
545            m_TreeView.signal_drag_data_get().connect(
546                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
547            );
548            m_TreeView.signal_drag_data_received().connect(
549                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
550            );
551        }
552    
553      // create samples treeview (including its data model)      // create samples treeview (including its data model)
554      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
555      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
556        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
557        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."));
558      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
559      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
560      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
561        {
562            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
563            Gtk::CellRendererText* cellrenderer =
564                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
565            column->add_attribute(
566                cellrenderer->property_foreground(), m_SamplesModel.m_color
567            );
568        }
569        {
570            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
571            Gtk::CellRendererText* cellrenderer =
572                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
573            column->add_attribute(
574                cellrenderer->property_foreground(), m_SamplesModel.m_color
575            );
576        }
577        m_TreeViewSamples.set_headers_visible(true);
578      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
579          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
580      );      );
# Line 242  MainWindow::MainWindow() Line 582  MainWindow::MainWindow()
582          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
583      );      );
584    
585        // create scripts treeview (including its data model)
586        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
587        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
588        m_TreeViewScripts.set_tooltip_text(_(
589            "Use CTRL + double click for editing a script."
590            "\n\n"
591            "Note: instrument scripts are a LinuxSampler extension of the gig "
592            "format. This feature will not work with the GigaStudio software!"
593        ));
594        // m_TreeViewScripts.set_reorderable();
595        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
596        m_TreeViewScripts.set_headers_visible(false);
597        m_TreeViewScripts.signal_button_press_event().connect_notify(
598            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
599        );
600        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
601        m_TreeViewScripts.signal_row_activated().connect(
602            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
603        );
604        m_refScriptsTreeModel->signal_row_changed().connect(
605            sigc::mem_fun(*this, &MainWindow::script_name_changed)
606        );
607    
608        // establish drag&drop between scripts tree view and ScriptSlots window
609        std::vector<Gtk::TargetEntry> drag_target_gig_script;
610        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
611        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
612        m_TreeViewScripts.signal_drag_begin().connect(
613            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
614        );
615        m_TreeViewScripts.signal_drag_data_get().connect(
616            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
617        );
618    
619      // 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
620      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
621      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
622      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
623      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
624          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 260  MainWindow::MainWindow() Line 634  MainWindow::MainWindow()
634          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
635      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
636          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
637        m_RegionChooser.signal_instrument_changed().connect(
638            sigc::mem_fun(*this, &MainWindow::region_changed));
639      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
640          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
641      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
642            sigc::mem_fun(*this, &MainWindow::file_changed));
643        propDialog.signal_changed().connect(
644            sigc::mem_fun(*this, &MainWindow::file_changed));
645        midiRules.signal_changed().connect(
646          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
647    
648      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 271  MainWindow::MainWindow() Line 651  MainWindow::MainWindow()
651          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
652      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
653          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
654        sample_ref_changed_signal.connect(
655            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
656        );
657        samples_to_be_removed_signal.connect(
658            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
659        );
660    
661        dimreg_edit.signal_select_sample().connect(
662            sigc::mem_fun(*this, &MainWindow::select_sample)
663        );
664    
665      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
666          sigc::hide(          sigc::hide(
# Line 293  MainWindow::MainWindow() Line 683  MainWindow::MainWindow()
683      m_RegionChooser.signal_region_changed_signal().connect(      m_RegionChooser.signal_region_changed_signal().connect(
684          region_changed_signal.make_slot());          region_changed_signal.make_slot());
685    
686        note_on_signal.connect(
687            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_on_event));
688        note_off_signal.connect(
689            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_off_event));
690    
691        dimreg_all_regions.signal_toggled().connect(
692            sigc::mem_fun(*this, &MainWindow::update_dimregs));
693        dimreg_all_dimregs.signal_toggled().connect(
694            sigc::mem_fun(*this, &MainWindow::dimreg_all_dimregs_toggled));
695        dimreg_stereo.signal_toggled().connect(
696            sigc::mem_fun(*this, &MainWindow::update_dimregs));
697    
698      file = 0;      file = 0;
699      file_is_changed = false;      file_is_changed = false;
     file_is_shared  = false;  
700    
701      show_all_children();      show_all_children();
702    
703      // start with a new gig file by default      // start with a new gig file by default
704      on_action_file_new();      on_action_file_new();
705    
706        // select 'Instruments' tab by default
707        // (gtk allows this only if the tab childs are visible, thats why it's here)
708        m_TreeViewNotebook.set_current_page(1);
709  }  }
710    
711  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 323  void MainWindow::region_changed() Line 728  void MainWindow::region_changed()
728      m_DimRegionChooser.set_region(m_RegionChooser.get_region());      m_DimRegionChooser.set_region(m_RegionChooser.get_region());
729  }  }
730    
731    gig::Instrument* MainWindow::get_instrument()
732    {
733        gig::Instrument* instrument = 0;
734        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
735        if (rows.empty()) return NULL;
736        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
737        if (it) {
738            Gtk::TreeModel::Row row = *it;
739            instrument = row[m_Columns.m_col_instr];
740        }
741        return instrument;
742    }
743    
744    void MainWindow::add_region_to_dimregs(gig::Region* region, bool stereo, bool all_dimregs)
745    {
746        if (all_dimregs) {
747            for (int i = 0 ; i < region->DimensionRegions ; i++) {
748                if (region->pDimensionRegions[i]) {
749                    dimreg_edit.dimregs.insert(region->pDimensionRegions[i]);
750                }
751            }
752        } else {
753            m_DimRegionChooser.get_dimregions(region, stereo, dimreg_edit.dimregs);
754        }
755    }
756    
757    void MainWindow::update_dimregs()
758    {
759        dimreg_edit.dimregs.clear();
760        bool all_regions = dimreg_all_regions.get_active();
761        bool stereo = dimreg_stereo.get_active();
762        bool all_dimregs = dimreg_all_dimregs.get_active();
763    
764        if (all_regions) {
765            gig::Instrument* instrument = get_instrument();
766            if (instrument) {
767                for (gig::Region* region = instrument->GetFirstRegion() ;
768                     region ;
769                     region = instrument->GetNextRegion()) {
770                    add_region_to_dimregs(region, stereo, all_dimregs);
771                }
772            }
773        } else {
774            gig::Region* region = m_RegionChooser.get_region();
775            if (region) {
776                add_region_to_dimregs(region, stereo, all_dimregs);
777            }
778        }
779    
780        m_DimRegionChooser.setModifyAllRegions(all_regions);
781        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
782        m_DimRegionChooser.setModifyBothChannels(stereo);
783    }
784    
785    void MainWindow::dimreg_all_dimregs_toggled()
786    {
787        dimreg_stereo.set_sensitive(!dimreg_all_dimregs.get_active());
788        update_dimregs();
789    }
790    
791  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
792  {  {
793      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      update_dimregs();
794        dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
795  }  }
796    
797  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
798  {  {
799      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      // select item in instrument menu
800        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
801        if (!rows.empty()) {
802            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
803            if (it) {
804                Gtk::TreePath path(it);
805                int index = path[0];
806                const std::vector<Gtk::Widget*> children =
807                    instrument_menu->get_children();
808                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
809            }
810        }
811    
812      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      m_RegionChooser.set_instrument(get_instrument());
     if (it) {  
         Gtk::TreeModel::Row row = *it;  
         std::cout << row[m_Columns.m_col_name] << std::endl;  
813    
814          m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);      if (Settings::singleton()->syncSamplerInstrumentSelection) {
815      } else {          switch_sampler_instrument_signal.emit(get_instrument());
         m_RegionChooser.set_instrument(0);  
816      }      }
817  }  }
818    
# Line 352  void loader_progress_callback(gig::progr Line 825  void loader_progress_callback(gig::progr
825  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
826  {  {
827      {      {
828          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
829          progress = fraction;          progress = fraction;
830      }      }
831      progress_dispatcher();      progress_dispatcher();
832  }  }
833    
834    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
835    // make sure stack is 16-byte aligned for SSE instructions
836    __attribute__((force_align_arg_pointer))
837    #endif
838  void Loader::thread_function()  void Loader::thread_function()
839  {  {
840      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
841      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
842      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
843      gig = new gig::File(riff);      try {
844      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
845      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
846      progress.custom = this;          gig::progress_t progress;
847            progress.callback = loader_progress_callback;
848      gig->GetInstrument(0, &progress);          progress.custom = this;
849      printf("End\n");  
850      finished_dispatcher();          gig->GetInstrument(0, &progress);
851            printf("End\n");
852            finished_dispatcher();
853        } catch (RIFF::Exception e) {
854            error_message = e.Message;
855            error_dispatcher.emit();
856        } catch (...) {
857            error_message = _("Unknown exception occurred");
858            error_dispatcher.emit();
859        }
860  }  }
861    
862  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
863      : thread(0), filename(filename)      : filename(filename), gig(0), thread(0), progress(0.f)
864  {  {
865  }  }
866    
867  void Loader::launch()  void Loader::launch()
868  {  {
869    #ifdef OLD_THREADS
870      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
871      printf("launch thread=%x\n", thread);  #else
872        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
873    #endif
874        printf("launch thread=%p\n", static_cast<void*>(thread));
875  }  }
876    
877  float Loader::get_progress()  float Loader::get_progress()
878  {  {
879      float res;      float res;
880      {      {
881          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
882          res = progress;          res = progress;
883      }      }
884      return res;      return res;
# Line 404  Glib::Dispatcher& Loader::signal_finishe Line 894  Glib::Dispatcher& Loader::signal_finishe
894      return finished_dispatcher;      return finished_dispatcher;
895  }  }
896    
897  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
898    {
899        return error_dispatcher;
900    }
901    
902    void saver_progress_callback(gig::progress_t* progress)
903    {
904        Saver* saver = static_cast<Saver*>(progress->custom);
905        saver->progress_callback(progress->factor);
906    }
907    
908    void Saver::progress_callback(float fraction)
909    {
910        {
911            Glib::Threads::Mutex::Lock lock(progressMutex);
912            progress = fraction;
913        }
914        progress_dispatcher.emit();
915    }
916    
917    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
918    // make sure stack is 16-byte aligned for SSE instructions
919    __attribute__((force_align_arg_pointer))
920    #endif
921    void Saver::thread_function()
922    {
923        printf("thread_function self=%p\n",
924               static_cast<void*>(Glib::Threads::Thread::self()));
925        printf("Start %s\n", filename.c_str());
926        try {
927            gig::progress_t progress;
928            progress.callback = saver_progress_callback;
929            progress.custom = this;
930    
931            // if no filename was provided, that means "save", if filename was provided means "save as"
932            if (filename.empty()) {
933                if (!Settings::singleton()->saveWithTemporaryFile) {
934                    // save directly over the existing .gig file
935                    // (requires less disk space than solution below
936                    // but may be slower)
937                    gig->Save(&progress);
938                } else {
939                    // save the file as separate temporary file first,
940                    // then move the saved file over the old file
941                    // (may result in performance speedup during save)
942                    String tmpname = filename + ".TMP";
943                    gig->Save(tmpname, &progress);
944                    #if defined(WIN32)
945                    if (!DeleteFile(filename.c_str())) {
946                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
947                    }
948                    #else // POSIX ...
949                    if (unlink(filename.c_str())) {
950                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
951                    }
952                    #endif
953                    if (rename(tmpname.c_str(), filename.c_str())) {
954                        #if defined(WIN32)
955                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
956                        #else
957                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
958                        #endif
959                    }
960                }
961            } else {
962                gig->Save(filename, &progress);
963            }
964    
965            printf("End\n");
966            finished_dispatcher.emit();
967        } catch (RIFF::Exception e) {
968            error_message = e.Message;
969            error_dispatcher.emit();
970        } catch (...) {
971            error_message = _("Unknown exception occurred");
972            error_dispatcher.emit();
973        }
974    }
975    
976    Saver::Saver(gig::File* file, Glib::ustring filename)
977        : gig(file), filename(filename), thread(0), progress(0.f)
978    {
979    }
980    
981    void Saver::launch()
982    {
983    #ifdef OLD_THREADS
984        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
985    #else
986        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
987    #endif
988        printf("launch thread=%p\n", static_cast<void*>(thread));
989    }
990    
991    float Saver::get_progress()
992    {
993        float res;
994        {
995            Glib::Threads::Mutex::Lock lock(progressMutex);
996            res = progress;
997        }
998        return res;
999    }
1000    
1001    Glib::Dispatcher& Saver::signal_progress()
1002    {
1003        return progress_dispatcher;
1004    }
1005    
1006    Glib::Dispatcher& Saver::signal_finished()
1007    {
1008        return finished_dispatcher;
1009    }
1010    
1011    Glib::Dispatcher& Saver::signal_error()
1012    {
1013        return error_dispatcher;
1014    }
1015    
1016    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1017      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1018  {  {
1019      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1020      show_all_children();      show_all_children();
1021        resize(600,50);
1022  }  }
1023    
1024  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
1025  // 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.
1026  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();  
1027      // forget all samples that ought to be imported      // forget all samples that ought to be imported
1028      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
1029      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1030      m_refTreeModel->clear();      m_refTreeModel->clear();
1031      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1032        m_refScriptsTreeModel->clear();
1033        // remove all entries from "Instrument" menu
1034        while (!instrument_menu->get_children().empty()) {
1035            remove_instrument_from_menu(0);
1036        }
1037      // free libgig's gig::File instance      // free libgig's gig::File instance
1038      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
1039      file = NULL;      file = NULL;
1040      file_is_shared = false;      set_file_is_shared(false);
1041    }
1042    
1043    void MainWindow::__refreshEntireGUI() {
1044        // clear the samples and instruments tree views
1045        m_refTreeModel->clear();
1046        m_refSamplesTreeModel->clear();
1047        m_refScriptsTreeModel->clear();
1048        // remove all entries from "Instrument" menu
1049        while (!instrument_menu->get_children().empty()) {
1050            remove_instrument_from_menu(0);
1051        }
1052    
1053        if (!this->file) return;
1054    
1055        load_gig(
1056            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1057        );
1058  }  }
1059    
1060  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
# Line 445  void MainWindow::on_action_file_new() Line 1069  void MainWindow::on_action_file_new()
1069      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
1070      // already add one new instrument by default      // already add one new instrument by default
1071      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
1072      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
1073      // update GUI with that new gig::File      // update GUI with that new gig::File
1074      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
1075  }  }
# Line 456  bool MainWindow::close_confirmation_dial Line 1080  bool MainWindow::close_confirmation_dial
1080                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
1081      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
1082      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1083      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
 #endif  
1084      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1085      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1086      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);
1087      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1088      int response = dialog.run();      int response = dialog.run();
1089      dialog.hide();      dialog.hide();
1090      if (response == Gtk::RESPONSE_YES) return file_save();  
1091      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1092        if (response == Gtk::RESPONSE_NO) return true;
1093    
1094        // user cancelled dialog, thus don't close app
1095        if (response == Gtk::RESPONSE_CANCEL) return false;
1096    
1097        // TODO: the following return valid is disabled and hard coded instead for
1098        // now, due to the fact that saving with progress bar is now implemented
1099        // asynchronously, as a result the app does not close automatically anymore
1100        // after saving the file has completed
1101        //
1102        //   if (response == Gtk::RESPONSE_YES) return file_save();
1103        //   return response != Gtk::RESPONSE_CANCEL;
1104        //
1105        if (response == Gtk::RESPONSE_YES) file_save();
1106        return false; // always prevent closing the app for now (see comment above)
1107  }  }
1108    
1109  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
1110      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
1111      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1112      dialog.set_secondary_text(      dialog.set_secondary_text(
1113          _("If you proceed to work on another instrument file, it won't be "          _("If you proceed to work on another instrument file, it won't be "
1114            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1115            "load it.")            "load it."));
    );  
 #endif  
1116      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1117      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1118      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1119      int response = dialog.run();      int response = dialog.run();
1120      dialog.hide();      dialog.hide();
# Line 494  void MainWindow::on_action_file_open() Line 1128  void MainWindow::on_action_file_open()
1128      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
1129    
1130      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1131      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1132      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1133      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1134    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1135      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1136      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1137    #else
1138        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1139        filter->add_pattern("*.gig");
1140    #endif
1141      dialog.set_filter(filter);      dialog.set_filter(filter);
1142      if (current_dir != "") {      if (current_gig_dir != "") {
1143          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1144      }      }
1145      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1146          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1147          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1148          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%p\n",
1149                   static_cast<void*>(Glib::Threads::Thread::self()));
1150          load_file(filename.c_str());          load_file(filename.c_str());
1151          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1152      }      }
1153  }  }
1154    
1155  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1156  {  {
1157      __clear();      __clear();
1158      load_dialog = new LoadDialog("Loading...", *this);  
1159      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1160      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1161            Glib::filename_display_basename(name) + "' ...",
1162            *this
1163        );
1164        progress_dialog->show_all();
1165        loader = new Loader(name); //FIXME: memory leak!
1166      loader->signal_progress().connect(      loader->signal_progress().connect(
1167          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1168      loader->signal_finished().connect(      loader->signal_finished().connect(
1169          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1170        loader->signal_error().connect(
1171            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1172      loader->launch();      loader->launch();
1173  }  }
1174    
# Line 537  void MainWindow::load_instrument(gig::In Line 1184  void MainWindow::load_instrument(gig::In
1184      // load the instrument      // load the instrument
1185      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1186      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1187      //TODO: automatically select the given instrument      // automatically select the given instrument
1188        int i = 0;
1189        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1190             instrument = pFile->GetNextInstrument(), ++i)
1191        {
1192            if (instrument == instr) {
1193                // select item in "instruments" tree view
1194                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1195                // make sure the selected item in the "instruments" tree view is
1196                // visible (scroll to it)
1197                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1198                // select item in instrument menu
1199                {
1200                    const std::vector<Gtk::Widget*> children =
1201                        instrument_menu->get_children();
1202                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1203                }
1204                // update region chooser and dimension region chooser
1205                m_RegionChooser.set_instrument(instr);
1206                break;
1207            }
1208        }
1209  }  }
1210    
1211  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1212  {  {
1213      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1214  }  }
1215    
1216  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1217  {  {
1218      printf("Loader finished!\n");      printf("Loader finished!\n");
1219      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
1220      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1221      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1222        progress_dialog->hide();
1223    }
1224    
1225    void MainWindow::on_loader_error()
1226    {
1227        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1228        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1229        msg.run();
1230        progress_dialog->hide();
1231  }  }
1232    
1233  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 589  bool MainWindow::file_save() Line 1266  bool MainWindow::file_save()
1266    
1267      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1268      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1269      try {  
1270          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1271          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1272              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1273              file_is_changed = false;          *this
1274          }      );
1275      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1276          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1277          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1278          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1279          msg.run();      saver->signal_finished().connect(
1280          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1281      }      saver->signal_error().connect(
1282      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1283        saver->launch();
1284    
1285        return true;
1286    }
1287    
1288    void MainWindow::on_saver_progress()
1289    {
1290        progress_dialog->set_fraction(saver->get_progress());
1291    }
1292    
1293    void MainWindow::on_saver_error()
1294    {
1295        file_structure_changed_signal.emit(this->file);
1296        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1297        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1298        msg.run();
1299    }
1300    
1301    void MainWindow::on_saver_finished()
1302    {
1303        this->file = saver->gig;
1304        this->filename = saver->filename;
1305        current_gig_dir = Glib::path_get_dirname(filename);
1306        set_title(Glib::filename_display_basename(filename));
1307        file_has_name = true;
1308        file_is_changed = false;
1309        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1310      __import_queued_samples();      __import_queued_samples();
1311        std::cout << "Importing queued samples done.\n" << std::flush;
1312    
1313      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1314      return true;  
1315        __refreshEntireGUI();
1316        progress_dialog->hide();
1317  }  }
1318    
1319  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 616  void MainWindow::on_action_file_save_as( Line 1324  void MainWindow::on_action_file_save_as(
1324    
1325  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1326  {  {
1327      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1328      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1329      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
1330      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  
1331      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1332      // TODO: an overwrite dialog for gtkmm < 2.8  
1333  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1334      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1335      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1336    #else
1337        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1338        filter->add_pattern("*.gig");
1339    #endif
1340      dialog.set_filter(filter);      dialog.set_filter(filter);
1341    
1342      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1343          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1344      } else if (current_dir != "") {      {
1345          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1346            std::string dir = Glib::path_get_dirname(filename);
1347            basename = std::string(_("copy_of_")) + basename;
1348            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1349            if (Glib::path_is_absolute(filename)) {
1350                dialog.set_filename(copyFileName);
1351            } else {
1352                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1353            }
1354            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1355      }      }
1356      dialog.set_current_name(Glib::filename_display_basename(filename));  
1357        // show warning in the dialog
1358        Gtk::HBox descriptionArea;
1359        descriptionArea.set_spacing(15);
1360        Gtk::Image warningIcon;
1361        warningIcon.set_from_icon_name("dialog-warning",
1362                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1363        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1364    #if GTKMM_MAJOR_VERSION < 3
1365        view::WrapLabel description;
1366    #else
1367        Gtk::Label description;
1368        description.set_line_wrap();
1369    #endif
1370        description.set_markup(
1371            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1372              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1373              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1374              "to the same .gig file. Using "
1375              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1376              "same .gig file will end up in corrupted sample wave data!\n")
1377        );
1378        descriptionArea.pack_start(description);
1379        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1380        descriptionArea.show_all();
1381    
1382      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1383          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1384          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1385              std::string filename = dialog.get_filename();              filename += ".gig";
             if (!Glib::str_has_suffix(filename, ".gig")) {  
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_dir = Glib::path_get_dirname(filename);  
             set_title(Glib::filename_display_basename(filename));  
             file_has_name = true;  
             file_is_changed = false;  
         } catch (RIFF::Exception e) {  
             file_structure_changed_signal.emit(this->file);  
             Glib::ustring txt = _("Could not save file: ") + e.Message;  
             Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
             msg.run();  
             return false;  
1386          }          }
1387          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1388          file_structure_changed_signal.emit(this->file);  
1389            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1390                _("Saving") +  Glib::ustring(" '") +
1391                Glib::filename_display_basename(filename) + "' ...",
1392                *this
1393            );
1394            progress_dialog->show_all();
1395    
1396            saver = new Saver(file, filename); //FIXME: memory leak!
1397            saver->signal_progress().connect(
1398                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1399            saver->signal_finished().connect(
1400                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1401            saver->signal_error().connect(
1402                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1403            saver->launch();
1404    
1405          return true;          return true;
1406      }      }
1407      return false;      return false;
# Line 668  bool MainWindow::file_save_as() Line 1411  bool MainWindow::file_save_as()
1411  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1412      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1413      Glib::ustring error_files;      Glib::ustring error_files;
1414      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1415      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1416           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1417          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",(*iter).sample_path.c_str());
1418          SF_INFO info;          SF_INFO info;
1419          info.format = 0;          info.format = 0;
1420          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
1421            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1422          try {          try {
1423              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1424              // determine sample's bit depth              // determine sample's bit depth
1425              int bitdepth;              int bitdepth;
1426              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 693  void MainWindow::__import_queued_samples Line 1437  void MainWindow::__import_queued_samples
1437                      break;                      break;
1438                  default:                  default:
1439                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1440                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1441              }              }
1442    
1443              const int bufsize = 10000;              const int bufsize = 10000;
# Line 735  void MainWindow::__import_queued_samples Line 1479  void MainWindow::__import_queued_samples
1479              }              }
1480              // cleanup              // cleanup
1481              sf_close(hFile);              sf_close(hFile);
1482                // let the sampler re-cache the sample if needed
1483                sample_changed_signal.emit(iter->gig_sample);
1484              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1485              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1486              std::list<SampleImportItem>::iterator cur = iter;              std::list<SampleImportItem>::iterator cur = iter;
# Line 742  void MainWindow::__import_queued_samples Line 1488  void MainWindow::__import_queued_samples
1488              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1489          } catch (std::string what) {          } catch (std::string what) {
1490              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1491              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1492              error_files += (*iter).sample_path += " (" + what + ")";              error_files += (*iter).sample_path += " (" + what + ")";
1493              ++iter;              ++iter;
1494          }          }
1495      }      }
1496      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1497      if (error_files.size()) {      if (!error_files.empty()) {
1498          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;
1499          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1500          msg.run();          msg.run();
# Line 761  void MainWindow::on_action_file_properti Line 1507  void MainWindow::on_action_file_properti
1507      propDialog.deiconify();      propDialog.deiconify();
1508  }  }
1509    
1510    void MainWindow::on_action_warn_user_on_extensions() {
1511        Settings::singleton()->warnUserOnExtensions =
1512            !Settings::singleton()->warnUserOnExtensions;
1513    }
1514    
1515    void MainWindow::on_action_sync_sampler_instrument_selection() {
1516        Settings::singleton()->syncSamplerInstrumentSelection =
1517            !Settings::singleton()->syncSamplerInstrumentSelection;
1518    }
1519    
1520    void MainWindow::on_action_move_root_note_with_region_moved() {
1521        Settings::singleton()->moveRootNoteWithRegionMoved =
1522            !Settings::singleton()->moveRootNoteWithRegionMoved;
1523    }
1524    
1525  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1526  {  {
 #ifdef ABOUT_DIALOG  
1527      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1528    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1529        dialog.set_program_name("Gigedit");
1530    #else
1531        dialog.set_name("Gigedit");
1532    #endif
1533      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1534        dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1535        const std::string sComment =
1536            _("Built " __DATE__ "\nUsing ") +
1537            ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1538            _(
1539                "Gigedit is released under the GNU General Public License.\n"
1540                "\n"
1541                "This program is distributed WITHOUT ANY WARRANTY; So better "
1542                "backup your Gigasampler/GigaStudio files before editing them with "
1543                "this application.\n"
1544                "\n"
1545                "Please report bugs to: http://bugs.linuxsampler.org"
1546            );
1547        dialog.set_comments(sComment.c_str());
1548        dialog.set_website("http://www.linuxsampler.org");
1549        dialog.set_website_label("http://www.linuxsampler.org");
1550      dialog.run();      dialog.run();
 #endif  
1551  }  }
1552    
1553  PropDialog::PropDialog()  PropDialog::PropDialog()
1554      : table(2,1)      : eFileFormat(_("File Format")),
1555  {        eName(_("Name")),
1556          eCreationDate(_("Creation date")),
1557          eComments(_("Comments")),
1558          eProduct(_("Product")),
1559          eCopyright(_("Copyright")),
1560          eArtists(_("Artists")),
1561          eGenre(_("Genre")),
1562          eKeywords(_("Keywords")),
1563          eEngineer(_("Engineer")),
1564          eTechnician(_("Technician")),
1565          eSoftware(_("Software")),
1566          eMedium(_("Medium")),
1567          eSource(_("Source")),
1568          eSourceForm(_("Source form")),
1569          eCommissioned(_("Commissioned")),
1570          eSubject(_("Subject")),
1571          quitButton(_("_Close"), true),
1572          table(2, 1),
1573          m_file(NULL)
1574    {
1575        set_title(_("File Properties"));
1576        eName.set_width_chars(50);
1577    
1578        connect(eName, &DLS::Info::Name);
1579        connect(eCreationDate, &DLS::Info::CreationDate);
1580        connect(eComments, &DLS::Info::Comments);
1581        connect(eProduct, &DLS::Info::Product);
1582        connect(eCopyright, &DLS::Info::Copyright);
1583        connect(eArtists, &DLS::Info::Artists);
1584        connect(eGenre, &DLS::Info::Genre);
1585        connect(eKeywords, &DLS::Info::Keywords);
1586        connect(eEngineer, &DLS::Info::Engineer);
1587        connect(eTechnician, &DLS::Info::Technician);
1588        connect(eSoftware, &DLS::Info::Software);
1589        connect(eMedium, &DLS::Info::Medium);
1590        connect(eSource, &DLS::Info::Source);
1591        connect(eSourceForm, &DLS::Info::SourceForm);
1592        connect(eCommissioned, &DLS::Info::Commissioned);
1593        connect(eSubject, &DLS::Info::Subject);
1594    
1595        table.add(eFileFormat);
1596        table.add(eName);
1597        table.add(eCreationDate);
1598        table.add(eComments);
1599        table.add(eProduct);
1600        table.add(eCopyright);
1601        table.add(eArtists);
1602        table.add(eGenre);
1603        table.add(eKeywords);
1604        table.add(eEngineer);
1605        table.add(eTechnician);
1606        table.add(eSoftware);
1607        table.add(eMedium);
1608        table.add(eSource);
1609        table.add(eSourceForm);
1610        table.add(eCommissioned);
1611        table.add(eSubject);
1612    
1613      table.set_col_spacings(5);      table.set_col_spacings(5);
1614      const char* propLabels[] = {      add(vbox);
1615          "Name:",      table.set_border_width(5);
1616          "CreationDate:",      vbox.add(table);
1617          "Comments:", // TODO: multiline      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
1618          "Product:",      buttonBox.set_layout(Gtk::BUTTONBOX_END);
1619          "Copyright:",      buttonBox.set_border_width(5);
1620          "Artists:",      buttonBox.show();
1621          "Genre:",      buttonBox.pack_start(quitButton);
1622          "Keywords:",      quitButton.set_can_default();
1623          "Engineer:",      quitButton.grab_focus();
1624          "Technician:",      quitButton.signal_clicked().connect(
1625          "Software:", // TODO: readonly          sigc::mem_fun(*this, &PropDialog::hide));
1626          "Medium:",      eFileFormat.signal_value_changed().connect(
1627          "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);  
     }  
1628    
1629      add(table);      quitButton.show();
1630      // add_button(Gtk::Stock::CANCEL, 0);      vbox.show();
     // add_button(Gtk::Stock::OK, 1);  
1631      show_all_children();      show_all_children();
1632  }  }
1633    
1634    void PropDialog::set_file(gig::File* file)
1635    {
1636        m_file = file;
1637    
1638        // update file format version combo box
1639        const std::string sGiga = "Gigasampler/GigaStudio v";
1640        const int major = file->pVersion->major;
1641        std::vector<std::string> txts;
1642        std::vector<int> values;
1643        txts.push_back(sGiga + "2"); values.push_back(2);
1644        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1645        if (major != 2 && major != 3) {
1646            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1647        }
1648        std::vector<const char*> texts;
1649        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1650        texts.push_back(NULL); values.push_back(0);
1651        eFileFormat.set_choices(&texts[0], &values[0]);
1652        eFileFormat.set_value(major);
1653    }
1654    
1655    void PropDialog::onFileFormatChanged() {
1656        const int major = eFileFormat.get_value();
1657        if (m_file) m_file->pVersion->major = major;
1658    }
1659    
1660  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_info(DLS::Info* info)
1661  {  {
1662      entry[0].set_text(info->Name);      update(info);
1663      entry[1].set_text(info->CreationDate);  }
1664      entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));  
1665      entry[3].set_text(info->Product);  
1666      entry[4].set_text(info->Copyright);  void InstrumentProps::set_Name(const gig::String& name)
     entry[5].set_text(info->Artists);  
     entry[6].set_text(info->Genre);  
     entry[7].set_text(info->Keywords);  
     entry[8].set_text(info->Engineer);  
     entry[9].set_text(info->Technician);  
     entry[10].set_text(info->Software);  
     entry[11].set_text(info->Medium);  
     entry[12].set_text(info->Source);  
     entry[13].set_text(info->SourceForm);  
     entry[14].set_text(info->Commissioned);  
     entry[15].set_text(info->Subject);  
 }  
   
 void InstrumentProps::add_prop(BoolEntry& boolentry)  
 {  
     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)  
 {  
     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 void InstrumentProps::add_prop(LabelWidget& prop)  
 {  
     table.attach(prop.label, 0, 1, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     table.attach(prop.widget, 1, 2, rowno, rowno + 1,  
                  Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);  
     rowno++;  
     prop.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 InstrumentProps::InstrumentProps()  
     : table(2,1),  
       quitButton(Gtk::Stock::CLOSE),  
       eName("Name"),  
       eIsDrum("Is drum"),  
       eMIDIBank("MIDI bank", 0, 16383),  
       eMIDIProgram("MIDI program"),  
       eAttenuation("Attenuation", 0, 96, 0, 1),  
       eGainPlus6("Gain +6dB", eAttenuation, -6),  
       eEffectSend("Effect send", 0, 65535),  
       eFineTune("Fine tune", -8400, 8400),  
       ePitchbendRange("Pitchbend range", 0, 12),  
       ePianoReleaseMode("Piano release mode"),  
       eDimensionKeyRangeLow("Dimension key range low"),  
       eDimensionKeyRangeHigh("Dimension key range high")  
1667  {  {
1668      set_title("Instrument properties");      m->pInfo->Name = name;
1669    }
1670    
1671    void InstrumentProps::update_name()
1672    {
1673        update_model++;
1674        eName.set_value(m->pInfo->Name);
1675        update_model--;
1676    }
1677    
1678    void InstrumentProps::set_IsDrum(bool value)
1679    {
1680        m->IsDrum = value;
1681    }
1682    
1683    void InstrumentProps::set_MIDIBank(uint16_t value)
1684    {
1685        m->MIDIBank = value;
1686    }
1687    
1688    void InstrumentProps::set_MIDIProgram(uint32_t value)
1689    {
1690        m->MIDIProgram = value;
1691    }
1692    
1693    InstrumentProps::InstrumentProps() :
1694        quitButton(_("_Close"), true),
1695        table(2,1),
1696        eName(_("Name")),
1697        eIsDrum(_("Is drum")),
1698        eMIDIBank(_("MIDI bank"), 0, 16383),
1699        eMIDIProgram(_("MIDI program")),
1700        eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1701        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1702        eEffectSend(_("Effect send"), 0, 65535),
1703        eFineTune(_("Fine tune"), -8400, 8400),
1704        ePitchbendRange(_("Pitchbend range"), 0, 12),
1705        ePianoReleaseMode(_("Piano release mode")),
1706        eDimensionKeyRangeLow(_("Keyswitching range low")),
1707        eDimensionKeyRangeHigh(_("Keyswitching range high"))
1708    {
1709        set_title(_("Instrument Properties"));
1710    
1711        eDimensionKeyRangeLow.set_tip(
1712            _("start of the keyboard area which should switch the "
1713              "\"keyswitching\" dimension")
1714        );
1715        eDimensionKeyRangeHigh.set_tip(
1716            _("end of the keyboard area which should switch the "
1717              "\"keyswitching\" dimension")
1718        );
1719    
1720        connect(eName, &InstrumentProps::set_Name);
1721        connect(eIsDrum, &InstrumentProps::set_IsDrum);
1722        connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1723        connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
1724        connect(eAttenuation, &gig::Instrument::Attenuation);
1725        connect(eGainPlus6, &gig::Instrument::Attenuation);
1726        connect(eEffectSend, &gig::Instrument::EffectSend);
1727        connect(eFineTune, &gig::Instrument::FineTune);
1728        connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1729        connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1730        connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1731                &gig::Instrument::DimensionKeyRange);
1732    
1733        eName.signal_value_changed().connect(sig_name_changed.make_slot());
1734    
     rowno = 0;  
1735      table.set_col_spacings(5);      table.set_col_spacings(5);
1736    
1737      add_prop(eName);      table.add(eName);
1738      add_prop(eIsDrum);      table.add(eIsDrum);
1739      add_prop(eMIDIBank);      table.add(eMIDIBank);
1740      add_prop(eMIDIProgram);      table.add(eMIDIProgram);
1741      add_prop(eAttenuation);      table.add(eAttenuation);
1742      add_prop(eGainPlus6);      table.add(eGainPlus6);
1743      add_prop(eEffectSend);      table.add(eEffectSend);
1744      add_prop(eFineTune);      table.add(eFineTune);
1745      add_prop(ePitchbendRange);      table.add(ePitchbendRange);
1746      add_prop(ePianoReleaseMode);      table.add(ePianoReleaseMode);
1747      add_prop(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
1748      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));  
1749    
1750      add(vbox);      add(vbox);
1751      table.set_border_width(5);      table.set_border_width(5);
# Line 900  InstrumentProps::InstrumentProps() Line 1756  InstrumentProps::InstrumentProps()
1756      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1757      buttonBox.show();      buttonBox.show();
1758      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1759      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1760      quitButton.grab_focus();      quitButton.grab_focus();
1761    
1762      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 913  InstrumentProps::InstrumentProps() Line 1769  InstrumentProps::InstrumentProps()
1769    
1770  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1771  {  {
1772      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);  
 }  
   
 void InstrumentProps::key_range_low_changed()  
 {  
     double l = eDimensionKeyRangeLow.get_value();  
     double h = eDimensionKeyRangeHigh.get_value();  
     if (h < l) eDimensionKeyRangeHigh.set_value(l);  
 }  
1773    
1774  void InstrumentProps::key_range_high_changed()      update_model++;
1775  {      eName.set_value(instrument->pInfo->Name);
1776      double l = eDimensionKeyRangeLow.get_value();      eIsDrum.set_value(instrument->IsDrum);
1777      double h = eDimensionKeyRangeHigh.get_value();      eMIDIBank.set_value(instrument->MIDIBank);
1778      if (h < l) eDimensionKeyRangeLow.set_value(h);      eMIDIProgram.set_value(instrument->MIDIProgram);
1779        update_model--;
1780  }  }
1781    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
1782    
1783  void MainWindow::file_changed()  void MainWindow::file_changed()
1784  {  {
# Line 956  void MainWindow::file_changed() Line 1788  void MainWindow::file_changed()
1788      }      }
1789  }  }
1790    
1791    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1792        sample_ref_count.clear();
1793        
1794        if (!gig) return;
1795    
1796        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1797             instrument = gig->GetNextInstrument())
1798        {
1799            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1800                 rgn = instrument->GetNextRegion())
1801            {
1802                for (int i = 0; i < 256; ++i) {
1803                    if (!rgn->pDimensionRegions[i]) continue;
1804                    if (rgn->pDimensionRegions[i]->pSample) {
1805                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1806                    }
1807                }
1808            }
1809        }
1810    }
1811    
1812  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1813  {  {
1814      file = 0;      file = 0;
1815      file_is_shared = isSharedInstrument;      set_file_is_shared(isSharedInstrument);
1816    
1817      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
1818            (filename && strlen(filename) > 0) ?
1819                filename : (!gig->GetFileName().empty()) ?
1820                    gig->GetFileName() : _("Unsaved Gig File");
1821      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1822      file_has_name = filename;      file_has_name = filename;
1823      file_is_changed = false;      file_is_changed = false;
1824    
1825        propDialog.set_file(gig);
1826      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1827    
1828      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
1829          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));      int index = 0;
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
1830      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1831           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
1832            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1833    
1834          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1835          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1836          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
1837            row[m_Columns.m_col_name] = name;
1838          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1839          // create a menu item for this instrument  
1840          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++;  
1841      }      }
1842      instrument_menu->show();      instrument_name_connection.unblock();
1843      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1844    
1845        updateSampleRefCountMap(gig);
1846    
1847      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1848          if (group->Name != "") {          if (group->Name != "") {
1849              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1850              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1851              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1852              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1853              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1854              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1006  void MainWindow::load_gig(gig::File* gig Line 1856  void MainWindow::load_gig(gig::File* gig
1856                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1857                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1858                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1859                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1860                        gig_to_utf8(sample->pInfo->Name);
1861                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1862                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1863                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1864                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1865                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1866              }              }
1867          }          }
1868      }      }
1869        
1870        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1871            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1872    
1873            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1874            Gtk::TreeModel::Row rowGroup = *iterGroup;
1875            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1876            rowGroup[m_ScriptsModel.m_col_group]  = group;
1877            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1878            for (int s = 0; group->GetScript(s); ++s) {
1879                gig::Script* script = group->GetScript(s);
1880    
1881                Gtk::TreeModel::iterator iterScript =
1882                    m_refScriptsTreeModel->append(rowGroup.children());
1883                Gtk::TreeModel::Row rowScript = *iterScript;
1884                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1885                rowScript[m_ScriptsModel.m_col_script] = script;
1886                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1887            }
1888        }
1889        // unfold all sample groups & script groups by default
1890        m_TreeViewSamples.expand_all();
1891        m_TreeViewScripts.expand_all();
1892    
1893      file = gig;      file = gig;
1894    
1895      // select the first instrument      // select the first instrument
1896      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1897      tree_sel_ref->select(Gtk::TreePath("0"));  
1898        instr_props_set_instrument();
1899        gig::Instrument* instrument = get_instrument();
1900        if (instrument) {
1901            midiRules.set_instrument(instrument);
1902        }
1903    }
1904    
1905    bool MainWindow::instr_props_set_instrument()
1906    {
1907        instrumentProps.signal_name_changed().clear();
1908    
1909        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1910        if (rows.empty()) {
1911            instrumentProps.hide();
1912            return false;
1913        }
1914        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
1915        if (it) {
1916            Gtk::TreeModel::Row row = *it;
1917            gig::Instrument* instrument = row[m_Columns.m_col_instr];
1918    
1919            instrumentProps.set_instrument(instrument);
1920    
1921            // make sure instrument tree is updated when user changes the
1922            // instrument name in instrument properties window
1923            instrumentProps.signal_name_changed().connect(
1924                sigc::bind(
1925                    sigc::mem_fun(*this,
1926                                  &MainWindow::instr_name_changed_by_instr_props),
1927                    it));
1928        } else {
1929            instrumentProps.hide();
1930        }
1931        return it;
1932  }  }
1933    
1934  void MainWindow::show_instr_props()  void MainWindow::show_instr_props()
1935  {  {
1936      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (instr_props_set_instrument()) {
1937      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();          instrumentProps.show();
1938      if (it)          instrumentProps.deiconify();
1939        }
1940    }
1941    
1942    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
1943    {
1944        Gtk::TreeModel::Row row = *it;
1945        Glib::ustring name = row[m_Columns.m_col_name];
1946    
1947        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1948        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
1949        if (gigname != name) {
1950            row[m_Columns.m_col_name] = gigname;
1951        }
1952    }
1953    
1954    void MainWindow::show_midi_rules()
1955    {
1956        if (gig::Instrument* instrument = get_instrument())
1957      {      {
1958          Gtk::TreeModel::Row row = *it;          midiRules.set_instrument(instrument);
1959          if (row[m_Columns.m_col_instr])          midiRules.show();
1960          {          midiRules.deiconify();
1961              instrumentProps.set_instrument(row[m_Columns.m_col_instr]);      }
1962              instrumentProps.show();  }
1963              instrumentProps.deiconify();  
1964          }  void MainWindow::show_script_slots() {
1965        if (!file) return;
1966        // get selected instrument
1967        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1968        if (rows.empty()) return;
1969        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1970        if (!it) return;
1971        Gtk::TreeModel::Row row = *it;
1972        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1973        if (!instrument) return;
1974    
1975        ScriptSlots* window = new ScriptSlots;
1976        window->setInstrument(instrument);
1977        //window->reparent(*this);
1978        window->show();
1979    }
1980    
1981    void MainWindow::on_action_refresh_all() {
1982        __refreshEntireGUI();
1983    }
1984    
1985    void MainWindow::on_action_view_status_bar() {
1986        Gtk::CheckMenuItem* item =
1987            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
1988        if (!item) {
1989            std::cerr << "/MenuBar/MenuView/Statusbar == NULL\n";
1990            return;
1991        }
1992        if (item->get_active()) m_StatusBar.show();
1993        else                    m_StatusBar.hide();
1994    }
1995    
1996    void MainWindow::on_auto_restore_win_dim() {
1997        Gtk::CheckMenuItem* item =
1998            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
1999        if (!item) {
2000            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2001            return;
2002        }
2003        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2004    }
2005    
2006    void MainWindow::on_save_with_temporary_file() {
2007        Gtk::CheckMenuItem* item =
2008            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2009        if (!item) {
2010            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2011            return;
2012        }
2013        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2014    }
2015    
2016    bool MainWindow::is_copy_samples_unity_note_enabled() const {
2017        Gtk::CheckMenuItem* item =
2018            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
2019        if (!item) {
2020            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
2021            return true;
2022        }
2023        return item->get_active();
2024    }
2025    
2026    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
2027        Gtk::CheckMenuItem* item =
2028            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
2029        if (!item) {
2030            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
2031            return true;
2032      }      }
2033        return item->get_active();
2034    }
2035    
2036    bool MainWindow::is_copy_samples_loop_enabled() const {
2037        Gtk::CheckMenuItem* item =
2038            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
2039        if (!item) {
2040            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
2041            return true;
2042        }
2043        return item->get_active();
2044  }  }
2045    
2046  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
# Line 1041  void MainWindow::on_button_release(GdkEv Line 2048  void MainWindow::on_button_release(GdkEv
2048      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2049          show_instr_props();          show_instr_props();
2050      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2051            // gig v2 files have no midi rules
2052            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2053            static_cast<Gtk::MenuItem*>(
2054                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2055                    bEnabled
2056                );
2057            static_cast<Gtk::MenuItem*>(
2058                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2059                    bEnabled
2060                );
2061          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2062      }      }
2063  }  }
2064    
2065  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
2066      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
2067            const std::vector<Gtk::Widget*> children =
2068                instrument_menu->get_children();
2069            std::vector<Gtk::Widget*>::const_iterator it =
2070                find(children.begin(), children.end(), item);
2071            if (it != children.end()) {
2072                int index = it - children.begin();
2073                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
2074    
2075                m_RegionChooser.set_instrument(file->GetInstrument(index));
2076            }
2077        }
2078    }
2079    
2080    void MainWindow::select_instrument(gig::Instrument* instrument) {
2081        if (!instrument) return;
2082    
2083        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2084        for (int i = 0; i < model->children().size(); ++i) {
2085            Gtk::TreeModel::Row row = model->children()[i];
2086            if (row[m_Columns.m_col_instr] == instrument) {
2087                // select and show the respective instrument in the list view
2088                show_intruments_tab();
2089                m_TreeView.get_selection()->unselect_all();
2090                m_TreeView.get_selection()->select(model->children()[i]);
2091                std::vector<Gtk::TreeModel::Path> rows =
2092                    m_TreeView.get_selection()->get_selected_rows();
2093                if (!rows.empty())
2094                    m_TreeView.scroll_to_row(rows[0]);
2095                on_sel_change(); // the regular instrument selection change callback
2096            }
2097        }
2098    }
2099    
2100    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2101    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2102        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2103        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2104    
2105        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2106        for (int i = 0; i < model->children().size(); ++i) {
2107            Gtk::TreeModel::Row row = model->children()[i];
2108            if (row[m_Columns.m_col_instr] == pInstrument) {
2109                // select and show the respective instrument in the list view
2110                show_intruments_tab();
2111                m_TreeView.get_selection()->unselect_all();
2112                m_TreeView.get_selection()->select(model->children()[i]);
2113                std::vector<Gtk::TreeModel::Path> rows =
2114                    m_TreeView.get_selection()->get_selected_rows();
2115                if (!rows.empty())
2116                    m_TreeView.scroll_to_row(rows[0]);
2117                on_sel_change(); // the regular instrument selection change callback
2118    
2119                // select respective region in the region selector
2120                m_RegionChooser.set_region(pRegion);
2121    
2122                // select and show the respective dimension region in the editor
2123                //update_dimregs();
2124                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2125                //dimreg_edit.set_dim_region(dimRgn);
2126    
2127                return true;
2128            }
2129        }
2130    
2131        return false;
2132    }
2133    
2134    void MainWindow::select_sample(gig::Sample* sample) {
2135        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2136        for (int g = 0; g < model->children().size(); ++g) {
2137            Gtk::TreeModel::Row rowGroup = model->children()[g];
2138            for (int s = 0; s < rowGroup.children().size(); ++s) {
2139                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2140                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2141                    show_samples_tab();
2142                    m_TreeViewSamples.get_selection()->unselect_all();
2143                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2144                    std::vector<Gtk::TreeModel::Path> rows =
2145                        m_TreeViewSamples.get_selection()->get_selected_rows();
2146                    if (rows.empty()) return;
2147                    m_TreeViewSamples.scroll_to_row(rows[0]);
2148                    return;
2149                }
2150            }
2151        }
2152  }  }
2153    
2154  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2155      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2156            // by default if Ctrl keys is pressed down, then a mouse right-click
2157            // does not select the respective row, so we must assure this
2158            // programmatically ...
2159            /*{
2160                Gtk::TreeModel::Path path;
2161                Gtk::TreeViewColumn* pColumn = NULL;
2162                int cellX, cellY;
2163                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2164                    (int)button->x, (int)button->y,
2165                    path, pColumn, cellX, cellY
2166                );
2167                if (bSuccess) {
2168                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2169                        printf("not selected !!!\n");
2170                        m_TreeViewSamples.get_selection()->select(path);
2171                    }
2172                }
2173            }*/
2174    
2175          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2176              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2177          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2178          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2179          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2180          bool group_selected  = false;          const int n = rows.size();
2181          bool sample_selected = false;          int nGroups  = 0;
2182          if (it) {          int nSamples = 0;
2183            for (int r = 0; r < n; ++r) {
2184                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2185                if (!it) continue;
2186              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2187              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2188              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2189          }          }
2190    
2191          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2192              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2193          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2194              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2195          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2196              set_sensitive(file);              set_sensitive(file);
2197            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2198                set_sensitive(nSamples == 1);
2199          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2200              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2201          // show sample popup          // show sample popup
2202          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2203    
2204            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2205                set_sensitive(n == 1);
2206            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2207                set_sensitive(n);
2208            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2209                set_sensitive(file);
2210            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2211                set_sensitive(nSamples == 1);
2212            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2213                set_sensitive(n);
2214      }      }
2215  }  }
2216    
2217  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2218      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2219      if (!file) return;          Gtk::Menu* script_popup =
2220      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2221      __instrument_indexer++;          // update enabled/disabled state of sample popup items
2222      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2223          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
2224            bool group_selected  = false;
2225            bool script_selected = false;
2226            if (it) {
2227                Gtk::TreeModel::Row row = *it;
2228                group_selected  = row[m_ScriptsModel.m_col_group];
2229                script_selected = row[m_ScriptsModel.m_col_script];
2230            }
2231            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2232                set_sensitive(group_selected || script_selected);
2233            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2234                set_sensitive(file);
2235            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2236                set_sensitive(script_selected);    
2237            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2238                set_sensitive(group_selected || script_selected);
2239            // show sample popup
2240            script_popup->popup(button->button, button->time);
2241    
2242            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2243                set_sensitive(group_selected || script_selected);
2244            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2245                set_sensitive(file);
2246            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2247                set_sensitive(script_selected);    
2248            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2249                set_sensitive(group_selected || script_selected);
2250        }
2251    }
2252    
2253    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2254        const Glib::ustring& name, int position) {
2255    
2256        Gtk::RadioMenuItem::Group instrument_group;
2257        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2258        if (!children.empty()) {
2259            instrument_group =
2260                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2261        }
2262        Gtk::RadioMenuItem* item =
2263            new Gtk::RadioMenuItem(instrument_group, name);
2264        if (position < 0) {
2265            instrument_menu->append(*item);
2266        } else {
2267            instrument_menu->insert(*item, position);
2268        }
2269        item->show();
2270        item->signal_activate().connect(
2271            sigc::bind(
2272                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2273                item));
2274        return item;
2275    }
2276    
2277    void MainWindow::remove_instrument_from_menu(int index) {
2278        const std::vector<Gtk::Widget*> children =
2279            instrument_menu->get_children();
2280        Gtk::Widget* child = children[index];
2281        instrument_menu->remove(*child);
2282        delete child;
2283    }
2284    
2285    void MainWindow::add_instrument(gig::Instrument* instrument) {
2286        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2287    
2288      // update instrument tree view      // update instrument tree view
2289        instrument_name_connection.block();
2290      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2291      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2292      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2293        rowInstr[m_Columns.m_col_name] = name;
2294      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2295        instrument_name_connection.unblock();
2296    
2297        add_instrument_to_menu(name);
2298    
2299        m_TreeView.get_selection()->select(iterInstr);
2300    
2301      file_changed();      file_changed();
2302  }  }
2303    
2304    void MainWindow::on_action_add_instrument() {
2305        static int __instrument_indexer = 0;
2306        if (!file) return;
2307        gig::Instrument* instrument = file->AddInstrument();
2308        __instrument_indexer++;
2309        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2310                                                ToString(__instrument_indexer));
2311    
2312        add_instrument(instrument);
2313    }
2314    
2315    void MainWindow::on_action_duplicate_instrument() {
2316        if (!file) return;
2317    
2318        // retrieve the currently selected instrument
2319        // (being the original instrument to be duplicated)
2320        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2321        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2322        for (int r = 0; r < rows.size(); ++r) {
2323            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2324            if (it) {
2325                Gtk::TreeModel::Row row = *it;
2326                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2327                if (instrOrig) {
2328                    // duplicate the orginal instrument
2329                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2330                    instrNew->pInfo->Name =
2331                        instrOrig->pInfo->Name +
2332                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2333    
2334                    add_instrument(instrNew);
2335                }
2336            }
2337        }
2338    }
2339    
2340  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2341      if (!file) return;      if (!file) return;
2342      if (file_is_shared) {      if (file_is_shared) {
# Line 1105  void MainWindow::on_action_remove_instru Line 2351  void MainWindow::on_action_remove_instru
2351      }      }
2352    
2353      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2354      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2355      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2356            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2357            if (!it) continue;
2358          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2359          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2360          try {          try {
2361                Gtk::TreePath path(it);
2362                int index = path[0];
2363    
2364              // remove instrument from the gig file              // remove instrument from the gig file
2365              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2366              file_changed();              file_changed();
2367    
2368                remove_instrument_from_menu(index);
2369    
2370                // remove row from instruments tree view
2371                m_refTreeModel->erase(it);
2372                // update "Nr" column of all instrument rows
2373                {
2374                    int index = 0;
2375                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2376                         it != m_refTreeModel->children().end(); ++it, ++index)
2377                    {
2378                        Gtk::TreeModel::Row row = *it;
2379                        row[m_Columns.m_col_nr] = index;
2380                    }
2381                }
2382    
2383    #if GTKMM_MAJOR_VERSION < 3
2384                // select another instrument (in gtk3 this is done
2385                // automatically)
2386                if (!m_refTreeModel->children().empty()) {
2387                    if (index == m_refTreeModel->children().size()) {
2388                        index--;
2389                    }
2390                    m_TreeView.get_selection()->select(
2391                        Gtk::TreePath(ToString(index)));
2392                }
2393    #endif
2394                instr_props_set_instrument();
2395                instr = get_instrument();
2396                if (instr) {
2397                    midiRules.set_instrument(instr);
2398                } else {
2399                    midiRules.hide();
2400                }
2401          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2402              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2403              msg.run();              msg.run();
# Line 1125  void MainWindow::on_action_remove_instru Line 2408  void MainWindow::on_action_remove_instru
2408  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2409      //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
2410      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2411          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2412      );      );
2413      msg.run();      msg.run();
2414  }  }
2415    
2416    void MainWindow::on_action_add_script_group() {
2417        static int __script_indexer = 0;
2418        if (!file) return;
2419        gig::ScriptGroup* group = file->AddScriptGroup();
2420        group->Name = gig_from_utf8(_("Unnamed Group"));
2421        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2422        __script_indexer++;
2423        // update sample tree view
2424        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2425        Gtk::TreeModel::Row rowGroup = *iterGroup;
2426        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2427        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2428        rowGroup[m_ScriptsModel.m_col_group] = group;
2429        file_changed();
2430    }
2431    
2432    void MainWindow::on_action_add_script() {
2433        if (!file) return;
2434        // get selected group
2435        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2436        Gtk::TreeModel::iterator it = sel->get_selected();
2437        if (!it) return;
2438        Gtk::TreeModel::Row row = *it;
2439        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2440        if (!group) { // not a group, but a script is selected (probably)
2441            gig::Script* script = row[m_ScriptsModel.m_col_script];
2442            if (!script) return;
2443            it = row.parent(); // resolve parent (that is the script's group)
2444            if (!it) return;
2445            row = *it;
2446            group = row[m_ScriptsModel.m_col_group];
2447            if (!group) return;
2448        }
2449    
2450        // add a new script to the .gig file
2451        gig::Script* script = group->AddScript();    
2452        Glib::ustring name = _("Unnamed Script");
2453        script->Name = gig_from_utf8(name);
2454    
2455        // add script to the tree view
2456        Gtk::TreeModel::iterator iterScript =
2457            m_refScriptsTreeModel->append(row.children());
2458        Gtk::TreeModel::Row rowScript = *iterScript;
2459        rowScript[m_ScriptsModel.m_col_name] = name;
2460        rowScript[m_ScriptsModel.m_col_script] = script;
2461        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2462    
2463        // unfold group of new script item in treeview
2464        Gtk::TreeModel::Path path(iterScript);
2465        m_TreeViewScripts.expand_to_path(path);
2466    }
2467    
2468    void MainWindow::on_action_edit_script() {
2469        if (!file) return;
2470        // get selected script
2471        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2472        Gtk::TreeModel::iterator it = sel->get_selected();
2473        if (!it) return;
2474        Gtk::TreeModel::Row row = *it;
2475        gig::Script* script = row[m_ScriptsModel.m_col_script];
2476        if (!script) return;
2477    
2478        ScriptEditor* editor = new ScriptEditor;
2479        editor->signal_script_to_be_changed.connect(
2480            signal_script_to_be_changed.make_slot()
2481        );
2482        editor->signal_script_changed.connect(
2483            signal_script_changed.make_slot()
2484        );
2485        editor->setScript(script);
2486        //editor->reparent(*this);
2487        editor->show();
2488    }
2489    
2490    void MainWindow::on_action_remove_script() {
2491        if (!file) return;
2492        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2493        Gtk::TreeModel::iterator it = sel->get_selected();
2494        if (it) {
2495            Gtk::TreeModel::Row row = *it;
2496            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2497            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2498            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2499            try {
2500                // remove script group or script from the gig file
2501                if (group) {
2502                    // notify everybody that we're going to remove these samples
2503    //TODO:         scripts_to_be_removed_signal.emit(members);
2504                    // delete the group in the .gig file including the
2505                    // samples that belong to the group
2506                    file->DeleteScriptGroup(group);
2507                    // notify that we're done with removal
2508    //TODO:         scripts_removed_signal.emit();
2509                    file_changed();
2510                } else if (script) {
2511                    // notify everybody that we're going to remove this sample
2512    //TODO:         std::list<gig::Script*> lscripts;
2513    //TODO:         lscripts.push_back(script);
2514    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2515                    // remove sample from the .gig file
2516                    script->GetGroup()->DeleteScript(script);
2517                    // notify that we're done with removal
2518    //TODO:         scripts_removed_signal.emit();
2519                    dimreg_changed();
2520                    file_changed();
2521                }
2522                // remove respective row(s) from samples tree view
2523                m_refScriptsTreeModel->erase(it);
2524            } catch (RIFF::Exception e) {
2525                // pretend we're done with removal (i.e. to avoid dead locks)
2526    //TODO:     scripts_removed_signal.emit();
2527                // show error message
2528                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2529                msg.run();
2530            }
2531        }
2532    }
2533    
2534  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2535      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2536      if (!file) return;      if (!file) return;
2537      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2538      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2539      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2540      __sample_indexer++;      __sample_indexer++;
2541      // update sample tree view      // update sample tree view
2542      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2543      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2544      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2545      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2546      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2547      file_changed();      file_changed();
2548  }  }
2549    
2550    void MainWindow::on_action_replace_sample() {
2551        add_or_replace_sample(true);
2552    }
2553    
2554  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2555        add_or_replace_sample(false);
2556    }
2557    
2558    void MainWindow::add_or_replace_sample(bool replace) {
2559      if (!file) return;      if (!file) return;
2560      // get selected group  
2561        // get selected group (and probably selected sample)
2562      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2563      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2564        if (rows.empty()) return;
2565        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2566      if (!it) return;      if (!it) return;
2567      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2568        gig::Sample* sample = NULL;
2569      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2570      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2571          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2572          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2573          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2574          if (!it) return;          if (!it) return;
2575          row = *it;          if (!replace) row = *it;
2576          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2577          if (!group) return;          if (!group) return;
2578      }      }
2579        if (replace && !sample) return;
2580    
2581      // show 'browse for file' dialog      // show 'browse for file' dialog
2582      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2583      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2584      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2585      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
2586      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2587        // matches all file types supported by libsndfile
2588    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2589        Gtk::FileFilter soundfilter;
2590    #else
2591        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2592    #endif
2593      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2594          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2595          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1176  void MainWindow::on_action_add_sample() Line 2597  void MainWindow::on_action_add_sample()
2597          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2598          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2599      };      };
2600        const char* soundfiles = _("Sound Files");
2601        const char* allfiles = _("All Files");
2602    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2603      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2604          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2605      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2606      Gtk::FileFilter allpassfilter; // matches every file  
2607        // matches every file
2608        Gtk::FileFilter allpassfilter;
2609      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2610      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2611    #else
2612        for (int i = 0; supportedFileTypes[i]; i++)
2613            soundfilter->add_pattern(supportedFileTypes[i]);
2614        soundfilter->set_name(soundfiles);
2615    
2616        // matches every file
2617        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2618        allpassfilter->add_pattern("*.*");
2619        allpassfilter->set_name(allfiles);
2620    #endif
2621      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2622      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2623        if (current_sample_dir != "") {
2624            dialog.set_current_folder(current_sample_dir);
2625        }
2626      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2627            current_sample_dir = dialog.get_current_folder();
2628          Glib::ustring error_files;          Glib::ustring error_files;
2629          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2630          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2631               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2632              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2633              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1195  void MainWindow::on_action_add_sample() Line 2635  void MainWindow::on_action_add_sample()
2635              info.format = 0;              info.format = 0;
2636              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2637              try {              try {
2638                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2639                  int bitdepth;                  int bitdepth;
2640                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2641                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1211  void MainWindow::on_action_add_sample() Line 2651  void MainWindow::on_action_add_sample()
2651                          break;                          break;
2652                      default:                      default:
2653                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2654                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2655                  }                  }
2656                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2657                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2658                  // file name without path                  // file name without path
2659                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2660                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1224  void MainWindow::on_action_add_sample() Line 2664  void MainWindow::on_action_add_sample()
2664                          break;                          break;
2665                      }                      }
2666                  }                  }
2667                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2668                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2669                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2670                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1238  void MainWindow::on_action_add_sample() Line 2678  void MainWindow::on_action_add_sample()
2678                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2679                  {                  {
2680                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2681                        sample->FineTune      = instrument.detune;
2682    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2683                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2684                          sample->Loops = 1;                          sample->Loops = 1;
2685    
# Line 1259  void MainWindow::on_action_add_sample() Line 2699  void MainWindow::on_action_add_sample()
2699                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2700                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2701                      }                      }
 #endif  
2702                  }                  }
2703    
2704                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
2705                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2706                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2707                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2708                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2709                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2710                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2711                  SampleImportItem sched_item;                  SampleImportItem sched_item;
# Line 1274  void MainWindow::on_action_add_sample() Line 2713  void MainWindow::on_action_add_sample()
2713                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2714                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue.push_back(sched_item);
2715                  // add sample to the tree view                  // add sample to the tree view
2716                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2717                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2718                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2719                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
2720                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
2721                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
2722                        rowSample[m_SamplesModel.m_col_name] =
2723                            gig_to_utf8(sample->pInfo->Name);
2724                        rowSample[m_SamplesModel.m_col_sample] = sample;
2725                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2726                    }
2727                  // close sound file                  // close sound file
2728                  sf_close(hFile);                  sf_close(hFile);
2729                  file_changed();                  file_changed();
2730              } 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)
2731                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2732                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2733              }              }
2734          }          }
2735          // 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
2736          if (error_files.size()) {          if (!error_files.empty()) {
2737              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
2738                    (replace
2739                        ? _("Failed to replace sample with:\n")
2740                        : _("Could not add the following sample(s):\n"))
2741                    + error_files;
2742                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2743                msg.run();
2744            }
2745        }
2746    }
2747    
2748    void MainWindow::on_action_replace_all_samples_in_all_groups()
2749    {
2750        if (!file) return;
2751        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2752                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2753        const char* str =
2754            _("This is a very specific function. It tries to replace all samples "
2755              "in the current gig file by samples located in the chosen "
2756              "directory.\n\n"
2757              "It works like this: For each sample in the gig file, it tries to "
2758              "find a sample file in the selected directory with the same name as "
2759              "the sample in the gig file. Optionally, you can add a filename "
2760              "extension below, which will be added to the filename expected to be "
2761              "found. That is, assume you have a gig file with a sample called "
2762              "'Snare', if you enter '.wav' below (like it's done by default), it "
2763              "expects to find a sample file called 'Snare.wav' and will replace "
2764              "the sample in the gig file accordingly. If you don't need an "
2765              "extension, blank the field below. Any gig sample where no "
2766              "appropriate sample file could be found will be reported and left "
2767              "untouched.\n");
2768    #if GTKMM_MAJOR_VERSION < 3
2769        view::WrapLabel description(str);
2770    #else
2771        Gtk::Label description(str);
2772        description.set_line_wrap();
2773    #endif
2774        Gtk::HBox entryArea;
2775        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2776        Gtk::Entry postfixEntryBox;
2777        postfixEntryBox.set_text(".wav");
2778        entryArea.pack_start(entryLabel);
2779        entryArea.pack_start(postfixEntryBox);
2780        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2781        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2782        description.show();
2783        entryArea.show_all();
2784        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2785        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2786        dialog.set_select_multiple(false);
2787        if (current_sample_dir != "") {
2788            dialog.set_current_folder(current_sample_dir);
2789        }
2790        if (dialog.run() == Gtk::RESPONSE_OK)
2791        {
2792            current_sample_dir = dialog.get_current_folder();
2793            Glib::ustring error_files;
2794            std::string folder = dialog.get_filename();
2795            for (gig::Sample* sample = file->GetFirstSample();
2796                 sample; sample = file->GetNextSample())
2797            {
2798                std::string filename =
2799                    folder + G_DIR_SEPARATOR_S +
2800                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2801                                             postfixEntryBox.get_text());
2802                SF_INFO info;
2803                info.format = 0;
2804                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2805                try
2806                {
2807                    if (!hFile) throw std::string(_("could not open file"));
2808                    switch (info.format & 0xff) {
2809                        case SF_FORMAT_PCM_S8:
2810                        case SF_FORMAT_PCM_16:
2811                        case SF_FORMAT_PCM_U8:
2812                        case SF_FORMAT_PCM_24:
2813                        case SF_FORMAT_PCM_32:
2814                        case SF_FORMAT_FLOAT:
2815                        case SF_FORMAT_DOUBLE:
2816                            break;
2817                        default:
2818                            sf_close(hFile);
2819                            throw std::string(_("format not supported"));
2820                    }
2821                    SampleImportItem sched_item;
2822                    sched_item.gig_sample  = sample;
2823                    sched_item.sample_path = filename;
2824                    m_SampleImportQueue.push_back(sched_item);
2825                    sf_close(hFile);
2826                    file_changed();
2827                }
2828                catch (std::string what)
2829                {
2830                    if (!error_files.empty()) error_files += "\n";
2831                    error_files += Glib::filename_to_utf8(filename) +
2832                        " (" + what + ")";
2833                }
2834            }
2835            // show error message box when some file(s) could not be opened / added
2836            if (!error_files.empty()) {
2837                Glib::ustring txt =
2838                    _("Could not replace the following sample(s):\n") + error_files;
2839              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2840              msg.run();              msg.run();
2841          }          }
# Line 1300  void MainWindow::on_action_add_sample() Line 2845  void MainWindow::on_action_add_sample()
2845  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
2846      if (!file) return;      if (!file) return;
2847      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2848      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2849      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2850            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2851            if (!it) continue;
2852          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2853          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
2854          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1309  void MainWindow::on_action_remove_sample Line 2856  void MainWindow::on_action_remove_sample
2856          try {          try {
2857              // remove group or sample from the gig file              // remove group or sample from the gig file
2858              if (group) {              if (group) {
2859                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2860                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2861                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2862                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1373  void MainWindow::on_action_remove_sample Line 2920  void MainWindow::on_action_remove_sample
2920      }      }
2921  }  }
2922    
2923    void MainWindow::on_action_remove_unused_samples() {
2924        if (!file) return;
2925    
2926        // collect all samples that are not referenced by any instrument
2927        std::list<gig::Sample*> lsamples;
2928        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
2929            gig::Sample* sample = file->GetSample(iSample);
2930            bool isUsed = false;
2931            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
2932                                  instrument = file->GetNextInstrument())
2933            {
2934                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2935                                  rgn = instrument->GetNextRegion())
2936                {
2937                    for (int i = 0; i < 256; ++i) {
2938                        if (!rgn->pDimensionRegions[i]) continue;
2939                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
2940                        isUsed = true;
2941                        goto endOfRefSearch;
2942                    }
2943                }
2944            }
2945            endOfRefSearch:
2946            if (!isUsed) lsamples.push_back(sample);
2947        }
2948    
2949        if (lsamples.empty()) return;
2950    
2951        // notify everybody that we're going to remove these samples
2952        samples_to_be_removed_signal.emit(lsamples);
2953    
2954        // remove collected samples
2955        try {
2956            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
2957                 itSample != lsamples.end(); ++itSample)
2958            {
2959                gig::Sample* sample = *itSample;
2960                // remove sample from the .gig file
2961                file->DeleteSample(sample);
2962                // if sample was just previously added, remove it fro the import queue
2963                for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2964                     iter != m_SampleImportQueue.end(); ++iter)
2965                {
2966                    if ((*iter).gig_sample == sample) {
2967                        printf("Removing previously added sample '%s'\n",
2968                               (*iter).sample_path.c_str());
2969                        m_SampleImportQueue.erase(iter);
2970                        break;
2971                    }
2972                }
2973            }
2974        } catch (RIFF::Exception e) {
2975            // show error message
2976            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2977            msg.run();
2978        }
2979    
2980        // notify everybody that we're done with removal
2981        samples_removed_signal.emit();
2982    
2983        dimreg_changed();
2984        file_changed();
2985        __refreshEntireGUI();
2986    }
2987    
2988    // see comment on on_sample_treeview_drag_begin()
2989    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
2990    {
2991        first_call_to_drag_data_get = true;
2992    }
2993    
2994    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
2995                                                       Gtk::SelectionData& selection_data, guint, guint)
2996    {
2997        if (!first_call_to_drag_data_get) return;
2998        first_call_to_drag_data_get = false;
2999    
3000        // get selected script
3001        gig::Script* script = NULL;
3002        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3003        Gtk::TreeModel::iterator it = sel->get_selected();
3004        if (it) {
3005            Gtk::TreeModel::Row row = *it;
3006            script = row[m_ScriptsModel.m_col_script];
3007        }
3008        // pass the gig::Script as pointer
3009        selection_data.set(selection_data.get_target(), 0/*unused*/,
3010                           (const guchar*)&script,
3011                           sizeof(script)/*length of data in bytes*/);
3012    }
3013    
3014    // see comment on on_sample_treeview_drag_begin()
3015    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3016    {
3017        first_call_to_drag_data_get = true;
3018    }
3019    
3020    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3021                                                           Gtk::SelectionData& selection_data, guint, guint)
3022    {
3023        if (!first_call_to_drag_data_get) return;
3024        first_call_to_drag_data_get = false;
3025    
3026        // get selected source instrument
3027        gig::Instrument* src = NULL;
3028        {
3029            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3030            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3031            if (!rows.empty()) {
3032                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3033                if (it) {
3034                    Gtk::TreeModel::Row row = *it;
3035                    src = row[m_Columns.m_col_instr];
3036                }
3037            }
3038        }
3039        if (!src) return;
3040    
3041        // pass the source gig::Instrument as pointer
3042        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3043                           sizeof(src)/*length of data in bytes*/);
3044    }
3045    
3046    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3047        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3048        const Gtk::SelectionData& selection_data, guint, guint time)
3049    {
3050        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3051        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3052            return;
3053    
3054        gig::Instrument* dst = NULL;
3055        {
3056            Gtk::TreeModel::Path path;
3057            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3058            if (!found) return;
3059    
3060            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3061            if (!iter) return;
3062            Gtk::TreeModel::Row row = *iter;
3063            dst = row[m_Columns.m_col_instr];
3064        }
3065        if (!dst) return;
3066    
3067        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3068        src->MoveTo(dst);
3069        __refreshEntireGUI();
3070        select_instrument(src);
3071    }
3072    
3073  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3074  // drag'n'drop (at least when target is an Entry). This work-around  // drag'n'drop (at least when target is an Entry). This work-around
3075  // makes sure the code in drag_data_get and drop_drag_data_received is  // makes sure the code in drag_data_get and drop_drag_data_received is
# Line 1391  void MainWindow::on_sample_treeview_drag Line 3088  void MainWindow::on_sample_treeview_drag
3088      // get selected sample      // get selected sample
3089      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3090      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3091      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3092      if (it) {      if (!rows.empty()) {
3093          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3094          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3095                Gtk::TreeModel::Row row = *it;
3096                sample = row[m_SamplesModel.m_col_sample];
3097            }
3098      }      }
3099      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3100      selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&sample,      selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&sample,
# Line 1431  void MainWindow::on_sample_label_drop_dr Line 3131  void MainWindow::on_sample_label_drop_dr
3131          bool channels_changed = false;          bool channels_changed = false;
3132          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
3133              // remove the samplechannel dimension              // remove the samplechannel dimension
3134    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3135              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
3136              channels_changed = true;              channels_changed = true;
3137              region_changed();              region_changed();
3138    */
3139          }          }
3140          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
3141                sample,
3142                is_copy_samples_unity_note_enabled(),
3143                is_copy_samples_fine_tune_enabled(),
3144                is_copy_samples_loop_enabled()
3145            );
3146    
3147          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
3148              // add samplechannel dimension              // add samplechannel dimension
# Line 1463  void MainWindow::on_sample_label_drop_dr Line 3170  void MainWindow::on_sample_label_drop_dr
3170          // notify we're done with altering          // notify we're done with altering
3171          region_changed_signal.emit(region);          region_changed_signal.emit(region);
3172    
3173            file_changed();
3174    
3175          return;          return;
3176      }      }
3177      // drop failed      // drop failed
# Line 1476  void MainWindow::sample_name_changed(con Line 3185  void MainWindow::sample_name_changed(con
3185      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
3186      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
3187      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3188        gig::String gigname(gig_from_utf8(name));
3189      if (group) {      if (group) {
3190          if (group->Name != name) {          if (group->Name != gigname) {
3191              group->Name = name;              group->Name = gigname;
3192              printf("group name changed\n");              printf("group name changed\n");
3193              file_changed();              file_changed();
3194          }          }
3195      } else if (sample) {      } else if (sample) {
3196          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
3197              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
3198              printf("sample name changed\n");              printf("sample name changed\n");
3199              file_changed();              file_changed();
3200          }          }
3201      }      }
3202  }  }
3203    
3204    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3205                                         const Gtk::TreeModel::iterator& iter) {
3206        if (!iter) return;
3207        Gtk::TreeModel::Row row = *iter;
3208        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3209        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3210        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3211        gig::String gigname(gig_from_utf8(name));
3212        if (group) {
3213            if (group->Name != gigname) {
3214                group->Name = gigname;
3215                printf("script group name changed\n");
3216                file_changed();
3217            }
3218        } else if (script) {
3219            if (script->Name != gigname) {
3220                script->Name = gigname;
3221                printf("script name changed\n");
3222                file_changed();
3223            }
3224        }
3225    }
3226    
3227    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3228                                           Gtk::TreeViewColumn* column)
3229    {
3230        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3231        if (!iter) return;
3232        Gtk::TreeModel::Row row = *iter;
3233        gig::Script* script = row[m_ScriptsModel.m_col_script];
3234        if (!script) return;
3235    
3236        ScriptEditor* editor = new ScriptEditor;
3237        editor->signal_script_to_be_changed.connect(
3238            signal_script_to_be_changed.make_slot()
3239        );
3240        editor->signal_script_changed.connect(
3241            signal_script_changed.make_slot()
3242        );
3243        editor->setScript(script);
3244        //editor->reparent(*this);
3245        editor->show();
3246    }
3247    
3248  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3249                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3250      if (!iter) return;      if (!iter) return;
3251      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
3252      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
3253    
3254        // change name in instrument menu
3255        int index = path[0];
3256        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3257        if (index < children.size()) {
3258    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
3259            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
3260    #else
3261            remove_instrument_from_menu(index);
3262            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
3263            item->set_active();
3264    #endif
3265        }
3266    
3267        // change name in gig
3268      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
3269      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
3270          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
3271            instrument->pInfo->Name = gigname;
3272    
3273            // change name in the instrument properties window
3274            if (instrumentProps.get_instrument() == instrument) {
3275                instrumentProps.update_name();
3276            }
3277    
3278          file_changed();          file_changed();
3279      }      }
3280  }  }
3281    
3282    void MainWindow::on_action_combine_instruments() {
3283        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3284        d->show_all();
3285        d->resize(500, 400);
3286        d->run();
3287        if (d->fileWasChanged()) {
3288            // update GUI with new instrument just created
3289            add_instrument(d->newCombinedInstrument());
3290        }
3291        delete d;
3292    }
3293    
3294    void MainWindow::on_action_view_references() {
3295        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3296        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3297        if (rows.empty()) return;
3298        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3299        if (!it) return;
3300        Gtk::TreeModel::Row row = *it;
3301        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3302        if (!sample) return;
3303    
3304        ReferencesView* d = new ReferencesView(*this);
3305        d->setSample(sample);
3306        d->dimension_region_selected.connect(
3307            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3308        );
3309        d->show_all();
3310        d->resize(500, 400);
3311        d->run();
3312        delete d;
3313    }
3314    
3315    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3316        struct _Source {
3317            std::vector<RIFF::File*> riffs;
3318            std::vector<gig::File*> gigs;
3319            
3320            ~_Source() {
3321                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3322                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3323                riffs.clear();
3324                gigs.clear();
3325            }
3326        } sources;
3327    
3328        if (filenames.empty())
3329            throw RIFF::Exception(_("No files selected, so nothing done."));
3330    
3331        // first open all input files (to avoid output file corruption)
3332        int i;
3333        try {
3334            for (i = 0; i < filenames.size(); ++i) {
3335                const std::string& filename = filenames[i];
3336                printf("opening file=%s\n", filename.c_str());
3337    
3338                RIFF::File* riff = new RIFF::File(filename);
3339                sources.riffs.push_back(riff);
3340    
3341                gig::File* gig = new gig::File(riff);
3342                sources.gigs.push_back(gig);
3343            }
3344        } catch (RIFF::Exception e) {
3345            throw RIFF::Exception(
3346                _("Error occurred while opening '") +
3347                filenames[i] +
3348                "': " +
3349                e.Message
3350            );
3351        } catch (...) {
3352            throw RIFF::Exception(
3353                _("Unknown exception occurred while opening '") +
3354                filenames[i] + "'"
3355            );
3356        }
3357    
3358        // now merge the opened .gig files to the main .gig file currently being
3359        // open in gigedit
3360        try {
3361            for (i = 0; i < filenames.size(); ++i) {
3362                const std::string& filename = filenames[i];
3363                printf("merging file=%s\n", filename.c_str());
3364                assert(i < sources.gigs.size());
3365    
3366                this->file->AddContentOf(sources.gigs[i]);
3367            }
3368        } catch (RIFF::Exception e) {
3369            throw RIFF::Exception(
3370                _("Error occurred while merging '") +
3371                filenames[i] +
3372                "': " +
3373                e.Message
3374            );
3375        } catch (...) {
3376            throw RIFF::Exception(
3377                _("Unknown exception occurred while merging '") +
3378                filenames[i] + "'"
3379            );
3380        }
3381    
3382        // Finally save gig file persistently to disk ...
3383        //NOTE: requires that this gig file already has a filename !
3384        {
3385            std::cout << "Saving file\n" << std::flush;
3386            file_structure_to_be_changed_signal.emit(this->file);
3387    
3388            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3389                _("Saving") +  Glib::ustring(" '") +
3390                Glib::filename_display_basename(this->filename) + "' ...",
3391                *this
3392            );
3393            progress_dialog->show_all();
3394            saver = new Saver(this->file); //FIXME: memory leak!
3395            saver->signal_progress().connect(
3396                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3397            saver->signal_finished().connect(
3398                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3399            saver->signal_error().connect(
3400                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3401            saver->launch();
3402        }
3403    }
3404    
3405    void MainWindow::on_action_merge_files() {
3406        if (this->file->GetFileName().empty()) {
3407            Glib::ustring txt = _(
3408                "You seem to have a new .gig file open that has not been saved "
3409                "yet. You must save it somewhere before starting to merge it with "
3410                "other .gig files though, because during the merge operation the "
3411                "other files' sample data must be written on file level to the "
3412                "target .gig file."
3413            );
3414            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3415            msg.run();
3416            return;
3417        }
3418    
3419        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3420        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3421        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3422        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3423    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3424        Gtk::FileFilter filter;
3425        filter.add_pattern("*.gig");
3426    #else
3427        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3428        filter->add_pattern("*.gig");
3429    #endif
3430        dialog.set_filter(filter);
3431        if (current_gig_dir != "") {
3432            dialog.set_current_folder(current_gig_dir);
3433        }
3434        dialog.set_select_multiple(true);
3435    
3436        // show warning in the file picker dialog
3437        Gtk::HBox descriptionArea;
3438        descriptionArea.set_spacing(15);
3439        Gtk::Image warningIcon;
3440        warningIcon.set_from_icon_name("dialog-warning",
3441                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3442        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3443    #if GTKMM_MAJOR_VERSION < 3
3444        view::WrapLabel description;
3445    #else
3446        Gtk::Label description;
3447        description.set_line_wrap();
3448    #endif
3449        description.set_markup(_(
3450            "\nSelect at least one .gig file that shall be merged to the .gig file "
3451            "currently being open in gigedit.\n\n"
3452            "<b>Please Note:</b> Merging with other files will modify your "
3453            "currently open .gig file on file level! And be aware that the current "
3454            "merge algorithm does not detect duplicate samples yet. So if you are "
3455            "merging files which are using equivalent sample data, those "
3456            "equivalent samples will currently be treated as separate samples and "
3457            "will accordingly be stored separately in the target .gig file!"
3458        ));
3459        descriptionArea.pack_start(description);
3460        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3461        descriptionArea.show_all();
3462    
3463        if (dialog.run() == Gtk::RESPONSE_OK) {
3464            printf("on_action_merge_files self=%p\n",
3465                   static_cast<void*>(Glib::Threads::Thread::self()));
3466            std::vector<std::string> filenames = dialog.get_filenames();
3467    
3468            // merge the selected files to the currently open .gig file
3469            try {
3470                mergeFiles(filenames);
3471            } catch (RIFF::Exception e) {
3472                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3473                msg.run();
3474            }
3475    
3476            // update GUI
3477            __refreshEntireGUI();
3478        }
3479    }
3480    
3481    void MainWindow::set_file_is_shared(bool b) {
3482        this->file_is_shared = b;
3483    
3484        if (file_is_shared) {
3485            m_AttachedStateLabel.set_label(_("live-mode"));
3486            m_AttachedStateImage.set(
3487                Gdk::Pixbuf::create_from_xpm_data(status_attached_xpm)
3488            );
3489        } else {
3490            m_AttachedStateLabel.set_label(_("stand-alone"));
3491            m_AttachedStateImage.set(
3492                Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3493            );
3494        }
3495    
3496        {
3497            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3498                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3499            if (item) item->set_sensitive(b);
3500        }
3501    }
3502    
3503    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3504        if (!sample) return;
3505        sample_ref_count[sample] += offset;
3506        const int refcount = sample_ref_count[sample];
3507    
3508        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3509        for (int g = 0; g < model->children().size(); ++g) {
3510            Gtk::TreeModel::Row rowGroup = model->children()[g];
3511            for (int s = 0; s < rowGroup.children().size(); ++s) {
3512                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3513                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3514                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3515                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3516            }
3517        }
3518    }
3519    
3520    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3521        on_sample_ref_count_incremented(oldSample, -1);
3522        on_sample_ref_count_incremented(newSample, +1);
3523    }
3524    
3525    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3526        // just in case a new sample is added later with exactly the same memory
3527        // address, which would lead to incorrect refcount if not deleted here
3528        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3529             it != samples.end(); ++it)
3530        {
3531            sample_ref_count.erase(*it);
3532        }
3533    }
3534    
3535    void MainWindow::show_samples_tab() {
3536        m_TreeViewNotebook.set_current_page(0);
3537    }
3538    
3539    void MainWindow::show_intruments_tab() {
3540        m_TreeViewNotebook.set_current_page(1);
3541    }
3542    
3543    void MainWindow::show_scripts_tab() {
3544        m_TreeViewNotebook.set_current_page(2);
3545    }
3546    
3547  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
3548      return file_structure_to_be_changed_signal;      return file_structure_to_be_changed_signal;
3549  }  }
# Line 1527  sigc::signal<void, gig::Region*>& MainWi Line 3568  sigc::signal<void, gig::Region*>& MainWi
3568      return region_changed_signal;      return region_changed_signal;
3569  }  }
3570    
3571    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3572        return sample_changed_signal;
3573    }
3574    
3575  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
3576      return sample_ref_changed_signal;      return sample_ref_changed_signal;
3577  }  }
# Line 1538  sigc::signal<void, gig::DimensionRegion* Line 3583  sigc::signal<void, gig::DimensionRegion*
3583  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
3584      return dimreg_changed_signal;      return dimreg_changed_signal;
3585  }  }
3586    
3587    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_on() {
3588        return note_on_signal;
3589    }
3590    
3591    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
3592        return note_off_signal;
3593    }
3594    
3595    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
3596        return m_RegionChooser.signal_keyboard_key_hit();
3597    }
3598    
3599    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3600        return m_RegionChooser.signal_keyboard_key_released();
3601    }
3602    
3603    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3604        return switch_sampler_instrument_signal;
3605    }

Legend:
Removed from v.1382  
changed lines
  Added in v.3089

  ViewVC Help
Powered by ViewVC