/[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 1656 by schoenebeck, Sat Feb 2 08:18:19 2008 UTC revision 3158 by schoenebeck, Mon May 8 18:05:35 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>
38  #include <gtkmm/stock.h>  #include <gtkmm/stock.h>
39  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
40  #include <gtkmm/main.h>  #include <gtkmm/main.h>
41  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
42    #include <gtkmm/accelmap.h>
43  #include "global.h"  #if GTKMM_MAJOR_VERSION < 3
44    #include "wrapLabel.hh"
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
 #define ABOUT_DIALOG  
 #include <gtkmm/aboutdialog.h>  
45  #endif  #endif
46    
47  #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2  #include "global.h"
48  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  
49    
50  #include <stdio.h>  #include <stdio.h>
51  #include <sndfile.h>  #include <sndfile.h>
52    #include <assert.h>
53    
54  #include "mainwindow.h"  #include "mainwindow.h"
55    #include "Settings.h"
56    #include "CombineInstrumentsDialog.h"
57    #include "scripteditor.h"
58    #include "scriptslots.h"
59    #include "ReferencesView.h"
60  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
61  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
62    #include "gfx/builtinpix.h"
63  template<class T> inline std::string ToString(T o) {  #include "MacroEditor.h"
64      std::stringstream ss;  #include "MacrosSetup.h"
     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++;  
 }  
65    
66  MainWindow::MainWindow() :  MainWindow::MainWindow() :
67        m_DimRegionChooser(*this),
68      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
69      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
70      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
71      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
72        labelLegend(_("Legend:")),
73        labelNoSample(_(" No Sample")),
74        labelMissingSample(_(" Missing some Sample(s)")),
75        labelLooped(_(" Looped")),
76        labelSomeLoops(_(" Some Loop(s)"))
77  {  {
78        loadBuiltInPix();
79    
80  //    set_border_width(5);  //    set_border_width(5);
81  //    set_default_size(400, 200);  //    set_default_size(400, 200);
82    
   
83      add(m_VBox);      add(m_VBox);
84    
85      // Handle selection      // Handle selection
86      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
87          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
88    
89      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
# Line 114  MainWindow::MainWindow() : Line 99  MainWindow::MainWindow() :
99      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
100      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
101    
102        m_ScrolledWindowScripts.add(m_TreeViewScripts);
103        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
104    
105    
106      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
107    
# Line 125  MainWindow::MainWindow() : Line 113  MainWindow::MainWindow() :
113      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
114      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
115      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
116      m_HPaned.add2(dimreg_vbox);      {
117            legend_hbox.add(labelLegend);
118    
119            imageNoSample.set(redDot);
120            imageNoSample.set_alignment(Gtk::ALIGN_END);
121            labelNoSample.set_alignment(Gtk::ALIGN_START);
122            legend_hbox.add(imageNoSample);
123            legend_hbox.add(labelNoSample);
124    
125            imageMissingSample.set(yellowDot);
126            imageMissingSample.set_alignment(Gtk::ALIGN_END);
127            labelMissingSample.set_alignment(Gtk::ALIGN_START);
128            legend_hbox.add(imageMissingSample);
129            legend_hbox.add(labelMissingSample);
130    
131            imageLooped.set(blackLoop);
132            imageLooped.set_alignment(Gtk::ALIGN_END);
133            labelLooped.set_alignment(Gtk::ALIGN_START);
134            legend_hbox.add(imageLooped);
135            legend_hbox.add(labelLooped);
136    
137            imageSomeLoops.set(grayLoop);
138            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
139            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
140            legend_hbox.add(imageSomeLoops);
141            legend_hbox.add(labelSomeLoops);
142    
143      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");          legend_hbox.show_all_children();
144      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");      }
145        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
146        m_HPaned.add2(dimreg_vbox);
147    
148        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
149        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."));
150        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."));
151        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)."));
152    
153        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
154        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
155        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
156    
157      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
158    
# Line 161  MainWindow::MainWindow() : Line 183  MainWindow::MainWindow() :
183                                           Gtk::Stock::PROPERTIES),                                           Gtk::Stock::PROPERTIES),
184                       sigc::mem_fun(                       sigc::mem_fun(
185                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
186        actionGroup->add(Gtk::Action::create("MidiRules",
187                                             _("_Midi Rules...")),
188                         sigc::mem_fun(
189                             *this, &MainWindow::show_midi_rules));
190        actionGroup->add(Gtk::Action::create("ScriptSlots",
191                                             _("_Script Slots...")),
192                         sigc::mem_fun(
193                             *this, &MainWindow::show_script_slots));
194      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
195                       sigc::mem_fun(                       sigc::mem_fun(
196                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
197      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
198            Gtk::Action::create("MenuSample", _("_Sample")),
199            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
200        );
201        actionGroup->add(
202            Gtk::Action::create("MenuInstrument", _("_Instrument")),
203            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
204        );
205        actionGroup->add(
206            Gtk::Action::create("MenuScript", _("Scr_ipt")),
207            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
208        );
209        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
210    
211        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
212    
213        const Gdk::ModifierType primaryModifierKey =
214    #if defined(__APPLE__)
215        Gdk::META_MASK; // Cmd key on Mac
216    #else
217        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
218    #endif
219    
220        actionGroup->add(Gtk::Action::create("CopyDimRgn",
221                                             _("Copy selected dimension region")),
222                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
223                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
224    
225        actionGroup->add(Gtk::Action::create("PasteDimRgn",
226                                             _("Paste dimension region")),
227                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
228                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
229    
230        actionGroup->add(Gtk::Action::create("AdjustClipboard",
231                                             _("Adjust Clipboard Content")),
232                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
233                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
234    
235        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
236                                             _("Select Previous Region")),
237                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
238                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
239    
240        actionGroup->add(Gtk::Action::create("SelectNextRegion",
241                                             _("Select Next Region")),
242                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
243                         sigc::mem_fun(*this, &MainWindow::select_next_region));
244    
245        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
246                                             _("Select Previous Dimension Region Zone")),
247                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
248                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
249    
250        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
251                                             _("Select Next Dimension Region Zone")),
252                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
253                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
254    
255        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
256                                             _("Select Previous Dimension")),
257                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
258                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
259    
260        actionGroup->add(Gtk::Action::create("SelectNextDimension",
261                                             _("Select Next Dimension")),
262                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
263                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
264    
265        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
266                                             _("Add Previous Dimension Region Zone to Selection")),
267                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
268                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
269    
270        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
271                                             _("Add Next Dimension Region Zone to Selection")),
272                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
273                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
274    
     actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  
275      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
276            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
277        toggle_action->set_active(true);
278        actionGroup->add(toggle_action);
279    
280        toggle_action =
281            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
282        toggle_action->set_active(true);
283        actionGroup->add(toggle_action);
284    
285        toggle_action =
286            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
287        toggle_action->set_active(true);
288        actionGroup->add(toggle_action);
289    
290    
291        actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
292    
293    
294        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
295        toggle_action =
296          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
297      toggle_action->set_active(true);      toggle_action->set_active(true);
298      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
299                       sigc::mem_fun(                       sigc::mem_fun(
300                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
301    
302        toggle_action =
303            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
304        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
305        actionGroup->add(toggle_action,
306                         sigc::mem_fun(
307                             *this, &MainWindow::on_auto_restore_win_dim));
308    
309        toggle_action =
310            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
311        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
312        actionGroup->add(toggle_action,
313                         sigc::mem_fun(
314                             *this, &MainWindow::on_save_with_temporary_file));
315    
316        actionGroup->add(
317            Gtk::Action::create("RefreshAll", _("_Refresh All")),
318            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
319        );                
320    
321      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
322      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
323                                           action->property_label()));                                           action->property_label()));
 #ifdef ABOUT_DIALOG  
324      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),
325                       sigc::mem_fun(                       sigc::mem_fun(
326                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
327      actionGroup->add(      actionGroup->add(
328          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
329          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
330      );      );
331      actionGroup->add(      actionGroup->add(
332            Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
333            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
334        );
335        actionGroup->add(
336          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
337          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
338      );      );
339    
340    
341        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
342        
343        toggle_action =
344            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
345        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
346        actionGroup->add(
347            toggle_action,
348            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
349        );
350    
351        toggle_action =
352            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
353        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
354        actionGroup->add(
355            toggle_action,
356            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
357        );
358    
359        toggle_action =
360            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
361        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
362        actionGroup->add(
363            toggle_action,
364            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
365        );
366    
367    
368        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
369    
370        actionGroup->add(
371            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
372            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
373        );
374    
375        actionGroup->add(
376            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
377            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
378        );
379    
380    
381      // sample right-click popup actions      // sample right-click popup actions
382      actionGroup->add(      actionGroup->add(
383          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
# Line 201  MainWindow::MainWindow() : Line 388  MainWindow::MainWindow() :
388          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
389      );      );
390      actionGroup->add(      actionGroup->add(
391          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
392          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
393      );      );
394      actionGroup->add(      actionGroup->add(
395          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),
396          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
397      );      );
398        actionGroup->add(
399            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
400            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
401        );
402        actionGroup->add(
403            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
404            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
405        );
406        actionGroup->add(
407            Gtk::Action::create("ReplaceSample",
408                                _("Replace Sample...")),
409            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
410        );
411        actionGroup->add(
412            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
413                                _("Replace All Samples in All Groups...")),
414            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
415        );
416        
417        // script right-click popup actions
418        actionGroup->add(
419            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
420            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
421        );
422        actionGroup->add(
423            Gtk::Action::create("AddScript", _("Add _Script")),
424            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
425        );
426        actionGroup->add(
427            Gtk::Action::create("EditScript", _("_Edit Script...")),
428            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
429        );
430        actionGroup->add(
431            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
432            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
433        );
434    
435      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
436      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 227  MainWindow::MainWindow() : Line 450  MainWindow::MainWindow() :
450          "      <separator/>"          "      <separator/>"
451          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
452          "    </menu>"          "    </menu>"
453            "    <menu action='MenuEdit'>"
454            "      <menuitem action='CopyDimRgn'/>"
455            "      <menuitem action='AdjustClipboard'/>"
456            "      <menuitem action='PasteDimRgn'/>"
457            "      <separator/>"
458            "      <menuitem action='SelectPrevRegion'/>"
459            "      <menuitem action='SelectNextRegion'/>"
460            "      <separator/>"
461            "      <menuitem action='SelectPrevDimension'/>"
462            "      <menuitem action='SelectNextDimension'/>"
463            "      <menuitem action='SelectPrevDimRgnZone'/>"
464            "      <menuitem action='SelectNextDimRgnZone'/>"
465            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
466            "      <menuitem action='SelectAddNextDimRgnZone'/>"
467            "      <separator/>"
468            "      <menuitem action='CopySampleUnity'/>"
469            "      <menuitem action='CopySampleTune'/>"
470            "      <menuitem action='CopySampleLoop'/>"
471            "    </menu>"
472            "    <menu action='MenuMacro'>"
473            "    </menu>"
474            "    <menu action='MenuSample'>"
475            "      <menuitem action='SampleProperties'/>"
476            "      <menuitem action='AddGroup'/>"
477            "      <menuitem action='AddSample'/>"
478            "      <menuitem action='ShowSampleRefs'/>"
479            "      <menuitem action='ReplaceSample' />"
480            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
481            "      <separator/>"
482            "      <menuitem action='RemoveSample'/>"
483            "      <menuitem action='RemoveUnusedSamples'/>"
484            "    </menu>"
485          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
486            "      <menu action='AllInstruments'>"
487            "      </menu>"
488            "      <separator/>"
489            "      <menuitem action='InstrProperties'/>"
490            "      <menuitem action='MidiRules'/>"
491            "      <menuitem action='ScriptSlots'/>"
492            "      <menuitem action='AddInstrument'/>"
493            "      <menuitem action='DupInstrument'/>"
494            "      <separator/>"
495            "      <menuitem action='RemoveInstrument'/>"
496            "    </menu>"
497            "    <menu action='MenuScript'>"
498            "      <menuitem action='AddScriptGroup'/>"
499            "      <menuitem action='AddScript'/>"
500            "      <menuitem action='EditScript'/>"
501            "      <separator/>"
502            "      <menuitem action='RemoveScript'/>"
503          "    </menu>"          "    </menu>"
504          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
505          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
506            "      <menuitem action='AutoRestoreWinDim'/>"
507            "      <separator/>"
508            "      <menuitem action='RefreshAll'/>"
509            "    </menu>"
510            "    <menu action='MenuTools'>"
511            "      <menuitem action='CombineInstruments'/>"
512            "      <menuitem action='MergeFiles'/>"
513            "    </menu>"
514            "    <menu action='MenuSettings'>"
515            "      <menuitem action='WarnUserOnExtensions'/>"
516            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
517            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
518            "      <menuitem action='SaveWithTemporaryFile'/>"
519          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
520          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
521          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
522          "    </menu>"          "    </menu>"
 #endif  
523          "  </menubar>"          "  </menubar>"
524          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
525          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
526            "    <menuitem action='MidiRules'/>"
527            "    <menuitem action='ScriptSlots'/>"
528          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
529            "    <menuitem action='DupInstrument'/>"
530          "    <separator/>"          "    <separator/>"
531          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
532          "  </popup>"          "  </popup>"
# Line 248  MainWindow::MainWindow() : Line 534  MainWindow::MainWindow() :
534          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
535          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
536          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
537            "    <menuitem action='ShowSampleRefs'/>"
538            "    <menuitem action='ReplaceSample' />"
539            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
540          "    <separator/>"          "    <separator/>"
541          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
542            "    <menuitem action='RemoveUnusedSamples'/>"
543            "  </popup>"
544            "  <popup name='ScriptPopupMenu'>"
545            "    <menuitem action='AddScriptGroup'/>"
546            "    <menuitem action='AddScript'/>"
547            "    <menuitem action='EditScript'/>"
548            "    <separator/>"
549            "    <menuitem action='RemoveScript'/>"
550          "  </popup>"          "  </popup>"
551          "</ui>";          "</ui>";
552      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
553    
554      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
555        
556        // Set tooltips for menu items (for some reason, setting a tooltip on the
557        // respective Gtk::Action objects above will simply be ignored, no matter
558        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
559        // Gtk::Action::create()).
560        {
561            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
562                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
563            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."));
564        }
565        {
566            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
567                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
568            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."));
569        }
570        {
571            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
572                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
573            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."));
574        }
575        {
576            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
577                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
578            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."));
579        }
580        {
581            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
582                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
583            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)."));
584        }
585        {
586            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
587                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
588            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."));
589        }
590        {
591            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
592                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
593            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
594            // copy tooltip to popup menu
595            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
596                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
597            item2->set_tooltip_text(item->get_tooltip_text());
598        }
599        {
600            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
601                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
602            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
603        }
604        {
605            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
606                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
607            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
608        }
609        {
610            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
611                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
612            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
613        }
614        {
615            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
616                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
617            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
618        }
619    
620    
621        instrument_menu = static_cast<Gtk::MenuItem*>(
622            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
623    
624      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
625      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
626      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
627      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
628        m_VBox.pack_start(m_RegionChooser.m_VirtKeybPropsBox, Gtk::PACK_SHRINK);
629      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
630      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
631    
632        set_file_is_shared(false);
633    
634      // Status Bar:      // Status Bar:
635      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
636      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
# Line 277  MainWindow::MainWindow() : Line 645  MainWindow::MainWindow() :
645      // Create the Tree model:      // Create the Tree model:
646      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
647      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
648      m_refTreeModel->signal_row_changed().connect(      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
649        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
650        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
651          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
652      );      );
653    
654      // Add the TreeView's view columns:      // Add the TreeView's view columns:
655      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
656      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
657        m_TreeView.set_headers_visible(true);
658        
659        // establish drag&drop within the instrument tree view, allowing to reorder
660        // the sequence of instruments within the gig file
661        {
662            std::vector<Gtk::TargetEntry> drag_target_instrument;
663            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
664            m_TreeView.drag_source_set(drag_target_instrument);
665            m_TreeView.drag_dest_set(drag_target_instrument);
666            m_TreeView.signal_drag_begin().connect(
667                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
668            );
669            m_TreeView.signal_drag_data_get().connect(
670                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
671            );
672            m_TreeView.signal_drag_data_received().connect(
673                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
674            );
675        }
676    
677      // create samples treeview (including its data model)      // create samples treeview (including its data model)
678      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
679      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
680        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
681        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."));
682      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
683      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
684      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
685        {
686            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
687            Gtk::CellRendererText* cellrenderer =
688                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
689            column->add_attribute(
690                cellrenderer->property_foreground(), m_SamplesModel.m_color
691            );
692        }
693        {
694            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
695            Gtk::CellRendererText* cellrenderer =
696                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
697            column->add_attribute(
698                cellrenderer->property_foreground(), m_SamplesModel.m_color
699            );
700        }
701        m_TreeViewSamples.set_headers_visible(true);
702      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
703          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
704      );      );
# Line 298  MainWindow::MainWindow() : Line 706  MainWindow::MainWindow() :
706          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
707      );      );
708    
709        // create scripts treeview (including its data model)
710        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
711        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
712        m_TreeViewScripts.set_tooltip_text(_(
713            "Use CTRL + double click for editing a script."
714            "\n\n"
715            "Note: instrument scripts are a LinuxSampler extension of the gig "
716            "format. This feature will not work with the GigaStudio software!"
717        ));
718        // m_TreeViewScripts.set_reorderable();
719        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
720        m_TreeViewScripts.set_headers_visible(false);
721        m_TreeViewScripts.signal_button_press_event().connect_notify(
722            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
723        );
724        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
725        m_TreeViewScripts.signal_row_activated().connect(
726            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
727        );
728        m_refScriptsTreeModel->signal_row_changed().connect(
729            sigc::mem_fun(*this, &MainWindow::script_name_changed)
730        );
731    
732        // establish drag&drop between scripts tree view and ScriptSlots window
733        std::vector<Gtk::TargetEntry> drag_target_gig_script;
734        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
735        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
736        m_TreeViewScripts.signal_drag_begin().connect(
737            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
738        );
739        m_TreeViewScripts.signal_drag_data_get().connect(
740            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
741        );
742    
743      // 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
744      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
745      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
746      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
747      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
748          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 316  MainWindow::MainWindow() : Line 758  MainWindow::MainWindow() :
758          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
759      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
760          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
761        m_RegionChooser.signal_instrument_changed().connect(
762            sigc::mem_fun(*this, &MainWindow::region_changed));
763      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
764          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
765      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
766          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
767      propDialog.signal_info_changed().connect(      propDialog.signal_changed().connect(
768            sigc::mem_fun(*this, &MainWindow::file_changed));
769        midiRules.signal_changed().connect(
770          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
771    
772      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 329  MainWindow::MainWindow() : Line 775  MainWindow::MainWindow() :
775          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
776      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
777          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
778        sample_ref_changed_signal.connect(
779            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
780        );
781        samples_to_be_removed_signal.connect(
782            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
783        );
784    
785        dimreg_edit.signal_select_sample().connect(
786            sigc::mem_fun(*this, &MainWindow::select_sample)
787        );
788    
789      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
790          sigc::hide(          sigc::hide(
# Line 365  MainWindow::MainWindow() : Line 821  MainWindow::MainWindow() :
821    
822      file = 0;      file = 0;
823      file_is_changed = false;      file_is_changed = false;
     set_file_is_shared(false);  
824    
825      show_all_children();      show_all_children();
826    
827      // start with a new gig file by default      // start with a new gig file by default
828      on_action_file_new();      on_action_file_new();
829    
830        // select 'Instruments' tab by default
831        // (gtk allows this only if the tab childs are visible, thats why it's here)
832        m_TreeViewNotebook.set_current_page(1);
833    
834        Gtk::Clipboard::get()->signal_owner_change().connect(
835            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
836        );
837        updateClipboardPasteAvailable();
838        updateClipboardCopyAvailable();
839    
840        // setup macros and their keyboard accelerators
841        {
842            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
843                uiManager->get_widget("/MenuBar/MenuMacro")
844            )->get_submenu();
845    
846            const Gdk::ModifierType primaryModifierKey =
847    #if defined(__APPLE__)
848                Gdk::META_MASK; // Cmd key on Mac
849    #else
850                Gdk::CONTROL_MASK; // Ctrl key on all other OSs
851    #endif
852    
853            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
854            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
855            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
856            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
857            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
858            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
859            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
860            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
861            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
862            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
863            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
864            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
865            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
866            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
867    
868            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
869            menuMacro->set_accel_group(accelGroup);
870    
871            updateMacroMenu();
872        }
873  }  }
874    
875  MainWindow::~MainWindow()  MainWindow::~MainWindow()
876  {  {
877  }  }
878    
879    void MainWindow::updateMacroMenu() {
880        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
881            uiManager->get_widget("/MenuBar/MenuMacro")
882        )->get_submenu();
883    
884        // remove all entries from "Macro" menu
885        {
886            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
887            for (int i = 0; i < children.size(); ++i) {
888                Gtk::Widget* child = children[i];
889                menuMacro->remove(*child);
890                delete child;
891            }
892        }
893    
894        // (re)load all macros from config file
895        try {
896            Settings::singleton()->loadMacros(m_macros);
897        } catch (Serialization::Exception e) {
898            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
899        } catch (...) {
900            std::cerr << "Unknown exception while loading macros!" << std::endl;
901        }
902    
903        // add all configured macros as menu items to the "Macro" menu
904        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
905            const Serialization::Archive& macro = m_macros[iMacro];
906            std::string name =
907                macro.name().empty() ?
908                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
909            Gtk::MenuItem* item = new Gtk::MenuItem(name);
910            item->signal_activate().connect(
911                sigc::bind(
912                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
913                )
914            );
915            menuMacro->append(*item);
916            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
917        }
918        // if there are no macros configured at all, then show a dummy entry instead
919        if (m_macros.empty()) {
920            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
921            item->set_sensitive(false);
922            menuMacro->append(*item);
923        }
924    
925        // add separator line to menu
926        menuMacro->append(*new Gtk::SeparatorMenuItem);
927    
928        {
929            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
930            item->signal_activate().connect(
931                sigc::mem_fun(*this, &MainWindow::setupMacros)
932            );
933            menuMacro->append(*item);
934            item->set_accel_path("<Macros>/SetupMacros");
935        }
936    
937        menuMacro->show_all_children();
938    }
939    
940    void MainWindow::onMacroSelected(int iMacro) {
941        printf("onMacroSelected(%d)\n", iMacro);
942        if (iMacro < 0 || iMacro >= m_macros.size()) return;
943        Glib::ustring errorText;
944        try {
945            applyMacro(m_macros[iMacro]);
946        } catch (Serialization::Exception e) {
947            errorText = e.Message;
948        } catch (...) {
949            errorText = _("Unknown exception while applying macro");
950        }
951        if (!errorText.empty()) {
952            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
953            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
954            msg.run();
955        }
956    }
957    
958    void MainWindow::setupMacros() {
959        MacrosSetup* setup = new MacrosSetup();
960        setup->setMacros(m_macros);
961        setup->signal_macros_changed().connect(
962            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
963        );
964        setup->show();
965    }
966    
967    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
968        m_macros = macros;
969        Settings::singleton()->saveMacros(m_macros);
970        updateMacroMenu();
971    }
972    
973  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
974  {  {
975      return !file_is_shared && file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
# Line 396  void MainWindow::region_changed() Line 989  void MainWindow::region_changed()
989  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
990  {  {
991      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
992      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
993        if (rows.empty()) return NULL;
994      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
995      if (it) {      if (it) {
996          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
997          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 441  void MainWindow::update_dimregs() Line 1034  void MainWindow::update_dimregs()
1034              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1035          }          }
1036      }      }
1037    
1038        m_RegionChooser.setModifyAllRegions(all_regions);
1039        m_DimRegionChooser.setModifyAllRegions(all_regions);
1040        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1041        m_DimRegionChooser.setModifyBothChannels(stereo);
1042    
1043        updateClipboardCopyAvailable();
1044  }  }
1045    
1046  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 452  void MainWindow::dimreg_all_dimregs_togg Line 1052  void MainWindow::dimreg_all_dimregs_togg
1052  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1053  {  {
1054      update_dimregs();      update_dimregs();
1055      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1056  }  }
1057    
1058  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1059  {  {
1060        // select item in instrument menu
1061        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1062        if (!rows.empty()) {
1063            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1064            if (it) {
1065                Gtk::TreePath path(it);
1066                int index = path[0];
1067                const std::vector<Gtk::Widget*> children =
1068                    instrument_menu->get_children();
1069                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1070            }
1071        }
1072    
1073      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1074    
1075        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1076            switch_sampler_instrument_signal.emit(get_instrument());
1077        }
1078  }  }
1079    
1080  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
# Line 469  void loader_progress_callback(gig::progr Line 1086  void loader_progress_callback(gig::progr
1086  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
1087  {  {
1088      {      {
1089          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1090          progress = fraction;          progress = fraction;
1091      }      }
1092      progress_dispatcher();      progress_dispatcher();
1093  }  }
1094    
1095    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1096    // make sure stack is 16-byte aligned for SSE instructions
1097    __attribute__((force_align_arg_pointer))
1098    #endif
1099  void Loader::thread_function()  void Loader::thread_function()
1100  {  {
1101      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
1102      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1103      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
1104      gig = new gig::File(riff);      try {
1105      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
1106      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
1107      progress.custom = this;          gig::progress_t progress;
1108            progress.callback = loader_progress_callback;
1109      gig->GetInstrument(0, &progress);          progress.custom = this;
1110      printf("End\n");  
1111      finished_dispatcher();          gig->GetInstrument(0, &progress);
1112            printf("End\n");
1113            finished_dispatcher();
1114        } catch (RIFF::Exception e) {
1115            error_message = e.Message;
1116            error_dispatcher.emit();
1117        } catch (...) {
1118            error_message = _("Unknown exception occurred");
1119            error_dispatcher.emit();
1120        }
1121  }  }
1122    
1123  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
1124      : thread(0), filename(filename)      : filename(filename), gig(0), thread(0), progress(0.f)
1125  {  {
1126  }  }
1127    
1128  void Loader::launch()  void Loader::launch()
1129  {  {
1130    #ifdef OLD_THREADS
1131      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
1132      printf("launch thread=%x\n", thread);  #else
1133        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
1134    #endif
1135        printf("launch thread=%p\n", static_cast<void*>(thread));
1136  }  }
1137    
1138  float Loader::get_progress()  float Loader::get_progress()
1139  {  {
1140      float res;      float res;
1141      {      {
1142          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1143          res = progress;          res = progress;
1144      }      }
1145      return res;      return res;
# Line 521  Glib::Dispatcher& Loader::signal_finishe Line 1155  Glib::Dispatcher& Loader::signal_finishe
1155      return finished_dispatcher;      return finished_dispatcher;
1156  }  }
1157    
1158  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
1159    {
1160        return error_dispatcher;
1161    }
1162    
1163    void saver_progress_callback(gig::progress_t* progress)
1164    {
1165        Saver* saver = static_cast<Saver*>(progress->custom);
1166        saver->progress_callback(progress->factor);
1167    }
1168    
1169    void Saver::progress_callback(float fraction)
1170    {
1171        {
1172            Glib::Threads::Mutex::Lock lock(progressMutex);
1173            progress = fraction;
1174        }
1175        progress_dispatcher.emit();
1176    }
1177    
1178    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1179    // make sure stack is 16-byte aligned for SSE instructions
1180    __attribute__((force_align_arg_pointer))
1181    #endif
1182    void Saver::thread_function()
1183    {
1184        printf("thread_function self=%p\n",
1185               static_cast<void*>(Glib::Threads::Thread::self()));
1186        printf("Start %s\n", filename.c_str());
1187        try {
1188            gig::progress_t progress;
1189            progress.callback = saver_progress_callback;
1190            progress.custom = this;
1191    
1192            // if no filename was provided, that means "save", if filename was provided means "save as"
1193            if (filename.empty()) {
1194                if (!Settings::singleton()->saveWithTemporaryFile) {
1195                    // save directly over the existing .gig file
1196                    // (requires less disk space than solution below
1197                    // but may be slower)
1198                    gig->Save(&progress);
1199                } else {
1200                    // save the file as separate temporary file first,
1201                    // then move the saved file over the old file
1202                    // (may result in performance speedup during save)
1203                    String tmpname = filename + ".TMP";
1204                    gig->Save(tmpname, &progress);
1205                    #if defined(WIN32)
1206                    if (!DeleteFile(filename.c_str())) {
1207                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1208                    }
1209                    #else // POSIX ...
1210                    if (unlink(filename.c_str())) {
1211                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
1212                    }
1213                    #endif
1214                    if (rename(tmpname.c_str(), filename.c_str())) {
1215                        #if defined(WIN32)
1216                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1217                        #else
1218                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
1219                        #endif
1220                    }
1221                }
1222            } else {
1223                gig->Save(filename, &progress);
1224            }
1225    
1226            printf("End\n");
1227            finished_dispatcher.emit();
1228        } catch (RIFF::Exception e) {
1229            error_message = e.Message;
1230            error_dispatcher.emit();
1231        } catch (...) {
1232            error_message = _("Unknown exception occurred");
1233            error_dispatcher.emit();
1234        }
1235    }
1236    
1237    Saver::Saver(gig::File* file, Glib::ustring filename)
1238        : gig(file), filename(filename), thread(0), progress(0.f)
1239    {
1240    }
1241    
1242    void Saver::launch()
1243    {
1244    #ifdef OLD_THREADS
1245        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1246    #else
1247        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1248    #endif
1249        printf("launch thread=%p\n", static_cast<void*>(thread));
1250    }
1251    
1252    float Saver::get_progress()
1253    {
1254        float res;
1255        {
1256            Glib::Threads::Mutex::Lock lock(progressMutex);
1257            res = progress;
1258        }
1259        return res;
1260    }
1261    
1262    Glib::Dispatcher& Saver::signal_progress()
1263    {
1264        return progress_dispatcher;
1265    }
1266    
1267    Glib::Dispatcher& Saver::signal_finished()
1268    {
1269        return finished_dispatcher;
1270    }
1271    
1272    Glib::Dispatcher& Saver::signal_error()
1273    {
1274        return error_dispatcher;
1275    }
1276    
1277    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1278      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1279  {  {
1280      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1281      show_all_children();      show_all_children();
1282        resize(600,50);
1283  }  }
1284    
1285  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
1286  // 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.
1287  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();  
1288      // forget all samples that ought to be imported      // forget all samples that ought to be imported
1289      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
1290      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1291      m_refTreeModel->clear();      m_refTreeModel->clear();
1292      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1293        m_refScriptsTreeModel->clear();
1294        // remove all entries from "Instrument" menu
1295        while (!instrument_menu->get_children().empty()) {
1296            remove_instrument_from_menu(0);
1297        }
1298      // free libgig's gig::File instance      // free libgig's gig::File instance
1299      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
1300      file = NULL;      file = NULL;
1301      set_file_is_shared(false);      set_file_is_shared(false);
1302  }  }
1303    
1304    void MainWindow::__refreshEntireGUI() {
1305        // clear the samples and instruments tree views
1306        m_refTreeModel->clear();
1307        m_refSamplesTreeModel->clear();
1308        m_refScriptsTreeModel->clear();
1309        // remove all entries from "Instrument" menu
1310        while (!instrument_menu->get_children().empty()) {
1311            remove_instrument_from_menu(0);
1312        }
1313    
1314        if (!this->file) return;
1315    
1316        load_gig(
1317            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1318        );
1319    }
1320    
1321  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
1322  {  {
1323      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 562  void MainWindow::on_action_file_new() Line 1330  void MainWindow::on_action_file_new()
1330      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
1331      // already add one new instrument by default      // already add one new instrument by default
1332      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
1333      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
1334      // update GUI with that new gig::File      // update GUI with that new gig::File
1335      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
1336  }  }
# Line 573  bool MainWindow::close_confirmation_dial Line 1341  bool MainWindow::close_confirmation_dial
1341                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
1342      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
1343      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1344      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  
1345      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1346      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1347      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);
1348      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1349      int response = dialog.run();      int response = dialog.run();
1350      dialog.hide();      dialog.hide();
1351      if (response == Gtk::RESPONSE_YES) return file_save();  
1352      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1353        if (response == Gtk::RESPONSE_NO) return true;
1354    
1355        // user cancelled dialog, thus don't close app
1356        if (response == Gtk::RESPONSE_CANCEL) return false;
1357    
1358        // TODO: the following return valid is disabled and hard coded instead for
1359        // now, due to the fact that saving with progress bar is now implemented
1360        // asynchronously, as a result the app does not close automatically anymore
1361        // after saving the file has completed
1362        //
1363        //   if (response == Gtk::RESPONSE_YES) return file_save();
1364        //   return response != Gtk::RESPONSE_CANCEL;
1365        //
1366        if (response == Gtk::RESPONSE_YES) file_save();
1367        return false; // always prevent closing the app for now (see comment above)
1368  }  }
1369    
1370  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
1371      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
1372      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  
1373      dialog.set_secondary_text(      dialog.set_secondary_text(
1374          _("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 "
1375            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1376            "load it.")            "load it."));
    );  
 #endif  
1377      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1378      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1379      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
# Line 614  void MainWindow::on_action_file_open() Line 1392  void MainWindow::on_action_file_open()
1392      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1393      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
1394      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1395    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1396      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1397      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1398    #else
1399        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1400        filter->add_pattern("*.gig");
1401    #endif
1402      dialog.set_filter(filter);      dialog.set_filter(filter);
1403      if (current_dir != "") {      if (current_gig_dir != "") {
1404          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1405      }      }
1406      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1407          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1408          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1409          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%p\n",
1410                   static_cast<void*>(Glib::Threads::Thread::self()));
1411          load_file(filename.c_str());          load_file(filename.c_str());
1412          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1413      }      }
1414  }  }
1415    
1416  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1417  {  {
1418      __clear();      __clear();
1419      load_dialog = new LoadDialog("Loading...", *this);  
1420      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1421      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1422            Glib::filename_display_basename(name) + "' ...",
1423            *this
1424        );
1425        progress_dialog->show_all();
1426        loader = new Loader(name); //FIXME: memory leak!
1427      loader->signal_progress().connect(      loader->signal_progress().connect(
1428          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1429      loader->signal_finished().connect(      loader->signal_finished().connect(
1430          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1431        loader->signal_error().connect(
1432            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1433      loader->launch();      loader->launch();
1434  }  }
1435    
# Line 654  void MainWindow::load_instrument(gig::In Line 1445  void MainWindow::load_instrument(gig::In
1445      // load the instrument      // load the instrument
1446      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1447      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1448      //TODO: automatically select the given instrument      // automatically select the given instrument
1449        int i = 0;
1450        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1451             instrument = pFile->GetNextInstrument(), ++i)
1452        {
1453            if (instrument == instr) {
1454                // select item in "instruments" tree view
1455                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1456                // make sure the selected item in the "instruments" tree view is
1457                // visible (scroll to it)
1458                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1459                // select item in instrument menu
1460                {
1461                    const std::vector<Gtk::Widget*> children =
1462                        instrument_menu->get_children();
1463                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1464                }
1465                // update region chooser and dimension region chooser
1466                m_RegionChooser.set_instrument(instr);
1467                break;
1468            }
1469        }
1470  }  }
1471    
1472  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1473  {  {
1474      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1475  }  }
1476    
1477  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1478  {  {
1479      printf("Loader finished!\n");      printf("Loader finished!\n");
1480      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
1481      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1482      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1483        progress_dialog->hide();
1484    }
1485    
1486    void MainWindow::on_loader_error()
1487    {
1488        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1489        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1490        msg.run();
1491        progress_dialog->hide();
1492  }  }
1493    
1494  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 706  bool MainWindow::file_save() Line 1527  bool MainWindow::file_save()
1527    
1528      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1529      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1530      try {  
1531          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1532          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1533              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1534              file_is_changed = false;          *this
1535          }      );
1536      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1537          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1538          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1539          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1540          msg.run();      saver->signal_finished().connect(
1541          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1542      }      saver->signal_error().connect(
1543      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1544        saver->launch();
1545    
1546        return true;
1547    }
1548    
1549    void MainWindow::on_saver_progress()
1550    {
1551        progress_dialog->set_fraction(saver->get_progress());
1552    }
1553    
1554    void MainWindow::on_saver_error()
1555    {
1556        file_structure_changed_signal.emit(this->file);
1557        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1558        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1559        msg.run();
1560    }
1561    
1562    void MainWindow::on_saver_finished()
1563    {
1564        this->file = saver->gig;
1565        this->filename = saver->filename;
1566        current_gig_dir = Glib::path_get_dirname(filename);
1567        set_title(Glib::filename_display_basename(filename));
1568        file_has_name = true;
1569        file_is_changed = false;
1570        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1571      __import_queued_samples();      __import_queued_samples();
1572        std::cout << "Importing queued samples done.\n" << std::flush;
1573    
1574      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1575      return true;  
1576        __refreshEntireGUI();
1577        progress_dialog->hide();
1578  }  }
1579    
1580  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 737  bool MainWindow::file_save_as() Line 1589  bool MainWindow::file_save_as()
1589      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
1590      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
1591      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  
1592      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1593      // TODO: an overwrite dialog for gtkmm < 2.8  
1594  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1595      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1596      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1597    #else
1598        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1599        filter->add_pattern("*.gig");
1600    #endif
1601      dialog.set_filter(filter);      dialog.set_filter(filter);
1602    
1603      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1604          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1605      } else if (current_dir != "") {      {
1606          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1607            std::string dir = Glib::path_get_dirname(filename);
1608            basename = std::string(_("copy_of_")) + basename;
1609            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1610            if (Glib::path_is_absolute(filename)) {
1611                dialog.set_filename(copyFileName);
1612            } else {
1613                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1614            }
1615            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1616      }      }
1617      dialog.set_current_name(Glib::filename_display_basename(filename));  
1618        // show warning in the dialog
1619        Gtk::HBox descriptionArea;
1620        descriptionArea.set_spacing(15);
1621        Gtk::Image warningIcon;
1622        warningIcon.set_from_icon_name("dialog-warning",
1623                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1624        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1625    #if GTKMM_MAJOR_VERSION < 3
1626        view::WrapLabel description;
1627    #else
1628        Gtk::Label description;
1629        description.set_line_wrap();
1630    #endif
1631        description.set_markup(
1632            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1633              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1634              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1635              "to the same .gig file. Using "
1636              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1637              "same .gig file will end up in corrupted sample wave data!\n")
1638        );
1639        descriptionArea.pack_start(description);
1640        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1641        descriptionArea.show_all();
1642    
1643      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1644          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1645          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1646              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;  
1647          }          }
1648          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1649          file_structure_changed_signal.emit(this->file);  
1650            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1651                _("Saving") +  Glib::ustring(" '") +
1652                Glib::filename_display_basename(filename) + "' ...",
1653                *this
1654            );
1655            progress_dialog->show_all();
1656    
1657            saver = new Saver(file, filename); //FIXME: memory leak!
1658            saver->signal_progress().connect(
1659                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1660            saver->signal_finished().connect(
1661                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1662            saver->signal_error().connect(
1663                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1664            saver->launch();
1665    
1666          return true;          return true;
1667      }      }
1668      return false;      return false;
# Line 785  bool MainWindow::file_save_as() Line 1672  bool MainWindow::file_save_as()
1672  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1673      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1674      Glib::ustring error_files;      Glib::ustring error_files;
1675      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1676      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1677           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1678          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1679          SF_INFO info;          SF_INFO info;
1680          info.format = 0;          info.format = 0;
1681          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);
1682            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1683          try {          try {
1684              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1685              // determine sample's bit depth              // determine sample's bit depth
1686              int bitdepth;              int bitdepth;
1687              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 810  void MainWindow::__import_queued_samples Line 1698  void MainWindow::__import_queued_samples
1698                      break;                      break;
1699                  default:                  default:
1700                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1701                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1702              }              }
1703    
1704                // reset write position for sample
1705                iter->first->SetPos(0);
1706    
1707              const int bufsize = 10000;              const int bufsize = 10000;
1708              switch (bitdepth) {              switch (bitdepth) {
1709                  case 16: {                  case 16: {
# Line 822  void MainWindow::__import_queued_samples Line 1713  void MainWindow::__import_queued_samples
1713                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1714                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1715                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1716                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1717                          cnt -= n;                          cnt -= n;
1718                      }                      }
1719                      delete[] buffer;                      delete[] buffer;
# Line 842  void MainWindow::__import_queued_samples Line 1733  void MainWindow::__import_queued_samples
1733                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1734                          }                          }
1735                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1736                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1737                          cnt -= n;                          cnt -= n;
1738                      }                      }
1739                      delete[] srcbuf;                      delete[] srcbuf;
# Line 852  void MainWindow::__import_queued_samples Line 1743  void MainWindow::__import_queued_samples
1743              }              }
1744              // cleanup              // cleanup
1745              sf_close(hFile);              sf_close(hFile);
1746                // let the sampler re-cache the sample if needed
1747                sample_changed_signal.emit(iter->first);
1748              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1749              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1750              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1751              ++iter;              ++iter;
1752              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1753          } catch (std::string what) {          } catch (std::string what) {
1754              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1755              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1756              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1757              ++iter;              ++iter;
1758          }          }
1759      }      }
1760      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1761      if (error_files.size()) {      if (!error_files.empty()) {
1762          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;
1763          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1764          msg.run();          msg.run();
# Line 878  void MainWindow::on_action_file_properti Line 1771  void MainWindow::on_action_file_properti
1771      propDialog.deiconify();      propDialog.deiconify();
1772  }  }
1773    
1774    void MainWindow::on_action_warn_user_on_extensions() {
1775        Settings::singleton()->warnUserOnExtensions =
1776            !Settings::singleton()->warnUserOnExtensions;
1777    }
1778    
1779    void MainWindow::on_action_sync_sampler_instrument_selection() {
1780        Settings::singleton()->syncSamplerInstrumentSelection =
1781            !Settings::singleton()->syncSamplerInstrumentSelection;
1782    }
1783    
1784    void MainWindow::on_action_move_root_note_with_region_moved() {
1785        Settings::singleton()->moveRootNoteWithRegionMoved =
1786            !Settings::singleton()->moveRootNoteWithRegionMoved;
1787    }
1788    
1789  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1790  {  {
 #ifdef ABOUT_DIALOG  
1791      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1792    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1793        dialog.set_program_name("Gigedit");
1794    #else
1795        dialog.set_name("Gigedit");
1796    #endif
1797      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1798      dialog.set_copyright("Copyright (C) 2006,2007 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1799      dialog.set_comments(      const std::string sComment =
1800          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
1801          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1802          "Please notice that this is still a very young instrument editor. "          _(
1803          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
1804          "this application.\n"              "\n"
1805          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
1806          "Please report bugs to: http://bugs.linuxsampler.org"              "backup your Gigasampler/GigaStudio files before editing them with "
1807      );              "this application.\n"
1808                "\n"
1809                "Please report bugs to: http://bugs.linuxsampler.org"
1810            );
1811        dialog.set_comments(sComment.c_str());
1812      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1813      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1814      dialog.run();      dialog.run();
 #endif  
1815  }  }
1816    
1817  PropDialog::PropDialog()  PropDialog::PropDialog()
1818      : table(2,1),      : eFileFormat(_("File Format")),
1819        eName("Name"),        eName(_("Name")),
1820        eCreationDate("Creation date"),        eCreationDate(_("Creation date")),
1821        eComments("Comments"),        eComments(_("Comments")),
1822        eProduct("Product"),        eProduct(_("Product")),
1823        eCopyright("Copyright"),        eCopyright(_("Copyright")),
1824        eArtists("Artists"),        eArtists(_("Artists")),
1825        eGenre("Genre"),        eGenre(_("Genre")),
1826        eKeywords("Keywords"),        eKeywords(_("Keywords")),
1827        eEngineer("Engineer"),        eEngineer(_("Engineer")),
1828        eTechnician("Technician"),        eTechnician(_("Technician")),
1829        eSoftware("Software"),        eSoftware(_("Software")),
1830        eMedium("Medium"),        eMedium(_("Medium")),
1831        eSource("Source"),        eSource(_("Source")),
1832        eSourceForm("Source form"),        eSourceForm(_("Source form")),
1833        eCommissioned("Commissioned"),        eCommissioned(_("Commissioned")),
1834        eSubject("Subject"),        eSubject(_("Subject")),
1835        quitButton(Gtk::Stock::CLOSE),        quitButton(Gtk::Stock::CLOSE),
1836        update_model(0)        table(2, 1),
1837          m_file(NULL)
1838  {  {
1839      set_title("File Properties");      set_title(_("File Properties"));
1840      eName.set_width_chars(50);      eName.set_width_chars(50);
1841    
1842      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
# Line 940  PropDialog::PropDialog() Line 1856  PropDialog::PropDialog()
1856      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
1857      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
1858    
1859        table.add(eFileFormat);
1860      table.add(eName);      table.add(eName);
1861      table.add(eCreationDate);      table.add(eCreationDate);
1862      table.add(eComments);      table.add(eComments);
# Line 966  PropDialog::PropDialog() Line 1883  PropDialog::PropDialog()
1883      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1884      buttonBox.show();      buttonBox.show();
1885      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1886      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1887      quitButton.grab_focus();      quitButton.grab_focus();
1888      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
1889          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &PropDialog::hide));
1890        eFileFormat.signal_value_changed().connect(
1891            sigc::mem_fun(*this, &PropDialog::onFileFormatChanged));
1892    
1893      quitButton.show();      quitButton.show();
1894      vbox.show();      vbox.show();
1895      show_all_children();      show_all_children();
1896  }  }
1897    
1898  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_file(gig::File* file)
1899  {  {
1900      this->info = info;      m_file = file;
1901      update_model++;  
1902      eName.set_value(info->Name);      // update file format version combo box
1903      eCreationDate.set_value(info->CreationDate);      const std::string sGiga = "Gigasampler/GigaStudio v";
1904      eComments.set_value(info->Comments);      const int major = file->pVersion->major;
1905      eProduct.set_value(info->Product);      std::vector<std::string> txts;
1906      eCopyright.set_value(info->Copyright);      std::vector<int> values;
1907      eArtists.set_value(info->Artists);      txts.push_back(sGiga + "2"); values.push_back(2);
1908      eGenre.set_value(info->Genre);      txts.push_back(sGiga + "3/v4"); values.push_back(3);
1909      eKeywords.set_value(info->Keywords);      if (major != 2 && major != 3) {
1910      eEngineer.set_value(info->Engineer);          txts.push_back(sGiga + ToString(major)); values.push_back(major);
1911      eTechnician.set_value(info->Technician);      }
1912      eSoftware.set_value(info->Software);      std::vector<const char*> texts;
1913      eMedium.set_value(info->Medium);      for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1914      eSource.set_value(info->Source);      texts.push_back(NULL); values.push_back(0);
1915      eSourceForm.set_value(info->SourceForm);      eFileFormat.set_choices(&texts[0], &values[0]);
1916      eCommissioned.set_value(info->Commissioned);      eFileFormat.set_value(major);
1917      eSubject.set_value(info->Subject);  }
1918      update_model--;  
1919    void PropDialog::onFileFormatChanged() {
1920        const int major = eFileFormat.get_value();
1921        if (m_file) m_file->pVersion->major = major;
1922  }  }
1923    
1924  sigc::signal<void>& PropDialog::signal_info_changed()  void PropDialog::set_info(DLS::Info* info)
1925  {  {
1926      return info_changed;      update(info);
1927  }  }
1928    
1929  void InstrumentProps::set_IsDrum(bool value)  
1930    void InstrumentProps::set_Name(const gig::String& name)
1931  {  {
1932      instrument->IsDrum = value;      m->pInfo->Name = name;
1933  }  }
1934    
1935  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
1936  {  {
1937      instrument->MIDIBank = value;      update_model++;
1938        eName.set_value(m->pInfo->Name);
1939        update_model--;
1940  }  }
1941    
1942  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
1943  {  {
1944      instrument->MIDIProgram = value;      m->IsDrum = value;
1945  }  }
1946    
1947  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
1948  {  {
1949      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
1950  }  }
1951    
1952  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
1953  {  {
1954      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
1955  }  }
1956    
1957  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
1958      : table(2,1),      quitButton(Gtk::Stock::CLOSE),
1959        quitButton(Gtk::Stock::CLOSE),      table(2,1),
1960        eName("Name"),      eName(_("Name")),
1961        eIsDrum("Is drum"),      eIsDrum(_("Is drum")),
1962        eMIDIBank("MIDI bank", 0, 16383),      eMIDIBank(_("MIDI bank"), 0, 16383),
1963        eMIDIProgram("MIDI program"),      eMIDIProgram(_("MIDI program")),
1964        eAttenuation("Attenuation", 0, 96, 0, 1),      eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1965        eGainPlus6("Gain +6dB", eAttenuation, -6),      eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1966        eEffectSend("Effect send", 0, 65535),      eEffectSend(_("Effect send"), 0, 65535),
1967        eFineTune("Fine tune", -8400, 8400),      eFineTune(_("Fine tune"), -8400, 8400),
1968        ePitchbendRange("Pitchbend range", 0, 12),      ePitchbendRange(_("Pitchbend range"), 0, 12),
1969        ePianoReleaseMode("Piano release mode"),      ePianoReleaseMode(_("Piano release mode")),
1970        eDimensionKeyRangeLow("Keyswitching range low"),      eDimensionKeyRangeLow(_("Keyswitching range low")),
1971        eDimensionKeyRangeHigh("Keyswitching range high"),      eDimensionKeyRangeHigh(_("Keyswitching range high"))
       update_model(0)  
1972  {  {
1973      set_title("Instrument Properties");      set_title(_("Instrument Properties"));
1974    
1975      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
1976          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
# Line 1063  InstrumentProps::InstrumentProps() Line 1981  InstrumentProps::InstrumentProps()
1981            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
1982      );      );
1983    
1984        connect(eName, &InstrumentProps::set_Name);
1985      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
1986      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1987      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
# Line 1072  InstrumentProps::InstrumentProps() Line 1991  InstrumentProps::InstrumentProps()
1991      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
1992      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1993      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1994      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1995              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
1996      connect(eDimensionKeyRangeHigh,  
1997              &InstrumentProps::set_DimensionKeyRange_high);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
1998    
1999      table.set_col_spacings(5);      table.set_col_spacings(5);
2000    
# Line 1101  InstrumentProps::InstrumentProps() Line 2020  InstrumentProps::InstrumentProps()
2020      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2021      buttonBox.show();      buttonBox.show();
2022      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2023      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
2024      quitButton.grab_focus();      quitButton.grab_focus();
2025    
2026      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 1114  InstrumentProps::InstrumentProps() Line 2033  InstrumentProps::InstrumentProps()
2033    
2034  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
2035  {  {
2036      this->instrument = instrument;      update(instrument);
2037    
2038      update_model++;      update_model++;
2039      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
2040      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
2041      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
2042      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);  
2043      update_model--;      update_model--;
2044  }  }
2045    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
2046    
2047  void MainWindow::file_changed()  void MainWindow::file_changed()
2048  {  {
# Line 1145  void MainWindow::file_changed() Line 2052  void MainWindow::file_changed()
2052      }      }
2053  }  }
2054    
2055    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
2056        sample_ref_count.clear();
2057        
2058        if (!gig) return;
2059    
2060        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
2061             instrument = gig->GetNextInstrument())
2062        {
2063            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2064                 rgn = instrument->GetNextRegion())
2065            {
2066                for (int i = 0; i < 256; ++i) {
2067                    if (!rgn->pDimensionRegions[i]) continue;
2068                    if (rgn->pDimensionRegions[i]->pSample) {
2069                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
2070                    }
2071                }
2072            }
2073        }
2074    }
2075    
2076  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
2077  {  {
2078      file = 0;      file = 0;
2079      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
2080    
2081      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
2082            (filename && strlen(filename) > 0) ?
2083                filename : (!gig->GetFileName().empty()) ?
2084                    gig->GetFileName() : _("Unsaved Gig File");
2085      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
2086      file_has_name = filename;      file_has_name = filename;
2087      file_is_changed = false;      file_is_changed = false;
2088    
2089        propDialog.set_file(gig);
2090      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
2091    
2092      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
2093          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));      int index = 0;
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
2094      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
2095           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
2096            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2097    
2098          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
2099          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
2100          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
2101            row[m_Columns.m_col_name] = name;
2102          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
2103          // create a menu item for this instrument  
2104          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++;  
2105      }      }
2106      instrument_menu->show();      instrument_name_connection.unblock();
2107      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
2108    
2109        updateSampleRefCountMap(gig);
2110    
2111      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
2112          if (group->Name != "") {          if (group->Name != "") {
2113              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2114              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
2115              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
2116              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
2117              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
2118              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1195  void MainWindow::load_gig(gig::File* gig Line 2120  void MainWindow::load_gig(gig::File* gig
2120                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
2121                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
2122                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
2123                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
2124                        gig_to_utf8(sample->pInfo->Name);
2125                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2126                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2127                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
2128                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
2129                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
2130              }              }
2131          }          }
2132      }      }
2133        
2134        for (int i = 0; gig->GetScriptGroup(i); ++i) {
2135            gig::ScriptGroup* group = gig->GetScriptGroup(i);
2136    
2137            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2138            Gtk::TreeModel::Row rowGroup = *iterGroup;
2139            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
2140            rowGroup[m_ScriptsModel.m_col_group]  = group;
2141            rowGroup[m_ScriptsModel.m_col_script] = NULL;
2142            for (int s = 0; group->GetScript(s); ++s) {
2143                gig::Script* script = group->GetScript(s);
2144    
2145                Gtk::TreeModel::iterator iterScript =
2146                    m_refScriptsTreeModel->append(rowGroup.children());
2147                Gtk::TreeModel::Row rowScript = *iterScript;
2148                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
2149                rowScript[m_ScriptsModel.m_col_script] = script;
2150                rowScript[m_ScriptsModel.m_col_group]  = NULL;
2151            }
2152        }
2153        // unfold all sample groups & script groups by default
2154        m_TreeViewSamples.expand_all();
2155        m_TreeViewScripts.expand_all();
2156    
2157      file = gig;      file = gig;
2158    
2159      // select the first instrument      // select the first instrument
2160      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
2161      tree_sel_ref->select(Gtk::TreePath("0"));  
2162        instr_props_set_instrument();
2163        gig::Instrument* instrument = get_instrument();
2164        if (instrument) {
2165            midiRules.set_instrument(instrument);
2166        }
2167  }  }
2168    
2169  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
2170  {  {
2171      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
2172      if (instrument)  
2173      {      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2174        if (rows.empty()) {
2175            instrumentProps.hide();
2176            return false;
2177        }
2178        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2179        if (it) {
2180            Gtk::TreeModel::Row row = *it;
2181            gig::Instrument* instrument = row[m_Columns.m_col_instr];
2182    
2183          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
2184    
2185            // make sure instrument tree is updated when user changes the
2186            // instrument name in instrument properties window
2187            instrumentProps.signal_name_changed().connect(
2188                sigc::bind(
2189                    sigc::mem_fun(*this,
2190                                  &MainWindow::instr_name_changed_by_instr_props),
2191                    it));
2192        } else {
2193            instrumentProps.hide();
2194        }
2195        return it;
2196    }
2197    
2198    void MainWindow::show_instr_props()
2199    {
2200        if (instr_props_set_instrument()) {
2201          instrumentProps.show();          instrumentProps.show();
2202          instrumentProps.deiconify();          instrumentProps.deiconify();
2203      }      }
2204  }  }
2205    
2206    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
2207    {
2208        Gtk::TreeModel::Row row = *it;
2209        Glib::ustring name = row[m_Columns.m_col_name];
2210    
2211        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2212        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
2213        if (gigname != name) {
2214            row[m_Columns.m_col_name] = gigname;
2215        }
2216    }
2217    
2218    void MainWindow::show_midi_rules()
2219    {
2220        if (gig::Instrument* instrument = get_instrument())
2221        {
2222            midiRules.set_instrument(instrument);
2223            midiRules.show();
2224            midiRules.deiconify();
2225        }
2226    }
2227    
2228    void MainWindow::show_script_slots() {
2229        if (!file) return;
2230        // get selected instrument
2231        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2232        if (rows.empty()) return;
2233        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2234        if (!it) return;
2235        Gtk::TreeModel::Row row = *it;
2236        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2237        if (!instrument) return;
2238    
2239        ScriptSlots* window = new ScriptSlots;
2240        window->setInstrument(instrument);
2241        //window->reparent(*this);
2242        window->show();
2243    }
2244    
2245    void MainWindow::on_action_refresh_all() {
2246        __refreshEntireGUI();
2247    }
2248    
2249  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2250      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2251          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1231  void MainWindow::on_action_view_status_b Line 2257  void MainWindow::on_action_view_status_b
2257      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2258  }  }
2259    
2260    void MainWindow::on_auto_restore_win_dim() {
2261        Gtk::CheckMenuItem* item =
2262            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2263        if (!item) {
2264            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2265            return;
2266        }
2267        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2268    }
2269    
2270    void MainWindow::on_save_with_temporary_file() {
2271        Gtk::CheckMenuItem* item =
2272            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2273        if (!item) {
2274            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2275            return;
2276        }
2277        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2278    }
2279    
2280    bool MainWindow::is_copy_samples_unity_note_enabled() const {
2281        Gtk::CheckMenuItem* item =
2282            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
2283        if (!item) {
2284            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
2285            return true;
2286        }
2287        return item->get_active();
2288    }
2289    
2290    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
2291        Gtk::CheckMenuItem* item =
2292            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
2293        if (!item) {
2294            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
2295            return true;
2296        }
2297        return item->get_active();
2298    }
2299    
2300    bool MainWindow::is_copy_samples_loop_enabled() const {
2301        Gtk::CheckMenuItem* item =
2302            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
2303        if (!item) {
2304            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
2305            return true;
2306        }
2307        return item->get_active();
2308    }
2309    
2310  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
2311  {  {
2312      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2313          show_instr_props();          show_instr_props();
2314      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2315            // gig v2 files have no midi rules
2316            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2317            static_cast<Gtk::MenuItem*>(
2318                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2319                    bEnabled
2320                );
2321            static_cast<Gtk::MenuItem*>(
2322                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2323                    bEnabled
2324                );
2325          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2326      }      }
2327  }  }
2328    
2329  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
2330      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
2331            const std::vector<Gtk::Widget*> children =
2332                instrument_menu->get_children();
2333            std::vector<Gtk::Widget*>::const_iterator it =
2334                find(children.begin(), children.end(), item);
2335            if (it != children.end()) {
2336                int index = it - children.begin();
2337                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
2338    
2339                m_RegionChooser.set_instrument(file->GetInstrument(index));
2340            }
2341        }
2342    }
2343    
2344    void MainWindow::select_instrument(gig::Instrument* instrument) {
2345        if (!instrument) return;
2346    
2347        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2348        for (int i = 0; i < model->children().size(); ++i) {
2349            Gtk::TreeModel::Row row = model->children()[i];
2350            if (row[m_Columns.m_col_instr] == instrument) {
2351                // select and show the respective instrument in the list view
2352                show_intruments_tab();
2353                m_TreeView.get_selection()->unselect_all();
2354                m_TreeView.get_selection()->select(model->children()[i]);
2355                std::vector<Gtk::TreeModel::Path> rows =
2356                    m_TreeView.get_selection()->get_selected_rows();
2357                if (!rows.empty())
2358                    m_TreeView.scroll_to_row(rows[0]);
2359                on_sel_change(); // the regular instrument selection change callback
2360            }
2361        }
2362    }
2363    
2364    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2365    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2366        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2367        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2368    
2369        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2370        for (int i = 0; i < model->children().size(); ++i) {
2371            Gtk::TreeModel::Row row = model->children()[i];
2372            if (row[m_Columns.m_col_instr] == pInstrument) {
2373                // select and show the respective instrument in the list view
2374                show_intruments_tab();
2375                m_TreeView.get_selection()->unselect_all();
2376                m_TreeView.get_selection()->select(model->children()[i]);
2377                std::vector<Gtk::TreeModel::Path> rows =
2378                    m_TreeView.get_selection()->get_selected_rows();
2379                if (!rows.empty())
2380                    m_TreeView.scroll_to_row(rows[0]);
2381                on_sel_change(); // the regular instrument selection change callback
2382    
2383                // select respective region in the region selector
2384                m_RegionChooser.set_region(pRegion);
2385    
2386                // select and show the respective dimension region in the editor
2387                //update_dimregs();
2388                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2389                //dimreg_edit.set_dim_region(dimRgn);
2390    
2391                return true;
2392            }
2393        }
2394    
2395        return false;
2396    }
2397    
2398    void MainWindow::select_sample(gig::Sample* sample) {
2399        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2400        for (int g = 0; g < model->children().size(); ++g) {
2401            Gtk::TreeModel::Row rowGroup = model->children()[g];
2402            for (int s = 0; s < rowGroup.children().size(); ++s) {
2403                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2404                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2405                    show_samples_tab();
2406                    m_TreeViewSamples.get_selection()->unselect_all();
2407                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2408                    std::vector<Gtk::TreeModel::Path> rows =
2409                        m_TreeViewSamples.get_selection()->get_selected_rows();
2410                    if (rows.empty()) return;
2411                    m_TreeViewSamples.scroll_to_row(rows[0]);
2412                    return;
2413                }
2414            }
2415        }
2416  }  }
2417    
2418  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2419      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2420            // by default if Ctrl keys is pressed down, then a mouse right-click
2421            // does not select the respective row, so we must assure this
2422            // programmatically ...
2423            /*{
2424                Gtk::TreeModel::Path path;
2425                Gtk::TreeViewColumn* pColumn = NULL;
2426                int cellX, cellY;
2427                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2428                    (int)button->x, (int)button->y,
2429                    path, pColumn, cellX, cellY
2430                );
2431                if (bSuccess) {
2432                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2433                        printf("not selected !!!\n");
2434                        m_TreeViewSamples.get_selection()->select(path);
2435                    }
2436                }
2437            }*/
2438    
2439          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2440              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2441          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2442          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2443          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2444          bool group_selected  = false;          const int n = rows.size();
2445          bool sample_selected = false;          int nGroups  = 0;
2446          if (it) {          int nSamples = 0;
2447            for (int r = 0; r < n; ++r) {
2448                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2449                if (!it) continue;
2450              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2451              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2452              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2453          }          }
2454    
2455          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2456              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2457          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2458              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2459          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2460              set_sensitive(file);              set_sensitive(file);
2461            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2462                set_sensitive(nSamples == 1);
2463          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2464              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2465          // show sample popup          // show sample popup
2466          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2467    
2468            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2469                set_sensitive(n == 1);
2470            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2471                set_sensitive(n);
2472            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2473                set_sensitive(file);
2474            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2475                set_sensitive(nSamples == 1);
2476            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2477                set_sensitive(n);
2478      }      }
2479  }  }
2480    
2481  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2482      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2483      if (!file) return;          Gtk::Menu* script_popup =
2484      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2485      __instrument_indexer++;          // update enabled/disabled state of sample popup items
2486      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2487          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
2488            bool group_selected  = false;
2489            bool script_selected = false;
2490            if (it) {
2491                Gtk::TreeModel::Row row = *it;
2492                group_selected  = row[m_ScriptsModel.m_col_group];
2493                script_selected = row[m_ScriptsModel.m_col_script];
2494            }
2495            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2496                set_sensitive(group_selected || script_selected);
2497            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2498                set_sensitive(file);
2499            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2500                set_sensitive(script_selected);    
2501            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2502                set_sensitive(group_selected || script_selected);
2503            // show sample popup
2504            script_popup->popup(button->button, button->time);
2505    
2506            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2507                set_sensitive(group_selected || script_selected);
2508            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2509                set_sensitive(file);
2510            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2511                set_sensitive(script_selected);    
2512            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2513                set_sensitive(group_selected || script_selected);
2514        }
2515    }
2516    
2517    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2518        const Glib::ustring& name, int position) {
2519    
2520        Gtk::RadioMenuItem::Group instrument_group;
2521        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2522        if (!children.empty()) {
2523            instrument_group =
2524                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2525        }
2526        Gtk::RadioMenuItem* item =
2527            new Gtk::RadioMenuItem(instrument_group, name);
2528        if (position < 0) {
2529            instrument_menu->append(*item);
2530        } else {
2531            instrument_menu->insert(*item, position);
2532        }
2533        item->show();
2534        item->signal_activate().connect(
2535            sigc::bind(
2536                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2537                item));
2538        return item;
2539    }
2540    
2541    void MainWindow::remove_instrument_from_menu(int index) {
2542        const std::vector<Gtk::Widget*> children =
2543            instrument_menu->get_children();
2544        Gtk::Widget* child = children[index];
2545        instrument_menu->remove(*child);
2546        delete child;
2547    }
2548    
2549    void MainWindow::add_instrument(gig::Instrument* instrument) {
2550        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2551    
2552      // update instrument tree view      // update instrument tree view
2553        instrument_name_connection.block();
2554      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2555      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2556      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2557        rowInstr[m_Columns.m_col_name] = name;
2558      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2559        instrument_name_connection.unblock();
2560    
2561        add_instrument_to_menu(name);
2562    
2563        m_TreeView.get_selection()->select(iterInstr);
2564    
2565      file_changed();      file_changed();
2566  }  }
2567    
2568    void MainWindow::on_action_add_instrument() {
2569        static int __instrument_indexer = 0;
2570        if (!file) return;
2571        gig::Instrument* instrument = file->AddInstrument();
2572        __instrument_indexer++;
2573        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2574                                                ToString(__instrument_indexer));
2575    
2576        add_instrument(instrument);
2577    }
2578    
2579    void MainWindow::on_action_duplicate_instrument() {
2580        if (!file) return;
2581    
2582        // retrieve the currently selected instrument
2583        // (being the original instrument to be duplicated)
2584        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2585        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2586        for (int r = 0; r < rows.size(); ++r) {
2587            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2588            if (it) {
2589                Gtk::TreeModel::Row row = *it;
2590                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2591                if (instrOrig) {
2592                    // duplicate the orginal instrument
2593                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2594                    instrNew->pInfo->Name =
2595                        instrOrig->pInfo->Name +
2596                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2597    
2598                    add_instrument(instrNew);
2599                }
2600            }
2601        }
2602    }
2603    
2604  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2605      if (!file) return;      if (!file) return;
2606      if (file_is_shared) {      if (file_is_shared) {
# Line 1300  void MainWindow::on_action_remove_instru Line 2615  void MainWindow::on_action_remove_instru
2615      }      }
2616    
2617      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2618      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2619      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2620            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2621            if (!it) continue;
2622          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2623          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2624          try {          try {
2625                Gtk::TreePath path(it);
2626                int index = path[0];
2627    
2628              // remove instrument from the gig file              // remove instrument from the gig file
2629              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2630              file_changed();              file_changed();
2631    
2632                remove_instrument_from_menu(index);
2633    
2634                // remove row from instruments tree view
2635                m_refTreeModel->erase(it);
2636                // update "Nr" column of all instrument rows
2637                {
2638                    int index = 0;
2639                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2640                         it != m_refTreeModel->children().end(); ++it, ++index)
2641                    {
2642                        Gtk::TreeModel::Row row = *it;
2643                        row[m_Columns.m_col_nr] = index;
2644                    }
2645                }
2646    
2647    #if GTKMM_MAJOR_VERSION < 3
2648                // select another instrument (in gtk3 this is done
2649                // automatically)
2650                if (!m_refTreeModel->children().empty()) {
2651                    if (index == m_refTreeModel->children().size()) {
2652                        index--;
2653                    }
2654                    m_TreeView.get_selection()->select(
2655                        Gtk::TreePath(ToString(index)));
2656                }
2657    #endif
2658                instr_props_set_instrument();
2659                instr = get_instrument();
2660                if (instr) {
2661                    midiRules.set_instrument(instr);
2662                } else {
2663                    midiRules.hide();
2664                }
2665          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2666              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2667              msg.run();              msg.run();
# Line 1320  void MainWindow::on_action_remove_instru Line 2672  void MainWindow::on_action_remove_instru
2672  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2673      //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
2674      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2675          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2676      );      );
2677      msg.run();      msg.run();
2678  }  }
2679    
2680    void MainWindow::on_action_add_script_group() {
2681        static int __script_indexer = 0;
2682        if (!file) return;
2683        gig::ScriptGroup* group = file->AddScriptGroup();
2684        group->Name = gig_from_utf8(_("Unnamed Group"));
2685        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2686        __script_indexer++;
2687        // update sample tree view
2688        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2689        Gtk::TreeModel::Row rowGroup = *iterGroup;
2690        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2691        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2692        rowGroup[m_ScriptsModel.m_col_group] = group;
2693        file_changed();
2694    }
2695    
2696    void MainWindow::on_action_add_script() {
2697        if (!file) return;
2698        // get selected group
2699        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2700        Gtk::TreeModel::iterator it = sel->get_selected();
2701        if (!it) return;
2702        Gtk::TreeModel::Row row = *it;
2703        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2704        if (!group) { // not a group, but a script is selected (probably)
2705            gig::Script* script = row[m_ScriptsModel.m_col_script];
2706            if (!script) return;
2707            it = row.parent(); // resolve parent (that is the script's group)
2708            if (!it) return;
2709            row = *it;
2710            group = row[m_ScriptsModel.m_col_group];
2711            if (!group) return;
2712        }
2713    
2714        // add a new script to the .gig file
2715        gig::Script* script = group->AddScript();    
2716        Glib::ustring name = _("Unnamed Script");
2717        script->Name = gig_from_utf8(name);
2718    
2719        // add script to the tree view
2720        Gtk::TreeModel::iterator iterScript =
2721            m_refScriptsTreeModel->append(row.children());
2722        Gtk::TreeModel::Row rowScript = *iterScript;
2723        rowScript[m_ScriptsModel.m_col_name] = name;
2724        rowScript[m_ScriptsModel.m_col_script] = script;
2725        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2726    
2727        // unfold group of new script item in treeview
2728        Gtk::TreeModel::Path path(iterScript);
2729        m_TreeViewScripts.expand_to_path(path);
2730    }
2731    
2732    void MainWindow::on_action_edit_script() {
2733        if (!file) return;
2734        // get selected script
2735        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2736        Gtk::TreeModel::iterator it = sel->get_selected();
2737        if (!it) return;
2738        Gtk::TreeModel::Row row = *it;
2739        gig::Script* script = row[m_ScriptsModel.m_col_script];
2740        if (!script) return;
2741    
2742        ScriptEditor* editor = new ScriptEditor;
2743        editor->signal_script_to_be_changed.connect(
2744            signal_script_to_be_changed.make_slot()
2745        );
2746        editor->signal_script_changed.connect(
2747            signal_script_changed.make_slot()
2748        );
2749        editor->setScript(script);
2750        //editor->reparent(*this);
2751        editor->show();
2752    }
2753    
2754    void MainWindow::on_action_remove_script() {
2755        if (!file) return;
2756        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2757        Gtk::TreeModel::iterator it = sel->get_selected();
2758        if (it) {
2759            Gtk::TreeModel::Row row = *it;
2760            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2761            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2762            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2763            try {
2764                // remove script group or script from the gig file
2765                if (group) {
2766                    // notify everybody that we're going to remove these samples
2767    //TODO:         scripts_to_be_removed_signal.emit(members);
2768                    // delete the group in the .gig file including the
2769                    // samples that belong to the group
2770                    file->DeleteScriptGroup(group);
2771                    // notify that we're done with removal
2772    //TODO:         scripts_removed_signal.emit();
2773                    file_changed();
2774                } else if (script) {
2775                    // notify everybody that we're going to remove this sample
2776    //TODO:         std::list<gig::Script*> lscripts;
2777    //TODO:         lscripts.push_back(script);
2778    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2779                    // remove sample from the .gig file
2780                    script->GetGroup()->DeleteScript(script);
2781                    // notify that we're done with removal
2782    //TODO:         scripts_removed_signal.emit();
2783                    dimreg_changed();
2784                    file_changed();
2785                }
2786                // remove respective row(s) from samples tree view
2787                m_refScriptsTreeModel->erase(it);
2788            } catch (RIFF::Exception e) {
2789                // pretend we're done with removal (i.e. to avoid dead locks)
2790    //TODO:     scripts_removed_signal.emit();
2791                // show error message
2792                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2793                msg.run();
2794            }
2795        }
2796    }
2797    
2798  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2799      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2800      if (!file) return;      if (!file) return;
2801      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2802      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2803      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2804      __sample_indexer++;      __sample_indexer++;
2805      // update sample tree view      // update sample tree view
2806      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2807      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2808      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2809      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2810      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2811      file_changed();      file_changed();
2812  }  }
2813    
2814    void MainWindow::on_action_replace_sample() {
2815        add_or_replace_sample(true);
2816    }
2817    
2818  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2819        add_or_replace_sample(false);
2820    }
2821    
2822    void MainWindow::add_or_replace_sample(bool replace) {
2823      if (!file) return;      if (!file) return;
2824      // get selected group  
2825        // get selected group (and probably selected sample)
2826      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2827      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2828        if (rows.empty()) return;
2829        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2830      if (!it) return;      if (!it) return;
2831      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2832        gig::Sample* sample = NULL;
2833      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2834      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2835          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2836          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2837          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2838          if (!it) return;          if (!it) return;
2839          row = *it;          if (!replace) row = *it;
2840          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2841          if (!group) return;          if (!group) return;
2842      }      }
2843        if (replace && !sample) return;
2844    
2845      // show 'browse for file' dialog      // show 'browse for file' dialog
2846      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2847      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2848      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2849      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
2850      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2851        // matches all file types supported by libsndfile
2852    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2853        Gtk::FileFilter soundfilter;
2854    #else
2855        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2856    #endif
2857      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2858          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2859          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1371  void MainWindow::on_action_add_sample() Line 2861  void MainWindow::on_action_add_sample()
2861          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2862          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2863      };      };
2864        const char* soundfiles = _("Sound Files");
2865        const char* allfiles = _("All Files");
2866    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2867      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2868          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2869      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2870      Gtk::FileFilter allpassfilter; // matches every file  
2871        // matches every file
2872        Gtk::FileFilter allpassfilter;
2873      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2874      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2875    #else
2876        for (int i = 0; supportedFileTypes[i]; i++)
2877            soundfilter->add_pattern(supportedFileTypes[i]);
2878        soundfilter->set_name(soundfiles);
2879    
2880        // matches every file
2881        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2882        allpassfilter->add_pattern("*.*");
2883        allpassfilter->set_name(allfiles);
2884    #endif
2885      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2886      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2887        if (current_sample_dir != "") {
2888            dialog.set_current_folder(current_sample_dir);
2889        }
2890      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2891            current_sample_dir = dialog.get_current_folder();
2892          Glib::ustring error_files;          Glib::ustring error_files;
2893          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2894          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2895               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2896              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2897              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1390  void MainWindow::on_action_add_sample() Line 2899  void MainWindow::on_action_add_sample()
2899              info.format = 0;              info.format = 0;
2900              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2901              try {              try {
2902                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2903                  int bitdepth;                  int bitdepth;
2904                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2905                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1406  void MainWindow::on_action_add_sample() Line 2915  void MainWindow::on_action_add_sample()
2915                          break;                          break;
2916                      default:                      default:
2917                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2918                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2919                  }                  }
2920                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2921                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2922                  // file name without path                  // file name without path
2923                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2924                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1419  void MainWindow::on_action_add_sample() Line 2928  void MainWindow::on_action_add_sample()
2928                          break;                          break;
2929                      }                      }
2930                  }                  }
2931                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2932                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2933                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2934                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1433  void MainWindow::on_action_add_sample() Line 2942  void MainWindow::on_action_add_sample()
2942                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2943                  {                  {
2944                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2945                        sample->FineTune      = instrument.detune;
2946    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2947                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2948                          sample->Loops = 1;                          sample->Loops = 1;
2949    
# Line 1454  void MainWindow::on_action_add_sample() Line 2963  void MainWindow::on_action_add_sample()
2963                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2964                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2965                      }                      }
 #endif  
2966                  }                  }
2967    
2968                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
2969                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2970                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2971                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2972                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2973                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2974                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2975                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2976                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2977                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2978                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2979                  // add sample to the tree view                  // add sample to the tree view
2980                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2981                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2982                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2983                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
2984                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
2985                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
2986                        rowSample[m_SamplesModel.m_col_name] =
2987                            gig_to_utf8(sample->pInfo->Name);
2988                        rowSample[m_SamplesModel.m_col_sample] = sample;
2989                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2990                    }
2991                  // close sound file                  // close sound file
2992                  sf_close(hFile);                  sf_close(hFile);
2993                  file_changed();                  file_changed();
2994              } 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)
2995                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2996                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2997              }              }
2998          }          }
2999          // 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
3000          if (error_files.size()) {          if (!error_files.empty()) {
3001              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
3002                    (replace
3003                        ? _("Failed to replace sample with:\n")
3004                        : _("Could not add the following sample(s):\n"))
3005                    + error_files;
3006                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3007                msg.run();
3008            }
3009        }
3010    }
3011    
3012    void MainWindow::on_action_replace_all_samples_in_all_groups()
3013    {
3014        if (!file) return;
3015        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
3016                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
3017        const char* str =
3018            _("This is a very specific function. It tries to replace all samples "
3019              "in the current gig file by samples located in the chosen "
3020              "directory.\n\n"
3021              "It works like this: For each sample in the gig file, it tries to "
3022              "find a sample file in the selected directory with the same name as "
3023              "the sample in the gig file. Optionally, you can add a filename "
3024              "extension below, which will be added to the filename expected to be "
3025              "found. That is, assume you have a gig file with a sample called "
3026              "'Snare', if you enter '.wav' below (like it's done by default), it "
3027              "expects to find a sample file called 'Snare.wav' and will replace "
3028              "the sample in the gig file accordingly. If you don't need an "
3029              "extension, blank the field below. Any gig sample where no "
3030              "appropriate sample file could be found will be reported and left "
3031              "untouched.\n");
3032    #if GTKMM_MAJOR_VERSION < 3
3033        view::WrapLabel description(str);
3034    #else
3035        Gtk::Label description(str);
3036        description.set_line_wrap();
3037    #endif
3038        Gtk::HBox entryArea;
3039        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
3040        Gtk::Entry postfixEntryBox;
3041        postfixEntryBox.set_text(".wav");
3042        entryArea.pack_start(entryLabel);
3043        entryArea.pack_start(postfixEntryBox);
3044        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
3045        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
3046        description.show();
3047        entryArea.show_all();
3048        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3049        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
3050        dialog.set_select_multiple(false);
3051        if (current_sample_dir != "") {
3052            dialog.set_current_folder(current_sample_dir);
3053        }
3054        if (dialog.run() == Gtk::RESPONSE_OK)
3055        {
3056            current_sample_dir = dialog.get_current_folder();
3057            Glib::ustring error_files;
3058            std::string folder = dialog.get_filename();
3059            for (gig::Sample* sample = file->GetFirstSample();
3060                 sample; sample = file->GetNextSample())
3061            {
3062                std::string filename =
3063                    folder + G_DIR_SEPARATOR_S +
3064                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
3065                                             postfixEntryBox.get_text());
3066                SF_INFO info;
3067                info.format = 0;
3068                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
3069                try
3070                {
3071                    if (!hFile) throw std::string(_("could not open file"));
3072                    switch (info.format & 0xff) {
3073                        case SF_FORMAT_PCM_S8:
3074                        case SF_FORMAT_PCM_16:
3075                        case SF_FORMAT_PCM_U8:
3076                        case SF_FORMAT_PCM_24:
3077                        case SF_FORMAT_PCM_32:
3078                        case SF_FORMAT_FLOAT:
3079                        case SF_FORMAT_DOUBLE:
3080                            break;
3081                        default:
3082                            sf_close(hFile);
3083                            throw std::string(_("format not supported"));
3084                    }
3085                    SampleImportItem sched_item;
3086                    sched_item.gig_sample  = sample;
3087                    sched_item.sample_path = filename;
3088                    m_SampleImportQueue[sample] = sched_item;
3089                    sf_close(hFile);
3090                    file_changed();
3091                }
3092                catch (std::string what)
3093                {
3094                    if (!error_files.empty()) error_files += "\n";
3095                    error_files += Glib::filename_to_utf8(filename) +
3096                        " (" + what + ")";
3097                }
3098            }
3099            // show error message box when some file(s) could not be opened / added
3100            if (!error_files.empty()) {
3101                Glib::ustring txt =
3102                    _("Could not replace the following sample(s):\n") + error_files;
3103              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3104              msg.run();              msg.run();
3105          }          }
# Line 1495  void MainWindow::on_action_add_sample() Line 3109  void MainWindow::on_action_add_sample()
3109  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
3110      if (!file) return;      if (!file) return;
3111      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3112      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3113      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3114            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3115            if (!it) continue;
3116          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3117          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
3118          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1504  void MainWindow::on_action_remove_sample Line 3120  void MainWindow::on_action_remove_sample
3120          try {          try {
3121              // remove group or sample from the gig file              // remove group or sample from the gig file
3122              if (group) {              if (group) {
3123                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
3124                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
3125                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
3126                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1521  void MainWindow::on_action_remove_sample Line 3137  void MainWindow::on_action_remove_sample
3137                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
3138                  // them from the import queue                  // them from the import queue
3139                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
3140                       member != members.end(); ++member) {                       member != members.end(); ++member)
3141                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
3142                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
3143                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
3144                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
3145                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
3146                      }                      }
3147                  }                  }
3148                  file_changed();                  file_changed();
# Line 1544  void MainWindow::on_action_remove_sample Line 3157  void MainWindow::on_action_remove_sample
3157                  samples_removed_signal.emit();                  samples_removed_signal.emit();
3158                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
3159                  // the import queue                  // the import queue
3160                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
3161                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
3162                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
3163                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
3164                  }                  }
3165                  dimreg_changed();                  dimreg_changed();
3166                  file_changed();                  file_changed();
# Line 1568  void MainWindow::on_action_remove_sample Line 3177  void MainWindow::on_action_remove_sample
3177      }      }
3178  }  }
3179    
3180    void MainWindow::on_action_remove_unused_samples() {
3181        if (!file) return;
3182    
3183        // collect all samples that are not referenced by any instrument
3184        std::list<gig::Sample*> lsamples;
3185        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3186            gig::Sample* sample = file->GetSample(iSample);
3187            bool isUsed = false;
3188            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3189                                  instrument = file->GetNextInstrument())
3190            {
3191                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3192                                  rgn = instrument->GetNextRegion())
3193                {
3194                    for (int i = 0; i < 256; ++i) {
3195                        if (!rgn->pDimensionRegions[i]) continue;
3196                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3197                        isUsed = true;
3198                        goto endOfRefSearch;
3199                    }
3200                }
3201            }
3202            endOfRefSearch:
3203            if (!isUsed) lsamples.push_back(sample);
3204        }
3205    
3206        if (lsamples.empty()) return;
3207    
3208        // notify everybody that we're going to remove these samples
3209        samples_to_be_removed_signal.emit(lsamples);
3210    
3211        // remove collected samples
3212        try {
3213            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3214                 itSample != lsamples.end(); ++itSample)
3215            {
3216                gig::Sample* sample = *itSample;
3217                // remove sample from the .gig file
3218                file->DeleteSample(sample);
3219                // if sample was just previously added, remove it from the import queue
3220                if (m_SampleImportQueue.count(sample)) {
3221                    printf("Removing previously added sample '%s'\n",
3222                           m_SampleImportQueue[sample].sample_path.c_str());
3223                    m_SampleImportQueue.erase(sample);
3224                }
3225            }
3226        } catch (RIFF::Exception e) {
3227            // show error message
3228            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3229            msg.run();
3230        }
3231    
3232        // notify everybody that we're done with removal
3233        samples_removed_signal.emit();
3234    
3235        dimreg_changed();
3236        file_changed();
3237        __refreshEntireGUI();
3238    }
3239    
3240    // see comment on on_sample_treeview_drag_begin()
3241    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3242    {
3243        first_call_to_drag_data_get = true;
3244    }
3245    
3246    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3247                                                       Gtk::SelectionData& selection_data, guint, guint)
3248    {
3249        if (!first_call_to_drag_data_get) return;
3250        first_call_to_drag_data_get = false;
3251    
3252        // get selected script
3253        gig::Script* script = NULL;
3254        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3255        Gtk::TreeModel::iterator it = sel->get_selected();
3256        if (it) {
3257            Gtk::TreeModel::Row row = *it;
3258            script = row[m_ScriptsModel.m_col_script];
3259        }
3260        // pass the gig::Script as pointer
3261        selection_data.set(selection_data.get_target(), 0/*unused*/,
3262                           (const guchar*)&script,
3263                           sizeof(script)/*length of data in bytes*/);
3264    }
3265    
3266    // see comment on on_sample_treeview_drag_begin()
3267    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3268    {
3269        first_call_to_drag_data_get = true;
3270    }
3271    
3272    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3273                                                           Gtk::SelectionData& selection_data, guint, guint)
3274    {
3275        if (!first_call_to_drag_data_get) return;
3276        first_call_to_drag_data_get = false;
3277    
3278        // get selected source instrument
3279        gig::Instrument* src = NULL;
3280        {
3281            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3282            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3283            if (!rows.empty()) {
3284                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3285                if (it) {
3286                    Gtk::TreeModel::Row row = *it;
3287                    src = row[m_Columns.m_col_instr];
3288                }
3289            }
3290        }
3291        if (!src) return;
3292    
3293        // pass the source gig::Instrument as pointer
3294        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3295                           sizeof(src)/*length of data in bytes*/);
3296    }
3297    
3298    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3299        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3300        const Gtk::SelectionData& selection_data, guint, guint time)
3301    {
3302        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3303        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3304            return;
3305    
3306        gig::Instrument* dst = NULL;
3307        {
3308            Gtk::TreeModel::Path path;
3309            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3310            if (!found) return;
3311    
3312            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3313            if (!iter) return;
3314            Gtk::TreeModel::Row row = *iter;
3315            dst = row[m_Columns.m_col_instr];
3316        }
3317        if (!dst) return;
3318    
3319        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3320        src->MoveTo(dst);
3321        __refreshEntireGUI();
3322        select_instrument(src);
3323    }
3324    
3325  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3326  // 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
3327  // 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 1586  void MainWindow::on_sample_treeview_drag Line 3340  void MainWindow::on_sample_treeview_drag
3340      // get selected sample      // get selected sample
3341      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3342      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3343      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3344      if (it) {      if (!rows.empty()) {
3345          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3346          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3347                Gtk::TreeModel::Row row = *it;
3348                sample = row[m_SamplesModel.m_col_sample];
3349            }
3350      }      }
3351      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3352      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 1626  void MainWindow::on_sample_label_drop_dr Line 3383  void MainWindow::on_sample_label_drop_dr
3383          bool channels_changed = false;          bool channels_changed = false;
3384          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
3385              // remove the samplechannel dimension              // remove the samplechannel dimension
3386    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3387              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
3388              channels_changed = true;              channels_changed = true;
3389              region_changed();              region_changed();
3390    */
3391          }          }
3392          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
3393                sample,
3394                is_copy_samples_unity_note_enabled(),
3395                is_copy_samples_fine_tune_enabled(),
3396                is_copy_samples_loop_enabled()
3397            );
3398    
3399          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
3400              // add samplechannel dimension              // add samplechannel dimension
# Line 1673  void MainWindow::sample_name_changed(con Line 3437  void MainWindow::sample_name_changed(con
3437      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
3438      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
3439      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3440        gig::String gigname(gig_from_utf8(name));
3441      if (group) {      if (group) {
3442          if (group->Name != name) {          if (group->Name != gigname) {
3443              group->Name = name;              group->Name = gigname;
3444              printf("group name changed\n");              printf("group name changed\n");
3445              file_changed();              file_changed();
3446          }          }
3447      } else if (sample) {      } else if (sample) {
3448          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
3449              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
3450              printf("sample name changed\n");              printf("sample name changed\n");
3451              file_changed();              file_changed();
3452          }          }
3453      }      }
3454  }  }
3455    
3456    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3457                                         const Gtk::TreeModel::iterator& iter) {
3458        if (!iter) return;
3459        Gtk::TreeModel::Row row = *iter;
3460        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3461        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3462        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3463        gig::String gigname(gig_from_utf8(name));
3464        if (group) {
3465            if (group->Name != gigname) {
3466                group->Name = gigname;
3467                printf("script group name changed\n");
3468                file_changed();
3469            }
3470        } else if (script) {
3471            if (script->Name != gigname) {
3472                script->Name = gigname;
3473                printf("script name changed\n");
3474                file_changed();
3475            }
3476        }
3477    }
3478    
3479    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3480                                           Gtk::TreeViewColumn* column)
3481    {
3482        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3483        if (!iter) return;
3484        Gtk::TreeModel::Row row = *iter;
3485        gig::Script* script = row[m_ScriptsModel.m_col_script];
3486        if (!script) return;
3487    
3488        ScriptEditor* editor = new ScriptEditor;
3489        editor->signal_script_to_be_changed.connect(
3490            signal_script_to_be_changed.make_slot()
3491        );
3492        editor->signal_script_changed.connect(
3493            signal_script_changed.make_slot()
3494        );
3495        editor->setScript(script);
3496        //editor->reparent(*this);
3497        editor->show();
3498    }
3499    
3500  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3501                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3502      if (!iter) return;      if (!iter) return;
3503      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
3504      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
3505    
3506        // change name in instrument menu
3507        int index = path[0];
3508        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3509        if (index < children.size()) {
3510    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
3511            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
3512    #else
3513            remove_instrument_from_menu(index);
3514            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
3515            item->set_active();
3516    #endif
3517        }
3518    
3519        // change name in gig
3520      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
3521      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
3522          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
3523            instrument->pInfo->Name = gigname;
3524    
3525            // change name in the instrument properties window
3526            if (instrumentProps.get_instrument() == instrument) {
3527                instrumentProps.update_name();
3528            }
3529    
3530          file_changed();          file_changed();
3531      }      }
3532  }  }
3533    
3534    void MainWindow::on_action_combine_instruments() {
3535        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3536        d->show_all();
3537        d->resize(500, 400);
3538        d->run();
3539        if (d->fileWasChanged()) {
3540            // update GUI with new instrument just created
3541            add_instrument(d->newCombinedInstrument());
3542        }
3543        delete d;
3544    }
3545    
3546    void MainWindow::on_action_view_references() {
3547        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3548        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3549        if (rows.empty()) return;
3550        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3551        if (!it) return;
3552        Gtk::TreeModel::Row row = *it;
3553        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3554        if (!sample) return;
3555    
3556        ReferencesView* d = new ReferencesView(*this);
3557        d->setSample(sample);
3558        d->dimension_region_selected.connect(
3559            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3560        );
3561        d->show_all();
3562        d->resize(500, 400);
3563        d->run();
3564        delete d;
3565    }
3566    
3567    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3568        struct _Source {
3569            std::vector<RIFF::File*> riffs;
3570            std::vector<gig::File*> gigs;
3571            
3572            ~_Source() {
3573                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3574                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3575                riffs.clear();
3576                gigs.clear();
3577            }
3578        } sources;
3579    
3580        if (filenames.empty())
3581            throw RIFF::Exception(_("No files selected, so nothing done."));
3582    
3583        // first open all input files (to avoid output file corruption)
3584        int i;
3585        try {
3586            for (i = 0; i < filenames.size(); ++i) {
3587                const std::string& filename = filenames[i];
3588                printf("opening file=%s\n", filename.c_str());
3589    
3590                RIFF::File* riff = new RIFF::File(filename);
3591                sources.riffs.push_back(riff);
3592    
3593                gig::File* gig = new gig::File(riff);
3594                sources.gigs.push_back(gig);
3595            }
3596        } catch (RIFF::Exception e) {
3597            throw RIFF::Exception(
3598                _("Error occurred while opening '") +
3599                filenames[i] +
3600                "': " +
3601                e.Message
3602            );
3603        } catch (...) {
3604            throw RIFF::Exception(
3605                _("Unknown exception occurred while opening '") +
3606                filenames[i] + "'"
3607            );
3608        }
3609    
3610        // now merge the opened .gig files to the main .gig file currently being
3611        // open in gigedit
3612        try {
3613            for (i = 0; i < filenames.size(); ++i) {
3614                const std::string& filename = filenames[i];
3615                printf("merging file=%s\n", filename.c_str());
3616                assert(i < sources.gigs.size());
3617    
3618                this->file->AddContentOf(sources.gigs[i]);
3619            }
3620        } catch (RIFF::Exception e) {
3621            throw RIFF::Exception(
3622                _("Error occurred while merging '") +
3623                filenames[i] +
3624                "': " +
3625                e.Message
3626            );
3627        } catch (...) {
3628            throw RIFF::Exception(
3629                _("Unknown exception occurred while merging '") +
3630                filenames[i] + "'"
3631            );
3632        }
3633    
3634        // Finally save gig file persistently to disk ...
3635        //NOTE: requires that this gig file already has a filename !
3636        {
3637            std::cout << "Saving file\n" << std::flush;
3638            file_structure_to_be_changed_signal.emit(this->file);
3639    
3640            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3641                _("Saving") +  Glib::ustring(" '") +
3642                Glib::filename_display_basename(this->filename) + "' ...",
3643                *this
3644            );
3645            progress_dialog->show_all();
3646            saver = new Saver(this->file); //FIXME: memory leak!
3647            saver->signal_progress().connect(
3648                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3649            saver->signal_finished().connect(
3650                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3651            saver->signal_error().connect(
3652                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3653            saver->launch();
3654        }
3655    }
3656    
3657    void MainWindow::on_action_merge_files() {
3658        if (this->file->GetFileName().empty()) {
3659            Glib::ustring txt = _(
3660                "You seem to have a new .gig file open that has not been saved "
3661                "yet. You must save it somewhere before starting to merge it with "
3662                "other .gig files though, because during the merge operation the "
3663                "other files' sample data must be written on file level to the "
3664                "target .gig file."
3665            );
3666            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3667            msg.run();
3668            return;
3669        }
3670    
3671        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3672        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3673        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3674        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3675    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3676        Gtk::FileFilter filter;
3677        filter.add_pattern("*.gig");
3678    #else
3679        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3680        filter->add_pattern("*.gig");
3681    #endif
3682        dialog.set_filter(filter);
3683        if (current_gig_dir != "") {
3684            dialog.set_current_folder(current_gig_dir);
3685        }
3686        dialog.set_select_multiple(true);
3687    
3688        // show warning in the file picker dialog
3689        Gtk::HBox descriptionArea;
3690        descriptionArea.set_spacing(15);
3691        Gtk::Image warningIcon;
3692        warningIcon.set_from_icon_name("dialog-warning",
3693                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3694        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3695    #if GTKMM_MAJOR_VERSION < 3
3696        view::WrapLabel description;
3697    #else
3698        Gtk::Label description;
3699        description.set_line_wrap();
3700    #endif
3701        description.set_markup(_(
3702            "\nSelect at least one .gig file that shall be merged to the .gig file "
3703            "currently being open in gigedit.\n\n"
3704            "<b>Please Note:</b> Merging with other files will modify your "
3705            "currently open .gig file on file level! And be aware that the current "
3706            "merge algorithm does not detect duplicate samples yet. So if you are "
3707            "merging files which are using equivalent sample data, those "
3708            "equivalent samples will currently be treated as separate samples and "
3709            "will accordingly be stored separately in the target .gig file!"
3710        ));
3711        descriptionArea.pack_start(description);
3712        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3713        descriptionArea.show_all();
3714    
3715        if (dialog.run() == Gtk::RESPONSE_OK) {
3716            printf("on_action_merge_files self=%p\n",
3717                   static_cast<void*>(Glib::Threads::Thread::self()));
3718            std::vector<std::string> filenames = dialog.get_filenames();
3719    
3720            // merge the selected files to the currently open .gig file
3721            try {
3722                mergeFiles(filenames);
3723            } catch (RIFF::Exception e) {
3724                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3725                msg.run();
3726            }
3727    
3728            // update GUI
3729            __refreshEntireGUI();
3730        }
3731    }
3732    
3733  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
3734      this->file_is_shared = b;      this->file_is_shared = b;
3735    
# Line 1714  void MainWindow::set_file_is_shared(bool Line 3744  void MainWindow::set_file_is_shared(bool
3744              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3745          );          );
3746      }      }
3747    
3748        {
3749            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3750                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3751            if (item) item->set_sensitive(b);
3752        }
3753    }
3754    
3755    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3756        if (!sample) return;
3757        sample_ref_count[sample] += offset;
3758        const int refcount = sample_ref_count[sample];
3759    
3760        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3761        for (int g = 0; g < model->children().size(); ++g) {
3762            Gtk::TreeModel::Row rowGroup = model->children()[g];
3763            for (int s = 0; s < rowGroup.children().size(); ++s) {
3764                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3765                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3766                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3767                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3768            }
3769        }
3770    }
3771    
3772    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3773        on_sample_ref_count_incremented(oldSample, -1);
3774        on_sample_ref_count_incremented(newSample, +1);
3775    }
3776    
3777    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3778        // just in case a new sample is added later with exactly the same memory
3779        // address, which would lead to incorrect refcount if not deleted here
3780        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3781             it != samples.end(); ++it)
3782        {
3783            sample_ref_count.erase(*it);
3784        }
3785    }
3786    
3787    void MainWindow::show_samples_tab() {
3788        m_TreeViewNotebook.set_current_page(0);
3789    }
3790    
3791    void MainWindow::show_intruments_tab() {
3792        m_TreeViewNotebook.set_current_page(1);
3793    }
3794    
3795    void MainWindow::show_scripts_tab() {
3796        m_TreeViewNotebook.set_current_page(2);
3797    }
3798    
3799    void MainWindow::select_prev_region() {
3800        m_RegionChooser.select_prev_region();
3801    }
3802    
3803    void MainWindow::select_next_region() {
3804        m_RegionChooser.select_next_region();
3805    }
3806    
3807    void MainWindow::select_next_dim_rgn_zone() {
3808        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3809        m_DimRegionChooser.select_next_dimzone();
3810    }
3811    
3812    void MainWindow::select_prev_dim_rgn_zone() {
3813        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3814        m_DimRegionChooser.select_prev_dimzone();
3815    }
3816    
3817    void MainWindow::select_add_next_dim_rgn_zone() {
3818        m_DimRegionChooser.select_next_dimzone(true);
3819    }
3820    
3821    void MainWindow::select_add_prev_dim_rgn_zone() {
3822        m_DimRegionChooser.select_prev_dimzone(true);
3823    }
3824    
3825    void MainWindow::select_prev_dimension() {
3826        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3827        m_DimRegionChooser.select_prev_dimension();
3828    }
3829    
3830    void MainWindow::select_next_dimension() {
3831        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3832        m_DimRegionChooser.select_next_dimension();
3833    }
3834    
3835    #define CLIPBOARD_DIMENSIONREGION_TARGET \
3836        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
3837    
3838    void MainWindow::copy_selected_dimrgn() {
3839        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3840        if (!pDimRgn) {
3841            updateClipboardPasteAvailable();
3842            updateClipboardCopyAvailable();
3843            return;
3844        }
3845    
3846        std::vector<Gtk::TargetEntry> targets;
3847        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
3848    
3849        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3850        clipboard->set(
3851            targets,
3852            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
3853            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
3854        );
3855    
3856        m_serializationArchive.serialize(pDimRgn);
3857    
3858        updateClipboardPasteAvailable();
3859    }
3860    
3861    void MainWindow::paste_copied_dimrgn() {
3862        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3863        clipboard->request_contents(
3864            CLIPBOARD_DIMENSIONREGION_TARGET,
3865            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
3866        );
3867        updateClipboardPasteAvailable();
3868    }
3869    
3870    void MainWindow::adjust_clipboard_content() {
3871        MacroEditor* editor = new MacroEditor();
3872        editor->setMacro(&m_serializationArchive);
3873        editor->show();
3874    }
3875    
3876    void MainWindow::updateClipboardPasteAvailable() {
3877        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3878        clipboard->request_targets(
3879            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
3880        );
3881    }
3882    
3883    void MainWindow::updateClipboardCopyAvailable() {
3884        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
3885        static_cast<Gtk::MenuItem*>(
3886            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
3887        )->set_sensitive(bDimensionRegionCopyIsPossible);
3888    }
3889    
3890    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
3891        updateClipboardPasteAvailable();
3892    }
3893    
3894    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
3895        const std::string target = selection_data.get_target();
3896        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3897            selection_data.set(
3898                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
3899                &m_serializationArchive.rawData()[0],
3900                m_serializationArchive.rawData().size()
3901            );
3902        } else {
3903            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
3904        }
3905    }
3906    
3907    void MainWindow::on_clipboard_clear() {
3908        m_serializationArchive.clear();
3909        updateClipboardPasteAvailable();
3910        updateClipboardCopyAvailable();
3911    }
3912    
3913    //NOTE: Might throw exception !!!
3914    void MainWindow::applyMacro(Serialization::Archive& macro) {
3915        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3916        if (!pDimRgn) return;
3917    
3918        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
3919             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
3920        {
3921            gig::DimensionRegion* pDimRgn = *itDimReg;
3922            dimreg_to_be_changed_signal.emit(pDimRgn);
3923            m_serializationArchive.deserialize(pDimRgn);
3924            dimreg_changed_signal.emit(pDimRgn);
3925        }
3926        //region_changed()
3927        file_changed();
3928        dimreg_changed();
3929    }
3930    
3931    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
3932        const std::string target = selection_data.get_target();
3933        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3934            Glib::ustring errorText;
3935            try {
3936                m_serializationArchive.decode(
3937                    selection_data.get_data(), selection_data.get_length()
3938                );
3939                applyMacro(m_serializationArchive);
3940            } catch (Serialization::Exception e) {
3941                errorText = e.Message;
3942            } catch (...) {
3943                errorText = _("Unknown exception while pasting DimensionRegion");
3944            }
3945            if (!errorText.empty()) {
3946                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
3947                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3948                msg.run();
3949            }
3950        }
3951    }
3952    
3953    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
3954        const bool bDimensionRegionPasteIsPossible =
3955            std::find(targets.begin(), targets.end(),
3956                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
3957    
3958        static_cast<Gtk::MenuItem*>(
3959            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
3960        )->set_sensitive(bDimensionRegionPasteIsPossible);
3961    
3962        static_cast<Gtk::MenuItem*>(
3963            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
3964        )->set_sensitive(bDimensionRegionPasteIsPossible);
3965  }  }
3966    
3967  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 1740  sigc::signal<void, gig::Region*>& MainWi Line 3988  sigc::signal<void, gig::Region*>& MainWi
3988      return region_changed_signal;      return region_changed_signal;
3989  }  }
3990    
3991    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3992        return sample_changed_signal;
3993    }
3994    
3995  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() {
3996      return sample_ref_changed_signal;      return sample_ref_changed_signal;
3997  }  }
# Line 1759  sigc::signal<void, int/*key*/, int/*velo Line 4011  sigc::signal<void, int/*key*/, int/*velo
4011  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
4012      return note_off_signal;      return note_off_signal;
4013  }  }
4014    
4015    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
4016        return m_RegionChooser.signal_keyboard_key_hit();
4017    }
4018    
4019    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
4020        return m_RegionChooser.signal_keyboard_key_released();
4021    }
4022    
4023    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
4024        return switch_sampler_instrument_signal;
4025    }

Legend:
Removed from v.1656  
changed lines
  Added in v.3158

  ViewVC Help
Powered by ViewVC