/[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 1673 by schoenebeck, Wed Feb 6 22:08:29 2008 UTC revision 3148 by schoenebeck, Thu May 4 11:47:45 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006 - 2008 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 18  Line 18 
18   */   */
19    
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>  #include <gtkmm/toggleaction.h>
41    #if GTKMM_MAJOR_VERSION < 3
42  #include "global.h"  #include "wrapLabel.hh"
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
 #define ABOUT_DIALOG  
 #include <gtkmm/aboutdialog.h>  
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"  #include "../../gfx/status_attached.xpm"
59  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
60    #include "gfx/builtinpix.h"
 template<class T> inline std::string ToString(T o) {  
     std::stringstream ss;  
     ss << o;  
     return ss.str();  
 }  
   
 Table::Table(int x, int y) : Gtk::Table(x, y), rowno(0) {  }  
   
 void Table::add(BoolEntry& boolentry)  
 {  
     attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
            Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
 }  
   
 void Table::add(BoolEntryPlus6& boolentry)  
 {  
     attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
            Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
 }  
   
 void Table::add(LabelWidget& prop)  
 {  
     attach(prop.label, 1, 2, rowno, rowno + 1,  
            Gtk::FILL, Gtk::SHRINK);  
     attach(prop.widget, 2, 3, rowno, rowno + 1,  
            Gtk::EXPAND | Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
 }  
61    
62  MainWindow::MainWindow() :  MainWindow::MainWindow() :
63        m_DimRegionChooser(*this),
64      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
65      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
66      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
67      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
68        labelLegend(_("Legend:")),
69        labelNoSample(_(" No Sample")),
70        labelMissingSample(_(" Missing some Sample(s)")),
71        labelLooped(_(" Looped")),
72        labelSomeLoops(_(" Some Loop(s)"))
73  {  {
74        loadBuiltInPix();
75    
76  //    set_border_width(5);  //    set_border_width(5);
77  //    set_default_size(400, 200);  //    set_default_size(400, 200);
78    
   
79      add(m_VBox);      add(m_VBox);
80    
81      // Handle selection      // Handle selection
82      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
83          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
84    
85      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
# Line 114  MainWindow::MainWindow() : Line 95  MainWindow::MainWindow() :
95      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
96      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
97    
98        m_ScrolledWindowScripts.add(m_TreeViewScripts);
99        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
100    
101    
102      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
103    
# Line 125  MainWindow::MainWindow() : Line 109  MainWindow::MainWindow() :
109      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
110      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
111      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
112      m_HPaned.add2(dimreg_vbox);      {
113            legend_hbox.add(labelLegend);
114    
115            imageNoSample.set(redDot);
116            imageNoSample.set_alignment(Gtk::ALIGN_END);
117            labelNoSample.set_alignment(Gtk::ALIGN_START);
118            legend_hbox.add(imageNoSample);
119            legend_hbox.add(labelNoSample);
120    
121            imageMissingSample.set(yellowDot);
122            imageMissingSample.set_alignment(Gtk::ALIGN_END);
123            labelMissingSample.set_alignment(Gtk::ALIGN_START);
124            legend_hbox.add(imageMissingSample);
125            legend_hbox.add(labelMissingSample);
126    
127            imageLooped.set(blackLoop);
128            imageLooped.set_alignment(Gtk::ALIGN_END);
129            labelLooped.set_alignment(Gtk::ALIGN_START);
130            legend_hbox.add(imageLooped);
131            legend_hbox.add(labelLooped);
132    
133            imageSomeLoops.set(grayLoop);
134            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
135            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
136            legend_hbox.add(imageSomeLoops);
137            legend_hbox.add(labelSomeLoops);
138    
139      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");          legend_hbox.show_all_children();
140      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");      }
141        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
142        m_HPaned.add2(dimreg_vbox);
143    
144        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
145        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."));
146        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."));
147        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)."));
148    
149        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
150        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
151        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
152    
153      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
154    
155      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
156      actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),      actionGroup->add(Gtk::Action::create("New", _("_New")),
157                         Gtk::AccelKey("<control>n"),
158                       sigc::mem_fun(                       sigc::mem_fun(
159                           *this, &MainWindow::on_action_file_new));                           *this, &MainWindow::on_action_file_new));
160      Glib::RefPtr<Gtk::Action> action =      actionGroup->add(Gtk::Action::create("Open", _("_Open...")),
161          Gtk::Action::create("Open", Gtk::Stock::OPEN);                       Gtk::AccelKey("<control>o"),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
162                       sigc::mem_fun(                       sigc::mem_fun(
163                           *this, &MainWindow::on_action_file_open));                           *this, &MainWindow::on_action_file_open));
164      actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),      actionGroup->add(Gtk::Action::create("Save", _("_Save")),
165                         Gtk::AccelKey("<control>s"),
166                       sigc::mem_fun(                       sigc::mem_fun(
167                           *this, &MainWindow::on_action_file_save));                           *this, &MainWindow::on_action_file_save));
168      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,  
169                       Gtk::AccelKey("<shift><control>s"),                       Gtk::AccelKey("<shift><control>s"),
170                       sigc::mem_fun(                       sigc::mem_fun(
171                           *this, &MainWindow::on_action_file_save_as));                           *this, &MainWindow::on_action_file_save_as));
172      actionGroup->add(Gtk::Action::create("Properties",      actionGroup->add(Gtk::Action::create("Properties",
173                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
174                       sigc::mem_fun(                       sigc::mem_fun(
175                           *this, &MainWindow::on_action_file_properties));                           *this, &MainWindow::on_action_file_properties));
176      actionGroup->add(Gtk::Action::create("InstrProperties",      actionGroup->add(Gtk::Action::create("InstrProperties",
177                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
178                       sigc::mem_fun(                       sigc::mem_fun(
179                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
180      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("MidiRules",
181                                             _("_Midi Rules...")),
182                         sigc::mem_fun(
183                             *this, &MainWindow::show_midi_rules));
184        actionGroup->add(Gtk::Action::create("ScriptSlots",
185                                             _("_Script Slots...")),
186                         sigc::mem_fun(
187                             *this, &MainWindow::show_script_slots));
188        actionGroup->add(Gtk::Action::create("Quit", _("_Quit")),
189                         Gtk::AccelKey("<control>q"),
190                       sigc::mem_fun(                       sigc::mem_fun(
191                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
192      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
193            Gtk::Action::create("MenuSample", _("_Sample")),
194            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
195        );
196        actionGroup->add(
197            Gtk::Action::create("MenuInstrument", _("_Instrument")),
198            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
199        );
200        actionGroup->add(
201            Gtk::Action::create("MenuScript", _("Scr_ipt")),
202            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
203        );
204        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
205    
206        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
207    
208        const Gdk::ModifierType primaryModifierKey =
209    #if defined(__APPLE__)
210        Gdk::META_MASK; // Cmd key on Mac
211    #else
212        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
213    #endif
214    
215        actionGroup->add(Gtk::Action::create("CopyDimRgn",
216                                             _("Copy selected dimension region")),
217                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
218                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
219    
220        actionGroup->add(Gtk::Action::create("PasteDimRgn",
221                                             _("Paste dimension region")),
222                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
223                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
224    
225        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
226                                             _("Select Previous Region")),
227                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
228                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
229    
230        actionGroup->add(Gtk::Action::create("SelectNextRegion",
231                                             _("Select Next Region")),
232                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
233                         sigc::mem_fun(*this, &MainWindow::select_next_region));
234    
235        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
236                                             _("Select Previous Dimension Region Zone")),
237                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
238                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
239    
240        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
241                                             _("Select Next Dimension Region Zone")),
242                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
243                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
244    
245        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
246                                             _("Select Previous Dimension")),
247                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
248                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
249    
250        actionGroup->add(Gtk::Action::create("SelectNextDimension",
251                                             _("Select Next Dimension")),
252                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
253                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
254    
255        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
256                                             _("Add Previous Dimension Region Zone to Selection")),
257                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
258                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
259    
260        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
261                                             _("Add Next Dimension Region Zone to Selection")),
262                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
263                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
264    
     actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  
265      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
266            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
267        toggle_action->set_active(true);
268        actionGroup->add(toggle_action);
269    
270        toggle_action =
271            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
272        toggle_action->set_active(true);
273        actionGroup->add(toggle_action);
274    
275        toggle_action =
276            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
277        toggle_action->set_active(true);
278        actionGroup->add(toggle_action);
279    
280    
281        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
282        toggle_action =
283          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
284      toggle_action->set_active(true);      toggle_action->set_active(true);
285      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
286                       sigc::mem_fun(                       sigc::mem_fun(
287                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
288    
289      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      toggle_action =
290      actionGroup->add(Gtk::Action::create("MenuHelp",          Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
291                                           action->property_label()));      toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
292  #ifdef ABOUT_DIALOG      actionGroup->add(toggle_action,
293      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),                       sigc::mem_fun(
294                             *this, &MainWindow::on_auto_restore_win_dim));
295    
296        toggle_action =
297            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
298        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
299        actionGroup->add(toggle_action,
300                         sigc::mem_fun(
301                             *this, &MainWindow::on_save_with_temporary_file));
302    
303        actionGroup->add(
304            Gtk::Action::create("RefreshAll", _("_Refresh All")),
305            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
306        );                
307    
308        actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
309        actionGroup->add(Gtk::Action::create("About", _("_About")),
310                       sigc::mem_fun(                       sigc::mem_fun(
311                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
312      actionGroup->add(      actionGroup->add(
313          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
314          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
315      );      );
316      actionGroup->add(      actionGroup->add(
317          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
318            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
319        );
320        actionGroup->add(
321            Gtk::Action::create("RemoveInstrument", _("_Remove")),
322          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
323      );      );
324    
325    
326        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
327        
328        toggle_action =
329            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
330        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
331        actionGroup->add(
332            toggle_action,
333            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
334        );
335    
336        toggle_action =
337            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
338        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
339        actionGroup->add(
340            toggle_action,
341            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
342        );
343    
344        toggle_action =
345            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
346        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
347        actionGroup->add(
348            toggle_action,
349            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
350        );
351    
352    
353        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
354    
355        actionGroup->add(
356            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
357            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
358        );
359    
360        actionGroup->add(
361            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
362            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
363        );
364    
365    
366      // sample right-click popup actions      // sample right-click popup actions
367      actionGroup->add(      actionGroup->add(
368          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", _("_Properties")),
369          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
370      );      );
371      actionGroup->add(      actionGroup->add(
# Line 201  MainWindow::MainWindow() : Line 373  MainWindow::MainWindow() :
373          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
374      );      );
375      actionGroup->add(      actionGroup->add(
376          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
377          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
378      );      );
379      actionGroup->add(      actionGroup->add(
380          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", _("_Remove")),
381          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
382      );      );
383      actionGroup->add(      actionGroup->add(
384          Gtk::Action::create("ReplaceAllSamplesInAllGroups", _("Replace All Samples In All Groups")),          Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
385            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
386        );
387        actionGroup->add(
388            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
389            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
390        );
391        actionGroup->add(
392            Gtk::Action::create("ReplaceSample",
393                                _("Replace Sample...")),
394            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
395        );
396        actionGroup->add(
397            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
398                                _("Replace All Samples in All Groups...")),
399          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
400      );      );
401        
402        // script right-click popup actions
403        actionGroup->add(
404            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
405            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
406        );
407        actionGroup->add(
408            Gtk::Action::create("AddScript", _("Add _Script")),
409            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
410        );
411        actionGroup->add(
412            Gtk::Action::create("EditScript", _("_Edit Script...")),
413            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
414        );
415        actionGroup->add(
416            Gtk::Action::create("RemoveScript", _("_Remove")),
417            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
418        );
419    
420      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
421      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 231  MainWindow::MainWindow() : Line 435  MainWindow::MainWindow() :
435          "      <separator/>"          "      <separator/>"
436          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
437          "    </menu>"          "    </menu>"
438            "    <menu action='MenuEdit'>"
439            "      <menuitem action='CopyDimRgn'/>"
440            "      <menuitem action='PasteDimRgn'/>"
441            "      <separator/>"
442            "      <menuitem action='SelectPrevRegion'/>"
443            "      <menuitem action='SelectNextRegion'/>"
444            "      <separator/>"
445            "      <menuitem action='SelectPrevDimension'/>"
446            "      <menuitem action='SelectNextDimension'/>"
447            "      <menuitem action='SelectPrevDimRgnZone'/>"
448            "      <menuitem action='SelectNextDimRgnZone'/>"
449            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
450            "      <menuitem action='SelectAddNextDimRgnZone'/>"
451            "      <separator/>"
452            "      <menuitem action='CopySampleUnity'/>"
453            "      <menuitem action='CopySampleTune'/>"
454            "      <menuitem action='CopySampleLoop'/>"
455            "    </menu>"
456            "    <menu action='MenuSample'>"
457            "      <menuitem action='SampleProperties'/>"
458            "      <menuitem action='AddGroup'/>"
459            "      <menuitem action='AddSample'/>"
460            "      <menuitem action='ShowSampleRefs'/>"
461            "      <menuitem action='ReplaceSample' />"
462            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
463            "      <separator/>"
464            "      <menuitem action='RemoveSample'/>"
465            "      <menuitem action='RemoveUnusedSamples'/>"
466            "    </menu>"
467          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
468            "      <menu action='AllInstruments'>"
469            "      </menu>"
470            "      <separator/>"
471            "      <menuitem action='InstrProperties'/>"
472            "      <menuitem action='MidiRules'/>"
473            "      <menuitem action='ScriptSlots'/>"
474            "      <menuitem action='AddInstrument'/>"
475            "      <menuitem action='DupInstrument'/>"
476            "      <separator/>"
477            "      <menuitem action='RemoveInstrument'/>"
478            "    </menu>"
479            "    <menu action='MenuScript'>"
480            "      <menuitem action='AddScriptGroup'/>"
481            "      <menuitem action='AddScript'/>"
482            "      <menuitem action='EditScript'/>"
483            "      <separator/>"
484            "      <menuitem action='RemoveScript'/>"
485          "    </menu>"          "    </menu>"
486          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
487          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
488            "      <menuitem action='AutoRestoreWinDim'/>"
489            "      <separator/>"
490            "      <menuitem action='RefreshAll'/>"
491            "    </menu>"
492            "    <menu action='MenuTools'>"
493            "      <menuitem action='CombineInstruments'/>"
494            "      <menuitem action='MergeFiles'/>"
495            "    </menu>"
496            "    <menu action='MenuSettings'>"
497            "      <menuitem action='WarnUserOnExtensions'/>"
498            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
499            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
500            "      <menuitem action='SaveWithTemporaryFile'/>"
501          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
502          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
503          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
504          "    </menu>"          "    </menu>"
 #endif  
505          "  </menubar>"          "  </menubar>"
506          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
507          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
508            "    <menuitem action='MidiRules'/>"
509            "    <menuitem action='ScriptSlots'/>"
510          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
511            "    <menuitem action='DupInstrument'/>"
512          "    <separator/>"          "    <separator/>"
513          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
514          "  </popup>"          "  </popup>"
# Line 252  MainWindow::MainWindow() : Line 516  MainWindow::MainWindow() :
516          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
517          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
518          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
519          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ShowSampleRefs'/>"
520            "    <menuitem action='ReplaceSample' />"
521            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
522          "    <separator/>"          "    <separator/>"
523          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
524            "    <menuitem action='RemoveUnusedSamples'/>"
525            "  </popup>"
526            "  <popup name='ScriptPopupMenu'>"
527            "    <menuitem action='AddScriptGroup'/>"
528            "    <menuitem action='AddScript'/>"
529            "    <menuitem action='EditScript'/>"
530            "    <separator/>"
531            "    <menuitem action='RemoveScript'/>"
532          "  </popup>"          "  </popup>"
533          "</ui>";          "</ui>";
534      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
535    
536      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
537        
538        // Set tooltips for menu items (for some reason, setting a tooltip on the
539        // respective Gtk::Action objects above will simply be ignored, no matter
540        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
541        // Gtk::Action::create()).
542        {
543            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
544                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
545            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."));
546        }
547        {
548            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
549                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
550            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."));
551        }
552        {
553            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
554                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
555            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."));
556        }
557        {
558            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
559                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
560            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."));
561        }
562        {
563            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
564                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
565            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)."));
566        }
567        {
568            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
569                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
570            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."));
571        }
572        {
573            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
574                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
575            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
576            // copy tooltip to popup menu
577            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
578                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
579            item2->set_tooltip_text(item->get_tooltip_text());
580        }
581        {
582            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
583                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
584            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
585        }
586        {
587            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
588                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
589            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
590        }
591        {
592            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
593                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
594            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
595        }
596        {
597            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
598                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
599            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
600        }
601    
602    
603        instrument_menu = static_cast<Gtk::MenuItem*>(
604            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
605    
606      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
607      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
# Line 269  MainWindow::MainWindow() : Line 611  MainWindow::MainWindow() :
611      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
612      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
613    
614        set_file_is_shared(false);
615    
616      // Status Bar:      // Status Bar:
617      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
618      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
# Line 283  MainWindow::MainWindow() : Line 627  MainWindow::MainWindow() :
627      // Create the Tree model:      // Create the Tree model:
628      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
629      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
630      m_refTreeModel->signal_row_changed().connect(      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
631        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
632        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
633          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
634      );      );
635    
636      // Add the TreeView's view columns:      // Add the TreeView's view columns:
637      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
638      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
639        m_TreeView.set_headers_visible(true);
640        
641        // establish drag&drop within the instrument tree view, allowing to reorder
642        // the sequence of instruments within the gig file
643        {
644            std::vector<Gtk::TargetEntry> drag_target_instrument;
645            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
646            m_TreeView.drag_source_set(drag_target_instrument);
647            m_TreeView.drag_dest_set(drag_target_instrument);
648            m_TreeView.signal_drag_begin().connect(
649                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
650            );
651            m_TreeView.signal_drag_data_get().connect(
652                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
653            );
654            m_TreeView.signal_drag_data_received().connect(
655                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
656            );
657        }
658    
659      // create samples treeview (including its data model)      // create samples treeview (including its data model)
660      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
661      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
662        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
663        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."));
664      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
665      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
666      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
667        {
668            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
669            Gtk::CellRendererText* cellrenderer =
670                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
671            column->add_attribute(
672                cellrenderer->property_foreground(), m_SamplesModel.m_color
673            );
674        }
675        {
676            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
677            Gtk::CellRendererText* cellrenderer =
678                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
679            column->add_attribute(
680                cellrenderer->property_foreground(), m_SamplesModel.m_color
681            );
682        }
683        m_TreeViewSamples.set_headers_visible(true);
684      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
685          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
686      );      );
# Line 304  MainWindow::MainWindow() : Line 688  MainWindow::MainWindow() :
688          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
689      );      );
690    
691        // create scripts treeview (including its data model)
692        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
693        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
694        m_TreeViewScripts.set_tooltip_text(_(
695            "Use CTRL + double click for editing a script."
696            "\n\n"
697            "Note: instrument scripts are a LinuxSampler extension of the gig "
698            "format. This feature will not work with the GigaStudio software!"
699        ));
700        // m_TreeViewScripts.set_reorderable();
701        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
702        m_TreeViewScripts.set_headers_visible(false);
703        m_TreeViewScripts.signal_button_press_event().connect_notify(
704            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
705        );
706        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
707        m_TreeViewScripts.signal_row_activated().connect(
708            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
709        );
710        m_refScriptsTreeModel->signal_row_changed().connect(
711            sigc::mem_fun(*this, &MainWindow::script_name_changed)
712        );
713    
714        // establish drag&drop between scripts tree view and ScriptSlots window
715        std::vector<Gtk::TargetEntry> drag_target_gig_script;
716        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
717        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
718        m_TreeViewScripts.signal_drag_begin().connect(
719            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
720        );
721        m_TreeViewScripts.signal_drag_data_get().connect(
722            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
723        );
724    
725      // 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
726      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
727      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
728      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
729      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
730          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 322  MainWindow::MainWindow() : Line 740  MainWindow::MainWindow() :
740          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
741      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
742          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
743        m_RegionChooser.signal_instrument_changed().connect(
744            sigc::mem_fun(*this, &MainWindow::region_changed));
745      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
746          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
747      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
748            sigc::mem_fun(*this, &MainWindow::file_changed));
749        propDialog.signal_changed().connect(
750          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
751      propDialog.signal_info_changed().connect(      midiRules.signal_changed().connect(
752          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
753    
754      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 335  MainWindow::MainWindow() : Line 757  MainWindow::MainWindow() :
757          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
758      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
759          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
760        sample_ref_changed_signal.connect(
761            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
762        );
763        samples_to_be_removed_signal.connect(
764            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
765        );
766    
767        dimreg_edit.signal_select_sample().connect(
768            sigc::mem_fun(*this, &MainWindow::select_sample)
769        );
770    
771      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
772          sigc::hide(          sigc::hide(
# Line 371  MainWindow::MainWindow() : Line 803  MainWindow::MainWindow() :
803    
804      file = 0;      file = 0;
805      file_is_changed = false;      file_is_changed = false;
     set_file_is_shared(false);  
806    
807      show_all_children();      show_all_children();
808    
809      // start with a new gig file by default      // start with a new gig file by default
810      on_action_file_new();      on_action_file_new();
811    
812        // select 'Instruments' tab by default
813        // (gtk allows this only if the tab childs are visible, thats why it's here)
814        m_TreeViewNotebook.set_current_page(1);
815    
816        Gtk::Clipboard::get()->signal_owner_change().connect(
817            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
818        );
819        updateClipboardPasteAvailable();
820        updateClipboardCopyAvailable();
821  }  }
822    
823  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 402  void MainWindow::region_changed() Line 843  void MainWindow::region_changed()
843  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
844  {  {
845      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
846      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
847        if (rows.empty()) return NULL;
848      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
849      if (it) {      if (it) {
850          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
851          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 447  void MainWindow::update_dimregs() Line 888  void MainWindow::update_dimregs()
888              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
889          }          }
890      }      }
891    
892        m_RegionChooser.setModifyAllRegions(all_regions);
893        m_DimRegionChooser.setModifyAllRegions(all_regions);
894        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
895        m_DimRegionChooser.setModifyBothChannels(stereo);
896    
897        updateClipboardCopyAvailable();
898  }  }
899    
900  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 458  void MainWindow::dimreg_all_dimregs_togg Line 906  void MainWindow::dimreg_all_dimregs_togg
906  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
907  {  {
908      update_dimregs();      update_dimregs();
909      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
910  }  }
911    
912  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
913  {  {
914        // select item in instrument menu
915        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
916        if (!rows.empty()) {
917            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
918            if (it) {
919                Gtk::TreePath path(it);
920                int index = path[0];
921                const std::vector<Gtk::Widget*> children =
922                    instrument_menu->get_children();
923                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
924            }
925        }
926    
927      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
928    
929        if (Settings::singleton()->syncSamplerInstrumentSelection) {
930            switch_sampler_instrument_signal.emit(get_instrument());
931        }
932  }  }
933    
934  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
# Line 475  void loader_progress_callback(gig::progr Line 940  void loader_progress_callback(gig::progr
940  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
941  {  {
942      {      {
943          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
944          progress = fraction;          progress = fraction;
945      }      }
946      progress_dispatcher();      progress_dispatcher();
947  }  }
948    
949    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
950    // make sure stack is 16-byte aligned for SSE instructions
951    __attribute__((force_align_arg_pointer))
952    #endif
953  void Loader::thread_function()  void Loader::thread_function()
954  {  {
955      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
956      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
957      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
958      gig = new gig::File(riff);      try {
959      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
960      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
961      progress.custom = this;          gig::progress_t progress;
962            progress.callback = loader_progress_callback;
963      gig->GetInstrument(0, &progress);          progress.custom = this;
964      printf("End\n");  
965      finished_dispatcher();          gig->GetInstrument(0, &progress);
966            printf("End\n");
967            finished_dispatcher();
968        } catch (RIFF::Exception e) {
969            error_message = e.Message;
970            error_dispatcher.emit();
971        } catch (...) {
972            error_message = _("Unknown exception occurred");
973            error_dispatcher.emit();
974        }
975  }  }
976    
977  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
978      : thread(0), filename(filename)      : filename(filename), gig(0), thread(0), progress(0.f)
979  {  {
980  }  }
981    
982  void Loader::launch()  void Loader::launch()
983  {  {
984    #ifdef OLD_THREADS
985      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
986      printf("launch thread=%x\n", thread);  #else
987        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
988    #endif
989        printf("launch thread=%p\n", static_cast<void*>(thread));
990  }  }
991    
992  float Loader::get_progress()  float Loader::get_progress()
993  {  {
994      float res;      float res;
995      {      {
996          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
997          res = progress;          res = progress;
998      }      }
999      return res;      return res;
# Line 527  Glib::Dispatcher& Loader::signal_finishe Line 1009  Glib::Dispatcher& Loader::signal_finishe
1009      return finished_dispatcher;      return finished_dispatcher;
1010  }  }
1011    
1012  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
1013    {
1014        return error_dispatcher;
1015    }
1016    
1017    void saver_progress_callback(gig::progress_t* progress)
1018    {
1019        Saver* saver = static_cast<Saver*>(progress->custom);
1020        saver->progress_callback(progress->factor);
1021    }
1022    
1023    void Saver::progress_callback(float fraction)
1024    {
1025        {
1026            Glib::Threads::Mutex::Lock lock(progressMutex);
1027            progress = fraction;
1028        }
1029        progress_dispatcher.emit();
1030    }
1031    
1032    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1033    // make sure stack is 16-byte aligned for SSE instructions
1034    __attribute__((force_align_arg_pointer))
1035    #endif
1036    void Saver::thread_function()
1037    {
1038        printf("thread_function self=%p\n",
1039               static_cast<void*>(Glib::Threads::Thread::self()));
1040        printf("Start %s\n", filename.c_str());
1041        try {
1042            gig::progress_t progress;
1043            progress.callback = saver_progress_callback;
1044            progress.custom = this;
1045    
1046            // if no filename was provided, that means "save", if filename was provided means "save as"
1047            if (filename.empty()) {
1048                if (!Settings::singleton()->saveWithTemporaryFile) {
1049                    // save directly over the existing .gig file
1050                    // (requires less disk space than solution below
1051                    // but may be slower)
1052                    gig->Save(&progress);
1053                } else {
1054                    // save the file as separate temporary file first,
1055                    // then move the saved file over the old file
1056                    // (may result in performance speedup during save)
1057                    String tmpname = filename + ".TMP";
1058                    gig->Save(tmpname, &progress);
1059                    #if defined(WIN32)
1060                    if (!DeleteFile(filename.c_str())) {
1061                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1062                    }
1063                    #else // POSIX ...
1064                    if (unlink(filename.c_str())) {
1065                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
1066                    }
1067                    #endif
1068                    if (rename(tmpname.c_str(), filename.c_str())) {
1069                        #if defined(WIN32)
1070                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1071                        #else
1072                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
1073                        #endif
1074                    }
1075                }
1076            } else {
1077                gig->Save(filename, &progress);
1078            }
1079    
1080            printf("End\n");
1081            finished_dispatcher.emit();
1082        } catch (RIFF::Exception e) {
1083            error_message = e.Message;
1084            error_dispatcher.emit();
1085        } catch (...) {
1086            error_message = _("Unknown exception occurred");
1087            error_dispatcher.emit();
1088        }
1089    }
1090    
1091    Saver::Saver(gig::File* file, Glib::ustring filename)
1092        : gig(file), filename(filename), thread(0), progress(0.f)
1093    {
1094    }
1095    
1096    void Saver::launch()
1097    {
1098    #ifdef OLD_THREADS
1099        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1100    #else
1101        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1102    #endif
1103        printf("launch thread=%p\n", static_cast<void*>(thread));
1104    }
1105    
1106    float Saver::get_progress()
1107    {
1108        float res;
1109        {
1110            Glib::Threads::Mutex::Lock lock(progressMutex);
1111            res = progress;
1112        }
1113        return res;
1114    }
1115    
1116    Glib::Dispatcher& Saver::signal_progress()
1117    {
1118        return progress_dispatcher;
1119    }
1120    
1121    Glib::Dispatcher& Saver::signal_finished()
1122    {
1123        return finished_dispatcher;
1124    }
1125    
1126    Glib::Dispatcher& Saver::signal_error()
1127    {
1128        return error_dispatcher;
1129    }
1130    
1131    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1132      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1133  {  {
1134      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1135      show_all_children();      show_all_children();
1136        resize(600,50);
1137  }  }
1138    
1139  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
1140  // 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.
1141  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();  
1142      // forget all samples that ought to be imported      // forget all samples that ought to be imported
1143      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
1144      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1145      m_refTreeModel->clear();      m_refTreeModel->clear();
1146      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1147        m_refScriptsTreeModel->clear();
1148        // remove all entries from "Instrument" menu
1149        while (!instrument_menu->get_children().empty()) {
1150            remove_instrument_from_menu(0);
1151        }
1152      // free libgig's gig::File instance      // free libgig's gig::File instance
1153      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
1154      file = NULL;      file = NULL;
1155      set_file_is_shared(false);      set_file_is_shared(false);
1156  }  }
1157    
1158    void MainWindow::__refreshEntireGUI() {
1159        // clear the samples and instruments tree views
1160        m_refTreeModel->clear();
1161        m_refSamplesTreeModel->clear();
1162        m_refScriptsTreeModel->clear();
1163        // remove all entries from "Instrument" menu
1164        while (!instrument_menu->get_children().empty()) {
1165            remove_instrument_from_menu(0);
1166        }
1167    
1168        if (!this->file) return;
1169    
1170        load_gig(
1171            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1172        );
1173    }
1174    
1175  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
1176  {  {
1177      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 568  void MainWindow::on_action_file_new() Line 1184  void MainWindow::on_action_file_new()
1184      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
1185      // already add one new instrument by default      // already add one new instrument by default
1186      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
1187      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
1188      // update GUI with that new gig::File      // update GUI with that new gig::File
1189      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
1190  }  }
# Line 579  bool MainWindow::close_confirmation_dial Line 1195  bool MainWindow::close_confirmation_dial
1195                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
1196      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
1197      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1198      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  
1199      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1200      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1201      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);
1202      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1203      int response = dialog.run();      int response = dialog.run();
1204      dialog.hide();      dialog.hide();
1205      if (response == Gtk::RESPONSE_YES) return file_save();  
1206      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1207        if (response == Gtk::RESPONSE_NO) return true;
1208    
1209        // user cancelled dialog, thus don't close app
1210        if (response == Gtk::RESPONSE_CANCEL) return false;
1211    
1212        // TODO: the following return valid is disabled and hard coded instead for
1213        // now, due to the fact that saving with progress bar is now implemented
1214        // asynchronously, as a result the app does not close automatically anymore
1215        // after saving the file has completed
1216        //
1217        //   if (response == Gtk::RESPONSE_YES) return file_save();
1218        //   return response != Gtk::RESPONSE_CANCEL;
1219        //
1220        if (response == Gtk::RESPONSE_YES) file_save();
1221        return false; // always prevent closing the app for now (see comment above)
1222  }  }
1223    
1224  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
1225      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
1226      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  
1227      dialog.set_secondary_text(      dialog.set_secondary_text(
1228          _("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 "
1229            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1230            "load it.")            "load it."));
    );  
 #endif  
1231      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1232      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1233      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1234      int response = dialog.run();      int response = dialog.run();
1235      dialog.hide();      dialog.hide();
# Line 617  void MainWindow::on_action_file_open() Line 1243  void MainWindow::on_action_file_open()
1243      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
1244    
1245      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1246      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1247      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1248      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1249    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1250      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1251      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1252    #else
1253        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1254        filter->add_pattern("*.gig");
1255    #endif
1256      dialog.set_filter(filter);      dialog.set_filter(filter);
1257      if (current_dir != "") {      if (current_gig_dir != "") {
1258          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1259      }      }
1260      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1261          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1262          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1263          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%p\n",
1264                   static_cast<void*>(Glib::Threads::Thread::self()));
1265          load_file(filename.c_str());          load_file(filename.c_str());
1266          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1267      }      }
1268  }  }
1269    
1270  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1271  {  {
1272      __clear();      __clear();
1273      load_dialog = new LoadDialog("Loading...", *this);  
1274      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1275      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1276            Glib::filename_display_basename(name) + "' ...",
1277            *this
1278        );
1279        progress_dialog->show_all();
1280        loader = new Loader(name); //FIXME: memory leak!
1281      loader->signal_progress().connect(      loader->signal_progress().connect(
1282          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1283      loader->signal_finished().connect(      loader->signal_finished().connect(
1284          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1285        loader->signal_error().connect(
1286            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1287      loader->launch();      loader->launch();
1288  }  }
1289    
# Line 660  void MainWindow::load_instrument(gig::In Line 1299  void MainWindow::load_instrument(gig::In
1299      // load the instrument      // load the instrument
1300      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1301      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1302      //TODO: automatically select the given instrument      // automatically select the given instrument
1303        int i = 0;
1304        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1305             instrument = pFile->GetNextInstrument(), ++i)
1306        {
1307            if (instrument == instr) {
1308                // select item in "instruments" tree view
1309                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1310                // make sure the selected item in the "instruments" tree view is
1311                // visible (scroll to it)
1312                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1313                // select item in instrument menu
1314                {
1315                    const std::vector<Gtk::Widget*> children =
1316                        instrument_menu->get_children();
1317                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1318                }
1319                // update region chooser and dimension region chooser
1320                m_RegionChooser.set_instrument(instr);
1321                break;
1322            }
1323        }
1324  }  }
1325    
1326  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1327  {  {
1328      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1329  }  }
1330    
1331  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1332  {  {
1333      printf("Loader finished!\n");      printf("Loader finished!\n");
1334      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
1335      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1336      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1337        progress_dialog->hide();
1338    }
1339    
1340    void MainWindow::on_loader_error()
1341    {
1342        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1343        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1344        msg.run();
1345        progress_dialog->hide();
1346  }  }
1347    
1348  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 712  bool MainWindow::file_save() Line 1381  bool MainWindow::file_save()
1381    
1382      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1383      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1384      try {  
1385          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1386          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1387              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1388              file_is_changed = false;          *this
1389          }      );
1390      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1391          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1392          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1393          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1394          msg.run();      saver->signal_finished().connect(
1395          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1396      }      saver->signal_error().connect(
1397      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1398        saver->launch();
1399    
1400        return true;
1401    }
1402    
1403    void MainWindow::on_saver_progress()
1404    {
1405        progress_dialog->set_fraction(saver->get_progress());
1406    }
1407    
1408    void MainWindow::on_saver_error()
1409    {
1410        file_structure_changed_signal.emit(this->file);
1411        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1412        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1413        msg.run();
1414    }
1415    
1416    void MainWindow::on_saver_finished()
1417    {
1418        this->file = saver->gig;
1419        this->filename = saver->filename;
1420        current_gig_dir = Glib::path_get_dirname(filename);
1421        set_title(Glib::filename_display_basename(filename));
1422        file_has_name = true;
1423        file_is_changed = false;
1424        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1425      __import_queued_samples();      __import_queued_samples();
1426        std::cout << "Importing queued samples done.\n" << std::flush;
1427    
1428      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1429      return true;  
1430        __refreshEntireGUI();
1431        progress_dialog->hide();
1432  }  }
1433    
1434  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 739  void MainWindow::on_action_file_save_as( Line 1439  void MainWindow::on_action_file_save_as(
1439    
1440  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1441  {  {
1442      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1443      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1444      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
1445      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  
1446      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1447      // TODO: an overwrite dialog for gtkmm < 2.8  
1448  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1449      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1450      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1451    #else
1452        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1453        filter->add_pattern("*.gig");
1454    #endif
1455      dialog.set_filter(filter);      dialog.set_filter(filter);
1456    
1457      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1458          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1459      } else if (current_dir != "") {      {
1460          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1461      }          std::string dir = Glib::path_get_dirname(filename);
1462      dialog.set_current_name(Glib::filename_display_basename(filename));          basename = std::string(_("copy_of_")) + basename;
1463            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1464            if (Glib::path_is_absolute(filename)) {
1465                dialog.set_filename(copyFileName);
1466            } else {
1467                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1468            }
1469            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1470        }
1471    
1472        // show warning in the dialog
1473        Gtk::HBox descriptionArea;
1474        descriptionArea.set_spacing(15);
1475        Gtk::Image warningIcon;
1476        warningIcon.set_from_icon_name("dialog-warning",
1477                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1478        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1479    #if GTKMM_MAJOR_VERSION < 3
1480        view::WrapLabel description;
1481    #else
1482        Gtk::Label description;
1483        description.set_line_wrap();
1484    #endif
1485        description.set_markup(
1486            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1487              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1488              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1489              "to the same .gig file. Using "
1490              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1491              "same .gig file will end up in corrupted sample wave data!\n")
1492        );
1493        descriptionArea.pack_start(description);
1494        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1495        descriptionArea.show_all();
1496    
1497      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1498          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1499          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1500              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;  
1501          }          }
1502          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1503          file_structure_changed_signal.emit(this->file);  
1504            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1505                _("Saving") +  Glib::ustring(" '") +
1506                Glib::filename_display_basename(filename) + "' ...",
1507                *this
1508            );
1509            progress_dialog->show_all();
1510    
1511            saver = new Saver(file, filename); //FIXME: memory leak!
1512            saver->signal_progress().connect(
1513                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1514            saver->signal_finished().connect(
1515                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1516            saver->signal_error().connect(
1517                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1518            saver->launch();
1519    
1520          return true;          return true;
1521      }      }
1522      return false;      return false;
# Line 791  bool MainWindow::file_save_as() Line 1526  bool MainWindow::file_save_as()
1526  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1527      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1528      Glib::ustring error_files;      Glib::ustring error_files;
1529      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1530      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1531           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1532          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1533          SF_INFO info;          SF_INFO info;
1534          info.format = 0;          info.format = 0;
1535          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open(iter->second.sample_path.c_str(), SFM_READ, &info);
1536            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1537          try {          try {
1538              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1539              // determine sample's bit depth              // determine sample's bit depth
1540              int bitdepth;              int bitdepth;
1541              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 816  void MainWindow::__import_queued_samples Line 1552  void MainWindow::__import_queued_samples
1552                      break;                      break;
1553                  default:                  default:
1554                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1555                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1556              }              }
1557    
1558                // reset write position for sample
1559                iter->first->SetPos(0);
1560    
1561              const int bufsize = 10000;              const int bufsize = 10000;
1562              switch (bitdepth) {              switch (bitdepth) {
1563                  case 16: {                  case 16: {
# Line 828  void MainWindow::__import_queued_samples Line 1567  void MainWindow::__import_queued_samples
1567                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1568                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1569                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1570                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1571                          cnt -= n;                          cnt -= n;
1572                      }                      }
1573                      delete[] buffer;                      delete[] buffer;
# Line 848  void MainWindow::__import_queued_samples Line 1587  void MainWindow::__import_queued_samples
1587                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1588                          }                          }
1589                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1590                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1591                          cnt -= n;                          cnt -= n;
1592                      }                      }
1593                      delete[] srcbuf;                      delete[] srcbuf;
# Line 858  void MainWindow::__import_queued_samples Line 1597  void MainWindow::__import_queued_samples
1597              }              }
1598              // cleanup              // cleanup
1599              sf_close(hFile);              sf_close(hFile);
1600                // let the sampler re-cache the sample if needed
1601                sample_changed_signal.emit(iter->first);
1602              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1603              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1604              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1605              ++iter;              ++iter;
1606              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1607          } catch (std::string what) {          } catch (std::string what) {
1608              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1609              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1610              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1611              ++iter;              ++iter;
1612          }          }
1613      }      }
1614      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1615      if (error_files.size()) {      if (!error_files.empty()) {
1616          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;
1617          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1618          msg.run();          msg.run();
# Line 884  void MainWindow::on_action_file_properti Line 1625  void MainWindow::on_action_file_properti
1625      propDialog.deiconify();      propDialog.deiconify();
1626  }  }
1627    
1628    void MainWindow::on_action_warn_user_on_extensions() {
1629        Settings::singleton()->warnUserOnExtensions =
1630            !Settings::singleton()->warnUserOnExtensions;
1631    }
1632    
1633    void MainWindow::on_action_sync_sampler_instrument_selection() {
1634        Settings::singleton()->syncSamplerInstrumentSelection =
1635            !Settings::singleton()->syncSamplerInstrumentSelection;
1636    }
1637    
1638    void MainWindow::on_action_move_root_note_with_region_moved() {
1639        Settings::singleton()->moveRootNoteWithRegionMoved =
1640            !Settings::singleton()->moveRootNoteWithRegionMoved;
1641    }
1642    
1643  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1644  {  {
 #ifdef ABOUT_DIALOG  
1645      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1646    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1647        dialog.set_program_name("Gigedit");
1648    #else
1649        dialog.set_name("Gigedit");
1650    #endif
1651      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1652      dialog.set_copyright("Copyright (C) 2006,2007 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1653      dialog.set_comments(      const std::string sComment =
1654          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
1655          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1656          "Please notice that this is still a very young instrument editor. "          _(
1657          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
1658          "this application.\n"              "\n"
1659          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
1660          "Please report bugs to: http://bugs.linuxsampler.org"              "backup your Gigasampler/GigaStudio files before editing them with "
1661      );              "this application.\n"
1662                "\n"
1663                "Please report bugs to: http://bugs.linuxsampler.org"
1664            );
1665        dialog.set_comments(sComment.c_str());
1666      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1667      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1668      dialog.run();      dialog.run();
 #endif  
1669  }  }
1670    
1671  PropDialog::PropDialog()  PropDialog::PropDialog()
1672      : table(2,1),      : eFileFormat(_("File Format")),
1673        eName("Name"),        eName(_("Name")),
1674        eCreationDate("Creation date"),        eCreationDate(_("Creation date")),
1675        eComments("Comments"),        eComments(_("Comments")),
1676        eProduct("Product"),        eProduct(_("Product")),
1677        eCopyright("Copyright"),        eCopyright(_("Copyright")),
1678        eArtists("Artists"),        eArtists(_("Artists")),
1679        eGenre("Genre"),        eGenre(_("Genre")),
1680        eKeywords("Keywords"),        eKeywords(_("Keywords")),
1681        eEngineer("Engineer"),        eEngineer(_("Engineer")),
1682        eTechnician("Technician"),        eTechnician(_("Technician")),
1683        eSoftware("Software"),        eSoftware(_("Software")),
1684        eMedium("Medium"),        eMedium(_("Medium")),
1685        eSource("Source"),        eSource(_("Source")),
1686        eSourceForm("Source form"),        eSourceForm(_("Source form")),
1687        eCommissioned("Commissioned"),        eCommissioned(_("Commissioned")),
1688        eSubject("Subject"),        eSubject(_("Subject")),
1689        quitButton(Gtk::Stock::CLOSE),        quitButton(_("_Close"), true),
1690        update_model(0)        table(2, 1),
1691          m_file(NULL)
1692  {  {
1693      set_title("File Properties");      set_title(_("File Properties"));
1694      eName.set_width_chars(50);      eName.set_width_chars(50);
1695    
1696      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
# Line 946  PropDialog::PropDialog() Line 1710  PropDialog::PropDialog()
1710      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
1711      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
1712    
1713        table.add(eFileFormat);
1714      table.add(eName);      table.add(eName);
1715      table.add(eCreationDate);      table.add(eCreationDate);
1716      table.add(eComments);      table.add(eComments);
# Line 972  PropDialog::PropDialog() Line 1737  PropDialog::PropDialog()
1737      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1738      buttonBox.show();      buttonBox.show();
1739      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1740      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1741      quitButton.grab_focus();      quitButton.grab_focus();
1742      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
1743          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &PropDialog::hide));
1744        eFileFormat.signal_value_changed().connect(
1745            sigc::mem_fun(*this, &PropDialog::onFileFormatChanged));
1746    
1747      quitButton.show();      quitButton.show();
1748      vbox.show();      vbox.show();
1749      show_all_children();      show_all_children();
1750  }  }
1751    
1752  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_file(gig::File* file)
1753  {  {
1754      this->info = info;      m_file = file;
1755      update_model++;  
1756      eName.set_value(info->Name);      // update file format version combo box
1757      eCreationDate.set_value(info->CreationDate);      const std::string sGiga = "Gigasampler/GigaStudio v";
1758      eComments.set_value(info->Comments);      const int major = file->pVersion->major;
1759      eProduct.set_value(info->Product);      std::vector<std::string> txts;
1760      eCopyright.set_value(info->Copyright);      std::vector<int> values;
1761      eArtists.set_value(info->Artists);      txts.push_back(sGiga + "2"); values.push_back(2);
1762      eGenre.set_value(info->Genre);      txts.push_back(sGiga + "3/v4"); values.push_back(3);
1763      eKeywords.set_value(info->Keywords);      if (major != 2 && major != 3) {
1764      eEngineer.set_value(info->Engineer);          txts.push_back(sGiga + ToString(major)); values.push_back(major);
1765      eTechnician.set_value(info->Technician);      }
1766      eSoftware.set_value(info->Software);      std::vector<const char*> texts;
1767      eMedium.set_value(info->Medium);      for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1768      eSource.set_value(info->Source);      texts.push_back(NULL); values.push_back(0);
1769      eSourceForm.set_value(info->SourceForm);      eFileFormat.set_choices(&texts[0], &values[0]);
1770      eCommissioned.set_value(info->Commissioned);      eFileFormat.set_value(major);
1771      eSubject.set_value(info->Subject);  }
1772      update_model--;  
1773    void PropDialog::onFileFormatChanged() {
1774        const int major = eFileFormat.get_value();
1775        if (m_file) m_file->pVersion->major = major;
1776  }  }
1777    
1778  sigc::signal<void>& PropDialog::signal_info_changed()  void PropDialog::set_info(DLS::Info* info)
1779  {  {
1780      return info_changed;      update(info);
1781  }  }
1782    
1783  void InstrumentProps::set_IsDrum(bool value)  
1784    void InstrumentProps::set_Name(const gig::String& name)
1785  {  {
1786      instrument->IsDrum = value;      m->pInfo->Name = name;
1787  }  }
1788    
1789  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
1790  {  {
1791      instrument->MIDIBank = value;      update_model++;
1792        eName.set_value(m->pInfo->Name);
1793        update_model--;
1794  }  }
1795    
1796  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
1797  {  {
1798      instrument->MIDIProgram = value;      m->IsDrum = value;
1799  }  }
1800    
1801  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
1802  {  {
1803      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
1804  }  }
1805    
1806  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
1807  {  {
1808      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
1809  }  }
1810    
1811  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
1812      : table(2,1),      quitButton(_("_Close"), true),
1813        quitButton(Gtk::Stock::CLOSE),      table(2,1),
1814        eName("Name"),      eName(_("Name")),
1815        eIsDrum("Is drum"),      eIsDrum(_("Is drum")),
1816        eMIDIBank("MIDI bank", 0, 16383),      eMIDIBank(_("MIDI bank"), 0, 16383),
1817        eMIDIProgram("MIDI program"),      eMIDIProgram(_("MIDI program")),
1818        eAttenuation("Attenuation", 0, 96, 0, 1),      eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1819        eGainPlus6("Gain +6dB", eAttenuation, -6),      eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1820        eEffectSend("Effect send", 0, 65535),      eEffectSend(_("Effect send"), 0, 65535),
1821        eFineTune("Fine tune", -8400, 8400),      eFineTune(_("Fine tune"), -8400, 8400),
1822        ePitchbendRange("Pitchbend range", 0, 12),      ePitchbendRange(_("Pitchbend range"), 0, 12),
1823        ePianoReleaseMode("Piano release mode"),      ePianoReleaseMode(_("Piano release mode")),
1824        eDimensionKeyRangeLow("Keyswitching range low"),      eDimensionKeyRangeLow(_("Keyswitching range low")),
1825        eDimensionKeyRangeHigh("Keyswitching range high"),      eDimensionKeyRangeHigh(_("Keyswitching range high"))
       update_model(0)  
1826  {  {
1827      set_title("Instrument Properties");      set_title(_("Instrument Properties"));
1828    
1829      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
1830          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
# Line 1069  InstrumentProps::InstrumentProps() Line 1835  InstrumentProps::InstrumentProps()
1835            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
1836      );      );
1837    
1838        connect(eName, &InstrumentProps::set_Name);
1839      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
1840      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1841      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
# Line 1078  InstrumentProps::InstrumentProps() Line 1845  InstrumentProps::InstrumentProps()
1845      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
1846      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1847      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1848      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1849              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
1850      connect(eDimensionKeyRangeHigh,  
1851              &InstrumentProps::set_DimensionKeyRange_high);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
1852    
1853      table.set_col_spacings(5);      table.set_col_spacings(5);
1854    
# Line 1107  InstrumentProps::InstrumentProps() Line 1874  InstrumentProps::InstrumentProps()
1874      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1875      buttonBox.show();      buttonBox.show();
1876      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1877      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1878      quitButton.grab_focus();      quitButton.grab_focus();
1879    
1880      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 1120  InstrumentProps::InstrumentProps() Line 1887  InstrumentProps::InstrumentProps()
1887    
1888  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1889  {  {
1890      this->instrument = instrument;      update(instrument);
1891    
1892      update_model++;      update_model++;
1893      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
1894      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
1895      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
1896      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
     eAttenuation.set_value(instrument->Attenuation);  
     eGainPlus6.set_value(instrument->Attenuation);  
     eEffectSend.set_value(instrument->EffectSend);  
     eFineTune.set_value(instrument->FineTune);  
     ePitchbendRange.set_value(instrument->PitchbendRange);  
     ePianoReleaseMode.set_value(instrument->PianoReleaseMode);  
     eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);  
     eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);  
1897      update_model--;      update_model--;
1898  }  }
1899    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
1900    
1901  void MainWindow::file_changed()  void MainWindow::file_changed()
1902  {  {
# Line 1151  void MainWindow::file_changed() Line 1906  void MainWindow::file_changed()
1906      }      }
1907  }  }
1908    
1909    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1910        sample_ref_count.clear();
1911        
1912        if (!gig) return;
1913    
1914        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1915             instrument = gig->GetNextInstrument())
1916        {
1917            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1918                 rgn = instrument->GetNextRegion())
1919            {
1920                for (int i = 0; i < 256; ++i) {
1921                    if (!rgn->pDimensionRegions[i]) continue;
1922                    if (rgn->pDimensionRegions[i]->pSample) {
1923                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1924                    }
1925                }
1926            }
1927        }
1928    }
1929    
1930  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1931  {  {
1932      file = 0;      file = 0;
1933      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
1934    
1935      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
1936            (filename && strlen(filename) > 0) ?
1937                filename : (!gig->GetFileName().empty()) ?
1938                    gig->GetFileName() : _("Unsaved Gig File");
1939      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1940      file_has_name = filename;      file_has_name = filename;
1941      file_is_changed = false;      file_is_changed = false;
1942    
1943        propDialog.set_file(gig);
1944      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1945    
1946      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
1947          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));      int index = 0;
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
1948      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1949           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
1950            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1951    
1952          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1953          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1954          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
1955            row[m_Columns.m_col_name] = name;
1956          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1957          // create a menu item for this instrument  
1958          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++;  
1959      }      }
1960      instrument_menu->show();      instrument_name_connection.unblock();
1961      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1962    
1963        updateSampleRefCountMap(gig);
1964    
1965      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1966          if (group->Name != "") {          if (group->Name != "") {
1967              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1968              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1969              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1970              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1971              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1972              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1201  void MainWindow::load_gig(gig::File* gig Line 1974  void MainWindow::load_gig(gig::File* gig
1974                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1975                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1976                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1977                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1978                        gig_to_utf8(sample->pInfo->Name);
1979                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1980                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1981                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1982                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1983                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1984              }              }
1985          }          }
1986      }      }
1987        
1988        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1989            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1990    
1991            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1992            Gtk::TreeModel::Row rowGroup = *iterGroup;
1993            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1994            rowGroup[m_ScriptsModel.m_col_group]  = group;
1995            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1996            for (int s = 0; group->GetScript(s); ++s) {
1997                gig::Script* script = group->GetScript(s);
1998    
1999                Gtk::TreeModel::iterator iterScript =
2000                    m_refScriptsTreeModel->append(rowGroup.children());
2001                Gtk::TreeModel::Row rowScript = *iterScript;
2002                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
2003                rowScript[m_ScriptsModel.m_col_script] = script;
2004                rowScript[m_ScriptsModel.m_col_group]  = NULL;
2005            }
2006        }
2007        // unfold all sample groups & script groups by default
2008        m_TreeViewSamples.expand_all();
2009        m_TreeViewScripts.expand_all();
2010    
2011      file = gig;      file = gig;
2012    
2013      // select the first instrument      // select the first instrument
2014      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
2015      tree_sel_ref->select(Gtk::TreePath("0"));  
2016        instr_props_set_instrument();
2017        gig::Instrument* instrument = get_instrument();
2018        if (instrument) {
2019            midiRules.set_instrument(instrument);
2020        }
2021  }  }
2022    
2023  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
2024  {  {
2025      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
2026      if (instrument)  
2027      {      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2028        if (rows.empty()) {
2029            instrumentProps.hide();
2030            return false;
2031        }
2032        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2033        if (it) {
2034            Gtk::TreeModel::Row row = *it;
2035            gig::Instrument* instrument = row[m_Columns.m_col_instr];
2036    
2037          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
2038    
2039            // make sure instrument tree is updated when user changes the
2040            // instrument name in instrument properties window
2041            instrumentProps.signal_name_changed().connect(
2042                sigc::bind(
2043                    sigc::mem_fun(*this,
2044                                  &MainWindow::instr_name_changed_by_instr_props),
2045                    it));
2046        } else {
2047            instrumentProps.hide();
2048        }
2049        return it;
2050    }
2051    
2052    void MainWindow::show_instr_props()
2053    {
2054        if (instr_props_set_instrument()) {
2055          instrumentProps.show();          instrumentProps.show();
2056          instrumentProps.deiconify();          instrumentProps.deiconify();
2057      }      }
2058  }  }
2059    
2060    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
2061    {
2062        Gtk::TreeModel::Row row = *it;
2063        Glib::ustring name = row[m_Columns.m_col_name];
2064    
2065        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2066        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
2067        if (gigname != name) {
2068            row[m_Columns.m_col_name] = gigname;
2069        }
2070    }
2071    
2072    void MainWindow::show_midi_rules()
2073    {
2074        if (gig::Instrument* instrument = get_instrument())
2075        {
2076            midiRules.set_instrument(instrument);
2077            midiRules.show();
2078            midiRules.deiconify();
2079        }
2080    }
2081    
2082    void MainWindow::show_script_slots() {
2083        if (!file) return;
2084        // get selected instrument
2085        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2086        if (rows.empty()) return;
2087        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2088        if (!it) return;
2089        Gtk::TreeModel::Row row = *it;
2090        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2091        if (!instrument) return;
2092    
2093        ScriptSlots* window = new ScriptSlots;
2094        window->setInstrument(instrument);
2095        //window->reparent(*this);
2096        window->show();
2097    }
2098    
2099    void MainWindow::on_action_refresh_all() {
2100        __refreshEntireGUI();
2101    }
2102    
2103  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2104      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2105          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1237  void MainWindow::on_action_view_status_b Line 2111  void MainWindow::on_action_view_status_b
2111      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2112  }  }
2113    
2114    void MainWindow::on_auto_restore_win_dim() {
2115        Gtk::CheckMenuItem* item =
2116            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2117        if (!item) {
2118            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2119            return;
2120        }
2121        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2122    }
2123    
2124    void MainWindow::on_save_with_temporary_file() {
2125        Gtk::CheckMenuItem* item =
2126            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2127        if (!item) {
2128            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2129            return;
2130        }
2131        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2132    }
2133    
2134    bool MainWindow::is_copy_samples_unity_note_enabled() const {
2135        Gtk::CheckMenuItem* item =
2136            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
2137        if (!item) {
2138            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
2139            return true;
2140        }
2141        return item->get_active();
2142    }
2143    
2144    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
2145        Gtk::CheckMenuItem* item =
2146            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
2147        if (!item) {
2148            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
2149            return true;
2150        }
2151        return item->get_active();
2152    }
2153    
2154    bool MainWindow::is_copy_samples_loop_enabled() const {
2155        Gtk::CheckMenuItem* item =
2156            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
2157        if (!item) {
2158            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
2159            return true;
2160        }
2161        return item->get_active();
2162    }
2163    
2164  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
2165  {  {
2166      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2167          show_instr_props();          show_instr_props();
2168      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2169            // gig v2 files have no midi rules
2170            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2171            static_cast<Gtk::MenuItem*>(
2172                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2173                    bEnabled
2174                );
2175            static_cast<Gtk::MenuItem*>(
2176                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2177                    bEnabled
2178                );
2179          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2180      }      }
2181  }  }
2182    
2183  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
2184      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
2185            const std::vector<Gtk::Widget*> children =
2186                instrument_menu->get_children();
2187            std::vector<Gtk::Widget*>::const_iterator it =
2188                find(children.begin(), children.end(), item);
2189            if (it != children.end()) {
2190                int index = it - children.begin();
2191                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
2192    
2193                m_RegionChooser.set_instrument(file->GetInstrument(index));
2194            }
2195        }
2196    }
2197    
2198    void MainWindow::select_instrument(gig::Instrument* instrument) {
2199        if (!instrument) return;
2200    
2201        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2202        for (int i = 0; i < model->children().size(); ++i) {
2203            Gtk::TreeModel::Row row = model->children()[i];
2204            if (row[m_Columns.m_col_instr] == instrument) {
2205                // select and show the respective instrument in the list view
2206                show_intruments_tab();
2207                m_TreeView.get_selection()->unselect_all();
2208                m_TreeView.get_selection()->select(model->children()[i]);
2209                std::vector<Gtk::TreeModel::Path> rows =
2210                    m_TreeView.get_selection()->get_selected_rows();
2211                if (!rows.empty())
2212                    m_TreeView.scroll_to_row(rows[0]);
2213                on_sel_change(); // the regular instrument selection change callback
2214            }
2215        }
2216    }
2217    
2218    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2219    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2220        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2221        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2222    
2223        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2224        for (int i = 0; i < model->children().size(); ++i) {
2225            Gtk::TreeModel::Row row = model->children()[i];
2226            if (row[m_Columns.m_col_instr] == pInstrument) {
2227                // select and show the respective instrument in the list view
2228                show_intruments_tab();
2229                m_TreeView.get_selection()->unselect_all();
2230                m_TreeView.get_selection()->select(model->children()[i]);
2231                std::vector<Gtk::TreeModel::Path> rows =
2232                    m_TreeView.get_selection()->get_selected_rows();
2233                if (!rows.empty())
2234                    m_TreeView.scroll_to_row(rows[0]);
2235                on_sel_change(); // the regular instrument selection change callback
2236    
2237                // select respective region in the region selector
2238                m_RegionChooser.set_region(pRegion);
2239    
2240                // select and show the respective dimension region in the editor
2241                //update_dimregs();
2242                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2243                //dimreg_edit.set_dim_region(dimRgn);
2244    
2245                return true;
2246            }
2247        }
2248    
2249        return false;
2250    }
2251    
2252    void MainWindow::select_sample(gig::Sample* sample) {
2253        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2254        for (int g = 0; g < model->children().size(); ++g) {
2255            Gtk::TreeModel::Row rowGroup = model->children()[g];
2256            for (int s = 0; s < rowGroup.children().size(); ++s) {
2257                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2258                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2259                    show_samples_tab();
2260                    m_TreeViewSamples.get_selection()->unselect_all();
2261                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2262                    std::vector<Gtk::TreeModel::Path> rows =
2263                        m_TreeViewSamples.get_selection()->get_selected_rows();
2264                    if (rows.empty()) return;
2265                    m_TreeViewSamples.scroll_to_row(rows[0]);
2266                    return;
2267                }
2268            }
2269        }
2270  }  }
2271    
2272  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2273      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2274            // by default if Ctrl keys is pressed down, then a mouse right-click
2275            // does not select the respective row, so we must assure this
2276            // programmatically ...
2277            /*{
2278                Gtk::TreeModel::Path path;
2279                Gtk::TreeViewColumn* pColumn = NULL;
2280                int cellX, cellY;
2281                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2282                    (int)button->x, (int)button->y,
2283                    path, pColumn, cellX, cellY
2284                );
2285                if (bSuccess) {
2286                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2287                        printf("not selected !!!\n");
2288                        m_TreeViewSamples.get_selection()->select(path);
2289                    }
2290                }
2291            }*/
2292    
2293          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2294              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2295          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2296          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2297          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2298          bool group_selected  = false;          const int n = rows.size();
2299          bool sample_selected = false;          int nGroups  = 0;
2300          if (it) {          int nSamples = 0;
2301            for (int r = 0; r < n; ++r) {
2302                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2303                if (!it) continue;
2304              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2305              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2306              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2307          }          }
2308    
2309          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2310              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2311          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2312              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2313          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2314              set_sensitive(file);              set_sensitive(file);
2315            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2316                set_sensitive(nSamples == 1);
2317          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2318              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2319          // show sample popup          // show sample popup
2320          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2321    
2322            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2323                set_sensitive(n == 1);
2324            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2325                set_sensitive(n);
2326            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2327                set_sensitive(file);
2328            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2329                set_sensitive(nSamples == 1);
2330            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2331                set_sensitive(n);
2332      }      }
2333  }  }
2334    
2335  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2336      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2337      if (!file) return;          Gtk::Menu* script_popup =
2338      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2339      __instrument_indexer++;          // update enabled/disabled state of sample popup items
2340      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2341          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
2342            bool group_selected  = false;
2343            bool script_selected = false;
2344            if (it) {
2345                Gtk::TreeModel::Row row = *it;
2346                group_selected  = row[m_ScriptsModel.m_col_group];
2347                script_selected = row[m_ScriptsModel.m_col_script];
2348            }
2349            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2350                set_sensitive(group_selected || script_selected);
2351            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2352                set_sensitive(file);
2353            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2354                set_sensitive(script_selected);    
2355            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2356                set_sensitive(group_selected || script_selected);
2357            // show sample popup
2358            script_popup->popup(button->button, button->time);
2359    
2360            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2361                set_sensitive(group_selected || script_selected);
2362            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2363                set_sensitive(file);
2364            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2365                set_sensitive(script_selected);    
2366            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2367                set_sensitive(group_selected || script_selected);
2368        }
2369    }
2370    
2371    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2372        const Glib::ustring& name, int position) {
2373    
2374        Gtk::RadioMenuItem::Group instrument_group;
2375        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2376        if (!children.empty()) {
2377            instrument_group =
2378                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2379        }
2380        Gtk::RadioMenuItem* item =
2381            new Gtk::RadioMenuItem(instrument_group, name);
2382        if (position < 0) {
2383            instrument_menu->append(*item);
2384        } else {
2385            instrument_menu->insert(*item, position);
2386        }
2387        item->show();
2388        item->signal_activate().connect(
2389            sigc::bind(
2390                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2391                item));
2392        return item;
2393    }
2394    
2395    void MainWindow::remove_instrument_from_menu(int index) {
2396        const std::vector<Gtk::Widget*> children =
2397            instrument_menu->get_children();
2398        Gtk::Widget* child = children[index];
2399        instrument_menu->remove(*child);
2400        delete child;
2401    }
2402    
2403    void MainWindow::add_instrument(gig::Instrument* instrument) {
2404        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2405    
2406      // update instrument tree view      // update instrument tree view
2407        instrument_name_connection.block();
2408      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2409      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2410      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2411        rowInstr[m_Columns.m_col_name] = name;
2412      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2413        instrument_name_connection.unblock();
2414    
2415        add_instrument_to_menu(name);
2416    
2417        m_TreeView.get_selection()->select(iterInstr);
2418    
2419      file_changed();      file_changed();
2420  }  }
2421    
2422    void MainWindow::on_action_add_instrument() {
2423        static int __instrument_indexer = 0;
2424        if (!file) return;
2425        gig::Instrument* instrument = file->AddInstrument();
2426        __instrument_indexer++;
2427        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2428                                                ToString(__instrument_indexer));
2429    
2430        add_instrument(instrument);
2431    }
2432    
2433    void MainWindow::on_action_duplicate_instrument() {
2434        if (!file) return;
2435    
2436        // retrieve the currently selected instrument
2437        // (being the original instrument to be duplicated)
2438        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2439        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2440        for (int r = 0; r < rows.size(); ++r) {
2441            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2442            if (it) {
2443                Gtk::TreeModel::Row row = *it;
2444                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2445                if (instrOrig) {
2446                    // duplicate the orginal instrument
2447                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2448                    instrNew->pInfo->Name =
2449                        instrOrig->pInfo->Name +
2450                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2451    
2452                    add_instrument(instrNew);
2453                }
2454            }
2455        }
2456    }
2457    
2458  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2459      if (!file) return;      if (!file) return;
2460      if (file_is_shared) {      if (file_is_shared) {
# Line 1306  void MainWindow::on_action_remove_instru Line 2469  void MainWindow::on_action_remove_instru
2469      }      }
2470    
2471      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2472      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2473      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2474            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2475            if (!it) continue;
2476          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2477          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2478          try {          try {
2479                Gtk::TreePath path(it);
2480                int index = path[0];
2481    
2482              // remove instrument from the gig file              // remove instrument from the gig file
2483              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2484              file_changed();              file_changed();
2485    
2486                remove_instrument_from_menu(index);
2487    
2488                // remove row from instruments tree view
2489                m_refTreeModel->erase(it);
2490                // update "Nr" column of all instrument rows
2491                {
2492                    int index = 0;
2493                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2494                         it != m_refTreeModel->children().end(); ++it, ++index)
2495                    {
2496                        Gtk::TreeModel::Row row = *it;
2497                        row[m_Columns.m_col_nr] = index;
2498                    }
2499                }
2500    
2501    #if GTKMM_MAJOR_VERSION < 3
2502                // select another instrument (in gtk3 this is done
2503                // automatically)
2504                if (!m_refTreeModel->children().empty()) {
2505                    if (index == m_refTreeModel->children().size()) {
2506                        index--;
2507                    }
2508                    m_TreeView.get_selection()->select(
2509                        Gtk::TreePath(ToString(index)));
2510                }
2511    #endif
2512                instr_props_set_instrument();
2513                instr = get_instrument();
2514                if (instr) {
2515                    midiRules.set_instrument(instr);
2516                } else {
2517                    midiRules.hide();
2518                }
2519          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2520              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2521              msg.run();              msg.run();
# Line 1326  void MainWindow::on_action_remove_instru Line 2526  void MainWindow::on_action_remove_instru
2526  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2527      //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
2528      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2529          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2530      );      );
2531      msg.run();      msg.run();
2532  }  }
2533    
2534    void MainWindow::on_action_add_script_group() {
2535        static int __script_indexer = 0;
2536        if (!file) return;
2537        gig::ScriptGroup* group = file->AddScriptGroup();
2538        group->Name = gig_from_utf8(_("Unnamed Group"));
2539        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2540        __script_indexer++;
2541        // update sample tree view
2542        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2543        Gtk::TreeModel::Row rowGroup = *iterGroup;
2544        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2545        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2546        rowGroup[m_ScriptsModel.m_col_group] = group;
2547        file_changed();
2548    }
2549    
2550    void MainWindow::on_action_add_script() {
2551        if (!file) return;
2552        // get selected group
2553        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2554        Gtk::TreeModel::iterator it = sel->get_selected();
2555        if (!it) return;
2556        Gtk::TreeModel::Row row = *it;
2557        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2558        if (!group) { // not a group, but a script is selected (probably)
2559            gig::Script* script = row[m_ScriptsModel.m_col_script];
2560            if (!script) return;
2561            it = row.parent(); // resolve parent (that is the script's group)
2562            if (!it) return;
2563            row = *it;
2564            group = row[m_ScriptsModel.m_col_group];
2565            if (!group) return;
2566        }
2567    
2568        // add a new script to the .gig file
2569        gig::Script* script = group->AddScript();    
2570        Glib::ustring name = _("Unnamed Script");
2571        script->Name = gig_from_utf8(name);
2572    
2573        // add script to the tree view
2574        Gtk::TreeModel::iterator iterScript =
2575            m_refScriptsTreeModel->append(row.children());
2576        Gtk::TreeModel::Row rowScript = *iterScript;
2577        rowScript[m_ScriptsModel.m_col_name] = name;
2578        rowScript[m_ScriptsModel.m_col_script] = script;
2579        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2580    
2581        // unfold group of new script item in treeview
2582        Gtk::TreeModel::Path path(iterScript);
2583        m_TreeViewScripts.expand_to_path(path);
2584    }
2585    
2586    void MainWindow::on_action_edit_script() {
2587        if (!file) return;
2588        // get selected script
2589        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2590        Gtk::TreeModel::iterator it = sel->get_selected();
2591        if (!it) return;
2592        Gtk::TreeModel::Row row = *it;
2593        gig::Script* script = row[m_ScriptsModel.m_col_script];
2594        if (!script) return;
2595    
2596        ScriptEditor* editor = new ScriptEditor;
2597        editor->signal_script_to_be_changed.connect(
2598            signal_script_to_be_changed.make_slot()
2599        );
2600        editor->signal_script_changed.connect(
2601            signal_script_changed.make_slot()
2602        );
2603        editor->setScript(script);
2604        //editor->reparent(*this);
2605        editor->show();
2606    }
2607    
2608    void MainWindow::on_action_remove_script() {
2609        if (!file) return;
2610        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2611        Gtk::TreeModel::iterator it = sel->get_selected();
2612        if (it) {
2613            Gtk::TreeModel::Row row = *it;
2614            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2615            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2616            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2617            try {
2618                // remove script group or script from the gig file
2619                if (group) {
2620                    // notify everybody that we're going to remove these samples
2621    //TODO:         scripts_to_be_removed_signal.emit(members);
2622                    // delete the group in the .gig file including the
2623                    // samples that belong to the group
2624                    file->DeleteScriptGroup(group);
2625                    // notify that we're done with removal
2626    //TODO:         scripts_removed_signal.emit();
2627                    file_changed();
2628                } else if (script) {
2629                    // notify everybody that we're going to remove this sample
2630    //TODO:         std::list<gig::Script*> lscripts;
2631    //TODO:         lscripts.push_back(script);
2632    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2633                    // remove sample from the .gig file
2634                    script->GetGroup()->DeleteScript(script);
2635                    // notify that we're done with removal
2636    //TODO:         scripts_removed_signal.emit();
2637                    dimreg_changed();
2638                    file_changed();
2639                }
2640                // remove respective row(s) from samples tree view
2641                m_refScriptsTreeModel->erase(it);
2642            } catch (RIFF::Exception e) {
2643                // pretend we're done with removal (i.e. to avoid dead locks)
2644    //TODO:     scripts_removed_signal.emit();
2645                // show error message
2646                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2647                msg.run();
2648            }
2649        }
2650    }
2651    
2652  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2653      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2654      if (!file) return;      if (!file) return;
2655      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2656      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2657      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2658      __sample_indexer++;      __sample_indexer++;
2659      // update sample tree view      // update sample tree view
2660      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2661      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2662      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2663      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2664      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2665      file_changed();      file_changed();
2666  }  }
2667    
2668    void MainWindow::on_action_replace_sample() {
2669        add_or_replace_sample(true);
2670    }
2671    
2672  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2673        add_or_replace_sample(false);
2674    }
2675    
2676    void MainWindow::add_or_replace_sample(bool replace) {
2677      if (!file) return;      if (!file) return;
2678      // get selected group  
2679        // get selected group (and probably selected sample)
2680      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2681      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2682        if (rows.empty()) return;
2683        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2684      if (!it) return;      if (!it) return;
2685      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2686        gig::Sample* sample = NULL;
2687      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2688      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2689          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2690          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2691          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2692          if (!it) return;          if (!it) return;
2693          row = *it;          if (!replace) row = *it;
2694          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2695          if (!group) return;          if (!group) return;
2696      }      }
2697        if (replace && !sample) return;
2698    
2699      // show 'browse for file' dialog      // show 'browse for file' dialog
2700      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2701      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2702      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2703      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
2704      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2705        // matches all file types supported by libsndfile
2706    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2707        Gtk::FileFilter soundfilter;
2708    #else
2709        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2710    #endif
2711      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2712          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2713          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1377  void MainWindow::on_action_add_sample() Line 2715  void MainWindow::on_action_add_sample()
2715          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2716          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2717      };      };
2718        const char* soundfiles = _("Sound Files");
2719        const char* allfiles = _("All Files");
2720    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2721      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2722          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2723      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2724      Gtk::FileFilter allpassfilter; // matches every file  
2725        // matches every file
2726        Gtk::FileFilter allpassfilter;
2727      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2728      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2729    #else
2730        for (int i = 0; supportedFileTypes[i]; i++)
2731            soundfilter->add_pattern(supportedFileTypes[i]);
2732        soundfilter->set_name(soundfiles);
2733    
2734        // matches every file
2735        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2736        allpassfilter->add_pattern("*.*");
2737        allpassfilter->set_name(allfiles);
2738    #endif
2739      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2740      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2741        if (current_sample_dir != "") {
2742            dialog.set_current_folder(current_sample_dir);
2743        }
2744      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2745            current_sample_dir = dialog.get_current_folder();
2746          Glib::ustring error_files;          Glib::ustring error_files;
2747          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2748          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2749               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2750              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2751              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1396  void MainWindow::on_action_add_sample() Line 2753  void MainWindow::on_action_add_sample()
2753              info.format = 0;              info.format = 0;
2754              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2755              try {              try {
2756                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2757                  int bitdepth;                  int bitdepth;
2758                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2759                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1412  void MainWindow::on_action_add_sample() Line 2769  void MainWindow::on_action_add_sample()
2769                          break;                          break;
2770                      default:                      default:
2771                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2772                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2773                  }                  }
2774                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2775                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2776                  // file name without path                  // file name without path
2777                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2778                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1425  void MainWindow::on_action_add_sample() Line 2782  void MainWindow::on_action_add_sample()
2782                          break;                          break;
2783                      }                      }
2784                  }                  }
2785                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2786                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2787                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2788                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1439  void MainWindow::on_action_add_sample() Line 2796  void MainWindow::on_action_add_sample()
2796                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2797                  {                  {
2798                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2799                        sample->FineTune      = instrument.detune;
2800    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2801                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2802                          sample->Loops = 1;                          sample->Loops = 1;
2803    
# Line 1460  void MainWindow::on_action_add_sample() Line 2817  void MainWindow::on_action_add_sample()
2817                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2818                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2819                      }                      }
 #endif  
2820                  }                  }
2821    
2822                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
2823                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2824                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2825                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2826                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2827                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2828                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2829                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2830                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2831                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2832                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2833                  // add sample to the tree view                  // add sample to the tree view
2834                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2835                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2836                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2837                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
2838                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
2839                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
2840                        rowSample[m_SamplesModel.m_col_name] =
2841                            gig_to_utf8(sample->pInfo->Name);
2842                        rowSample[m_SamplesModel.m_col_sample] = sample;
2843                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2844                    }
2845                  // close sound file                  // close sound file
2846                  sf_close(hFile);                  sf_close(hFile);
2847                  file_changed();                  file_changed();
2848              } 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)
2849                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2850                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2851              }              }
2852          }          }
2853          // 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
2854          if (error_files.size()) {          if (!error_files.empty()) {
2855              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
2856                    (replace
2857                        ? _("Failed to replace sample with:\n")
2858                        : _("Could not add the following sample(s):\n"))
2859                    + error_files;
2860              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2861              msg.run();              msg.run();
2862          }          }
# Line 1503  void MainWindow::on_action_replace_all_s Line 2868  void MainWindow::on_action_replace_all_s
2868      if (!file) return;      if (!file) return;
2869      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2870                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2871      Gtk::Label description(      const char* str =
2872          _("This is a very specific function. It tries to replace all samples "          _("This is a very specific function. It tries to replace all samples "
2873            "in the current gig file by samples located in the directory chosen "            "in the current gig file by samples located in the chosen "
2874            "by you above.\n\n"            "directory.\n\n"
2875            "It works like this: For each sample in the gig file it tries to "            "It works like this: For each sample in the gig file, it tries to "
2876            "find a sample file in the selected directory with the same name as "            "find a sample file in the selected directory with the same name as "
2877            "the sample in the gig file. Optionally you can add a filename "            "the sample in the gig file. Optionally, you can add a filename "
2878            "postfix below, which will be added to the filename expected to be "            "extension below, which will be added to the filename expected to be "
2879            "found. That is, assume you have a gig file with a sample called "            "found. That is, assume you have a gig file with a sample called "
2880            "'Snare', if you enter '.wav' below (like it's done by default), it "            "'Snare', if you enter '.wav' below (like it's done by default), it "
2881            "assumes to find a sample file called 'Snare.wav' and will replace "            "expects to find a sample file called 'Snare.wav' and will replace "
2882            "the sample in the gig file accordingly. If you don't need such a "            "the sample in the gig file accordingly. If you don't need an "
2883            "postfix, blank the field below. Any gig sample where no "            "extension, blank the field below. Any gig sample where no "
2884            "appropriate sample file could be found, will be reported and left "            "appropriate sample file could be found will be reported and left "
2885            "untouched.\n\n")            "untouched.\n");
2886      );  #if GTKMM_MAJOR_VERSION < 3
2887      description.set_line_wrap(true);      view::WrapLabel description(str);
2888    #else
2889        Gtk::Label description(str);
2890        description.set_line_wrap();
2891    #endif
2892      Gtk::HBox entryArea;      Gtk::HBox entryArea;
2893      Gtk::Label entryLabel( _("Add Filename Extension: "), Gtk::ALIGN_RIGHT);      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2894      Gtk::Entry postfixEntryBox;      Gtk::Entry postfixEntryBox;
2895      postfixEntryBox.set_text(".wav");      postfixEntryBox.set_text(".wav");
2896      entryArea.pack_start(entryLabel);      entryArea.pack_start(entryLabel);
# Line 1529  void MainWindow::on_action_replace_all_s Line 2898  void MainWindow::on_action_replace_all_s
2898      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2899      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2900      description.show();      description.show();
2901      entryLabel.show();      entryArea.show_all();
2902      postfixEntryBox.show();      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
     entryArea.show();  
     dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);  
2903      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2904      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
2905      // fix label width (because Gtk by design doesn't      if (current_sample_dir != "") {
2906      // know anything about the parent's size)          dialog.set_current_folder(current_sample_dir);
2907  #if 0 //FIXME: doesn't work      }
     int dialogW, dialogH, labelW, labelH;  
     dialog.get_size_request(dialogW, dialogH);  
     description.get_size_request(labelW, labelH);  
     std::cout << "dialog(" << dialogW << "," << dialogH << ")\nlabel(" << labelW << "," << labelH << ")\n" << std::flush;  
     description.set_size_request(dialogW, labelH);  
 #endif  
2908      if (dialog.run() == Gtk::RESPONSE_OK)      if (dialog.run() == Gtk::RESPONSE_OK)
2909      {      {
2910            current_sample_dir = dialog.get_current_folder();
2911          Glib::ustring error_files;          Glib::ustring error_files;
2912          Glib::ustring folder = dialog.get_filename();          std::string folder = dialog.get_filename();
2913          for (gig::Sample* sample = file->GetFirstSample();          for (gig::Sample* sample = file->GetFirstSample();
2914               sample; sample = file->GetNextSample())               sample; sample = file->GetNextSample())
2915          {          {
2916              std::string filename =              std::string filename =
2917                  folder + G_DIR_SEPARATOR_S + sample->pInfo->Name +                  folder + G_DIR_SEPARATOR_S +
2918                  postfixEntryBox.get_text().raw();                  Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2919                                             postfixEntryBox.get_text());
2920              SF_INFO info;              SF_INFO info;
2921              info.format = 0;              info.format = 0;
2922              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2923              try              try
2924              {              {
2925                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
2926                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2927                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
2928                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
2929                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
2930                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
2931                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
2932                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
2933                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
2934                          break;                          break;
2935                      default:                      default:
2936                          sf_close(hFile);                          sf_close(hFile);
2937                          throw std::string("format not supported");                          throw std::string(_("format not supported"));
2938                  }                  }
2939                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2940                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2941                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
2942                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2943                  sf_close(hFile);                  sf_close(hFile);
2944                  file_changed();                  file_changed();
2945              }              }
2946              catch (std::string what)              catch (std::string what)
2947              {              {
2948                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2949                      error_files += filename += " (" + what + ")";                  error_files += Glib::filename_to_utf8(filename) +
2950                        " (" + what + ")";
2951              }              }
2952          }          }
2953          // 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
2954          if (error_files.size()) {          if (!error_files.empty()) {
2955              Glib::ustring txt =              Glib::ustring txt =
2956                  _("Could not replace the following sample(s):\n") + error_files;                  _("Could not replace the following sample(s):\n") + error_files;
2957              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
# Line 1603  void MainWindow::on_action_replace_all_s Line 2963  void MainWindow::on_action_replace_all_s
2963  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
2964      if (!file) return;      if (!file) return;
2965      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2966      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2967      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2968            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2969            if (!it) continue;
2970          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2971          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
2972          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1612  void MainWindow::on_action_remove_sample Line 2974  void MainWindow::on_action_remove_sample
2974          try {          try {
2975              // remove group or sample from the gig file              // remove group or sample from the gig file
2976              if (group) {              if (group) {
2977                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2978                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2979                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2980                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1629  void MainWindow::on_action_remove_sample Line 2991  void MainWindow::on_action_remove_sample
2991                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
2992                  // them from the import queue                  // them from the import queue
2993                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
2994                       member != members.end(); ++member) {                       member != members.end(); ++member)
2995                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
2996                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
2997                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
2998                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
2999                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
3000                      }                      }
3001                  }                  }
3002                  file_changed();                  file_changed();
# Line 1652  void MainWindow::on_action_remove_sample Line 3011  void MainWindow::on_action_remove_sample
3011                  samples_removed_signal.emit();                  samples_removed_signal.emit();
3012                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
3013                  // the import queue                  // the import queue
3014                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
3015                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
3016                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
3017                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
3018                  }                  }
3019                  dimreg_changed();                  dimreg_changed();
3020                  file_changed();                  file_changed();
# Line 1676  void MainWindow::on_action_remove_sample Line 3031  void MainWindow::on_action_remove_sample
3031      }      }
3032  }  }
3033    
3034    void MainWindow::on_action_remove_unused_samples() {
3035        if (!file) return;
3036    
3037        // collect all samples that are not referenced by any instrument
3038        std::list<gig::Sample*> lsamples;
3039        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3040            gig::Sample* sample = file->GetSample(iSample);
3041            bool isUsed = false;
3042            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3043                                  instrument = file->GetNextInstrument())
3044            {
3045                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3046                                  rgn = instrument->GetNextRegion())
3047                {
3048                    for (int i = 0; i < 256; ++i) {
3049                        if (!rgn->pDimensionRegions[i]) continue;
3050                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3051                        isUsed = true;
3052                        goto endOfRefSearch;
3053                    }
3054                }
3055            }
3056            endOfRefSearch:
3057            if (!isUsed) lsamples.push_back(sample);
3058        }
3059    
3060        if (lsamples.empty()) return;
3061    
3062        // notify everybody that we're going to remove these samples
3063        samples_to_be_removed_signal.emit(lsamples);
3064    
3065        // remove collected samples
3066        try {
3067            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3068                 itSample != lsamples.end(); ++itSample)
3069            {
3070                gig::Sample* sample = *itSample;
3071                // remove sample from the .gig file
3072                file->DeleteSample(sample);
3073                // if sample was just previously added, remove it from the import queue
3074                if (m_SampleImportQueue.count(sample)) {
3075                    printf("Removing previously added sample '%s'\n",
3076                           m_SampleImportQueue[sample].sample_path.c_str());
3077                    m_SampleImportQueue.erase(sample);
3078                }
3079            }
3080        } catch (RIFF::Exception e) {
3081            // show error message
3082            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3083            msg.run();
3084        }
3085    
3086        // notify everybody that we're done with removal
3087        samples_removed_signal.emit();
3088    
3089        dimreg_changed();
3090        file_changed();
3091        __refreshEntireGUI();
3092    }
3093    
3094    // see comment on on_sample_treeview_drag_begin()
3095    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3096    {
3097        first_call_to_drag_data_get = true;
3098    }
3099    
3100    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3101                                                       Gtk::SelectionData& selection_data, guint, guint)
3102    {
3103        if (!first_call_to_drag_data_get) return;
3104        first_call_to_drag_data_get = false;
3105    
3106        // get selected script
3107        gig::Script* script = NULL;
3108        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3109        Gtk::TreeModel::iterator it = sel->get_selected();
3110        if (it) {
3111            Gtk::TreeModel::Row row = *it;
3112            script = row[m_ScriptsModel.m_col_script];
3113        }
3114        // pass the gig::Script as pointer
3115        selection_data.set(selection_data.get_target(), 0/*unused*/,
3116                           (const guchar*)&script,
3117                           sizeof(script)/*length of data in bytes*/);
3118    }
3119    
3120    // see comment on on_sample_treeview_drag_begin()
3121    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3122    {
3123        first_call_to_drag_data_get = true;
3124    }
3125    
3126    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3127                                                           Gtk::SelectionData& selection_data, guint, guint)
3128    {
3129        if (!first_call_to_drag_data_get) return;
3130        first_call_to_drag_data_get = false;
3131    
3132        // get selected source instrument
3133        gig::Instrument* src = NULL;
3134        {
3135            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3136            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3137            if (!rows.empty()) {
3138                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3139                if (it) {
3140                    Gtk::TreeModel::Row row = *it;
3141                    src = row[m_Columns.m_col_instr];
3142                }
3143            }
3144        }
3145        if (!src) return;
3146    
3147        // pass the source gig::Instrument as pointer
3148        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3149                           sizeof(src)/*length of data in bytes*/);
3150    }
3151    
3152    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3153        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3154        const Gtk::SelectionData& selection_data, guint, guint time)
3155    {
3156        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3157        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3158            return;
3159    
3160        gig::Instrument* dst = NULL;
3161        {
3162            Gtk::TreeModel::Path path;
3163            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3164            if (!found) return;
3165    
3166            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3167            if (!iter) return;
3168            Gtk::TreeModel::Row row = *iter;
3169            dst = row[m_Columns.m_col_instr];
3170        }
3171        if (!dst) return;
3172    
3173        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3174        src->MoveTo(dst);
3175        __refreshEntireGUI();
3176        select_instrument(src);
3177    }
3178    
3179  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3180  // 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
3181  // 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 1694  void MainWindow::on_sample_treeview_drag Line 3194  void MainWindow::on_sample_treeview_drag
3194      // get selected sample      // get selected sample
3195      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3196      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3197      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3198      if (it) {      if (!rows.empty()) {
3199          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3200          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3201                Gtk::TreeModel::Row row = *it;
3202                sample = row[m_SamplesModel.m_col_sample];
3203            }
3204      }      }
3205      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3206      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 1734  void MainWindow::on_sample_label_drop_dr Line 3237  void MainWindow::on_sample_label_drop_dr
3237          bool channels_changed = false;          bool channels_changed = false;
3238          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
3239              // remove the samplechannel dimension              // remove the samplechannel dimension
3240    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3241              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
3242              channels_changed = true;              channels_changed = true;
3243              region_changed();              region_changed();
3244    */
3245          }          }
3246          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
3247                sample,
3248                is_copy_samples_unity_note_enabled(),
3249                is_copy_samples_fine_tune_enabled(),
3250                is_copy_samples_loop_enabled()
3251            );
3252    
3253          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
3254              // add samplechannel dimension              // add samplechannel dimension
# Line 1781  void MainWindow::sample_name_changed(con Line 3291  void MainWindow::sample_name_changed(con
3291      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
3292      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
3293      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3294        gig::String gigname(gig_from_utf8(name));
3295      if (group) {      if (group) {
3296          if (group->Name != name) {          if (group->Name != gigname) {
3297              group->Name = name;              group->Name = gigname;
3298              printf("group name changed\n");              printf("group name changed\n");
3299              file_changed();              file_changed();
3300          }          }
3301      } else if (sample) {      } else if (sample) {
3302          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
3303              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
3304              printf("sample name changed\n");              printf("sample name changed\n");
3305              file_changed();              file_changed();
3306          }          }
3307      }      }
3308  }  }
3309    
3310    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3311                                         const Gtk::TreeModel::iterator& iter) {
3312        if (!iter) return;
3313        Gtk::TreeModel::Row row = *iter;
3314        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3315        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3316        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3317        gig::String gigname(gig_from_utf8(name));
3318        if (group) {
3319            if (group->Name != gigname) {
3320                group->Name = gigname;
3321                printf("script group name changed\n");
3322                file_changed();
3323            }
3324        } else if (script) {
3325            if (script->Name != gigname) {
3326                script->Name = gigname;
3327                printf("script name changed\n");
3328                file_changed();
3329            }
3330        }
3331    }
3332    
3333    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3334                                           Gtk::TreeViewColumn* column)
3335    {
3336        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3337        if (!iter) return;
3338        Gtk::TreeModel::Row row = *iter;
3339        gig::Script* script = row[m_ScriptsModel.m_col_script];
3340        if (!script) return;
3341    
3342        ScriptEditor* editor = new ScriptEditor;
3343        editor->signal_script_to_be_changed.connect(
3344            signal_script_to_be_changed.make_slot()
3345        );
3346        editor->signal_script_changed.connect(
3347            signal_script_changed.make_slot()
3348        );
3349        editor->setScript(script);
3350        //editor->reparent(*this);
3351        editor->show();
3352    }
3353    
3354  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3355                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3356      if (!iter) return;      if (!iter) return;
3357      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
3358      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
3359    
3360        // change name in instrument menu
3361        int index = path[0];
3362        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3363        if (index < children.size()) {
3364    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
3365            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
3366    #else
3367            remove_instrument_from_menu(index);
3368            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
3369            item->set_active();
3370    #endif
3371        }
3372    
3373        // change name in gig
3374      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
3375      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
3376          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
3377            instrument->pInfo->Name = gigname;
3378    
3379            // change name in the instrument properties window
3380            if (instrumentProps.get_instrument() == instrument) {
3381                instrumentProps.update_name();
3382            }
3383    
3384          file_changed();          file_changed();
3385      }      }
3386  }  }
3387    
3388    void MainWindow::on_action_combine_instruments() {
3389        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3390        d->show_all();
3391        d->resize(500, 400);
3392        d->run();
3393        if (d->fileWasChanged()) {
3394            // update GUI with new instrument just created
3395            add_instrument(d->newCombinedInstrument());
3396        }
3397        delete d;
3398    }
3399    
3400    void MainWindow::on_action_view_references() {
3401        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3402        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3403        if (rows.empty()) return;
3404        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3405        if (!it) return;
3406        Gtk::TreeModel::Row row = *it;
3407        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3408        if (!sample) return;
3409    
3410        ReferencesView* d = new ReferencesView(*this);
3411        d->setSample(sample);
3412        d->dimension_region_selected.connect(
3413            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3414        );
3415        d->show_all();
3416        d->resize(500, 400);
3417        d->run();
3418        delete d;
3419    }
3420    
3421    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3422        struct _Source {
3423            std::vector<RIFF::File*> riffs;
3424            std::vector<gig::File*> gigs;
3425            
3426            ~_Source() {
3427                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3428                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3429                riffs.clear();
3430                gigs.clear();
3431            }
3432        } sources;
3433    
3434        if (filenames.empty())
3435            throw RIFF::Exception(_("No files selected, so nothing done."));
3436    
3437        // first open all input files (to avoid output file corruption)
3438        int i;
3439        try {
3440            for (i = 0; i < filenames.size(); ++i) {
3441                const std::string& filename = filenames[i];
3442                printf("opening file=%s\n", filename.c_str());
3443    
3444                RIFF::File* riff = new RIFF::File(filename);
3445                sources.riffs.push_back(riff);
3446    
3447                gig::File* gig = new gig::File(riff);
3448                sources.gigs.push_back(gig);
3449            }
3450        } catch (RIFF::Exception e) {
3451            throw RIFF::Exception(
3452                _("Error occurred while opening '") +
3453                filenames[i] +
3454                "': " +
3455                e.Message
3456            );
3457        } catch (...) {
3458            throw RIFF::Exception(
3459                _("Unknown exception occurred while opening '") +
3460                filenames[i] + "'"
3461            );
3462        }
3463    
3464        // now merge the opened .gig files to the main .gig file currently being
3465        // open in gigedit
3466        try {
3467            for (i = 0; i < filenames.size(); ++i) {
3468                const std::string& filename = filenames[i];
3469                printf("merging file=%s\n", filename.c_str());
3470                assert(i < sources.gigs.size());
3471    
3472                this->file->AddContentOf(sources.gigs[i]);
3473            }
3474        } catch (RIFF::Exception e) {
3475            throw RIFF::Exception(
3476                _("Error occurred while merging '") +
3477                filenames[i] +
3478                "': " +
3479                e.Message
3480            );
3481        } catch (...) {
3482            throw RIFF::Exception(
3483                _("Unknown exception occurred while merging '") +
3484                filenames[i] + "'"
3485            );
3486        }
3487    
3488        // Finally save gig file persistently to disk ...
3489        //NOTE: requires that this gig file already has a filename !
3490        {
3491            std::cout << "Saving file\n" << std::flush;
3492            file_structure_to_be_changed_signal.emit(this->file);
3493    
3494            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3495                _("Saving") +  Glib::ustring(" '") +
3496                Glib::filename_display_basename(this->filename) + "' ...",
3497                *this
3498            );
3499            progress_dialog->show_all();
3500            saver = new Saver(this->file); //FIXME: memory leak!
3501            saver->signal_progress().connect(
3502                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3503            saver->signal_finished().connect(
3504                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3505            saver->signal_error().connect(
3506                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3507            saver->launch();
3508        }
3509    }
3510    
3511    void MainWindow::on_action_merge_files() {
3512        if (this->file->GetFileName().empty()) {
3513            Glib::ustring txt = _(
3514                "You seem to have a new .gig file open that has not been saved "
3515                "yet. You must save it somewhere before starting to merge it with "
3516                "other .gig files though, because during the merge operation the "
3517                "other files' sample data must be written on file level to the "
3518                "target .gig file."
3519            );
3520            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3521            msg.run();
3522            return;
3523        }
3524    
3525        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3526        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3527        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3528        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3529    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3530        Gtk::FileFilter filter;
3531        filter.add_pattern("*.gig");
3532    #else
3533        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3534        filter->add_pattern("*.gig");
3535    #endif
3536        dialog.set_filter(filter);
3537        if (current_gig_dir != "") {
3538            dialog.set_current_folder(current_gig_dir);
3539        }
3540        dialog.set_select_multiple(true);
3541    
3542        // show warning in the file picker dialog
3543        Gtk::HBox descriptionArea;
3544        descriptionArea.set_spacing(15);
3545        Gtk::Image warningIcon;
3546        warningIcon.set_from_icon_name("dialog-warning",
3547                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3548        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3549    #if GTKMM_MAJOR_VERSION < 3
3550        view::WrapLabel description;
3551    #else
3552        Gtk::Label description;
3553        description.set_line_wrap();
3554    #endif
3555        description.set_markup(_(
3556            "\nSelect at least one .gig file that shall be merged to the .gig file "
3557            "currently being open in gigedit.\n\n"
3558            "<b>Please Note:</b> Merging with other files will modify your "
3559            "currently open .gig file on file level! And be aware that the current "
3560            "merge algorithm does not detect duplicate samples yet. So if you are "
3561            "merging files which are using equivalent sample data, those "
3562            "equivalent samples will currently be treated as separate samples and "
3563            "will accordingly be stored separately in the target .gig file!"
3564        ));
3565        descriptionArea.pack_start(description);
3566        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3567        descriptionArea.show_all();
3568    
3569        if (dialog.run() == Gtk::RESPONSE_OK) {
3570            printf("on_action_merge_files self=%p\n",
3571                   static_cast<void*>(Glib::Threads::Thread::self()));
3572            std::vector<std::string> filenames = dialog.get_filenames();
3573    
3574            // merge the selected files to the currently open .gig file
3575            try {
3576                mergeFiles(filenames);
3577            } catch (RIFF::Exception e) {
3578                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3579                msg.run();
3580            }
3581    
3582            // update GUI
3583            __refreshEntireGUI();
3584        }
3585    }
3586    
3587  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
3588      this->file_is_shared = b;      this->file_is_shared = b;
3589    
# Line 1822  void MainWindow::set_file_is_shared(bool Line 3598  void MainWindow::set_file_is_shared(bool
3598              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3599          );          );
3600      }      }
3601    
3602        {
3603            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3604                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3605            if (item) item->set_sensitive(b);
3606        }
3607    }
3608    
3609    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3610        if (!sample) return;
3611        sample_ref_count[sample] += offset;
3612        const int refcount = sample_ref_count[sample];
3613    
3614        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3615        for (int g = 0; g < model->children().size(); ++g) {
3616            Gtk::TreeModel::Row rowGroup = model->children()[g];
3617            for (int s = 0; s < rowGroup.children().size(); ++s) {
3618                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3619                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3620                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3621                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3622            }
3623        }
3624    }
3625    
3626    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3627        on_sample_ref_count_incremented(oldSample, -1);
3628        on_sample_ref_count_incremented(newSample, +1);
3629    }
3630    
3631    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3632        // just in case a new sample is added later with exactly the same memory
3633        // address, which would lead to incorrect refcount if not deleted here
3634        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3635             it != samples.end(); ++it)
3636        {
3637            sample_ref_count.erase(*it);
3638        }
3639    }
3640    
3641    void MainWindow::show_samples_tab() {
3642        m_TreeViewNotebook.set_current_page(0);
3643    }
3644    
3645    void MainWindow::show_intruments_tab() {
3646        m_TreeViewNotebook.set_current_page(1);
3647    }
3648    
3649    void MainWindow::show_scripts_tab() {
3650        m_TreeViewNotebook.set_current_page(2);
3651    }
3652    
3653    void MainWindow::select_prev_region() {
3654        m_RegionChooser.select_prev_region();
3655    }
3656    
3657    void MainWindow::select_next_region() {
3658        m_RegionChooser.select_next_region();
3659    }
3660    
3661    void MainWindow::select_next_dim_rgn_zone() {
3662        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3663        m_DimRegionChooser.select_next_dimzone();
3664    }
3665    
3666    void MainWindow::select_prev_dim_rgn_zone() {
3667        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3668        m_DimRegionChooser.select_prev_dimzone();
3669    }
3670    
3671    void MainWindow::select_add_next_dim_rgn_zone() {
3672        m_DimRegionChooser.select_next_dimzone(true);
3673    }
3674    
3675    void MainWindow::select_add_prev_dim_rgn_zone() {
3676        m_DimRegionChooser.select_prev_dimzone(true);
3677    }
3678    
3679    void MainWindow::select_prev_dimension() {
3680        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3681        m_DimRegionChooser.select_prev_dimension();
3682    }
3683    
3684    void MainWindow::select_next_dimension() {
3685        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3686        m_DimRegionChooser.select_next_dimension();
3687    }
3688    
3689    #define CLIPBOARD_DIMENSIONREGION_TARGET \
3690        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
3691    
3692    void MainWindow::copy_selected_dimrgn() {
3693        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3694        if (!pDimRgn) {
3695            updateClipboardPasteAvailable();
3696            updateClipboardCopyAvailable();
3697            return;
3698        }
3699    
3700        std::vector<Gtk::TargetEntry> targets;
3701        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
3702    
3703        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3704        clipboard->set(
3705            targets,
3706            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
3707            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
3708        );
3709    
3710        m_serializationArchive.serialize(pDimRgn);
3711    
3712        updateClipboardPasteAvailable();
3713    }
3714    
3715    void MainWindow::paste_copied_dimrgn() {
3716        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3717        clipboard->request_contents(
3718            CLIPBOARD_DIMENSIONREGION_TARGET,
3719            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
3720        );
3721        updateClipboardPasteAvailable();
3722    }
3723    
3724    void MainWindow::updateClipboardPasteAvailable() {
3725        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3726        clipboard->request_targets(
3727            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
3728        );
3729    }
3730    
3731    void MainWindow::updateClipboardCopyAvailable() {
3732        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
3733        static_cast<Gtk::MenuItem*>(
3734            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
3735        )->set_sensitive(bDimensionRegionCopyIsPossible);
3736    }
3737    
3738    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
3739        updateClipboardPasteAvailable();
3740    }
3741    
3742    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
3743        const std::string target = selection_data.get_target();
3744        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3745            selection_data.set(
3746                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
3747                &m_serializationArchive.rawData()[0],
3748                m_serializationArchive.rawData().size()
3749            );
3750        } else {
3751            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
3752        }
3753    }
3754    
3755    void MainWindow::on_clipboard_clear() {
3756        m_serializationArchive.clear();
3757        updateClipboardPasteAvailable();
3758        updateClipboardCopyAvailable();
3759    }
3760    
3761    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
3762        const std::string target = selection_data.get_target();
3763        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3764            gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3765            if (!pDimRgn) return;
3766    
3767            Glib::ustring errorText;
3768            try {
3769                m_serializationArchive.decode(
3770                    selection_data.get_data(), selection_data.get_length()
3771                );
3772    
3773                for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
3774                     itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
3775                {
3776                    gig::DimensionRegion* pDimRgn = *itDimReg;
3777    
3778                    dimreg_to_be_changed_signal.emit(pDimRgn);
3779    
3780                    m_serializationArchive.deserialize(pDimRgn);
3781    
3782                    dimreg_changed_signal.emit(pDimRgn);
3783                }
3784    
3785                //region_changed()
3786                file_changed();
3787                dimreg_changed();
3788    
3789            } catch (Serialization::Exception e) {
3790                errorText = e.Message;
3791            } catch (...) {
3792                errorText = _("Unknown exception during deserialization decoding");
3793            }
3794            if (!errorText.empty()) {
3795                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
3796                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3797                msg.run();
3798            }
3799        }
3800    }
3801    
3802    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
3803        const bool bDimensionRegionPasteIsPossible =
3804            std::find(targets.begin(), targets.end(),
3805                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
3806    
3807        static_cast<Gtk::MenuItem*>(
3808            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
3809        )->set_sensitive(bDimensionRegionPasteIsPossible);
3810  }  }
3811    
3812  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
# Line 1848  sigc::signal<void, gig::Region*>& MainWi Line 3833  sigc::signal<void, gig::Region*>& MainWi
3833      return region_changed_signal;      return region_changed_signal;
3834  }  }
3835    
3836    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3837        return sample_changed_signal;
3838    }
3839    
3840  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() {
3841      return sample_ref_changed_signal;      return sample_ref_changed_signal;
3842  }  }
# Line 1875  sigc::signal<void, int/*key*/, int/*velo Line 3864  sigc::signal<void, int/*key*/, int/*velo
3864  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3865      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
3866  }  }
3867    
3868    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3869        return switch_sampler_instrument_signal;
3870    }

Legend:
Removed from v.1673  
changed lines
  Added in v.3148

  ViewVC Help
Powered by ViewVC