/[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 2332 by persson, Wed Mar 14 05:22:26 2012 UTC revision 3811 by schoenebeck, Fri Aug 14 11:54:49 2020 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006-2012 Andreas Persson   * Copyright (C) 2006-2020 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 20  Line 20 
20  #include <iostream>  #include <iostream>
21  #include <cstring>  #include <cstring>
22    
23    #include "compat.h"
24    
25  #include <glibmm/convert.h>  #include <glibmm/convert.h>
26  #include <glibmm/dispatcher.h>  #include <glibmm/dispatcher.h>
27  #include <glibmm/miscutils.h>  #include <glibmm/miscutils.h>
28  #include <glibmm/stringutils.h>  #include <glibmm/stringutils.h>
29    #include <glibmm/regex.h>
30  #include <gtkmm/aboutdialog.h>  #include <gtkmm/aboutdialog.h>
31  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
32  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
33  #include <gtkmm/stock.h>  #if HAS_GTKMM_STOCK
34    # include <gtkmm/stock.h>
35    #endif
36  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
37  #include <gtkmm/main.h>  #include <gtkmm/main.h>
38  #include <gtkmm/radiomenuitem.h>  #if GTKMM_MAJOR_VERSION < 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION < 89)
39  #include <gtkmm/toggleaction.h>  # include <gtkmm/toggleaction.h>
40    #endif
41    #include <gtkmm/accelmap.h>
42    #if GTKMM_MAJOR_VERSION < 3
43  #include "wrapLabel.hh"  #include "wrapLabel.hh"
44    #endif
45    
46  #include "global.h"  #include "global.h"
47  #include "compat.h"  #include "compat.h"
48    
49  #include <stdio.h>  #include <stdio.h>
50  #include <sndfile.h>  #ifdef LIBSNDFILE_HEADER_FILE
51    # include LIBSNDFILE_HEADER_FILE(sndfile.h)
52    #else
53    # include <sndfile.h>
54    #endif
55    #include <assert.h>
56    
57  #include "mainwindow.h"  #include "mainwindow.h"
58    #include "Settings.h"
59    #include "CombineInstrumentsDialog.h"
60    #include "scripteditor.h"
61    #include "scriptslots.h"
62    #include "ReferencesView.h"
63  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
64  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
65    #include "gfx/builtinpix.h"
66    #include "MacroEditor.h"
67    #include "MacrosSetup.h"
68    #if defined(__APPLE__)
69    # include "MacHelper.h"
70    #endif
71    
72  template<class T> inline std::string ToString(T o) {  static const Gdk::ModifierType primaryModifierKey =
73      std::stringstream ss;      #if defined(__APPLE__)
74      ss << o;      Gdk::META_MASK; // Cmd key on Mac
75      return ss.str();      #else
76  }      Gdk::CONTROL_MASK; // Ctrl key on all other OSs
77        #endif
 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++;  
 }  
78    
79  MainWindow::MainWindow() :  MainWindow::MainWindow() :
80        m_DimRegionChooser(*this),
81      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
82      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
83      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
84      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
85        labelLegend(_("Legend:")),
86        labelNoSample(_(" No Sample")),
87        labelMissingSample(_(" Missing some Sample(s)")),
88        labelLooped(_(" Looped")),
89        labelSomeLoops(_(" Some Loop(s)"))
90  {  {
91        loadBuiltInPix();
92    
93        this->file = NULL;
94    
95  //    set_border_width(5);  //    set_border_width(5);
 //    set_default_size(400, 200);  
96    
97        if (!Settings::singleton()->autoRestoreWindowDimension) {
98    #if GTKMM_MAJOR_VERSION >= 3
99            set_default_size(1010, -1);
100    #else
101            set_default_size(915, -1);
102    #endif
103            set_position(Gtk::WIN_POS_CENTER);
104        }
105    
106      add(m_VBox);      add(m_VBox);
107    
108      // Handle selection      // Handle selection
109      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeViewInstruments.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
110          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
111    
112      // m_TreeView.set_reorderable();      // m_TreeViewInstruments.set_reorderable();
113    
114      m_TreeView.signal_button_press_event().connect_notify(  #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
115        m_TreeViewInstruments.signal_button_press_event().connect(
116            sigc::mem_fun(*this, &MainWindow::on_button_release));
117    #else
118        m_TreeViewInstruments.signal_button_press_event().connect_notify(
119          sigc::mem_fun(*this, &MainWindow::on_button_release));          sigc::mem_fun(*this, &MainWindow::on_button_release));
120    #endif
121    
122      // Add the TreeView tab, inside a ScrolledWindow, with the button underneath:      // Add the TreeView tab, inside a ScrolledWindow, with the button underneath:
123      m_ScrolledWindow.add(m_TreeView);      m_ScrolledWindow.add(m_TreeViewInstruments);
124  //    m_ScrolledWindow.set_size_request(200, 600);  //    m_ScrolledWindow.set_size_request(200, 600);
125      m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
126    
127      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
128      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
129    
130        m_ScrolledWindowScripts.add(m_TreeViewScripts);
131        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
132    
133    #if GTKMM_MAJOR_VERSION < 3
134      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
135    #endif
136    
137        m_searchLabel.set_text(Glib::ustring(" ") + _("Filter:"));
138        m_searchField.pack_start(m_searchLabel, Gtk::PACK_SHRINK);
139        m_searchField.pack_start(m_searchText);
140        m_searchField.set_spacing(5);
141    
142        m_left_vbox.pack_start(m_TreeViewNotebook);
143        m_left_vbox.pack_start(m_searchField, Gtk::PACK_SHRINK);
144    
145        m_HPaned.add1(m_left_vbox);
146    
     m_HPaned.add1(m_TreeViewNotebook);  
147      dimreg_hbox.add(dimreg_label);      dimreg_hbox.add(dimreg_label);
148      dimreg_hbox.add(dimreg_all_regions);      dimreg_hbox.add(dimreg_all_regions);
149      dimreg_hbox.add(dimreg_all_dimregs);      dimreg_hbox.add(dimreg_all_dimregs);
# Line 117  MainWindow::MainWindow() : Line 151  MainWindow::MainWindow() :
151      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
152      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
153      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
154        {
155            legend_hbox.add(labelLegend);
156    
157            imageNoSample.set(redDot);
158    #if HAS_GTKMM_ALIGNMENT
159            imageNoSample.set_alignment(Gtk::ALIGN_END);
160            labelNoSample.set_alignment(Gtk::ALIGN_START);
161    #else
162            imageNoSample.set_halign(Gtk::ALIGN_END);
163            labelNoSample.set_halign(Gtk::ALIGN_START);
164    #endif
165            legend_hbox.add(imageNoSample);
166            legend_hbox.add(labelNoSample);
167    
168            imageMissingSample.set(yellowDot);
169    #if HAS_GTKMM_ALIGNMENT
170            imageMissingSample.set_alignment(Gtk::ALIGN_END);
171            labelMissingSample.set_alignment(Gtk::ALIGN_START);
172    #else
173            imageMissingSample.set_halign(Gtk::ALIGN_END);
174            labelMissingSample.set_halign(Gtk::ALIGN_START);
175    #endif
176            legend_hbox.add(imageMissingSample);
177            legend_hbox.add(labelMissingSample);
178    
179            imageLooped.set(blackLoop);
180    #if HAS_GTKMM_ALIGNMENT
181            imageLooped.set_alignment(Gtk::ALIGN_END);
182            labelLooped.set_alignment(Gtk::ALIGN_START);
183    #else
184            imageLooped.set_halign(Gtk::ALIGN_END);
185            labelLooped.set_halign(Gtk::ALIGN_START);
186    #endif
187            legend_hbox.add(imageLooped);
188            legend_hbox.add(labelLooped);
189    
190            imageSomeLoops.set(grayLoop);
191    #if HAS_GTKMM_ALIGNMENT
192            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
193            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
194    #else
195            imageSomeLoops.set_halign(Gtk::ALIGN_END);
196            labelSomeLoops.set_halign(Gtk::ALIGN_START);
197    #endif
198            legend_hbox.add(imageSomeLoops);
199            legend_hbox.add(labelSomeLoops);
200    
201    #if HAS_GTKMM_SHOW_ALL_CHILDREN
202            legend_hbox.show_all_children();
203    #endif
204        }
205        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
206      m_HPaned.add2(dimreg_vbox);      m_HPaned.add2(dimreg_vbox);
207    
208        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
209        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."));
210        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."));
211        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)."));
212    
213      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
214      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
215        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
216    
217    #if USE_GLIB_ACTION
218        m_actionGroup = Gio::SimpleActionGroup::create();
219        m_actionGroup->add_action(
220            "New", sigc::mem_fun(*this, &MainWindow::on_action_file_new)
221        );
222        m_actionGroup->add_action(
223            "Open", sigc::mem_fun(*this, &MainWindow::on_action_file_open)
224        );
225        m_actionGroup->add_action(
226            "Save", sigc::mem_fun(*this, &MainWindow::on_action_file_save)
227        );
228        m_actionGroup->add_action(
229            "SaveAs", sigc::mem_fun(*this, &MainWindow::on_action_file_save_as)
230        );
231        m_actionGroup->add_action(
232            "Properties", sigc::mem_fun(*this, &MainWindow::on_action_file_properties)
233        );
234        m_actionGroup->add_action(
235            "InstrProperties", sigc::mem_fun(*this, &MainWindow::show_instr_props)
236        );
237        m_actionMIDIRules = m_actionGroup->add_action(
238            "MidiRules", sigc::mem_fun(*this, &MainWindow::show_midi_rules)
239        );
240        m_actionGroup->add_action(
241            "ScriptSlots", sigc::mem_fun(*this, &MainWindow::show_script_slots)
242        );
243        m_actionGroup->add_action(
244            "Quit", sigc::mem_fun(*this, &MainWindow::on_action_quit)
245        );
246        m_actionGroup->add_action(
247            "MenuSample", sigc::mem_fun(*this, &MainWindow::show_samples_tab)
248        );
249        m_actionGroup->add_action(
250            "MenuInstrument", sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
251        );
252        m_actionGroup->add_action(
253            "MenuScript", sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
254        );
255    #else
256      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
257    
258      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
# Line 153  MainWindow::MainWindow() : Line 282  MainWindow::MainWindow() :
282                                           Gtk::Stock::PROPERTIES),                                           Gtk::Stock::PROPERTIES),
283                       sigc::mem_fun(                       sigc::mem_fun(
284                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
285        actionGroup->add(Gtk::Action::create("MidiRules",
286                                             _("_Midi Rules...")),
287                         sigc::mem_fun(
288                             *this, &MainWindow::show_midi_rules));
289        actionGroup->add(Gtk::Action::create("ScriptSlots",
290                                             _("_Script Slots...")),
291                         sigc::mem_fun(
292                             *this, &MainWindow::show_script_slots));
293      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
294                       sigc::mem_fun(                       sigc::mem_fun(
295                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
296      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
297            Gtk::Action::create("MenuSample", _("_Sample")),
298            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
299        );
300        actionGroup->add(
301            Gtk::Action::create("MenuInstrument", _("_Instrument")),
302            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
303        );
304        actionGroup->add(
305            Gtk::Action::create("MenuScript", _("Scr_ipt")),
306            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
307        );
308        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
309        actionGroup->add(Gtk::Action::create("AssignScripts", _("Assign Script")));
310    
311      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
312    #endif
313    
314        const Gdk::ModifierType primaryModifierKey =
315    #if defined(__APPLE__)
316        Gdk::META_MASK; // Cmd key on Mac
317    #else
318        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
319    #endif
320    
321    #if USE_GLIB_ACTION
322        m_actionCopyDimRgn = m_actionGroup->add_action(
323            "CopyDimRgn", sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn)
324        );
325        m_actionPasteDimRgn = m_actionGroup->add_action(
326            "PasteDimRgn", sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn)
327        );
328        m_actionAdjustClipboard = m_actionGroup->add_action(
329            "AdjustClipboard", sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content)
330        );
331        m_actionGroup->add_action(
332            "SelectPrevInstr", sigc::mem_fun(*this, &MainWindow::select_prev_instrument)
333        );
334        m_actionGroup->add_action(
335            "SelectNextInstr", sigc::mem_fun(*this, &MainWindow::select_next_instrument)
336        );
337        m_actionGroup->add_action(
338            "SelectPrevRegion", sigc::mem_fun(*this, &MainWindow::select_prev_region)
339        );
340        m_actionGroup->add_action(
341            "SelectNextRegion", sigc::mem_fun(*this, &MainWindow::select_next_region)
342        );
343        m_actionGroup->add_action(
344            "SelectPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone)
345        );
346        m_actionGroup->add_action(
347            "SelectNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone)
348        );
349        m_actionGroup->add_action(
350            "SelectPrevDimension", sigc::mem_fun(*this, &MainWindow::select_prev_dimension)
351        );
352        m_actionGroup->add_action(
353            "SelectNextDimension", sigc::mem_fun(*this, &MainWindow::select_next_dimension)
354        );
355        m_actionGroup->add_action(
356            "SelectAddPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone)
357        );
358        m_actionGroup->add_action(
359            "SelectAddNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone)
360        );
361    #else
362        actionGroup->add(Gtk::Action::create("CopyDimRgn",
363                                             _("Copy selected dimension region")),
364                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
365                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
366    
367        actionGroup->add(Gtk::Action::create("PasteDimRgn",
368                                             _("Paste dimension region")),
369                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
370                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
371    
372        actionGroup->add(Gtk::Action::create("AdjustClipboard",
373                                             _("Adjust Clipboard Content")),
374                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
375                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
376    
377        actionGroup->add(Gtk::Action::create("SelectPrevInstr",
378                                             _("Select Previous Instrument")),
379                         Gtk::AccelKey(GDK_KEY_Up, primaryModifierKey),
380                         sigc::mem_fun(*this, &MainWindow::select_prev_instrument));
381    
382        actionGroup->add(Gtk::Action::create("SelectNextInstr",
383                                             _("Select Next Instrument")),
384                         Gtk::AccelKey(GDK_KEY_Down, primaryModifierKey),
385                         sigc::mem_fun(*this, &MainWindow::select_next_instrument));
386    
387        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
388                                             _("Select Previous Region")),
389                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
390                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
391    
392        actionGroup->add(Gtk::Action::create("SelectNextRegion",
393                                             _("Select Next Region")),
394                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
395                         sigc::mem_fun(*this, &MainWindow::select_next_region));
396    
397        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
398                                             _("Select Previous Dimension Region Zone")),
399                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
400                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
401    
402        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
403                                             _("Select Next Dimension Region Zone")),
404                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
405                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
406    
407        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
408                                             _("Select Previous Dimension")),
409                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
410                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
411    
412        actionGroup->add(Gtk::Action::create("SelectNextDimension",
413                                             _("Select Next Dimension")),
414                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
415                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
416    
417        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
418                                             _("Add Previous Dimension Region Zone to Selection")),
419                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
420                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
421    
422        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
423                                             _("Add Next Dimension Region Zone to Selection")),
424                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
425                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
426    #endif
427    
428    #if USE_GLIB_ACTION
429        m_actionToggleCopySampleUnity = m_actionGroup->add_action_bool("CopySampleUnity", true);
430        m_actionToggleCopySampleTune  = m_actionGroup->add_action_bool("CopySampleTune", true);
431        m_actionToggleCopySampleLoop  = m_actionGroup->add_action_bool("CopySampleLoop", true);
432    #else
433      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
434            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
435        toggle_action->set_active(true);
436        actionGroup->add(toggle_action);
437    
438        toggle_action =
439            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
440        toggle_action->set_active(true);
441        actionGroup->add(toggle_action);
442    
443        toggle_action =
444            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
445        toggle_action->set_active(true);
446        actionGroup->add(toggle_action);
447    #endif
448    
449    #if USE_GLIB_ACTION
450        m_actionToggleStatusBar =
451            m_actionGroup->add_action_bool("Statusbar", sigc::mem_fun(*this, &MainWindow::on_action_view_status_bar), true);
452        m_actionToggleRestoreWinDim =
453            m_actionGroup->add_action_bool("AutoRestoreWinDim", sigc::mem_fun(*this, &MainWindow::on_auto_restore_win_dim), Settings::singleton()->autoRestoreWindowDimension);
454        m_actionInstrDoubleClickOpensProps =
455            m_actionGroup->add_action_bool(
456                "OpenInstrPropsByDoubleClick",
457                sigc::mem_fun(*this, &MainWindow::on_instr_double_click_opens_props),
458                Settings::singleton()->instrumentDoubleClickOpensProps
459            );
460        m_actionToggleShowTooltips = m_actionGroup->add_action_bool(
461            "ShowTooltips", sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips),
462            Settings::singleton()->showTooltips
463        );
464        m_actionToggleSaveWithTempFile =
465            m_actionGroup->add_action_bool("SaveWithTemporaryFile", sigc::mem_fun(*this, &MainWindow::on_save_with_temporary_file), Settings::singleton()->saveWithTemporaryFile);
466        m_actionGroup->add_action("RefreshAll", sigc::mem_fun(*this, &MainWindow::on_action_refresh_all));
467    #else
468        actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
469    
470    
471        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
472        toggle_action =
473          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
474      toggle_action->set_active(true);      toggle_action->set_active(true);
475      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
476                       sigc::mem_fun(                       sigc::mem_fun(
477                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
478    
479        toggle_action =
480            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
481        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
482        actionGroup->add(toggle_action,
483                         sigc::mem_fun(
484                             *this, &MainWindow::on_auto_restore_win_dim));
485    
486        toggle_action =
487            Gtk::ToggleAction::create("OpenInstrPropsByDoubleClick", _("Instrument Properties by Double Click"));
488        toggle_action->set_active(Settings::singleton()->instrumentDoubleClickOpensProps);
489        actionGroup->add(toggle_action,
490                         sigc::mem_fun(
491                             *this, &MainWindow::on_instr_double_click_opens_props));
492    
493        toggle_action =
494            Gtk::ToggleAction::create("ShowTooltips", _("Tooltips for Beginners"));
495        toggle_action->set_active(Settings::singleton()->showTooltips);
496        actionGroup->add(
497            toggle_action,
498            sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips)
499        );
500    
501        toggle_action =
502            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
503        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
504        actionGroup->add(toggle_action,
505                         sigc::mem_fun(
506                             *this, &MainWindow::on_save_with_temporary_file));
507    
508        actionGroup->add(
509            Gtk::Action::create("RefreshAll", _("_Refresh All")),
510            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
511        );                
512    #endif
513    
514    #if USE_GLIB_ACTION
515        m_actionGroup->add_action(
516            "About", sigc::mem_fun(*this, &MainWindow::on_action_help_about)
517        );
518        m_actionGroup->add_action(
519            "AddInstrument", sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
520        );
521        m_actionGroup->add_action(
522            "DupInstrument", sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
523        );
524        m_actionGroup->add_action(
525            "MoveInstrument", sigc::mem_fun(*this, &MainWindow::on_action_move_instr)
526        );
527        m_actionGroup->add_action(
528            "CombInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
529        );
530        m_actionGroup->add_action(
531            "RemoveInstrument", sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
532        );
533    #else
534      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
535      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
536                                           action->property_label()));                                           action->property_label()));
# Line 177  MainWindow::MainWindow() : Line 542  MainWindow::MainWindow() :
542          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
543      );      );
544      actionGroup->add(      actionGroup->add(
545            Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
546            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
547        );
548        actionGroup->add(
549            Gtk::Action::create("MoveInstrument", _("Move _Instrument To ...")),
550            Gtk::AccelKey(GDK_KEY_i, primaryModifierKey),
551            sigc::mem_fun(*this, &MainWindow::on_action_move_instr)
552        );
553        actionGroup->add(
554            Gtk::Action::create("CombInstruments", _("_Combine Instruments ...")),
555            Gtk::AccelKey(GDK_KEY_j, primaryModifierKey),
556            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
557        );
558        actionGroup->add(
559          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
560          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
561      );      );
562    #endif
563    
564    #if USE_GLIB_ACTION
565        m_actionToggleWarnOnExtensions = m_actionGroup->add_action_bool(
566            "WarnUserOnExtensions", sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions),
567            Settings::singleton()->warnUserOnExtensions
568        );
569        m_actionToggleSyncSamplerSelection = m_actionGroup->add_action_bool(
570            "SyncSamplerInstrumentSelection", sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection),
571            Settings::singleton()->syncSamplerInstrumentSelection
572        );
573        m_actionToggleMoveRootNoteWithRegion = m_actionGroup->add_action_bool(
574            "MoveRootNoteWithRegionMoved", sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved),
575            Settings::singleton()->moveRootNoteWithRegionMoved
576        );
577    #else
578        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
579        
580        toggle_action =
581            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
582        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
583        actionGroup->add(
584            toggle_action,
585            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
586        );
587    
588        toggle_action =
589            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
590        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
591        actionGroup->add(
592            toggle_action,
593            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
594        );
595    
596        toggle_action =
597            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
598        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
599        actionGroup->add(
600            toggle_action,
601            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
602        );
603    #endif
604    
605    #if USE_GLIB_ACTION
606        m_actionGroup->add_action(
607            "CombineInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
608        );
609        m_actionGroup->add_action(
610            "MergeFiles", sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
611        );
612    #else
613        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
614    
615        actionGroup->add(
616            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
617            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
618        );
619    
620        actionGroup->add(
621            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
622            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
623        );
624    #endif
625    
626      // sample right-click popup actions      // sample right-click popup actions
627    #if USE_GLIB_ACTION
628        m_actionSampleProperties = m_actionGroup->add_action(
629            "SampleProperties", sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
630        );
631        m_actionAddSampleGroup = m_actionGroup->add_action(
632            "AddGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_group)
633        );
634        m_actionAddSample = m_actionGroup->add_action(
635            "AddSample", sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
636        );
637        m_actionRemoveSample = m_actionGroup->add_action(
638            "RemoveSample", sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
639        );
640        m_actionGroup->add_action(
641            "RemoveUnusedSamples", sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
642        );
643        m_actionViewSampleRefs = m_actionGroup->add_action(
644            "ShowSampleRefs", sigc::mem_fun(*this, &MainWindow::on_action_view_references)
645        );
646        m_actionReplaceSample = m_actionGroup->add_action(
647            "ReplaceSample", sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
648        );
649        m_actionGroup->add_action(
650            "ReplaceAllSamplesInAllGroups", sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
651        );
652    #else
653      actionGroup->add(      actionGroup->add(
654          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
655          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
# Line 199  MainWindow::MainWindow() : Line 667  MainWindow::MainWindow() :
667          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
668      );      );
669      actionGroup->add(      actionGroup->add(
670            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
671            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
672        );
673        actionGroup->add(
674            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
675            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
676        );
677        actionGroup->add(
678            Gtk::Action::create("ReplaceSample",
679                                _("Replace Sample...")),
680            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
681        );
682        actionGroup->add(
683          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
684                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
685          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
686      );      );
687    #endif
688        
689        // script right-click popup actions
690    #if USE_GLIB_ACTION
691        m_actionAddScriptGroup = m_actionGroup->add_action(
692            "AddScriptGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
693        );
694        m_actionAddScript = m_actionGroup->add_action(
695            "AddScript", sigc::mem_fun(*this, &MainWindow::on_action_add_script)
696        );
697        m_actionEditScript = m_actionGroup->add_action(
698            "EditScript", sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
699        );
700        m_actionRemoveScript = m_actionGroup->add_action(
701            "RemoveScript", sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
702        );
703    #else
704        actionGroup->add(
705            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
706            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
707        );
708        actionGroup->add(
709            Gtk::Action::create("AddScript", _("Add _Script")),
710            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
711        );
712        actionGroup->add(
713            Gtk::Action::create("EditScript", _("_Edit Script...")),
714            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
715        );
716        actionGroup->add(
717            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
718            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
719        );
720    #endif
721    
722    #if USE_GTKMM_BUILDER
723        insert_action_group("AppMenu", m_actionGroup);
724        
725        m_uiManager = Gtk::Builder::create();
726        Glib::ustring ui_info =
727            "<interface>"
728            "  <menubar id='MenuBar'>"
729            "    <menu id='MenuFile'>"
730            "      <attribute name='label' translatable='yes'>_File</attribute>"
731            "      <section>"
732            "        <item id='New'>"
733            "          <attribute name='label' translatable='yes'>New</attribute>"
734            "          <attribute name='action'>AppMenu.New</attribute>"
735            "        </item>"
736            "        <item id='Open'>"
737            "          <attribute name='label' translatable='yes'>Open</attribute>"
738            "          <attribute name='action'>AppMenu.Open</attribute>"
739            "        </item>"
740            "      </section>"
741            "      <section>"
742            "        <item id='Save'>"
743            "          <attribute name='label' translatable='yes'>Save</attribute>"
744            "          <attribute name='action'>AppMenu.Save</attribute>"
745            "        </item>"
746            "        <item id='SaveAs'>"
747            "          <attribute name='label' translatable='yes'>Save As</attribute>"
748            "          <attribute name='action'>AppMenu.SaveAs</attribute>"
749            "        </item>"
750            "      </section>"
751            "      <section>"
752            "        <item id='Properties'>"
753            "          <attribute name='label' translatable='yes'>Properties</attribute>"
754            "          <attribute name='action'>AppMenu.Properties</attribute>"
755            "        </item>"
756            "      </section>"
757            "      <section>"
758            "        <item id='Quit'>"
759            "          <attribute name='label' translatable='yes'>Quit</attribute>"
760            "          <attribute name='action'>AppMenu.Quit</attribute>"
761            "        </item>"
762            "      </section>"
763            "    </menu>"
764            "    <menu id='MenuEdit'>"
765            "      <attribute name='label' translatable='yes'>Edit</attribute>"
766            "      <section>"
767            "        <item id='CopyDimRgn'>"
768            "          <attribute name='label' translatable='yes'>Copy Dimension Region</attribute>"
769            "          <attribute name='action'>AppMenu.CopyDimRgn</attribute>"
770            "        </item>"
771            "        <item id='AdjustClipboard'>"
772            "          <attribute name='label' translatable='yes'>Adjust Clipboard</attribute>"
773            "          <attribute name='action'>AppMenu.AdjustClipboard</attribute>"
774            "        </item>"
775            "        <item id='PasteDimRgn'>"
776            "          <attribute name='label' translatable='yes'>Paste Dimension Region</attribute>"
777            "          <attribute name='action'>AppMenu.PasteDimRgn</attribute>"
778            "        </item>"
779            "      </section>"
780            "        <item id='SelectPrevInstr'>"
781            "          <attribute name='label' translatable='yes'>Previous Instrument</attribute>"
782            "          <attribute name='action'>AppMenu.SelectPrevInstr</attribute>"
783            "        </item>"
784            "        <item id='SelectNextInstr'>"
785            "          <attribute name='label' translatable='yes'>Next Instrument</attribute>"
786            "          <attribute name='action'>AppMenu.SelectNextInstr</attribute>"
787            "        </item>"
788            "      <section>"
789            "        <item id='SelectPrevRegion'>"
790            "          <attribute name='label' translatable='yes'>Previous Region</attribute>"
791            "          <attribute name='action'>AppMenu.SelectPrevRegion</attribute>"
792            "        </item>"
793            "        <item id='SelectNextRegion'>"
794            "          <attribute name='label' translatable='yes'>Next Region</attribute>"
795            "          <attribute name='action'>AppMenu.SelectNextRegion</attribute>"
796            "        </item>"
797            "      </section>"
798            "        <item id='SelectPrevDimension'>"
799            "          <attribute name='label' translatable='yes'>Previous Dimension</attribute>"
800            "          <attribute name='action'>AppMenu.SelectPrevDimension</attribute>"
801            "        </item>"
802            "        <item id='SelectNextDimension'>"
803            "          <attribute name='label' translatable='yes'>Next Dimension</attribute>"
804            "          <attribute name='action'>AppMenu.SelectNextDimension</attribute>"
805            "        </item>"
806            "        <item id='SelectPrevDimRgnZone'>"
807            "          <attribute name='label' translatable='yes'>Previous Dimension Region Zone</attribute>"
808            "          <attribute name='action'>AppMenu.SelectPrevDimRgnZone</attribute>"
809            "        </item>"
810            "        <item id='SelectNextDimRgnZone'>"
811            "          <attribute name='label' translatable='yes'>Next Dimension Region Zone</attribute>"
812            "          <attribute name='action'>AppMenu.SelectNextDimRgnZone</attribute>"
813            "        </item>"
814            "        <item id='SelectAddPrevDimRgnZone'>"
815            "          <attribute name='label' translatable='yes'>Add Previous Dimension Region Zone</attribute>"
816            "          <attribute name='action'>AppMenu.SelectAddPrevDimRgnZone</attribute>"
817            "        </item>"
818            "        <item id='SelectAddNextDimRgnZone'>"
819            "          <attribute name='label' translatable='yes'>Add Next Dimension Region Zone</attribute>"
820            "          <attribute name='action'>AppMenu.SelectAddNextDimRgnZone</attribute>"
821            "        </item>"
822            "      <section>"
823            "        <item id='CopySampleUnity'>"
824            "          <attribute name='label' translatable='yes'>Copy Sample Unity</attribute>"
825            "          <attribute name='action'>AppMenu.CopySampleUnity</attribute>"
826            "        </item>"
827            "        <item id='CopySampleTune'>"
828            "          <attribute name='label' translatable='yes'>Copy Sample Tune</attribute>"
829            "          <attribute name='action'>AppMenu.CopySampleTune</attribute>"
830            "        </item>"
831            "        <item id='CopySampleLoop'>"
832            "          <attribute name='label' translatable='yes'>Copy Sample Loop</attribute>"
833            "          <attribute name='action'>AppMenu.CopySampleLoop</attribute>"
834            "        </item>"
835            "      </section>"
836            "    </menu>"
837            "    <menu id='MenuMacro'>"
838            "      <attribute name='label' translatable='yes'>Macro</attribute>"
839            "      <section>"
840            "      </section>"
841            "    </menu>"
842            "    <menu id='MenuSample'>"
843            "      <attribute name='label' translatable='yes'>Sample</attribute>"
844            "      <section>"
845            "        <item id='SampleProperties'>"
846            "          <attribute name='label' translatable='yes'>Properties</attribute>"
847            "          <attribute name='action'>AppMenu.SampleProperties</attribute>"
848            "        </item>"
849            "        <item id='AddGroup'>"
850            "          <attribute name='label' translatable='yes'>Add Group</attribute>"
851            "          <attribute name='action'>AppMenu.AddGroup</attribute>"
852            "        </item>"
853            "        <item id='AddSample'>"
854            "          <attribute name='label' translatable='yes'>Add Sample</attribute>"
855            "          <attribute name='action'>AppMenu.AddSample</attribute>"
856            "        </item>"
857            "        <item id='ShowSampleRefs'>"
858            "          <attribute name='label' translatable='yes'>Show Sample References</attribute>"
859            "          <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
860            "        </item>"
861            "        <item id='ReplaceSample'>"
862            "          <attribute name='label' translatable='yes'>Replace Sample</attribute>"
863            "          <attribute name='action'>AppMenu.ReplaceSample</attribute>"
864            "        </item>"
865            "        <item id='ReplaceAllSamplesInAllGroups'>"
866            "          <attribute name='label' translatable='yes'>Replace all Samples in all Groups</attribute>"
867            "          <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
868            "        </item>"
869            "      </section>"
870            "      <section>"
871            "        <item id='RemoveSample'>"
872            "          <attribute name='label' translatable='yes'>Remove Sample</attribute>"
873            "          <attribute name='action'>AppMenu.RemoveSample</attribute>"
874            "        </item>"
875            "        <item id='RemoveUnusedSamples'>"
876            "          <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
877            "          <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
878            "        </item>"
879            "      </section>"
880            "    </menu>"
881            "    <menu id='MenuInstrument'>"
882            "      <attribute name='label' translatable='yes'>Instrument</attribute>"
883            "      <section>"
884            "        <item id='InstrProperties'>"
885            "          <attribute name='label' translatable='yes'>Properties</attribute>"
886            "          <attribute name='action'>AppMenu.InstrProperties</attribute>"
887            "        </item>"
888            "        <item id='MidiRules'>"
889            "          <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
890            "          <attribute name='action'>AppMenu.MidiRules</attribute>"
891            "        </item>"
892            "        <item id='ScriptSlots'>"
893            "          <attribute name='label' translatable='yes'>Script Slots</attribute>"
894            "          <attribute name='action'>AppMenu.ScriptSlots</attribute>"
895            "        </item>"
896            "      </section>"
897            "      <submenu id='AssignScripts'>"
898            "        <attribute name='label' translatable='yes'>Assign Scripts</attribute>"
899            "      </submenu>"
900            "      <section>"
901            "        <item id='AddInstrument'>"
902            "          <attribute name='label' translatable='yes'>Add Instrument</attribute>"
903            "          <attribute name='action'>AppMenu.AddInstrument</attribute>"
904            "        </item>"
905            "        <item id='DupInstrument'>"
906            "          <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
907            "          <attribute name='action'>AppMenu.DupInstrument</attribute>"
908            "        </item>"
909            "        <item id='MoveInstrument'>"
910            "          <attribute name='label' translatable='yes'>Move Instrument To ...</attribute>"
911            "          <attribute name='action'>AppMenu.MoveInstrument</attribute>"
912            "        </item>"
913            "        <item id='CombInstruments'>"
914            "          <attribute name='label' translatable='yes'>Combine Instrument</attribute>"
915            "          <attribute name='action'>AppMenu.CombInstruments</attribute>"
916            "        </item>"
917            "      </section>"
918            "      <section>"
919            "        <item id='RemoveInstrument'>"
920            "          <attribute name='label' translatable='yes'>Remove Instrument</attribute>"
921            "          <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
922            "        </item>"
923            "      </section>"
924            "    </menu>"
925            "    <menu id='MenuScript'>"
926            "      <attribute name='label' translatable='yes'>Script</attribute>"
927            "      <section>"
928            "        <item id='AddScriptGroup'>"
929            "          <attribute name='label' translatable='yes'>Add Script Group</attribute>"
930            "          <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
931            "        </item>"
932            "        <item id='AddScript'>"
933            "          <attribute name='label' translatable='yes'>Add Script</attribute>"
934            "          <attribute name='action'>AppMenu.AddScript</attribute>"
935            "        </item>"
936            "        <item id='EditScript'>"
937            "          <attribute name='label' translatable='yes'>Edit Script</attribute>"
938            "          <attribute name='action'>AppMenu.EditScript</attribute>"
939            "        </item>"
940            "      </section>"
941            "      <section>"
942            "        <item id='RemoveScript'>"
943            "          <attribute name='label' translatable='yes'>Remove Script</attribute>"
944            "          <attribute name='action'>AppMenu.RemoveScript</attribute>"
945            "        </item>"
946            "      </section>"
947            "    </menu>"
948            "    <menu id='MenuView'>"
949            "      <attribute name='label' translatable='yes'>View</attribute>"
950            "      <section>"
951            "        <item id='Statusbar'>"
952            "          <attribute name='label' translatable='yes'>Statusbar</attribute>"
953            "          <attribute name='action'>AppMenu.Statusbar</attribute>"
954            "        </item>"
955            "        <item id='ShowTooltips'>"
956            "          <attribute name='label' translatable='yes'>Tooltips for Beginners</attribute>"
957            "          <attribute name='action'>AppMenu.ShowTooltips</attribute>"
958            "        </item>"
959            "        <item id='AutoRestoreWinDim'>"
960            "          <attribute name='label' translatable='yes'>Auto restore Window Dimensions</attribute>"
961            "          <attribute name='action'>AppMenu.AutoRestoreWinDim</attribute>"
962            "        </item>"
963            "        <item id='OpenInstrPropsByDoubleClick'>"
964            "          <attribute name='label' translatable='yes'>Instrument Properties by Double Click</attribute>"
965            "          <attribute name='action'>AppMenu.OpenInstrPropsByDoubleClick</attribute>"
966            "        </item>"
967            "      </section>"
968            "      <section>"
969            "        <item id='RefreshAll'>"
970            "          <attribute name='label' translatable='yes'>Refresh All</attribute>"
971            "          <attribute name='action'>AppMenu.RefreshAll</attribute>"
972            "        </item>"
973            "      </section>"
974            "    </menu>"
975            "    <menu id='MenuTools'>"
976            "      <attribute name='label' translatable='yes'>Tools</attribute>"
977            "      <section>"
978            "        <item id='CombineInstruments'>"
979            "          <attribute name='label' translatable='yes'>Combine Instruments ...</attribute>"
980            "          <attribute name='action'>AppMenu.CombineInstruments</attribute>"
981            "        </item>"
982            "        <item id='MergeFiles'>"
983            "          <attribute name='label' translatable='yes'>Merge Files ...</attribute>"
984            "          <attribute name='action'>AppMenu.MergeFiles</attribute>"
985            "        </item>"
986            "      </section>"
987            "    </menu>"
988            "    <menu id='MenuSettings'>"
989            "      <attribute name='label' translatable='yes'>Settings</attribute>"
990            "      <section>"
991            "        <item id='WarnUserOnExtensions'>"
992            "          <attribute name='label' translatable='yes'>Warning on Format Extensions</attribute>"
993            "          <attribute name='action'>AppMenu.WarnUserOnExtensions</attribute>"
994            "        </item>"
995            "        <item id='SyncSamplerInstrumentSelection'>"
996            "          <attribute name='label' translatable='yes'>Synchronize Sampler Selection</attribute>"
997            "          <attribute name='action'>AppMenu.SyncSamplerInstrumentSelection</attribute>"
998            "        </item>"
999            "        <item id='MoveRootNoteWithRegionMoved'>"
1000            "          <attribute name='label' translatable='yes'>Move Root Note with Region moved</attribute>"
1001            "          <attribute name='action'>AppMenu.MoveRootNoteWithRegionMoved</attribute>"
1002            "        </item>"
1003            "        <item id='SaveWithTemporaryFile'>"
1004            "          <attribute name='label' translatable='yes'>Save with temporary file</attribute>"
1005            "          <attribute name='action'>AppMenu.SaveWithTemporaryFile</attribute>"
1006            "        </item>"
1007            "      </section>"
1008            "    </menu>"
1009            "    <menu id='MenuHelp'>"
1010            "      <attribute name='label' translatable='yes'>Help</attribute>"
1011            "      <section>"
1012            "        <item id='About'>"
1013            "          <attribute name='label' translatable='yes'>About ...</attribute>"
1014            "          <attribute name='action'>AppMenu.About</attribute>"
1015            "        </item>"
1016            "      </section>"
1017            "    </menu>"
1018            "  </menubar>"
1019            // popups
1020            "  <menu id='PopupMenu'>"
1021            "    <section>"
1022            "      <item id='InstrProperties'>"
1023            "        <attribute name='label' translatable='yes'>Instrument Properties</attribute>"
1024            "        <attribute name='action'>AppMenu.InstrProperties</attribute>"
1025            "      </item>"
1026            "      <item id='MidiRules'>"
1027            "        <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
1028            "        <attribute name='action'>AppMenu.MidiRules</attribute>"
1029            "      </item>"
1030            "      <item id='ScriptSlots'>"
1031            "        <attribute name='label' translatable='yes'>Script Slots</attribute>"
1032            "        <attribute name='action'>AppMenu.ScriptSlots</attribute>"
1033            "      </item>"
1034            "      <item id='AddInstrument'>"
1035            "        <attribute name='label' translatable='yes'>Add Instrument</attribute>"
1036            "        <attribute name='action'>AppMenu.AddInstrument</attribute>"
1037            "      </item>"
1038            "      <item id='DupInstrument'>"
1039            "        <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
1040            "        <attribute name='action'>AppMenu.DupInstrument</attribute>"
1041            "      </item>"
1042            "      <item id='MoveInstrument'>"
1043            "        <attribute name='label' translatable='yes'>Move Instrument To ...</attribute>"
1044            "        <attribute name='action'>AppMenu.MoveInstrument</attribute>"
1045            "      </item>"
1046            "      <item id='CombInstruments'>"
1047            "        <attribute name='label' translatable='yes'>Combine Instruments</attribute>"
1048            "        <attribute name='action'>AppMenu.CombInstruments</attribute>"
1049            "      </item>"
1050            "    </section>"
1051            "    <section>"
1052            "      <item id='RemoveInstrument'>"
1053            "        <attribute name='label' translatable='yes'>Remove Instruments</attribute>"
1054            "        <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
1055            "      </item>"
1056            "    </section>"
1057            "  </menu>"
1058            "  <menu id='SamplePopupMenu'>"
1059            "    <section>"
1060            "      <item id='SampleProperties'>"
1061            "        <attribute name='label' translatable='yes'>Sample Properties</attribute>"
1062            "        <attribute name='action'>AppMenu.SampleProperties</attribute>"
1063            "      </item>"
1064            "      <item id='AddGroup'>"
1065            "        <attribute name='label' translatable='yes'>Add Sample Group</attribute>"
1066            "        <attribute name='action'>AppMenu.AddGroup</attribute>"
1067            "      </item>"
1068            "      <item id='AddSample'>"
1069            "        <attribute name='label' translatable='yes'>Add Sample</attribute>"
1070            "        <attribute name='action'>AppMenu.AddSample</attribute>"
1071            "      </item>"
1072            "      <item id='ShowSampleRefs'>"
1073            "        <attribute name='label' translatable='yes'>Show Sample References ...</attribute>"
1074            "        <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
1075            "      </item>"
1076            "      <item id='ReplaceSample'>"
1077            "        <attribute name='label' translatable='yes'>Replace Sample</attribute>"
1078            "        <attribute name='action'>AppMenu.ReplaceSample</attribute>"
1079            "      </item>"
1080            "      <item id='ReplaceAllSamplesInAllGroups'>"
1081            "        <attribute name='label' translatable='yes'>Replace all Samples ...</attribute>"
1082            "        <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
1083            "      </item>"
1084            "    </section>"
1085            "    <section>"
1086            "      <item id='RemoveSample'>"
1087            "        <attribute name='label' translatable='yes'>Remove Sample</attribute>"
1088            "        <attribute name='action'>AppMenu.RemoveSample</attribute>"
1089            "      </item>"
1090            "      <item id='RemoveUnusedSamples'>"
1091            "        <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
1092            "        <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
1093            "      </item>"
1094            "    </section>"
1095            "  </menu>"
1096            "  <menu id='ScriptPopupMenu'>"
1097            "    <section>"
1098            "      <item id='AddScriptGroup'>"
1099            "        <attribute name='label' translatable='yes'>Add Script Group</attribute>"
1100            "        <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
1101            "      </item>"
1102            "      <item id='AddScript'>"
1103            "        <attribute name='label' translatable='yes'>Add Script</attribute>"
1104            "        <attribute name='action'>AppMenu.AddScript</attribute>"
1105            "      </item>"
1106            "      <item id='EditScript'>"
1107            "        <attribute name='label' translatable='yes'>Edit Script</attribute>"
1108            "        <attribute name='action'>AppMenu.EditScript</attribute>"
1109            "      </item>"
1110            "    </section>"
1111            "    <section>"
1112            "      <item id='RemoveScript'>"
1113            "        <attribute name='label' translatable='yes'>Remove Script</attribute>"
1114            "        <attribute name='action'>AppMenu.RemoveScript</attribute>"
1115            "      </item>"
1116            "    </section>"
1117            "  </menu>"
1118            "</interface>";
1119        m_uiManager->add_from_string(ui_info);
1120    #else
1121      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
1122      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
1123      add_accel_group(uiManager->get_accel_group());      add_accel_group(uiManager->get_accel_group());
# Line 222  MainWindow::MainWindow() : Line 1136  MainWindow::MainWindow() :
1136          "      <separator/>"          "      <separator/>"
1137          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
1138          "    </menu>"          "    </menu>"
1139            "    <menu action='MenuEdit'>"
1140            "      <menuitem action='CopyDimRgn'/>"
1141            "      <menuitem action='AdjustClipboard'/>"
1142            "      <menuitem action='PasteDimRgn'/>"
1143            "      <separator/>"
1144            "      <menuitem action='SelectPrevInstr'/>"
1145            "      <menuitem action='SelectNextInstr'/>"
1146            "      <separator/>"
1147            "      <menuitem action='SelectPrevRegion'/>"
1148            "      <menuitem action='SelectNextRegion'/>"
1149            "      <separator/>"
1150            "      <menuitem action='SelectPrevDimension'/>"
1151            "      <menuitem action='SelectNextDimension'/>"
1152            "      <menuitem action='SelectPrevDimRgnZone'/>"
1153            "      <menuitem action='SelectNextDimRgnZone'/>"
1154            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
1155            "      <menuitem action='SelectAddNextDimRgnZone'/>"
1156            "      <separator/>"
1157            "      <menuitem action='CopySampleUnity'/>"
1158            "      <menuitem action='CopySampleTune'/>"
1159            "      <menuitem action='CopySampleLoop'/>"
1160            "    </menu>"
1161            "    <menu action='MenuMacro'>"
1162            "    </menu>"
1163            "    <menu action='MenuSample'>"
1164            "      <menuitem action='SampleProperties'/>"
1165            "      <menuitem action='AddGroup'/>"
1166            "      <menuitem action='AddSample'/>"
1167            "      <menuitem action='ShowSampleRefs'/>"
1168            "      <menuitem action='ReplaceSample' />"
1169            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
1170            "      <separator/>"
1171            "      <menuitem action='RemoveSample'/>"
1172            "      <menuitem action='RemoveUnusedSamples'/>"
1173            "    </menu>"
1174          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
1175            "      <menu action='AllInstruments'>"
1176            "      </menu>"
1177            "      <separator/>"
1178            "      <menuitem action='InstrProperties'/>"
1179            "      <menuitem action='MidiRules'/>"
1180            "      <menuitem action='ScriptSlots'/>"
1181            "      <menu action='AssignScripts'/>"
1182            "      <menuitem action='AddInstrument'/>"
1183            "      <menuitem action='DupInstrument'/>"
1184            "      <menuitem action='MoveInstrument'/>"
1185            "      <menuitem action='CombInstruments'/>"
1186            "      <separator/>"
1187            "      <menuitem action='RemoveInstrument'/>"
1188            "    </menu>"
1189            "    <menu action='MenuScript'>"
1190            "      <menuitem action='AddScriptGroup'/>"
1191            "      <menuitem action='AddScript'/>"
1192            "      <menuitem action='EditScript'/>"
1193            "      <separator/>"
1194            "      <menuitem action='RemoveScript'/>"
1195          "    </menu>"          "    </menu>"
1196          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
1197          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
1198            "      <menuitem action='ShowTooltips'/>"
1199            "      <menuitem action='AutoRestoreWinDim'/>"
1200            "      <menuitem action='OpenInstrPropsByDoubleClick'/>"
1201            "      <separator/>"
1202            "      <menuitem action='RefreshAll'/>"
1203            "    </menu>"
1204            "    <menu action='MenuTools'>"
1205            "      <menuitem action='CombineInstruments'/>"
1206            "      <menuitem action='MergeFiles'/>"
1207            "    </menu>"
1208            "    <menu action='MenuSettings'>"
1209            "      <menuitem action='WarnUserOnExtensions'/>"
1210            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
1211            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
1212            "      <menuitem action='SaveWithTemporaryFile'/>"
1213          "    </menu>"          "    </menu>"
1214          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
1215          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 233  MainWindow::MainWindow() : Line 1217  MainWindow::MainWindow() :
1217          "  </menubar>"          "  </menubar>"
1218          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
1219          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
1220            "    <menuitem action='MidiRules'/>"
1221            "    <menuitem action='ScriptSlots'/>"
1222          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
1223            "    <menuitem action='DupInstrument'/>"
1224            "    <menuitem action='MoveInstrument'/>"
1225            "    <menuitem action='CombInstruments'/>"
1226          "    <separator/>"          "    <separator/>"
1227          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
1228          "  </popup>"          "  </popup>"
# Line 241  MainWindow::MainWindow() : Line 1230  MainWindow::MainWindow() :
1230          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
1231          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
1232          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
1233          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ShowSampleRefs'/>"
1234            "    <menuitem action='ReplaceSample' />"
1235            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
1236          "    <separator/>"          "    <separator/>"
1237          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
1238            "    <menuitem action='RemoveUnusedSamples'/>"
1239            "  </popup>"
1240            "  <popup name='ScriptPopupMenu'>"
1241            "    <menuitem action='AddScriptGroup'/>"
1242            "    <menuitem action='AddScript'/>"
1243            "    <menuitem action='EditScript'/>"
1244            "    <separator/>"
1245            "    <menuitem action='RemoveScript'/>"
1246          "  </popup>"          "  </popup>"
1247          "</ui>";          "</ui>";
1248      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
1249    #endif
1250    
1251    #if USE_GTKMM_BUILDER
1252        popup_menu = new Gtk::Menu(
1253            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1254                m_uiManager->get_object("PopupMenu")
1255            )
1256        );
1257        sample_popup = new Gtk::Menu(
1258            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1259                m_uiManager->get_object("SamplePopupMenu")
1260            )
1261        );
1262        script_popup = new Gtk::Menu(
1263            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1264                m_uiManager->get_object("ScriptPopupMenu")
1265            )
1266        );
1267    #else
1268      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
1269        
1270        // Set tooltips for menu items (for some reason, setting a tooltip on the
1271        // respective Gtk::Action objects above will simply be ignored, no matter
1272        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
1273        // Gtk::Action::create()).
1274        {
1275            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1276                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1277            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."));
1278        }
1279        {
1280            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1281                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
1282            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."));
1283        }
1284        {
1285            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1286                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
1287            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 information to be altered by this action."));
1288        }
1289        {
1290            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1291                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
1292            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."));
1293        }
1294        {
1295            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1296                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
1297            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)."));
1298        }
1299        {
1300            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1301                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
1302            item->set_tooltip_text(_("If checked, and when a region is moved by dragging it around on the virtual keyboard, the keyboard position dependent pitch will move exactly with the amount of semi tones the region was moved around."));
1303        }
1304        {
1305            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1306                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
1307            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
1308            // copy tooltip to popup menu
1309            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
1310                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
1311            item2->set_tooltip_text(item->get_tooltip_text());
1312        }
1313        {
1314            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1315                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
1316            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
1317        }
1318        {
1319            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1320                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
1321            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
1322        }
1323        {
1324            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1325                uiManager->get_widget("/MenuBar/MenuView/OpenInstrPropsByDoubleClick"));
1326            item->set_tooltip_text(_("If checked, double clicking an instrument opens its properties dialog."));
1327        }
1328        {
1329            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1330                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
1331            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
1332        }
1333        {
1334            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1335                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
1336            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
1337        }
1338    #endif
1339    
1340    #if USE_GTKMM_BUILDER
1341        assign_scripts_menu = new Gtk::Menu(
1342            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1343                m_uiManager->get_object("AssignScripts")
1344            )
1345        );
1346    #else
1347        instrument_menu = static_cast<Gtk::MenuItem*>(
1348            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
1349    
1350        assign_scripts_menu = static_cast<Gtk::MenuItem*>(
1351            uiManager->get_widget("/MenuBar/MenuInstrument/AssignScripts"))->get_submenu();
1352    #endif
1353    
1354    #if USE_GTKMM_BUILDER
1355        Gtk::Widget* menuBar = NULL;
1356        m_uiManager->get_widget("MenuBar", menuBar);
1357    #else
1358      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
1359    #endif
1360    
1361      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
1362      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
1363      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
# Line 261  MainWindow::MainWindow() : Line 1368  MainWindow::MainWindow() :
1368      set_file_is_shared(false);      set_file_is_shared(false);
1369    
1370      // Status Bar:      // Status Bar:
1371    #if USE_GTKMM_BOX
1372    # warning No status bar layout for GTKMM 4 yet
1373    #else
1374      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
1375      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
1376    #endif
1377      m_StatusBar.show();      m_StatusBar.show();
1378    
1379      m_RegionChooser.signal_region_selected().connect(      m_RegionChooser.signal_region_selected().connect(
# Line 272  MainWindow::MainWindow() : Line 1383  MainWindow::MainWindow() :
1383    
1384    
1385      // Create the Tree model:      // Create the Tree model:
1386      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refInstrumentsTreeModel = Gtk::ListStore::create(m_InstrumentsModel);
1387      m_TreeView.set_model(m_refTreeModel);      m_refInstrumentsModelFilter = Gtk::TreeModelFilter::create(m_refInstrumentsTreeModel);
1388      m_refTreeModel->signal_row_changed().connect(      m_refInstrumentsModelFilter->set_visible_func(
1389            sigc::mem_fun(*this, &MainWindow::instrument_row_visible)
1390        );
1391        m_TreeViewInstruments.set_model(m_refInstrumentsModelFilter);
1392    
1393        m_TreeViewInstruments.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1394        m_TreeViewInstruments.set_has_tooltip(true);
1395        m_TreeViewInstruments.signal_query_tooltip().connect(
1396            sigc::mem_fun(*this, &MainWindow::onQueryTreeViewTooltip)
1397        );
1398        instrument_name_connection = m_refInstrumentsTreeModel->signal_row_changed().connect(
1399          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
1400      );      );
1401    
1402      // Add the TreeView's view columns:      // Add the TreeView's view columns:
1403      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeViewInstruments.append_column(_("Nr"), m_InstrumentsModel.m_col_nr);
1404      m_TreeView.set_headers_visible(false);      m_TreeViewInstruments.append_column_editable(_("Instrument"), m_InstrumentsModel.m_col_name);
1405        m_TreeViewInstruments.append_column(_("Scripts"), m_InstrumentsModel.m_col_scripts);
1406        m_TreeViewInstruments.set_headers_visible(true);
1407        
1408        // establish drag&drop within the instrument tree view, allowing to reorder
1409        // the sequence of instruments within the gig file
1410        {
1411            std::vector<Gtk::TargetEntry> drag_target_instrument;
1412            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
1413            m_TreeViewInstruments.drag_source_set(drag_target_instrument);
1414            m_TreeViewInstruments.drag_dest_set(drag_target_instrument);
1415            m_TreeViewInstruments.signal_drag_begin().connect(
1416                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
1417            );
1418            m_TreeViewInstruments.signal_drag_data_get().connect(
1419                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
1420            );
1421            m_TreeViewInstruments.signal_drag_data_received().connect(
1422                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
1423            );
1424        }
1425    
1426      // create samples treeview (including its data model)      // create samples treeview (including its data model)
1427      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
1428      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
1429        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1430        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."));
1431      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
1432      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
1433      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
1434        {
1435            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
1436            Gtk::CellRendererText* cellrenderer =
1437                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1438            column->add_attribute(
1439                cellrenderer->property_foreground(), m_SamplesModel.m_color
1440            );
1441        }
1442        {
1443            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
1444            Gtk::CellRendererText* cellrenderer =
1445                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1446            column->add_attribute(
1447                cellrenderer->property_foreground(), m_SamplesModel.m_color
1448            );
1449        }
1450        m_TreeViewSamples.set_headers_visible(true);
1451    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
1452        m_TreeViewSamples.signal_button_press_event().connect(
1453            sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1454        );
1455    #else
1456      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
1457          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1458      );      );
1459    #endif
1460      m_refSamplesTreeModel->signal_row_changed().connect(      m_refSamplesTreeModel->signal_row_changed().connect(
1461          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
1462      );      );
1463    
1464        // create scripts treeview (including its data model)
1465        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
1466        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
1467        m_TreeViewScripts.set_tooltip_text(_(
1468            "Use CTRL + double click for editing a script."
1469            "\n\n"
1470            "Note: instrument scripts are a LinuxSampler extension of the gig "
1471            "format. This feature will not work with the GigaStudio software!"
1472        ));
1473        // m_TreeViewScripts.set_reorderable();
1474        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
1475        m_TreeViewScripts.set_headers_visible(false);
1476    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
1477        m_TreeViewScripts.signal_button_press_event().connect(
1478            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1479        );
1480    #else
1481        m_TreeViewScripts.signal_button_press_event().connect_notify(
1482            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1483        );
1484    #endif
1485        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
1486        m_TreeViewScripts.signal_row_activated().connect(
1487            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
1488        );
1489        m_refScriptsTreeModel->signal_row_changed().connect(
1490            sigc::mem_fun(*this, &MainWindow::script_name_changed)
1491        );
1492    
1493        // establish drag&drop between scripts tree view and ScriptSlots window
1494        std::vector<Gtk::TargetEntry> drag_target_gig_script;
1495        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
1496        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
1497        m_TreeViewScripts.signal_drag_begin().connect(
1498            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
1499        );
1500        m_TreeViewScripts.signal_drag_data_get().connect(
1501            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
1502        );
1503    
1504      // 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
1505      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
1506      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
# Line 313  MainWindow::MainWindow() : Line 1519  MainWindow::MainWindow() :
1519          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
1520      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
1521          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1522        m_RegionChooser.signal_instrument_changed().connect(
1523            sigc::mem_fun(*this, &MainWindow::region_changed));
1524      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
1525          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1526      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
1527          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1528      propDialog.signal_info_changed().connect(      sampleProps.signal_changed().connect(
1529            sigc::mem_fun(*this, &MainWindow::file_changed));
1530        fileProps.signal_changed().connect(
1531            sigc::mem_fun(*this, &MainWindow::file_changed));
1532        midiRules.signal_changed().connect(
1533          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1534    
1535      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 326  MainWindow::MainWindow() : Line 1538  MainWindow::MainWindow() :
1538          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
1539      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
1540          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
1541        sample_ref_changed_signal.connect(
1542            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
1543        );
1544        samples_to_be_removed_signal.connect(
1545            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
1546        );
1547    
1548        dimreg_edit.signal_select_sample().connect(
1549            sigc::mem_fun(*this, &MainWindow::select_sample)
1550        );
1551    
1552        dimreg_edit.editScriptSlotsButton.signal_clicked().connect(
1553            sigc::mem_fun(*this, &MainWindow::show_script_slots)
1554        );
1555        // simply sending the same signal (pair) to the sampler on 'patch' variable
1556        // changes as the already existing signal (pair) when the user edits the
1557        // script's source code, because the sampler would reload the source code
1558        // and the 'patch' variables from the instrument on this signal anyway
1559        dimreg_edit.scriptVars.signal_vars_to_be_changed.connect(
1560            [this](gig::Instrument* instr) {
1561                for (int i = 0; i < instr->ScriptSlotCount(); ++i) {
1562                    gig::Script* script = instr->GetScriptOfSlot(i);
1563                    signal_script_to_be_changed.emit(script);
1564                }
1565            }
1566        );
1567        dimreg_edit.scriptVars.signal_vars_changed.connect(
1568            [this](gig::Instrument* instr) {
1569                for (int i = 0; i < instr->ScriptSlotCount(); ++i) {
1570                    gig::Script* script = instr->GetScriptOfSlot(i);
1571                    signal_script_changed.emit(script);
1572                }
1573            }
1574        );
1575        dimreg_edit.scriptVars.signal_edit_script.connect(
1576            [this](gig::Script* script) {
1577                editScript(script);
1578            }
1579        );
1580    
1581      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
1582          sigc::hide(          sigc::hide(
1583              sigc::bind(              sigc::bind(
1584                  file_structure_to_be_changed_signal.make_slot(),                  file_structure_to_be_changed_signal.make_slot(),
1585    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1586                    std::ref(this->file)
1587    #else
1588                  sigc::ref(this->file)                  sigc::ref(this->file)
1589    #endif
1590              )              )
1591          )          )
1592      );      );
# Line 339  MainWindow::MainWindow() : Line 1594  MainWindow::MainWindow() :
1594          sigc::hide(          sigc::hide(
1595              sigc::bind(              sigc::bind(
1596                  file_structure_changed_signal.make_slot(),                  file_structure_changed_signal.make_slot(),
1597    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1598                    std::ref(this->file)
1599    #else
1600                  sigc::ref(this->file)                  sigc::ref(this->file)
1601    #endif
1602              )              )
1603          )          )
1604      );      );
# Line 360  MainWindow::MainWindow() : Line 1619  MainWindow::MainWindow() :
1619      dimreg_stereo.signal_toggled().connect(      dimreg_stereo.signal_toggled().connect(
1620          sigc::mem_fun(*this, &MainWindow::update_dimregs));          sigc::mem_fun(*this, &MainWindow::update_dimregs));
1621    
1622        m_searchText.signal_changed().connect(
1623            sigc::mem_fun(*m_refInstrumentsModelFilter.operator->(), &Gtk::TreeModelFilter::refilter)
1624        );
1625    
1626      file = 0;      file = 0;
1627      file_is_changed = false;      file_is_changed = false;
1628    
1629    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1630      show_all_children();      show_all_children();
1631    #endif
1632    
1633      // start with a new gig file by default      // start with a new gig file by default
1634      on_action_file_new();      on_action_file_new();
1635    
1636        m_TreeViewNotebook.signal_switch_page().connect(
1637            sigc::mem_fun(*this, &MainWindow::on_notebook_tab_switched)
1638        );
1639    
1640        // select 'Instruments' tab by default
1641        // (gtk allows this only if the tab childs are visible, thats why it's here)
1642        m_TreeViewNotebook.set_current_page(1);
1643    
1644        Gtk::Clipboard::get()->signal_owner_change().connect(
1645            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
1646        );
1647        updateClipboardPasteAvailable();
1648        updateClipboardCopyAvailable();
1649    
1650        // setup macros and their keyboard accelerators
1651        {
1652    #if USE_GTKMM_BUILDER
1653            menuMacro = new Gtk::Menu(
1654                Glib::RefPtr<Gio::Menu>::cast_dynamic(
1655                    m_uiManager->get_object("MenuMacro")
1656                )
1657            );
1658    #else
1659            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1660                uiManager->get_widget("/MenuBar/MenuMacro")
1661            )->get_submenu();
1662    #endif
1663    
1664            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
1665            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
1666            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
1667            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
1668            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
1669            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
1670            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
1671            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
1672            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
1673            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
1674            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
1675            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
1676            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
1677            Gtk::AccelMap::add_entry("<Macros>/macro_12", GDK_KEY_F13, noModifier);
1678            Gtk::AccelMap::add_entry("<Macros>/macro_13", GDK_KEY_F14, noModifier);
1679            Gtk::AccelMap::add_entry("<Macros>/macro_14", GDK_KEY_F15, noModifier);
1680            Gtk::AccelMap::add_entry("<Macros>/macro_15", GDK_KEY_F16, noModifier);
1681            Gtk::AccelMap::add_entry("<Macros>/macro_16", GDK_KEY_F17, noModifier);
1682            Gtk::AccelMap::add_entry("<Macros>/macro_17", GDK_KEY_F18, noModifier);
1683            Gtk::AccelMap::add_entry("<Macros>/macro_18", GDK_KEY_F19, noModifier);
1684            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
1685    
1686            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1687            menuMacro->set_accel_group(accelGroup);
1688    
1689            updateMacroMenu();
1690        }
1691    
1692        // setup "Assign Scripts" keyboard accelerators
1693        {
1694            Gtk::AccelMap::add_entry("<Scripts>/script_0", GDK_KEY_F1, Gdk::SHIFT_MASK);
1695            Gtk::AccelMap::add_entry("<Scripts>/script_1", GDK_KEY_F2, Gdk::SHIFT_MASK);
1696            Gtk::AccelMap::add_entry("<Scripts>/script_2", GDK_KEY_F3, Gdk::SHIFT_MASK);
1697            Gtk::AccelMap::add_entry("<Scripts>/script_3", GDK_KEY_F4, Gdk::SHIFT_MASK);
1698            Gtk::AccelMap::add_entry("<Scripts>/script_4", GDK_KEY_F5, Gdk::SHIFT_MASK);
1699            Gtk::AccelMap::add_entry("<Scripts>/script_5", GDK_KEY_F6, Gdk::SHIFT_MASK);
1700            Gtk::AccelMap::add_entry("<Scripts>/script_6", GDK_KEY_F7, Gdk::SHIFT_MASK);
1701            Gtk::AccelMap::add_entry("<Scripts>/script_7", GDK_KEY_F8, Gdk::SHIFT_MASK);
1702            Gtk::AccelMap::add_entry("<Scripts>/script_8", GDK_KEY_F9, Gdk::SHIFT_MASK);
1703            Gtk::AccelMap::add_entry("<Scripts>/script_9", GDK_KEY_F10, Gdk::SHIFT_MASK);
1704            Gtk::AccelMap::add_entry("<Scripts>/script_10", GDK_KEY_F11, Gdk::SHIFT_MASK);
1705            Gtk::AccelMap::add_entry("<Scripts>/script_11", GDK_KEY_F12, Gdk::SHIFT_MASK);
1706            Gtk::AccelMap::add_entry("<Scripts>/script_12", GDK_KEY_F13, Gdk::SHIFT_MASK);
1707            Gtk::AccelMap::add_entry("<Scripts>/script_13", GDK_KEY_F14, Gdk::SHIFT_MASK);
1708            Gtk::AccelMap::add_entry("<Scripts>/script_14", GDK_KEY_F15, Gdk::SHIFT_MASK);
1709            Gtk::AccelMap::add_entry("<Scripts>/script_15", GDK_KEY_F16, Gdk::SHIFT_MASK);
1710            Gtk::AccelMap::add_entry("<Scripts>/script_16", GDK_KEY_F17, Gdk::SHIFT_MASK);
1711            Gtk::AccelMap::add_entry("<Scripts>/script_17", GDK_KEY_F18, Gdk::SHIFT_MASK);
1712            Gtk::AccelMap::add_entry("<Scripts>/script_18", GDK_KEY_F19, Gdk::SHIFT_MASK);
1713            Gtk::AccelMap::add_entry("<Scripts>/DropAllScriptSlots", GDK_KEY_BackSpace, Gdk::SHIFT_MASK);
1714    
1715            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1716            assign_scripts_menu->set_accel_group(accelGroup);
1717        }
1718    
1719        on_show_tooltips_changed();
1720    
1721        Glib::signal_idle().connect_once(
1722            sigc::mem_fun(*this, &MainWindow::bringToFront),
1723            200
1724        );
1725  }  }
1726    
1727  MainWindow::~MainWindow()  MainWindow::~MainWindow()
1728  {  {
1729  }  }
1730    
1731    void MainWindow::bringToFront() {
1732        #if defined(__APPLE__)
1733        macRaiseAppWindow();
1734        #endif
1735        raise();
1736        present();
1737    }
1738    
1739    void MainWindow::updateMacroMenu() {
1740    #if !USE_GTKMM_BUILDER
1741        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1742            uiManager->get_widget("/MenuBar/MenuMacro")
1743        )->get_submenu();
1744    #endif
1745    
1746        // remove all entries from "Macro" menu
1747        {
1748            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
1749            for (int i = 0; i < children.size(); ++i) {
1750                Gtk::Widget* child = children[i];
1751                menuMacro->remove(*child);
1752                delete child;
1753            }
1754        }
1755    
1756        // (re)load all macros from config file
1757        try {
1758            Settings::singleton()->loadMacros(m_macros);
1759        } catch (Serialization::Exception e) {
1760            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
1761        } catch (...) {
1762            std::cerr << "Unknown exception while loading macros!" << std::endl;
1763        }
1764    
1765        // add all configured macros as menu items to the "Macro" menu
1766        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
1767            const Serialization::Archive& macro = m_macros[iMacro];
1768            std::string name =
1769                macro.name().empty() ?
1770                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
1771            Gtk::MenuItem* item = new Gtk::MenuItem(name);
1772            item->signal_activate().connect(
1773                sigc::bind(
1774                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
1775                )
1776            );
1777            menuMacro->append(*item);
1778            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
1779            Glib::ustring comment = macro.comment();
1780            if (!comment.empty())
1781                item->set_tooltip_text(comment);
1782        }
1783        // if there are no macros configured at all, then show a dummy entry instead
1784        if (m_macros.empty()) {
1785            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
1786            item->set_sensitive(false);
1787            menuMacro->append(*item);
1788        }
1789    
1790        // add separator line to menu
1791        menuMacro->append(*new Gtk::SeparatorMenuItem);
1792    
1793        {
1794            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
1795            item->signal_activate().connect(
1796                sigc::mem_fun(*this, &MainWindow::setupMacros)
1797            );
1798            menuMacro->append(*item);
1799            item->set_accel_path("<Macros>/SetupMacros");
1800        }
1801    
1802    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1803        menuMacro->show_all_children();
1804    #endif
1805    }
1806    
1807    void MainWindow::onMacroSelected(int iMacro) {
1808        printf("onMacroSelected(%d)\n", iMacro);
1809        if (iMacro < 0 || iMacro >= m_macros.size()) return;
1810        Glib::ustring errorText;
1811        try {
1812            applyMacro(m_macros[iMacro]);
1813        } catch (Serialization::Exception e) {
1814            errorText = e.Message;
1815        } catch (...) {
1816            errorText = _("Unknown exception while applying macro");
1817        }
1818        if (!errorText.empty()) {
1819            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
1820            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1821            msg.run();
1822        }
1823    }
1824    
1825    void MainWindow::setupMacros() {
1826        MacrosSetup* setup = new MacrosSetup();
1827        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
1828        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
1829        setup->signal_macros_changed().connect(
1830            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
1831        );
1832        setup->show();
1833    }
1834    
1835    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
1836        m_macros = macros;
1837        Settings::singleton()->saveMacros(m_macros);
1838        updateMacroMenu();
1839    }
1840    
1841    //NOTE: the actual signal's first argument for argument 'page' is on some gtkmm version GtkNotebookPage* and on some Gtk::Widget*. Since we don't need that argument, it is simply void* here for now.
1842    void MainWindow::on_notebook_tab_switched(void* page, guint page_num) {
1843        bool isInstrumentsPage = (page_num == 1);
1844        // so far we only support filtering for the instruments list, so hide the
1845        // filter text entry field if another tab is selected
1846        m_searchField.set_visible(isInstrumentsPage);
1847    }
1848    
1849  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
1850  {  {
1851      return !file_is_shared && file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
# Line 391  void MainWindow::region_changed() Line 1864  void MainWindow::region_changed()
1864    
1865  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1866  {  {
1867      gig::Instrument* instrument = 0;      gig::Instrument* instrument = NULL;
     Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();  
1868    
1869      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      // get indeces of visual selection
1870        std::vector<Gtk::TreeModel::Path> rows = m_TreeViewInstruments.get_selection()->get_selected_rows();
1871        if (rows.empty()) return NULL;
1872    
1873        // convert index of visual selection (i.e. if filtered) to index of model
1874        Gtk::TreeModel::Path path = m_refInstrumentsModelFilter->convert_path_to_child_path(rows[0]);
1875        if (!path) return NULL;
1876    
1877        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
1878        Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(path);
1879      if (it) {      if (it) {
1880          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1881          instrument = row[m_Columns.m_col_instr];          instrument = row[m_InstrumentsModel.m_col_instr];
1882      }      }
1883      return instrument;      return instrument;
1884  }  }
# Line 437  void MainWindow::update_dimregs() Line 1918  void MainWindow::update_dimregs()
1918              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1919          }          }
1920      }      }
1921    
1922        m_RegionChooser.setModifyAllRegions(all_regions);
1923        m_DimRegionChooser.setModifyAllRegions(all_regions);
1924        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1925        m_DimRegionChooser.setModifyBothChannels(stereo);
1926    
1927        updateClipboardCopyAvailable();
1928  }  }
1929    
1930  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 448  void MainWindow::dimreg_all_dimregs_togg Line 1936  void MainWindow::dimreg_all_dimregs_togg
1936  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1937  {  {
1938      update_dimregs();      update_dimregs();
1939      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1940  }  }
1941    
1942  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1943  {  {
1944      m_RegionChooser.set_instrument(get_instrument());  #if !USE_GTKMM_BUILDER
1945        // select item in instrument menu
1946        std::vector<Gtk::TreeModel::Path> rows = m_TreeViewInstruments.get_selection()->get_selected_rows();
1947        if (!rows.empty()) {
1948            // convert index of visual selection (i.e. if filtered) to index of model
1949            Gtk::TreeModel::Path row = m_refInstrumentsModelFilter->convert_path_to_child_path(rows[0]);
1950            Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(row);
1951            if (it) {
1952                Gtk::TreePath path(it);
1953                int index = path[0];
1954                const std::vector<Gtk::Widget*> children =
1955                    instrument_menu->get_children();
1956                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1957            }
1958        }
1959    #endif
1960    
1961        updateScriptListOfMenu();
1962    
1963        gig::Instrument* instr = get_instrument();
1964    
1965        m_RegionChooser.set_instrument(instr);
1966        dimreg_edit.scriptVars.setInstrument(instr, true/*force update*/);
1967    
1968        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1969            switch_sampler_instrument_signal.emit(get_instrument());
1970        }
1971    }
1972    
1973    
1974    LoaderSaverBase::LoaderSaverBase(const Glib::ustring filename, gig::File* gig) :
1975        filename(filename), gig(gig),
1976    #ifdef GLIB_THREADS
1977        thread(0),
1978    #endif
1979        progress(0.f)
1980    {
1981  }  }
1982    
1983  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
1984  {  {
1985      Loader* loader = static_cast<Loader*>(progress->custom);      LoaderSaverBase* loader = static_cast<LoaderSaverBase*>(progress->custom);
1986      loader->progress_callback(progress->factor);      loader->progress_callback(progress->factor);
1987  }  }
1988    
1989  void Loader::progress_callback(float fraction)  void LoaderSaverBase::progress_callback(float fraction)
1990  {  {
1991      {      {
1992    #ifdef GLIB_THREADS
1993          Glib::Threads::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1994    #else
1995            std::lock_guard<std::mutex> lock(progressMutex);
1996    #endif
1997          progress = fraction;          progress = fraction;
1998      }      }
1999      progress_dispatcher();      progress_dispatcher();
2000  }  }
2001    
2002  void Loader::thread_function()  #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
2003    // make sure stack is 16-byte aligned for SSE instructions
2004    __attribute__((force_align_arg_pointer))
2005    #endif
2006    void LoaderSaverBase::thread_function()
2007  {  {
2008      printf("thread_function self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2009      printf("Start %s\n", filename);      printf("thread_function self=%p\n",
2010      RIFF::File* riff = new RIFF::File(filename);             static_cast<void*>(Glib::Threads::Thread::self()));
2011      gig = new gig::File(riff);  #else
2012      gig::progress_t progress;      std::cout << "thread_function self=" << std::this_thread::get_id() << "\n";
2013      progress.callback = loader_progress_callback;  #endif
2014      progress.custom = this;      printf("Start %s\n", filename.c_str());
2015        try {
2016            gig::progress_t progress;
2017            progress.callback = loader_progress_callback;
2018            progress.custom = this;
2019    
2020            thread_function_sub(progress);
2021            printf("End\n");
2022            finished_dispatcher();
2023        } catch (RIFF::Exception e) {
2024            error_message = e.Message;
2025            error_dispatcher.emit();
2026        } catch (...) {
2027            error_message = _("Unknown exception occurred");
2028            error_dispatcher.emit();
2029        }
2030    }
2031    
2032      gig->GetInstrument(0, &progress);  void LoaderSaverBase::launch()
2033      printf("End\n");  {
2034      finished_dispatcher();  #ifdef GLIB_THREADS
2035    #ifdef OLD_THREADS
2036        thread = Glib::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function), true);
2037    #else
2038        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function));
2039    #endif
2040        printf("launch thread=%p\n", static_cast<void*>(thread));
2041    #else
2042        thread = std::thread([this](){ thread_function(); });
2043        std::cout << "launch thread=" << thread.get_id() << "\n";
2044    #endif
2045  }  }
2046    
2047  Loader::Loader(const char* filename)  float LoaderSaverBase::get_progress()
     : filename(filename), thread(0)  
2048  {  {
2049    #ifdef GLIB_THREADS
2050        Glib::Threads::Mutex::Lock lock(progressMutex);
2051    #else
2052        std::lock_guard<std::mutex> lock(progressMutex);
2053    #endif
2054        return progress;
2055  }  }
2056    
2057  void Loader::launch()  Glib::Dispatcher& LoaderSaverBase::signal_progress()
2058  {  {
2059  #ifdef OLD_THREADS      return progress_dispatcher;
2060      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);  }
2061    
2062    Glib::Dispatcher& LoaderSaverBase::signal_finished()
2063    {
2064        return finished_dispatcher;
2065    }
2066    
2067    Glib::Dispatcher& LoaderSaverBase::signal_error()
2068    {
2069        return error_dispatcher;
2070    }
2071    
2072    void LoaderSaverBase::join() {
2073    #ifdef GLIB_THREADS
2074        thread->join();
2075  #else  #else
2076      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread.join();
2077  #endif  #endif
     printf("launch thread=%x\n", thread);  
2078  }  }
2079    
2080  float Loader::get_progress()  
2081    Loader::Loader(const char* filename) :
2082        LoaderSaverBase(filename, 0)
2083  {  {
     float res;  
     {  
         Glib::Threads::Mutex::Lock lock(progressMutex);  
         res = progress;  
     }  
     return res;  
2084  }  }
2085    
2086  Glib::Dispatcher& Loader::signal_progress()  void Loader::thread_function_sub(gig::progress_t& progress)
2087  {  {
2088      return progress_dispatcher;      RIFF::File* riff = new RIFF::File(filename);
2089        gig = new gig::File(riff);
2090    
2091        gig->GetInstrument(0, &progress);
2092  }  }
2093    
2094  Glib::Dispatcher& Loader::signal_finished()  
2095    Saver::Saver(gig::File* file, Glib::ustring filename) :
2096        LoaderSaverBase(filename, file)
2097  {  {
     return finished_dispatcher;  
2098  }  }
2099    
2100  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  void Saver::thread_function_sub(gig::progress_t& progress)
2101    {
2102        // if no filename was provided, that means "save", if filename was provided means "save as"
2103        if (filename.empty()) {
2104            if (!Settings::singleton()->saveWithTemporaryFile) {
2105                // save directly over the existing .gig file
2106                // (requires less disk space than solution below
2107                // but may be slower)
2108                gig->Save(&progress);
2109            } else {
2110                // save the file as separate temporary file first,
2111                // then move the saved file over the old file
2112                // (may result in performance speedup during save)
2113                gig::String tmpname = filename + ".TMP";
2114                gig->Save(tmpname, &progress);
2115    #if defined(WIN32)
2116                if (!DeleteFile(filename.c_str())) {
2117                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
2118                }
2119    #else // POSIX ...
2120                if (unlink(filename.c_str())) {
2121                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
2122                }
2123    #endif
2124                if (rename(tmpname.c_str(), filename.c_str())) {
2125    #if defined(WIN32)
2126                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
2127    #else
2128                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
2129    #endif
2130                }
2131            }
2132        } else {
2133            gig->Save(filename, &progress);
2134        }
2135    }
2136    
2137    
2138    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
2139      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
2140  {  {
2141    #if USE_GTKMM_BOX
2142        get_content_area()->pack_start(progressBar);
2143    #else
2144      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
2145    #endif
2146    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2147      show_all_children();      show_all_children();
2148    #endif
2149        resize(600,50);
2150  }  }
2151    
2152  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
2153  // 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.
2154  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();  
     Gtk::Menu* menu = instrument_menu->get_submenu();  
     while (menu->get_children().size()) {  
         Gtk::Widget* child = *menu->get_children().begin();  
         menu->remove(*child);  
         delete child;  
     }  
2155      // forget all samples that ought to be imported      // forget all samples that ought to be imported
2156      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
2157      // clear the samples and instruments tree views      // clear the samples and instruments tree views
2158      m_refTreeModel->clear();      m_refInstrumentsTreeModel->clear();
2159      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
2160        m_refScriptsTreeModel->clear();
2161    #if !USE_GTKMM_BUILDER
2162        // remove all entries from "Instrument" menu
2163        while (!instrument_menu->get_children().empty()) {
2164            remove_instrument_from_menu(0);
2165        }
2166    #endif
2167      // free libgig's gig::File instance      // free libgig's gig::File instance
2168      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
2169      file = NULL;      file = NULL;
2170      set_file_is_shared(false);      set_file_is_shared(false);
2171  }  }
2172    
2173    void MainWindow::__refreshEntireGUI() {
2174        // clear the samples and instruments tree views
2175        m_refInstrumentsTreeModel->clear();
2176        m_refSamplesTreeModel->clear();
2177        m_refScriptsTreeModel->clear();
2178    #if !USE_GTKMM_BUILDER
2179        // remove all entries from "Instrument" menu
2180        while (!instrument_menu->get_children().empty()) {
2181            remove_instrument_from_menu(0);
2182        }
2183    #endif
2184    
2185        if (!this->file) return;
2186    
2187        load_gig(
2188            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
2189        );
2190    }
2191    
2192  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
2193  {  {
2194      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 564  void MainWindow::on_action_file_new() Line 2201  void MainWindow::on_action_file_new()
2201      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
2202      // already add one new instrument by default      // already add one new instrument by default
2203      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
2204      pInstrument->pInfo->Name = _("Unnamed Instrument");      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
2205      // update GUI with that new gig::File      // update GUI with that new gig::File
2206      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
2207  }  }
# Line 577  bool MainWindow::close_confirmation_dial Line 2214  bool MainWindow::close_confirmation_dial
2214      g_free(msg);      g_free(msg);
2215      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."));
2216      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
2217    #if HAS_GTKMM_STOCK
2218      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2219      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);
2220    #else
2221        dialog.add_button(_("_OK"), Gtk::RESPONSE_OK);
2222        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2223    #endif
2224      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
2225      int response = dialog.run();      int response = dialog.run();
2226      dialog.hide();      dialog.hide();
2227      if (response == Gtk::RESPONSE_YES) return file_save();  
2228      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
2229        if (response == Gtk::RESPONSE_NO) return true;
2230    
2231        // user cancelled dialog, thus don't close app
2232        if (response == Gtk::RESPONSE_CANCEL) return false;
2233    
2234        // TODO: the following return valid is disabled and hard coded instead for
2235        // now, due to the fact that saving with progress bar is now implemented
2236        // asynchronously, as a result the app does not close automatically anymore
2237        // after saving the file has completed
2238        //
2239        //   if (response == Gtk::RESPONSE_YES) return file_save();
2240        //   return response != Gtk::RESPONSE_CANCEL;
2241        //
2242        if (response == Gtk::RESPONSE_YES) file_save();
2243        return false; // always prevent closing the app for now (see comment above)
2244  }  }
2245    
2246  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 594  bool MainWindow::leaving_shared_mode_dia Line 2251  bool MainWindow::leaving_shared_mode_dia
2251            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
2252            "load it."));            "load it."));
2253      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
2254    #if HAS_GTKMM_STOCK
2255      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2256    #else
2257        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2258    #endif
2259      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
2260      int response = dialog.run();      int response = dialog.run();
2261      dialog.hide();      dialog.hide();
# Line 608  void MainWindow::on_action_file_open() Line 2269  void MainWindow::on_action_file_open()
2269      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
2270    
2271      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
2272    #if HAS_GTKMM_STOCK
2273      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2274      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2275    #else
2276        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2277        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2278    #endif
2279      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2280  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2281      Gtk::FileFilter filter;      Gtk::FileFilter filter;
# Line 623  void MainWindow::on_action_file_open() Line 2289  void MainWindow::on_action_file_open()
2289          dialog.set_current_folder(current_gig_dir);          dialog.set_current_folder(current_gig_dir);
2290      }      }
2291      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2292            dialog.hide();
2293          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
2294          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
2295          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2296            printf("on_action_file_open self=%p\n",
2297                   static_cast<void*>(Glib::Threads::Thread::self()));
2298    #else
2299            std::cout << "on_action_file_open self=" <<
2300                std::this_thread::get_id() << "\n";
2301    #endif
2302          load_file(filename.c_str());          load_file(filename.c_str());
2303          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
2304      }      }
# Line 634  void MainWindow::on_action_file_open() Line 2307  void MainWindow::on_action_file_open()
2307  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
2308  {  {
2309      __clear();      __clear();
2310      load_dialog = new LoadDialog(_("Loading..."), *this);  
2311      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2312      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
2313            Glib::filename_display_basename(name) + "' ...",
2314            *this
2315        );
2316    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2317        progress_dialog->show_all();
2318    #endif
2319        loader = new Loader(name); //FIXME: memory leak!
2320      loader->signal_progress().connect(      loader->signal_progress().connect(
2321          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
2322      loader->signal_finished().connect(      loader->signal_finished().connect(
2323          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
2324        loader->signal_error().connect(
2325            sigc::mem_fun(*this, &MainWindow::on_loader_error));
2326      loader->launch();      loader->launch();
2327  }  }
2328    
# Line 656  void MainWindow::load_instrument(gig::In Line 2338  void MainWindow::load_instrument(gig::In
2338      // load the instrument      // load the instrument
2339      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
2340      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
2341      //TODO: automatically select the given instrument      // automatically select the given instrument
2342        int i = 0;
2343        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
2344             instrument = pFile->GetNextInstrument(), ++i)
2345        {
2346            if (instrument == instr) {
2347                // select item in "instruments" tree view
2348                m_TreeViewInstruments.get_selection()->select(Gtk::TreePath(ToString(i)));
2349                // make sure the selected item in the "instruments" tree view is
2350                // visible (scroll to it)
2351                m_TreeViewInstruments.scroll_to_row(Gtk::TreePath(ToString(i)));
2352    #if !USE_GTKMM_BUILDER
2353                // select item in instrument menu
2354                {
2355                    const std::vector<Gtk::Widget*> children =
2356                        instrument_menu->get_children();
2357                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
2358                }
2359    #endif
2360                // update region chooser and dimension region chooser
2361                m_RegionChooser.set_instrument(instr);
2362                break;
2363            }
2364        }
2365  }  }
2366    
2367  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
2368  {  {
2369      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
2370  }  }
2371    
2372  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
2373  {  {
2374        loader->join();
2375      printf("Loader finished!\n");      printf("Loader finished!\n");
2376      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2377      load_gig(loader->gig, loader->filename);      printf("on_loader_finished self=%p\n",
2378      load_dialog->hide();             static_cast<void*>(Glib::Threads::Thread::self()));
2379    #else
2380        std::cout << "on_loader_finished self=" <<
2381            std::this_thread::get_id() << "\n";
2382    #endif
2383        load_gig(loader->gig, loader->filename.c_str());
2384        progress_dialog->hide();
2385    }
2386    
2387    void MainWindow::on_loader_error()
2388    {
2389        loader->join();
2390        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
2391        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2392        msg.run();
2393        progress_dialog->hide();
2394  }  }
2395    
2396  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 708  bool MainWindow::file_save() Line 2429  bool MainWindow::file_save()
2429    
2430      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
2431      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
2432      try {  
2433          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2434          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
2435              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
2436              file_is_changed = false;          *this
2437          }      );
2438      } catch (RIFF::Exception e) {  #if HAS_GTKMM_SHOW_ALL_CHILDREN
2439          file_structure_changed_signal.emit(this->file);      progress_dialog->show_all();
2440          Glib::ustring txt = _("Could not save file: ") + e.Message;  #endif
2441          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);      saver = new Saver(this->file); //FIXME: memory leak!
2442          msg.run();      saver->signal_progress().connect(
2443          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2444      }      saver->signal_finished().connect(
2445      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2446        saver->signal_error().connect(
2447            sigc::mem_fun(*this, &MainWindow::on_saver_error));
2448        saver->launch();
2449    
2450        return true;
2451    }
2452    
2453    void MainWindow::on_saver_progress()
2454    {
2455        progress_dialog->set_fraction(saver->get_progress());
2456    }
2457    
2458    void MainWindow::on_saver_error()
2459    {
2460        saver->join();
2461        file_structure_changed_signal.emit(this->file);
2462        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
2463        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2464        msg.run();
2465    }
2466    
2467    void MainWindow::on_saver_finished()
2468    {
2469        saver->join();
2470        this->file = saver->gig;
2471        this->filename = saver->filename;
2472        current_gig_dir = Glib::path_get_dirname(filename);
2473        set_title(Glib::filename_display_basename(filename));
2474        file_has_name = true;
2475        file_is_changed = false;
2476        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
2477      __import_queued_samples();      __import_queued_samples();
2478        std::cout << "Importing queued samples done.\n" << std::flush;
2479    
2480      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
2481      return true;  
2482        __refreshEntireGUI();
2483        progress_dialog->hide();
2484  }  }
2485    
2486  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 736  void MainWindow::on_action_file_save_as( Line 2492  void MainWindow::on_action_file_save_as(
2492  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
2493  {  {
2494      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
2495    #if HAS_GTKMM_STOCK
2496      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2497      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
2498    #else
2499        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2500        dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
2501    #endif
2502      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2503      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
2504    
# Line 766  bool MainWindow::file_save_as() Line 2527  bool MainWindow::file_save_as()
2527      }      }
2528    
2529      // show warning in the dialog      // show warning in the dialog
2530      Gtk::HBox descriptionArea;      HBox descriptionArea;
2531      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
2532      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
2533        warningIcon.set_from_icon_name("dialog-warning",
2534                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
2535      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
2536    #if GTKMM_MAJOR_VERSION < 3
2537      view::WrapLabel description;      view::WrapLabel description;
2538    #else
2539        Gtk::Label description;
2540        description.set_line_wrap();
2541    #endif
2542      description.set_markup(      description.set_markup(
2543          _("\n<b>CAUTION:</b> You <b>MUST</b> use the "          _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
2544            "<span style=\"italic\">\"Save\"</span> dialog instead of "            "<span style=\"italic\">\"Save\"</span> dialog instead of "
# Line 780  bool MainWindow::file_save_as() Line 2548  bool MainWindow::file_save_as()
2548            "same .gig file will end up in corrupted sample wave data!\n")            "same .gig file will end up in corrupted sample wave data!\n")
2549      );      );
2550      descriptionArea.pack_start(description);      descriptionArea.pack_start(description);
2551    #if USE_GTKMM_BOX
2552        dialog.get_content_area()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2553    #else
2554      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2555    #endif
2556    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2557      descriptionArea.show_all();      descriptionArea.show_all();
2558    #endif
2559    
2560      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2561          file_structure_to_be_changed_signal.emit(this->file);          dialog.hide();
2562          try {          std::string filename = dialog.get_filename();
2563              std::string filename = dialog.get_filename();          if (!Glib::str_has_suffix(filename, ".gig")) {
2564              if (!Glib::str_has_suffix(filename, ".gig")) {              filename += ".gig";
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_gig_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;  
2565          }          }
2566          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
2567          file_structure_changed_signal.emit(this->file);  
2568            progress_dialog = new ProgressDialog( //FIXME: memory leak!
2569                _("Saving") +  Glib::ustring(" '") +
2570                Glib::filename_display_basename(filename) + "' ...",
2571                *this
2572            );
2573    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2574            progress_dialog->show_all();
2575    #endif
2576    
2577            saver = new Saver(file, filename); //FIXME: memory leak!
2578            saver->signal_progress().connect(
2579                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2580            saver->signal_finished().connect(
2581                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2582            saver->signal_error().connect(
2583                sigc::mem_fun(*this, &MainWindow::on_saver_error));
2584            saver->launch();
2585    
2586          return true;          return true;
2587      }      }
2588      return false;      return false;
# Line 815  bool MainWindow::file_save_as() Line 2592  bool MainWindow::file_save_as()
2592  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
2593      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
2594      Glib::ustring error_files;      Glib::ustring error_files;
2595      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
2596      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2597           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
2598          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
2599          SF_INFO info;          SF_INFO info;
2600          info.format = 0;          info.format = 0;
2601          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);
2602            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
2603          try {          try {
2604              if (!hFile) throw std::string(_("could not open file"));              if (!hFile) throw std::string(_("could not open file"));
2605              // determine sample's bit depth              // determine sample's bit depth
# Line 843  void MainWindow::__import_queued_samples Line 2621  void MainWindow::__import_queued_samples
2621                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
2622              }              }
2623    
2624                // reset write position for sample
2625                iter->first->SetPos(0);
2626    
2627              const int bufsize = 10000;              const int bufsize = 10000;
2628              switch (bitdepth) {              switch (bitdepth) {
2629                  case 16: {                  case 16: {
# Line 852  void MainWindow::__import_queued_samples Line 2633  void MainWindow::__import_queued_samples
2633                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
2634                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
2635                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2636                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
2637                          cnt -= n;                          cnt -= n;
2638                      }                      }
2639                      delete[] buffer;                      delete[] buffer;
# Line 872  void MainWindow::__import_queued_samples Line 2653  void MainWindow::__import_queued_samples
2653                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
2654                          }                          }
2655                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2656                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
2657                          cnt -= n;                          cnt -= n;
2658                      }                      }
2659                      delete[] srcbuf;                      delete[] srcbuf;
# Line 883  void MainWindow::__import_queued_samples Line 2664  void MainWindow::__import_queued_samples
2664              // cleanup              // cleanup
2665              sf_close(hFile);              sf_close(hFile);
2666              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
2667              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
2668              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
2669              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
2670              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
2671              ++iter;              ++iter;
2672              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
2673          } catch (std::string what) {          } catch (std::string what) {
2674              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
2675              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
2676              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
2677              ++iter;              ++iter;
2678          }          }
2679      }      }
2680      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
2681      if (error_files.size()) {      if (!error_files.empty()) {
2682          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;
2683          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2684          msg.run();          msg.run();
# Line 906  void MainWindow::__import_queued_samples Line 2687  void MainWindow::__import_queued_samples
2687    
2688  void MainWindow::on_action_file_properties()  void MainWindow::on_action_file_properties()
2689  {  {
2690      propDialog.show();      fileProps.show();
2691      propDialog.deiconify();      fileProps.deiconify();
2692    }
2693    
2694    void MainWindow::on_action_warn_user_on_extensions() {
2695        Settings::singleton()->warnUserOnExtensions =
2696            !Settings::singleton()->warnUserOnExtensions;
2697    }
2698    
2699    void MainWindow::on_action_show_tooltips() {
2700        Settings::singleton()->showTooltips =
2701            !Settings::singleton()->showTooltips;
2702    
2703        on_show_tooltips_changed();
2704    }
2705    
2706    void MainWindow::on_show_tooltips_changed() {
2707        const bool b = Settings::singleton()->showTooltips;
2708    
2709        dimreg_label.set_has_tooltip(b);
2710        dimreg_all_regions.set_has_tooltip(b);
2711        dimreg_all_dimregs.set_has_tooltip(b);
2712        dimreg_stereo.set_has_tooltip(b);
2713    
2714        // Not doing this here, we let onQueryTreeViewTooltip() handle this per cell
2715        //m_TreeViewInstruments.set_has_tooltip(b);
2716    
2717        m_TreeViewSamples.set_has_tooltip(b);
2718        m_TreeViewScripts.set_has_tooltip(b);
2719    
2720        set_has_tooltip(b);
2721    }
2722    
2723    void MainWindow::on_action_sync_sampler_instrument_selection() {
2724        Settings::singleton()->syncSamplerInstrumentSelection =
2725            !Settings::singleton()->syncSamplerInstrumentSelection;
2726    }
2727    
2728    void MainWindow::on_action_move_root_note_with_region_moved() {
2729        Settings::singleton()->moveRootNoteWithRegionMoved =
2730            !Settings::singleton()->moveRootNoteWithRegionMoved;
2731  }  }
2732    
2733  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
# Line 919  void MainWindow::on_action_help_about() Line 2739  void MainWindow::on_action_help_about()
2739      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
2740  #endif  #endif
2741      dialog.set_version(VERSION);      dialog.set_version(VERSION);
2742      dialog.set_copyright("Copyright (C) 2006-2012 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2019 Andreas Persson");
2743      dialog.set_comments(_(      const std::string sComment =
2744          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
2745          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
2746          "Please notice that this is still a very young instrument editor. "          _(
2747          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
2748          "this application.\n"              "\n"
2749          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
2750          "Please report bugs to: http://bugs.linuxsampler.org")              "backup your Gigasampler/GigaStudio files before editing them with "
2751      );              "this application.\n"
2752      dialog.set_website("http://www.linuxsampler.org");              "\n"
2753      dialog.set_website_label("http://www.linuxsampler.org");              "Please report bugs to: https://bugs.linuxsampler.org"
2754            );
2755        dialog.set_comments(sComment.c_str());
2756        dialog.set_website("https://www.linuxsampler.org");
2757        dialog.set_website_label("https://www.linuxsampler.org");
2758        dialog.set_position(Gtk::WIN_POS_CENTER);
2759      dialog.run();      dialog.run();
2760  }  }
2761    
2762  PropDialog::PropDialog()  FilePropDialog::FilePropDialog()
2763      : eName(_("Name")),      : eFileFormat(_("File Format")),
2764          eName(_("Name")),
2765        eCreationDate(_("Creation date")),        eCreationDate(_("Creation date")),
2766        eComments(_("Comments")),        eComments(_("Comments")),
2767        eProduct(_("Product")),        eProduct(_("Product")),
# Line 951  PropDialog::PropDialog() Line 2777  PropDialog::PropDialog()
2777        eSourceForm(_("Source form")),        eSourceForm(_("Source form")),
2778        eCommissioned(_("Commissioned")),        eCommissioned(_("Commissioned")),
2779        eSubject(_("Subject")),        eSubject(_("Subject")),
2780    #if HAS_GTKMM_STOCK
2781        quitButton(Gtk::Stock::CLOSE),        quitButton(Gtk::Stock::CLOSE),
2782    #else
2783          quitButton(_("_Close")),
2784    #endif
2785        table(2, 1),        table(2, 1),
2786        update_model(0)        m_file(NULL)
2787  {  {
2788        if (!Settings::singleton()->autoRestoreWindowDimension) {
2789            set_default_size(470, 390);
2790            set_position(Gtk::WIN_POS_MOUSE);
2791        }
2792    
2793      set_title(_("File Properties"));      set_title(_("File Properties"));
2794      eName.set_width_chars(50);      eName.set_width_chars(50);
2795    
2796        connect(eFileFormat, &FilePropDialog::set_FileFormat);
2797      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
2798      connect(eCreationDate, &DLS::Info::CreationDate);      connect(eCreationDate, &DLS::Info::CreationDate);
2799      connect(eComments, &DLS::Info::Comments);      connect(eComments, &DLS::Info::Comments);
# Line 975  PropDialog::PropDialog() Line 2811  PropDialog::PropDialog()
2811      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
2812      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
2813    
2814        table.add(eFileFormat);
2815      table.add(eName);      table.add(eName);
2816      table.add(eCreationDate);      table.add(eCreationDate);
2817      table.add(eComments);      table.add(eComments);
# Line 992  PropDialog::PropDialog() Line 2829  PropDialog::PropDialog()
2829      table.add(eCommissioned);      table.add(eCommissioned);
2830      table.add(eSubject);      table.add(eSubject);
2831    
2832    #if USE_GTKMM_GRID
2833        table.set_column_spacing(5);
2834    #else
2835      table.set_col_spacings(5);      table.set_col_spacings(5);
2836    #endif
2837    
2838      add(vbox);      add(vbox);
2839    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2840        table.set_margin(5);
2841    #else
2842      table.set_border_width(5);      table.set_border_width(5);
2843    #endif
2844      vbox.add(table);      vbox.add(table);
2845      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
2846      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
2847    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2848        buttonBox.set_margin(5);
2849    #else
2850      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2851    #endif
2852      buttonBox.show();      buttonBox.show();
2853      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2854      quitButton.set_can_default();      quitButton.set_can_default();
2855      quitButton.grab_focus();      quitButton.grab_focus();
2856      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
2857          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &FilePropDialog::hide));
2858    
2859      quitButton.show();      quitButton.show();
2860      vbox.show();      vbox.show();
2861    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2862      show_all_children();      show_all_children();
2863    #endif
2864  }  }
2865    
2866  void PropDialog::set_info(DLS::Info* info)  void FilePropDialog::set_file(gig::File* file)
2867  {  {
2868      this->info = info;      m_file = file;
2869        update(file->pInfo);
2870    
2871        // update file format version combo box
2872        const std::string sGiga = "Gigasampler/GigaStudio v";
2873        const int major = file->pVersion->major;
2874        std::vector<std::string> txts;
2875        std::vector<int> values;
2876        txts.push_back(sGiga + "2"); values.push_back(2);
2877        txts.push_back(sGiga + "3"); values.push_back(3);
2878        txts.push_back(sGiga + "4"); values.push_back(4);
2879        if (major < 2 || major > 4) {
2880            txts.push_back(sGiga + ToString(major)); values.push_back(major);
2881        }
2882        std::vector<const char*> texts;
2883        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
2884        texts.push_back(NULL); values.push_back(0);
2885    
2886      update_model++;      update_model++;
2887      eName.set_value(info->Name);      eFileFormat.set_choices(&texts[0], &values[0]);
2888      eCreationDate.set_value(info->CreationDate);      eFileFormat.set_value(major);
     eComments.set_value(info->Comments);  
     eProduct.set_value(info->Product);  
     eCopyright.set_value(info->Copyright);  
     eArtists.set_value(info->Artists);  
     eGenre.set_value(info->Genre);  
     eKeywords.set_value(info->Keywords);  
     eEngineer.set_value(info->Engineer);  
     eTechnician.set_value(info->Technician);  
     eSoftware.set_value(info->Software);  
     eMedium.set_value(info->Medium);  
     eSource.set_value(info->Source);  
     eSourceForm.set_value(info->SourceForm);  
     eCommissioned.set_value(info->Commissioned);  
     eSubject.set_value(info->Subject);  
2889      update_model--;      update_model--;
2890  }  }
2891    
2892  sigc::signal<void>& PropDialog::signal_info_changed()  void FilePropDialog::set_FileFormat(int value)
2893  {  {
2894      return info_changed;      m_file->pVersion->major = value;
2895  }  }
2896    
2897  void InstrumentProps::set_IsDrum(bool value)  
2898    void InstrumentProps::set_Name(const gig::String& name)
2899  {  {
2900      instrument->IsDrum = value;      m->pInfo->Name = name;
2901  }  }
2902    
2903  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
2904  {  {
2905      instrument->MIDIBank = value;      update_model++;
2906        eName.set_value(m->pInfo->Name);
2907        update_model--;
2908  }  }
2909    
2910  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
2911  {  {
2912      instrument->MIDIProgram = value;      m->IsDrum = value;
2913  }  }
2914    
2915  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
2916  {  {
2917      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
2918  }  }
2919    
2920  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
2921  {  {
2922      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
2923  }  }
2924    
2925  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
2926      : update_model(0),  #if HAS_GTKMM_STOCK
2927        quitButton(Gtk::Stock::CLOSE),      quitButton(Gtk::Stock::CLOSE),
2928        table(2,1),  #else
2929        eName(_("Name")),      quitButton(_("_Close")),
2930        eIsDrum(_("Is drum")),  #endif
2931        eMIDIBank(_("MIDI bank"), 0, 16383),      table(2,1),
2932        eMIDIProgram(_("MIDI program")),      eName(_("Name")),
2933        eAttenuation(_("Attenuation"), 0, 96, 0, 1),      eIsDrum(_("Is drum")),
2934        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),      eMIDIBank(_("MIDI bank"), 0, 16383),
2935        eEffectSend(_("Effect send"), 0, 65535),      eMIDIProgram(_("MIDI program")),
2936        eFineTune(_("Fine tune"), -8400, 8400),      eAttenuation(_("Attenuation (dB)"), -96, +96, 0, 1),
2937        ePitchbendRange(_("Pitchbend range"), 0, 12),      eEffectSend(_("Effect send"), 0, 65535),
2938        ePianoReleaseMode(_("Piano release mode")),      eFineTune(_("Fine tune"), -8400, 8400),
2939        eDimensionKeyRangeLow(_("Keyswitching range low")),      ePitchbendRange(_("Pitchbend range (halftones)"), 0, 48),
2940        eDimensionKeyRangeHigh(_("Keyswitching range high"))      ePianoReleaseMode(_("Piano release mode")),
2941  {      eDimensionKeyRangeLow(_("Keyswitching range low")),
2942        eDimensionKeyRangeHigh(_("Keyswitching range high")),
2943        table2(2,1),
2944        eName2(_("Name")),
2945        eCreationDate(_("Creation date")),
2946        eComments(_("Comments")),
2947        eProduct(_("Product")),
2948        eCopyright(_("Copyright")),
2949        eArtists(_("Artists")),
2950        eGenre(_("Genre")),
2951        eKeywords(_("Keywords")),
2952        eEngineer(_("Engineer")),
2953        eTechnician(_("Technician")),
2954        eSoftware(_("Software")),
2955        eMedium(_("Medium")),
2956        eSource(_("Source")),
2957        eSourceForm(_("Source form")),
2958        eCommissioned(_("Commissioned")),
2959        eSubject(_("Subject"))
2960    {
2961        if (!Settings::singleton()->autoRestoreWindowDimension) {
2962            //set_default_size(470, 390);
2963            set_position(Gtk::WIN_POS_MOUSE);
2964        }
2965    
2966      set_title(_("Instrument Properties"));      set_title(_("Instrument Properties"));
2967    
2968        tabs.append_page(vbox[1], _("Settings"));
2969        tabs.append_page(vbox[2], _("Info"));
2970    
2971      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
2972          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
2973            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
# Line 1098  InstrumentProps::InstrumentProps() Line 2977  InstrumentProps::InstrumentProps()
2977            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
2978      );      );
2979    
2980        connect(eName, &InstrumentProps::set_Name);
2981      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
2982      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
2983      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
2984      connect(eAttenuation, &gig::Instrument::Attenuation);      connect(eAttenuation, &gig::Instrument::Attenuation);
     connect(eGainPlus6, &gig::Instrument::Attenuation);  
2985      connect(eEffectSend, &gig::Instrument::EffectSend);      connect(eEffectSend, &gig::Instrument::EffectSend);
2986      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
2987      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
2988      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
2989      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
2990              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
     connect(eDimensionKeyRangeHigh,  
             &InstrumentProps::set_DimensionKeyRange_high);  
2991    
2992      table.set_col_spacings(5);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
2993    
2994        connect(eName2, &InstrumentProps::set_Name);
2995        connectLambda(eCreationDate, [this](gig::String s) {
2996            m->pInfo->CreationDate = s;
2997        });
2998        connectLambda(eComments, [this](gig::String s) {
2999            m->pInfo->Comments = s;
3000        });
3001        connectLambda(eProduct, [this](gig::String s) {
3002            m->pInfo->Product = s;
3003        });
3004        connectLambda(eCopyright, [this](gig::String s) {
3005            m->pInfo->Copyright = s;
3006        });
3007        connectLambda(eArtists, [this](gig::String s) {
3008            m->pInfo->Artists = s;
3009        });
3010        connectLambda(eGenre, [this](gig::String s) {
3011            m->pInfo->Genre = s;
3012        });
3013        connectLambda(eKeywords, [this](gig::String s) {
3014            m->pInfo->Keywords = s;
3015        });
3016        connectLambda(eEngineer, [this](gig::String s) {
3017            m->pInfo->Engineer = s;
3018        });
3019        connectLambda(eTechnician, [this](gig::String s) {
3020            m->pInfo->Technician = s;
3021        });
3022        connectLambda(eSoftware, [this](gig::String s) {
3023            m->pInfo->Software = s;
3024        });
3025        connectLambda(eMedium, [this](gig::String s) {
3026            m->pInfo->Medium = s;
3027        });
3028        connectLambda(eSource, [this](gig::String s) {
3029            m->pInfo->Source = s;
3030        });
3031        connectLambda(eSourceForm, [this](gig::String s) {
3032            m->pInfo->SourceForm = s;
3033        });
3034        connectLambda(eCommissioned, [this](gig::String s) {
3035            m->pInfo->Commissioned = s;
3036        });
3037        connectLambda(eSubject, [this](gig::String s) {
3038            m->pInfo->Subject = s;
3039        });
3040    
3041        // tab 1
3042    #if USE_GTKMM_GRID
3043        table.set_column_spacing(5);
3044    #else
3045        table.set_col_spacings(5);
3046    #endif
3047      table.add(eName);      table.add(eName);
3048      table.add(eIsDrum);      table.add(eIsDrum);
3049      table.add(eMIDIBank);      table.add(eMIDIBank);
3050      table.add(eMIDIProgram);      table.add(eMIDIProgram);
3051      table.add(eAttenuation);      table.add(eAttenuation);
     table.add(eGainPlus6);  
3052      table.add(eEffectSend);      table.add(eEffectSend);
3053      table.add(eFineTune);      table.add(eFineTune);
3054      table.add(ePitchbendRange);      table.add(ePitchbendRange);
# Line 1127  InstrumentProps::InstrumentProps() Line 3056  InstrumentProps::InstrumentProps()
3056      table.add(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
3057      table.add(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
3058    
3059      add(vbox);      // tab 2
3060    #if USE_GTKMM_GRID
3061        table2.set_column_spacing(5);
3062    #else
3063        table2.set_col_spacings(5);
3064    #endif
3065        table2.add(eName2);
3066        table2.add(eCreationDate);
3067        table2.add(eComments);
3068        table2.add(eProduct);
3069        table2.add(eCopyright);
3070        table2.add(eArtists);
3071        table2.add(eGenre);
3072        table2.add(eKeywords);
3073        table2.add(eEngineer);
3074        table2.add(eTechnician);
3075        table2.add(eSoftware);
3076        table2.add(eMedium);
3077        table2.add(eSource);
3078        table2.add(eSourceForm);
3079        table2.add(eCommissioned);
3080        table2.add(eSubject);
3081    
3082        add(vbox[0]);
3083    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3084        table.set_margin(5);
3085    #else
3086      table.set_border_width(5);      table.set_border_width(5);
3087      vbox.pack_start(table);  #endif
3088        vbox[1].pack_start(table);
3089        vbox[2].pack_start(table2);
3090      table.show();      table.show();
3091      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      table2.show();
3092        vbox[0].pack_start(tabs);
3093        vbox[0].pack_start(buttonBox, Gtk::PACK_SHRINK);
3094      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
3095    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3096        buttonBox.set_margin(5);
3097    #else
3098      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
3099    #endif
3100      buttonBox.show();      buttonBox.show();
3101      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
3102      quitButton.set_can_default();      quitButton.set_can_default();
# Line 1143  InstrumentProps::InstrumentProps() Line 3106  InstrumentProps::InstrumentProps()
3106          sigc::mem_fun(*this, &InstrumentProps::hide));          sigc::mem_fun(*this, &InstrumentProps::hide));
3107    
3108      quitButton.show();      quitButton.show();
3109      vbox.show();      vbox[0].show();
3110    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3111      show_all_children();      show_all_children();
3112    #endif
3113  }  }
3114    
3115  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
3116  {  {
3117      this->instrument = instrument;      update(instrument);
3118    
3119      update_model++;      update_model++;
3120    
3121        // tab 1
3122      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
3123      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
3124      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
3125      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
3126      eAttenuation.set_value(instrument->Attenuation);      // tab 2
3127      eGainPlus6.set_value(instrument->Attenuation);      eName2.set_value(instrument->pInfo->Name);
3128      eEffectSend.set_value(instrument->EffectSend);      eCreationDate.set_value(instrument->pInfo->CreationDate);
3129      eFineTune.set_value(instrument->FineTune);      eComments.set_value(instrument->pInfo->Comments);
3130      ePitchbendRange.set_value(instrument->PitchbendRange);      eProduct.set_value(instrument->pInfo->Product);
3131      ePianoReleaseMode.set_value(instrument->PianoReleaseMode);      eCopyright.set_value(instrument->pInfo->Copyright);
3132      eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);      eArtists.set_value(instrument->pInfo->Artists);
3133      eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);      eGenre.set_value(instrument->pInfo->Genre);
3134        eKeywords.set_value(instrument->pInfo->Keywords);
3135        eEngineer.set_value(instrument->pInfo->Engineer);
3136        eTechnician.set_value(instrument->pInfo->Technician);
3137        eSoftware.set_value(instrument->pInfo->Software);
3138        eMedium.set_value(instrument->pInfo->Medium);
3139        eSource.set_value(instrument->pInfo->Source);
3140        eSourceForm.set_value(instrument->pInfo->SourceForm);
3141        eCommissioned.set_value(instrument->pInfo->Commissioned);
3142        eSubject.set_value(instrument->pInfo->Subject);
3143    
3144      update_model--;      update_model--;
3145  }  }
3146    
3147  sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
3148    SampleProps::SampleProps() :
3149    #if HAS_GTKMM_STOCK
3150        quitButton(Gtk::Stock::CLOSE),
3151    #else
3152        quitButton(_("_Close")),
3153    #endif
3154        table(2,1),
3155        eName(_("Name")),
3156        eUnityNote(_("Unity Note")),
3157        eSampleGroup(_("Sample Group")),
3158        eSampleFormatInfo(_("Sample Format")),
3159        eSampleID("Sample ID"),
3160        eChecksum("Wave Data CRC-32"),
3161        eLoopsCount(_("Loops"), 0, 1), // we might support more than 1 loop in future
3162        eLoopStart(_("Loop start position"), 0, 9999999),
3163        eLoopLength(_("Loop size"), 0, 9999999),
3164        eLoopType(_("Loop type")),
3165        eLoopPlayCount(_("Playback count")),
3166        table2(2,1),
3167        eName2(_("Name")),
3168        eCreationDate(_("Creation date")),
3169        eComments(_("Comments")),
3170        eProduct(_("Product")),
3171        eCopyright(_("Copyright")),
3172        eArtists(_("Artists")),
3173        eGenre(_("Genre")),
3174        eKeywords(_("Keywords")),
3175        eEngineer(_("Engineer")),
3176        eTechnician(_("Technician")),
3177        eSoftware(_("Software")),
3178        eMedium(_("Medium")),
3179        eSource(_("Source")),
3180        eSourceForm(_("Source form")),
3181        eCommissioned(_("Commissioned")),
3182        eSubject(_("Subject"))
3183    {
3184        if (!Settings::singleton()->autoRestoreWindowDimension) {
3185            //set_default_size(470, 390);
3186            set_position(Gtk::WIN_POS_MOUSE);
3187        }
3188    
3189        set_title(_("Sample Properties"));
3190    
3191        tabs.append_page(vbox[1], _("Settings"));
3192        tabs.append_page(vbox[2], _("Info"));
3193    
3194        connect(eName, &SampleProps::set_Name);
3195        connect(eUnityNote, &gig::Sample::MIDIUnityNote);
3196        connect(eLoopsCount, &gig::Sample::Loops);
3197        connectLambda(eLoopStart, [this](uint32_t start){
3198            m->LoopStart = start;
3199            m->LoopEnd = start + m->LoopSize;
3200        });
3201        connectLambda(eLoopLength, [this](uint32_t length){
3202            m->LoopSize = length;
3203            m->LoopEnd = m->LoopStart + length;
3204        });
3205        {
3206            const char* choices[] = { _("normal"), _("bidirectional"), _("backward"), 0 };
3207            static const gig::loop_type_t values[] = {
3208                gig::loop_type_normal,
3209                gig::loop_type_bidirectional,
3210                gig::loop_type_backward
3211            };
3212            eLoopType.set_choices(choices, values);
3213        }
3214        connect(eLoopType, &gig::Sample::LoopType);
3215        connect(eLoopPlayCount, &gig::Sample::LoopPlayCount);
3216    
3217        eName.signal_value_changed().connect(sig_name_changed.make_slot());
3218    
3219        connect(eName2, &SampleProps::set_Name);
3220        connectLambda(eCreationDate, [this](gig::String s) {
3221            m->pInfo->CreationDate = s;
3222        });
3223        connectLambda(eComments, [this](gig::String s) {
3224            m->pInfo->Comments = s;
3225        });
3226        connectLambda(eProduct, [this](gig::String s) {
3227            m->pInfo->Product = s;
3228        });
3229        connectLambda(eCopyright, [this](gig::String s) {
3230            m->pInfo->Copyright = s;
3231        });
3232        connectLambda(eArtists, [this](gig::String s) {
3233            m->pInfo->Artists = s;
3234        });
3235        connectLambda(eGenre, [this](gig::String s) {
3236            m->pInfo->Genre = s;
3237        });
3238        connectLambda(eKeywords, [this](gig::String s) {
3239            m->pInfo->Keywords = s;
3240        });
3241        connectLambda(eEngineer, [this](gig::String s) {
3242            m->pInfo->Engineer = s;
3243        });
3244        connectLambda(eTechnician, [this](gig::String s) {
3245            m->pInfo->Technician = s;
3246        });
3247        connectLambda(eSoftware, [this](gig::String s) {
3248            m->pInfo->Software = s;
3249        });
3250        connectLambda(eMedium, [this](gig::String s) {
3251            m->pInfo->Medium = s;
3252        });
3253        connectLambda(eSource, [this](gig::String s) {
3254            m->pInfo->Source = s;
3255        });
3256        connectLambda(eSourceForm, [this](gig::String s) {
3257            m->pInfo->SourceForm = s;
3258        });
3259        connectLambda(eCommissioned, [this](gig::String s) {
3260            m->pInfo->Commissioned = s;
3261        });
3262        connectLambda(eSubject, [this](gig::String s) {
3263            m->pInfo->Subject = s;
3264        });
3265    
3266        // tab 1
3267    #if USE_GTKMM_GRID
3268        table.set_column_spacing(5);
3269    #else
3270        table.set_col_spacings(5);
3271    #endif
3272        table.add(eName);
3273        table.add(eUnityNote);
3274        table.add(eSampleGroup);
3275        table.add(eSampleFormatInfo);
3276        table.add(eSampleID);
3277        table.add(eChecksum);
3278        table.add(eLoopsCount);
3279        table.add(eLoopStart);
3280        table.add(eLoopLength);
3281        table.add(eLoopType);
3282        table.add(eLoopPlayCount);
3283    
3284        // tab 2
3285    #if USE_GTKMM_GRID
3286        table2.set_column_spacing(5);
3287    #else
3288        table2.set_col_spacings(5);
3289    #endif
3290        table2.add(eName2);
3291        table2.add(eCreationDate);
3292        table2.add(eComments);
3293        table2.add(eProduct);
3294        table2.add(eCopyright);
3295        table2.add(eArtists);
3296        table2.add(eGenre);
3297        table2.add(eKeywords);
3298        table2.add(eEngineer);
3299        table2.add(eTechnician);
3300        table2.add(eSoftware);
3301        table2.add(eMedium);
3302        table2.add(eSource);
3303        table2.add(eSourceForm);
3304        table2.add(eCommissioned);
3305        table2.add(eSubject);
3306    
3307        add(vbox[0]);
3308    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3309        table.set_margin(5);
3310    #else
3311        table.set_border_width(5);
3312    #endif
3313        vbox[1].pack_start(table);
3314        vbox[2].pack_start(table2);
3315        table.show();
3316        table2.show();
3317        vbox[0].pack_start(tabs);
3318        vbox[0].pack_start(buttonBox, Gtk::PACK_SHRINK);
3319        buttonBox.set_layout(Gtk::BUTTONBOX_END);
3320    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3321        buttonBox.set_margin(5);
3322    #else
3323        buttonBox.set_border_width(5);
3324    #endif
3325        buttonBox.show();
3326        buttonBox.pack_start(quitButton);
3327        quitButton.set_can_default();
3328        quitButton.grab_focus();
3329    
3330        quitButton.signal_clicked().connect(
3331            sigc::mem_fun(*this, &SampleProps::hide));
3332    
3333        quitButton.show();
3334        vbox[0].show();
3335    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3336        show_all_children();
3337    #endif
3338    }
3339    
3340    void SampleProps::set_sample(gig::Sample* sample)
3341    {
3342        update(sample);
3343    
3344        update_model++;
3345    
3346        // tab 1
3347        eName.set_value(sample->pInfo->Name);
3348        eUnityNote.set_value(sample->MIDIUnityNote);
3349        // show sample group name
3350        {
3351            Glib::ustring s = "---";
3352            if (sample && sample->GetGroup())
3353                s = sample->GetGroup()->Name;
3354            eSampleGroup.text.set_text(s);
3355        }
3356        // assemble sample format info string
3357        {
3358            Glib::ustring s;
3359            if (sample) {
3360                switch (sample->Channels) {
3361                    case 1: s = _("Mono"); break;
3362                    case 2: s = _("Stereo"); break;
3363                    default:
3364                        s = ToString(sample->Channels) + _(" audio channels");
3365                        break;
3366                }
3367                s += " " + ToString(sample->BitDepth) + " Bits";
3368                s += " " + ToString(sample->SamplesPerSecond/1000) + "."
3369                         + ToString((sample->SamplesPerSecond%1000)/100) + " kHz";
3370            } else {
3371                s = _("No sample assigned to this dimension region.");
3372            }
3373            eSampleFormatInfo.text.set_text(s);
3374        }
3375        // generate sample's memory address pointer string
3376        {
3377            Glib::ustring s;
3378            if (sample) {
3379                char buf[64] = {};
3380                snprintf(buf, sizeof(buf), "%p", sample);
3381                s = buf;
3382            } else {
3383                s = "---";
3384            }
3385            eSampleID.text.set_text(s);
3386        }
3387        // generate raw wave form data CRC-32 checksum string
3388        {
3389            Glib::ustring s = "---";
3390            if (sample) {
3391                char buf[64] = {};
3392                snprintf(buf, sizeof(buf), "%x", sample->GetWaveDataCRC32Checksum());
3393                s = buf;
3394            }
3395            eChecksum.text.set_text(s);
3396        }
3397        eLoopsCount.set_value(sample->Loops);
3398        eLoopStart.set_value(sample->LoopStart);
3399        eLoopLength.set_value(sample->LoopSize);
3400        eLoopType.set_value(sample->LoopType);
3401        eLoopPlayCount.set_value(sample->LoopPlayCount);
3402        // tab 2
3403        eName2.set_value(sample->pInfo->Name);
3404        eCreationDate.set_value(sample->pInfo->CreationDate);
3405        eComments.set_value(sample->pInfo->Comments);
3406        eProduct.set_value(sample->pInfo->Product);
3407        eCopyright.set_value(sample->pInfo->Copyright);
3408        eArtists.set_value(sample->pInfo->Artists);
3409        eGenre.set_value(sample->pInfo->Genre);
3410        eKeywords.set_value(sample->pInfo->Keywords);
3411        eEngineer.set_value(sample->pInfo->Engineer);
3412        eTechnician.set_value(sample->pInfo->Technician);
3413        eSoftware.set_value(sample->pInfo->Software);
3414        eMedium.set_value(sample->pInfo->Medium);
3415        eSource.set_value(sample->pInfo->Source);
3416        eSourceForm.set_value(sample->pInfo->SourceForm);
3417        eCommissioned.set_value(sample->pInfo->Commissioned);
3418        eSubject.set_value(sample->pInfo->Subject);
3419    
3420        update_model--;
3421    }
3422    
3423    void SampleProps::set_Name(const gig::String& name)
3424  {  {
3425      return instrument_changed;      m->pInfo->Name = name;
3426    }
3427    
3428    void SampleProps::update_name()
3429    {
3430        update_model++;
3431        eName.set_value(m->pInfo->Name);
3432        update_model--;
3433  }  }
3434    
3435    
3436  void MainWindow::file_changed()  void MainWindow::file_changed()
3437  {  {
3438      if (file && !file_is_changed) {      if (file && !file_is_changed) {
# Line 1180  void MainWindow::file_changed() Line 3441  void MainWindow::file_changed()
3441      }      }
3442  }  }
3443    
3444    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
3445        sample_ref_count.clear();
3446        
3447        if (!gig) return;
3448    
3449        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
3450             instrument = gig->GetNextInstrument())
3451        {
3452            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3453                 rgn = instrument->GetNextRegion())
3454            {
3455                for (int i = 0; i < 256; ++i) {
3456                    if (!rgn->pDimensionRegions[i]) continue;
3457                    if (rgn->pDimensionRegions[i]->pSample) {
3458                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
3459                    }
3460                }
3461            }
3462        }
3463    }
3464    
3465    bool MainWindow::onQueryTreeViewTooltip(int x, int y, bool keyboardTip, const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
3466        Gtk::TreeModel::iterator iter;
3467        if (!m_TreeViewInstruments.get_tooltip_context_iter(x, y, keyboardTip, iter)) {
3468            return false;
3469        }
3470        Gtk::TreeModel::Path path(iter);
3471        Gtk::TreeModel::Row row = *iter;
3472        Gtk::TreeViewColumn* pointedColumn = NULL;
3473        // resolve the precise table column the mouse points to
3474        {
3475            Gtk::TreeModel::Path path; // unused
3476            int cellX, cellY; // unused
3477            m_TreeViewInstruments.get_path_at_pos(x, y, path, pointedColumn, cellX, cellY);
3478        }
3479        Gtk::TreeViewColumn* scriptsColumn = m_TreeViewInstruments.get_column(2);
3480        if (pointedColumn == scriptsColumn) { // mouse hovers scripts column ...
3481            // show the script(s) assigned to the hovered instrument as tooltip
3482            tooltip->set_markup( row[m_InstrumentsModel.m_col_tooltip] );
3483            m_TreeViewInstruments.set_tooltip_cell(tooltip, &path, scriptsColumn, NULL);
3484        } else {
3485            // if beginners' tooltips is disabled then don't show the following one
3486            if (!Settings::singleton()->showTooltips)
3487                return false;
3488            // yeah, a beginners tooltip
3489            tooltip->set_text(_(
3490                "Right click here for actions on instruments & MIDI Rules. "
3491                "Drag & drop to change the order of instruments."
3492            ));
3493            m_TreeViewInstruments.set_tooltip_cell(tooltip, &path, pointedColumn, NULL);
3494        }
3495        return true;
3496    }
3497    
3498    static Glib::ustring scriptTooltipFor(gig::Instrument* instrument, int index) {
3499        Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3500        const int iScriptSlots = instrument->ScriptSlotCount();
3501        Glib::ustring tooltip = "<u>(" + ToString(index) + ") “"  + name + "”</u>\n\n";
3502        if (!iScriptSlots)
3503            tooltip += "<span foreground='red'><i>No script assigned</i></span>";
3504        else {
3505            for (int i = 0; i < iScriptSlots; ++i) {
3506                tooltip += "• " + ToString(i+1) + ". Script: “<span foreground='#46DEFF'><b>" +
3507                           instrument->GetScriptOfSlot(i)->Name + "</b></span>”";
3508                if (i + 1 < iScriptSlots) tooltip += "\n\n";
3509            }
3510        }
3511        return tooltip;
3512    }
3513    
3514  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
3515  {  {
3516      file = 0;      file = 0;
3517      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
3518    
3519      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
3520            (filename && strlen(filename) > 0) ?
3521                filename : (!gig->GetFileName().empty()) ?
3522                    gig->GetFileName() : _("Unsaved Gig File");
3523      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
3524      file_has_name = filename;      file_has_name = filename;
3525      file_is_changed = false;      file_is_changed = false;
3526    
3527      propDialog.set_info(gig->pInfo);      fileProps.set_file(gig);
   
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
3528    
3529      int instrument_index = 0;      instrument_name_connection.block();
3530      Gtk::RadioMenuItem::Group instrument_group;      int index = 0;
3531      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
3532           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
3533          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3534            const int iScriptSlots = instrument->ScriptSlotCount();
3535    
3536            Gtk::TreeModel::iterator iter = m_refInstrumentsTreeModel->append();
3537          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
3538          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_InstrumentsModel.m_col_nr] = index;
3539          row[m_Columns.m_col_instr] = instrument;          row[m_InstrumentsModel.m_col_name] = name;
3540          // create a menu item for this instrument          row[m_InstrumentsModel.m_col_instr] = instrument;
3541          Gtk::RadioMenuItem* item =          row[m_InstrumentsModel.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3542              new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());          row[m_InstrumentsModel.m_col_tooltip] = scriptTooltipFor(instrument, index);
3543          instrument_menu->get_submenu()->append(*item);  
3544          item->signal_activate().connect(  #if !USE_GTKMM_BUILDER
3545              sigc::bind(          add_instrument_to_menu(name);
3546                  sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  #endif
                 instrument_index  
             )  
         );  
         instrument_index++;  
3547      }      }
3548      instrument_menu->show();      instrument_name_connection.unblock();
3549      instrument_menu->get_submenu()->show_all_children();  #if !USE_GTKMM_BUILDER
3550        uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
3551    #endif
3552    
3553        updateSampleRefCountMap(gig);
3554    
3555      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
3556          if (group->Name != "") {          if (group->Name != "") {
3557              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
3558              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
3559              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
3560              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
3561              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
3562              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1230  void MainWindow::load_gig(gig::File* gig Line 3564  void MainWindow::load_gig(gig::File* gig
3564                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
3565                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
3566                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
3567                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
3568                        gig_to_utf8(sample->pInfo->Name);
3569                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
3570                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
3571                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
3572                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3573                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3574              }              }
3575          }          }
3576      }      }
3577        
3578        for (int i = 0; gig->GetScriptGroup(i); ++i) {
3579            gig::ScriptGroup* group = gig->GetScriptGroup(i);
3580    
3581            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
3582            Gtk::TreeModel::Row rowGroup = *iterGroup;
3583            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
3584            rowGroup[m_ScriptsModel.m_col_group]  = group;
3585            rowGroup[m_ScriptsModel.m_col_script] = NULL;
3586            for (int s = 0; group->GetScript(s); ++s) {
3587                gig::Script* script = group->GetScript(s);
3588    
3589                Gtk::TreeModel::iterator iterScript =
3590                    m_refScriptsTreeModel->append(rowGroup.children());
3591                Gtk::TreeModel::Row rowScript = *iterScript;
3592                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
3593                rowScript[m_ScriptsModel.m_col_script] = script;
3594                rowScript[m_ScriptsModel.m_col_group]  = NULL;
3595            }
3596        }
3597        // unfold all sample groups & script groups by default
3598        m_TreeViewSamples.expand_all();
3599        m_TreeViewScripts.expand_all();
3600    
3601      file = gig;      file = gig;
3602    
3603      // select the first instrument      // select the first instrument
3604      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeViewInstruments.get_selection()->select(Gtk::TreePath("0"));
3605      tree_sel_ref->select(Gtk::TreePath("0"));  
3606        instr_props_set_instrument();
3607        gig::Instrument* instrument = get_instrument();
3608        if (instrument) {
3609            midiRules.set_instrument(instrument);
3610        }
3611  }  }
3612    
3613  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
3614  {  {
3615      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
3616      if (instrument)  
3617      {      // get visual selection
3618        std::vector<Gtk::TreeModel::Path> rows = m_TreeViewInstruments.get_selection()->get_selected_rows();
3619        if (rows.empty()) {
3620            instrumentProps.hide();
3621            return false;
3622        }
3623    
3624        // convert index of visual selection (i.e. if filtered) to index of model
3625        Gtk::TreeModel::Path path = m_refInstrumentsModelFilter->convert_path_to_child_path(rows[0]);
3626    
3627        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3628        Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(path);
3629        if (it) {
3630            Gtk::TreeModel::Row row = *it;
3631            gig::Instrument* instrument = row[m_InstrumentsModel.m_col_instr];
3632    
3633          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
3634    
3635            // make sure instrument tree is updated when user changes the
3636            // instrument name in instrument properties window
3637            instrumentProps.signal_name_changed().connect(
3638                sigc::bind(
3639                    sigc::mem_fun(*this,
3640                                  &MainWindow::instr_name_changed_by_instr_props),
3641                    it));
3642        } else {
3643            instrumentProps.hide();
3644        }
3645        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3646        return it ? true : false;
3647    }
3648    
3649    void MainWindow::show_instr_props()
3650    {
3651        if (instr_props_set_instrument()) {
3652          instrumentProps.show();          instrumentProps.show();
3653          instrumentProps.deiconify();          instrumentProps.deiconify();
3654      }      }
3655  }  }
3656    
3657    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
3658    {
3659        Gtk::TreeModel::Row row = *it;
3660        Glib::ustring name = row[m_InstrumentsModel.m_col_name];
3661    
3662        gig::Instrument* instrument = row[m_InstrumentsModel.m_col_instr];
3663        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
3664        if (gigname != name) {
3665            Gtk::TreeModel::Path path(*it);
3666            const int index = path[0];
3667            row[m_InstrumentsModel.m_col_name] = gigname;
3668            row[m_InstrumentsModel.m_col_tooltip] = scriptTooltipFor(instrument, index);
3669        }
3670    }
3671    
3672    bool MainWindow::sample_props_set_sample()
3673    {
3674        sampleProps.signal_name_changed().clear();
3675    
3676        std::vector<Gtk::TreeModel::Path> rows = m_TreeViewSamples.get_selection()->get_selected_rows();
3677        if (rows.empty()) {
3678            sampleProps.hide();
3679            return false;
3680        }
3681        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3682        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3683        if (it) {
3684            Gtk::TreeModel::Row row = *it;
3685            gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3686    
3687            sampleProps.set_sample(sample);
3688    
3689            // make sure sample tree is updated when user changes the
3690            // sample name in sample properties window
3691            sampleProps.signal_name_changed().connect(
3692                sigc::bind(
3693                    sigc::mem_fun(*this,
3694                        &MainWindow::sample_name_changed_by_sample_props
3695                    ), it
3696                )
3697            );
3698        } else {
3699            sampleProps.hide();
3700        }
3701        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3702        return it ? true : false;
3703    }
3704    
3705    void MainWindow::show_sample_props()
3706    {
3707        if (sample_props_set_sample()) {
3708            sampleProps.show();
3709            sampleProps.deiconify();
3710        }
3711    }
3712    
3713    void MainWindow::sample_name_changed_by_sample_props(Gtk::TreeModel::iterator& it)
3714    {
3715        Gtk::TreeModel::Row row = *it;
3716        Glib::ustring name = row[m_SamplesModel.m_col_name];
3717    
3718        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3719        Glib::ustring gigname(gig_to_utf8(sample->pInfo->Name));
3720        if (gigname != name) {
3721            Gtk::TreeModel::Path path(*it);
3722            row[m_SamplesModel.m_col_name] = gigname;
3723        }
3724    }
3725    
3726    void MainWindow::show_midi_rules()
3727    {
3728        if (gig::Instrument* instrument = get_instrument())
3729        {
3730            midiRules.set_instrument(instrument);
3731            midiRules.show();
3732            midiRules.deiconify();
3733        }
3734    }
3735    
3736    void MainWindow::show_script_slots() {
3737        if (!file) return;
3738    
3739        // get selected instrument
3740        gig::Instrument* instrument = get_instrument();
3741        if (!instrument) return;
3742    
3743        ScriptSlots* window = new ScriptSlots;
3744        window->setInstrument(instrument);
3745        window->signal_script_slots_changed().connect(
3746            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
3747        );
3748        //window->reparent(*this);
3749        window->show();
3750    }
3751    
3752    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
3753        if (!pInstrument) return;
3754        const int iScriptSlots = pInstrument->ScriptSlotCount();
3755    
3756        //NOTE: This is a big mess! Sometimes GTK requires m_TreeViewInstruments.get_model(), here we need m_refInstrumentsModelFilter->get_model(), otherwise accessing children below causes an error!
3757        //Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewInstruments.get_model();
3758        Glib::RefPtr<Gtk::TreeModel> model = m_refInstrumentsModelFilter->get_model();
3759    
3760        for (int i = 0; i < model->children().size(); ++i) {
3761            Gtk::TreeModel::Row row = model->children()[i];
3762            if (row[m_InstrumentsModel.m_col_instr] != pInstrument) continue;
3763            row[m_InstrumentsModel.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3764            row[m_InstrumentsModel.m_col_tooltip] = scriptTooltipFor(pInstrument, i);
3765            break;
3766        }
3767    
3768        // causes the sampler to reload the instrument with the new script
3769        on_sel_change();
3770    
3771        // force script 'patch' variables editor ("Script" tab) to be refreshed
3772        dimreg_edit.scriptVars.setInstrument(pInstrument, true/*force update*/);
3773    }
3774    
3775    void MainWindow::assignScript(gig::Script* pScript) {
3776        if (!pScript) {
3777            printf("assignScript() : !script\n");
3778            return;
3779        }
3780        printf("assignScript('%s')\n", pScript->Name.c_str());
3781    
3782        gig::Instrument* pInstrument = get_instrument();
3783        if (!pInstrument) {
3784            printf("!instrument\n");
3785            return;
3786        }
3787    
3788        pInstrument->AddScriptSlot(pScript);
3789    
3790        onScriptSlotsModified(pInstrument);
3791    }
3792    
3793    void MainWindow::dropAllScriptSlots() {
3794        gig::Instrument* pInstrument = get_instrument();
3795        if (!pInstrument) {
3796            printf("!instrument\n");
3797            return;
3798        }
3799    
3800        const int iScriptSlots = pInstrument->ScriptSlotCount();
3801        for (int i = iScriptSlots - 1; i >= 0; --i)
3802            pInstrument->RemoveScriptSlot(i);
3803    
3804        onScriptSlotsModified(pInstrument);
3805    }
3806    
3807    void MainWindow::on_action_refresh_all() {
3808        __refreshEntireGUI();
3809    }
3810    
3811  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
3812    #if USE_GLIB_ACTION
3813        bool active = false;
3814        m_actionToggleStatusBar->get_state(active);
3815        // for some reason toggle state does not change automatically
3816        active = !active;
3817        m_actionToggleStatusBar->change_state(active);
3818        if (active)
3819            m_StatusBar.show();
3820        else
3821            m_StatusBar.hide();
3822    #else
3823      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
3824          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
3825      if (!item) {      if (!item) {
# Line 1264  void MainWindow::on_action_view_status_b Line 3828  void MainWindow::on_action_view_status_b
3828      }      }
3829      if (item->get_active()) m_StatusBar.show();      if (item->get_active()) m_StatusBar.show();
3830      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
3831    #endif
3832  }  }
3833    
3834  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_auto_restore_win_dim() {
3835  {  #if USE_GLIB_ACTION
3836        bool active = false;
3837        m_actionToggleRestoreWinDim->get_state(active);
3838        // for some reason toggle state does not change automatically
3839        active = !active;
3840        m_actionToggleRestoreWinDim->change_state(active);
3841        Settings::singleton()->autoRestoreWindowDimension = active;
3842    #else
3843        Gtk::CheckMenuItem* item =
3844            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
3845        if (!item) {
3846            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
3847            return;
3848        }
3849        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
3850    #endif
3851    }
3852    
3853    void MainWindow::on_instr_double_click_opens_props() {
3854    #if USE_GLIB_ACTION
3855        bool active = false;
3856        m_actionInstrDoubleClickOpensProps->get_state(active);
3857        // for some reason toggle state does not change automatically
3858        active = !active;
3859        m_actionInstrDoubleClickOpensProps->change_state(active);
3860        Settings::singleton()->instrumentDoubleClickOpensProps = active;
3861    #else
3862        Gtk::CheckMenuItem* item =
3863            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/OpenInstrPropsByDoubleClick"));
3864        if (!item) {
3865            std::cerr << "/MenuBar/MenuView/OpenInstrPropsByDoubleClick == NULL\n";
3866            return;
3867        }
3868        Settings::singleton()->instrumentDoubleClickOpensProps = item->get_active();
3869    #endif
3870    }
3871    
3872    void MainWindow::on_save_with_temporary_file() {
3873    #if USE_GLIB_ACTION
3874        bool active = false;
3875        m_actionToggleSaveWithTempFile->get_state(active);
3876        // for some reason toggle state does not change automatically
3877        active = !active;
3878        m_actionToggleSaveWithTempFile->change_state(active);
3879        Settings::singleton()->saveWithTemporaryFile = active;
3880    #else
3881        Gtk::CheckMenuItem* item =
3882            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
3883        if (!item) {
3884            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
3885            return;
3886        }
3887        Settings::singleton()->saveWithTemporaryFile = item->get_active();
3888    #endif
3889    }
3890    
3891    bool MainWindow::is_copy_samples_unity_note_enabled() const {
3892    #if USE_GLIB_ACTION
3893        bool active = false;
3894        m_actionToggleCopySampleUnity->get_state(active);
3895        return active;
3896    #else
3897        Gtk::CheckMenuItem* item =
3898            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
3899        if (!item) {
3900            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
3901            return true;
3902        }
3903        return item->get_active();
3904    #endif
3905    }
3906    
3907    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
3908    #if USE_GLIB_ACTION
3909        bool active = false;
3910        m_actionToggleCopySampleTune->get_state(active);
3911        return active;
3912    #else
3913        Gtk::CheckMenuItem* item =
3914            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
3915        if (!item) {
3916            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
3917            return true;
3918        }
3919        return item->get_active();
3920    #endif
3921    }
3922    
3923    bool MainWindow::is_copy_samples_loop_enabled() const {
3924    #if USE_GLIB_ACTION
3925        bool active = false;
3926        m_actionToggleCopySampleLoop->get_state(active);
3927        return active;
3928    #else
3929        Gtk::CheckMenuItem* item =
3930            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
3931        if (!item) {
3932            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
3933            return true;
3934        }
3935        return item->get_active();
3936    #endif
3937    }
3938    
3939    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
3940    bool MainWindow::on_button_release(Gdk::EventButton& _button) {
3941        GdkEventButton* button = _button.gobj();
3942    #else
3943    void MainWindow::on_button_release(GdkEventButton* button) {
3944    #endif
3945      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
3946          show_instr_props();          if (Settings::singleton()->instrumentDoubleClickOpensProps)
3947                show_instr_props();
3948      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3949            // gig v2 files have no midi rules
3950            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
3951    #if USE_GTKMM_BUILDER
3952            m_actionMIDIRules->property_enabled() = bEnabled;
3953    #else
3954            static_cast<Gtk::MenuItem*>(
3955                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
3956                    bEnabled
3957                );
3958            static_cast<Gtk::MenuItem*>(
3959                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
3960                    bEnabled
3961                );
3962    #endif
3963          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
3964      }      }
3965    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
3966        return false;
3967    #endif
3968    }
3969    
3970    #if !USE_GTKMM_BUILDER
3971    void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
3972        if (item->get_active()) {
3973            const std::vector<Gtk::Widget*> children =
3974                instrument_menu->get_children();
3975            std::vector<Gtk::Widget*>::const_iterator it =
3976                find(children.begin(), children.end(), item);
3977            if (it != children.end()) {
3978                int index = it - children.begin();
3979                m_TreeViewInstruments.get_selection()->select(Gtk::TreePath(ToString(index)));
3980    
3981                m_RegionChooser.set_instrument(file->GetInstrument(index));
3982            }
3983        }
3984    }
3985    #endif
3986    
3987    void MainWindow::on_action_move_instr() {
3988        gig::Instrument* instr = get_instrument();
3989        if (!instr) return;
3990    
3991        int currentIndex = getIndexOf(instr);
3992    
3993        Gtk::Dialog dialog(_("Move Instrument"), true /*modal*/);
3994    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3995        Gtk::Adjustment adjustment(
3996            currentIndex,
3997            0 /*min*/, file->CountInstruments() - 1 /*max*/
3998        );
3999        Gtk::SpinButton spinBox(adjustment);
4000    #else
4001        Gtk::SpinButton spinBox(
4002            Gtk::Adjustment::create(
4003                currentIndex,
4004                0 /*min*/, file->CountInstruments() - 1 /*max*/
4005            )
4006        );
4007    #endif
4008    #if USE_GTKMM_BOX
4009        dialog.get_content_area()->pack_start(spinBox);
4010    #else
4011        dialog.get_vbox()->pack_start(spinBox);
4012    #endif
4013    #if HAS_GTKMM_STOCK
4014        Gtk::Button* okButton = dialog.add_button(Gtk::Stock::OK, 0);
4015        dialog.add_button(Gtk::Stock::CANCEL, 1);
4016    #else
4017        Gtk::Button* okButton = dialog.add_button(_("_OK"), 0);
4018        dialog.add_button(_("_Cancel"), 1);
4019    #endif
4020        okButton->set_sensitive(false);
4021        // show the dialog at a reasonable screen position
4022        dialog.set_position(Gtk::WIN_POS_MOUSE);
4023        // only enable the 'OK' button if entered new index is not instrument's
4024        // current index already
4025        spinBox.signal_value_changed().connect([&]{
4026            okButton->set_sensitive( spinBox.get_value_as_int() != currentIndex );
4027        });
4028        // usability acceleration: if user hits enter key on the text entry field
4029        // then auto trigger the 'OK' button
4030        spinBox.signal_activate().connect([&]{
4031            if (okButton->get_sensitive())
4032                okButton->clicked();
4033        });
4034    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4035        dialog.show_all_children();
4036    #endif
4037        if (!dialog.run()) { // 'OK' selected ...
4038            int newIndex = spinBox.get_value_as_int();
4039            printf("MOVE TO %d\n", newIndex);
4040            gig::Instrument* dst = file->GetInstrument(newIndex);
4041            instr->MoveTo(dst);
4042            __refreshEntireGUI();
4043            select_instrument(instr);
4044        }
4045    }
4046    
4047    void MainWindow::select_instrument(gig::Instrument* instrument) {
4048        if (!instrument) return;
4049    
4050        //NOTE: This is a big mess! Sometimes GTK requires m_refInstrumentsModelFilter->get_model(), here we need m_TreeViewInstruments.get_model(), otherwise treeview selection below causes an error!
4051        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewInstruments.get_model();
4052        //Glib::RefPtr<Gtk::TreeModel> model = m_refInstrumentsModelFilter->get_model();
4053    
4054        for (int i = 0; i < model->children().size(); ++i) {
4055            Gtk::TreeModel::Row row = model->children()[i];
4056            if (row[m_InstrumentsModel.m_col_instr] == instrument) {
4057                // select and show the respective instrument in the list view
4058                show_intruments_tab();
4059                m_TreeViewInstruments.get_selection()->unselect_all();
4060                
4061    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
4062                auto iterSel = model->children()[i].get_iter();
4063                m_TreeViewInstruments.get_selection()->select(iterSel);
4064    #else
4065                m_TreeViewInstruments.get_selection()->select(model->children()[i]);
4066    #endif
4067                std::vector<Gtk::TreeModel::Path> rows =
4068                    m_TreeViewInstruments.get_selection()->get_selected_rows();
4069                if (!rows.empty())
4070                    m_TreeViewInstruments.scroll_to_row(rows[0]);
4071                on_sel_change(); // the regular instrument selection change callback
4072            }
4073        }
4074  }  }
4075    
4076  void MainWindow::on_instrument_selection_change(int index) {  /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
4077      m_RegionChooser.set_instrument(file->GetInstrument(index));  bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
4078        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
4079        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
4080    
4081        //NOTE: This is a big mess! Sometimes GTK requires m_refInstrumentsModelFilter->get_model(), here we need m_TreeViewInstruments.get_model(), otherwise treeview selection below causes an error!
4082        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewInstruments.get_model();
4083        //Glib::RefPtr<Gtk::TreeModel> model = m_refInstrumentsModelFilter->get_model();
4084    
4085        for (int i = 0; i < model->children().size(); ++i) {
4086            Gtk::TreeModel::Row row = model->children()[i];
4087            if (row[m_InstrumentsModel.m_col_instr] == pInstrument) {
4088                // select and show the respective instrument in the list view
4089                show_intruments_tab();
4090                m_TreeViewInstruments.get_selection()->unselect_all();
4091    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
4092                auto iterSel = model->children()[i].get_iter();
4093                m_TreeViewInstruments.get_selection()->select(iterSel);
4094    #else
4095                m_TreeViewInstruments.get_selection()->select(model->children()[i]);
4096    #endif
4097                std::vector<Gtk::TreeModel::Path> rows =
4098                    m_TreeViewInstruments.get_selection()->get_selected_rows();
4099                if (!rows.empty())
4100                    m_TreeViewInstruments.scroll_to_row(rows[0]);
4101                on_sel_change(); // the regular instrument selection change callback
4102    
4103                // select respective region in the region selector
4104                m_RegionChooser.set_region(pRegion);
4105    
4106                // select and show the respective dimension region in the editor
4107                //update_dimregs();
4108                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
4109                //dimreg_edit.set_dim_region(dimRgn);
4110    
4111                return true;
4112            }
4113        }
4114    
4115        return false;
4116  }  }
4117    
4118    void MainWindow::select_sample(gig::Sample* sample) {
4119        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
4120        for (int g = 0; g < model->children().size(); ++g) {
4121            Gtk::TreeModel::Row rowGroup = model->children()[g];
4122            for (int s = 0; s < rowGroup.children().size(); ++s) {
4123                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
4124                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
4125                    show_samples_tab();
4126                    m_TreeViewSamples.get_selection()->unselect_all();
4127    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
4128                    auto iterSel = rowGroup.children()[s].get_iter();
4129                    m_TreeViewSamples.get_selection()->select(iterSel);
4130    #else
4131                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
4132    #endif
4133                    std::vector<Gtk::TreeModel::Path> rows =
4134                        m_TreeViewSamples.get_selection()->get_selected_rows();
4135                    if (rows.empty()) return;
4136                    m_TreeViewSamples.scroll_to_row(rows[0]);
4137                    return;
4138                }
4139            }
4140        }
4141    }
4142    
4143    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
4144    bool MainWindow::on_sample_treeview_button_release(Gdk::EventButton& _button) {
4145        GdkEventButton* button = _button.gobj();
4146    #else
4147  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
4148    #endif
4149      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
4150            // by default if Ctrl keys is pressed down, then a mouse right-click
4151            // does not select the respective row, so we must assure this
4152            // programmatically ...
4153            /*{
4154                Gtk::TreeModel::Path path;
4155                Gtk::TreeViewColumn* pColumn = NULL;
4156                int cellX, cellY;
4157                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
4158                    (int)button->x, (int)button->y,
4159                    path, pColumn, cellX, cellY
4160                );
4161                if (bSuccess) {
4162                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
4163                        printf("not selected !!!\n");
4164                        m_TreeViewSamples.get_selection()->select(path);
4165                    }
4166                }
4167            }*/
4168    
4169    #if !USE_GTKMM_BUILDER
4170          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
4171              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
4172    #endif
4173    
4174          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
4175          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4176          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4177          bool group_selected  = false;          const int n = rows.size();
4178          bool sample_selected = false;          int nGroups  = 0;
4179          if (it) {          int nSamples = 0;
4180            for (int r = 0; r < n; ++r) {
4181                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4182                if (!it) continue;
4183              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
4184              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
4185              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
4186          }          }
4187    
4188    #if USE_GTKMM_BUILDER
4189            m_actionSampleProperties->property_enabled() = (n == 1);
4190            m_actionAddSample->property_enabled() = (n);
4191            m_actionAddSampleGroup->property_enabled() = (file);
4192            m_actionViewSampleRefs->property_enabled() = (nSamples == 1);
4193            m_actionRemoveSample->property_enabled() = (n);
4194            m_actionReplaceSample->property_enabled() = (nSamples == 1);
4195    #else
4196          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
4197              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
4198          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
4199              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
4200          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
4201              set_sensitive(file);              set_sensitive(file);
4202            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
4203                set_sensitive(nSamples == 1);
4204          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
4205              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
4206    #endif
4207          // show sample popup          // show sample popup
4208          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
4209    
4210    #if !USE_GTKMM_BUILDER
4211            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
4212                set_sensitive(n == 1);
4213            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
4214                set_sensitive(n);
4215            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
4216                set_sensitive(file);
4217            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
4218                set_sensitive(nSamples == 1);
4219            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
4220                set_sensitive(n);
4221    #endif
4222      }      }
4223        
4224    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
4225        return false;
4226    #endif
4227    }
4228    
4229    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
4230    bool MainWindow::on_script_treeview_button_release(Gdk::EventButton& _button) {
4231        GdkEventButton* button = _button.gobj();
4232    #else
4233    void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
4234    #endif
4235        if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
4236    #if !USE_GTKMM_BUILDER
4237            Gtk::Menu* script_popup =
4238                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
4239    #endif
4240            // update enabled/disabled state of sample popup items
4241            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4242            Gtk::TreeModel::iterator it = sel->get_selected();
4243            bool group_selected  = false;
4244            bool script_selected = false;
4245            if (it) {
4246                Gtk::TreeModel::Row row = *it;
4247                group_selected  = row[m_ScriptsModel.m_col_group];
4248                script_selected = row[m_ScriptsModel.m_col_script];
4249            }
4250    #if USE_GTKMM_BUILDER
4251            m_actionAddScript->property_enabled() = (group_selected || script_selected);
4252            m_actionAddScriptGroup->property_enabled() = (file);
4253            m_actionEditScript->property_enabled() = (script_selected);
4254            m_actionRemoveScript->property_enabled() = (group_selected || script_selected);
4255    #else
4256            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
4257                set_sensitive(group_selected || script_selected);
4258            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
4259                set_sensitive(file);
4260            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
4261                set_sensitive(script_selected);    
4262            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
4263                set_sensitive(group_selected || script_selected);
4264    #endif
4265            // show sample popup
4266            script_popup->popup(button->button, button->time);
4267    
4268    #if !USE_GTKMM_BUILDER
4269            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
4270                set_sensitive(group_selected || script_selected);
4271            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
4272                set_sensitive(file);
4273            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
4274                set_sensitive(script_selected);    
4275            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
4276                set_sensitive(group_selected || script_selected);
4277    #endif
4278        }
4279    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
4280        return false;
4281    #endif
4282    }
4283    
4284    void MainWindow::updateScriptListOfMenu() {
4285        // remove all entries from "Assign Script" menu
4286        {
4287            const std::vector<Gtk::Widget*> children = assign_scripts_menu->get_children();
4288            for (int i = 0; i < children.size(); ++i) {
4289                Gtk::Widget* child = children[i];
4290                assign_scripts_menu->remove(*child);
4291                delete child;
4292            }
4293        }
4294    
4295        int iTotalScripts = 0;
4296    
4297        if (!file) goto noScripts;
4298    
4299        // add all configured macros as menu items to the "Macro" menu
4300        for (int iGroup = 0; file->GetScriptGroup(iGroup); ++iGroup) {
4301            gig::ScriptGroup* pGroup = file->GetScriptGroup(iGroup);
4302            for (int iScript = 0; pGroup->GetScript(iScript); ++iScript, ++iTotalScripts) {
4303                gig::Script* pScript = pGroup->GetScript(iScript);
4304                std::string name = pScript->Name;
4305    
4306                Gtk::MenuItem* item = new Gtk::MenuItem(name);
4307                item->signal_activate().connect(
4308                    sigc::bind(
4309                        sigc::mem_fun(*this, &MainWindow::assignScript), pScript
4310                    )
4311                );
4312                assign_scripts_menu->append(*item);
4313                item->set_accel_path("<Scripts>/script_" + ToString(iTotalScripts));
4314                //item->set_tooltip_text(comment);
4315            }
4316        }
4317    
4318        noScripts:
4319    
4320        // if there are no macros configured at all, then show a dummy entry instead
4321        if (!iTotalScripts) {
4322            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Scripts"));
4323            item->set_sensitive(false);
4324            assign_scripts_menu->append(*item);
4325        }
4326    
4327        // add separator line to menu
4328        assign_scripts_menu->append(*new Gtk::SeparatorMenuItem);
4329    
4330        {
4331            Gtk::MenuItem* item = new Gtk::MenuItem(_("Unassign All Scripts"));
4332            item->signal_activate().connect(
4333                sigc::mem_fun(*this, &MainWindow::dropAllScriptSlots)
4334            );
4335            assign_scripts_menu->append(*item);
4336            item->set_accel_path("<Scripts>/DropAllScriptSlots");
4337        }
4338    
4339    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4340        assign_scripts_menu->show_all_children();
4341    #endif
4342    }
4343    
4344    #if !USE_GTKMM_BUILDER
4345    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
4346        const Glib::ustring& name, int position) {
4347    
4348        Gtk::RadioMenuItem::Group instrument_group;
4349        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
4350        if (!children.empty()) {
4351            instrument_group =
4352                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
4353        }
4354        Gtk::RadioMenuItem* item =
4355            new Gtk::RadioMenuItem(instrument_group, name);
4356        if (position < 0) {
4357            instrument_menu->append(*item);
4358        } else {
4359            instrument_menu->insert(*item, position);
4360        }
4361        item->show();
4362        item->signal_activate().connect(
4363            sigc::bind(
4364                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
4365                item));
4366        return item;
4367    }
4368    #endif
4369    
4370    #if !USE_GTKMM_BUILDER
4371    void MainWindow::remove_instrument_from_menu(int index) {
4372        const std::vector<Gtk::Widget*> children =
4373            instrument_menu->get_children();
4374        Gtk::Widget* child = children[index];
4375        instrument_menu->remove(*child);
4376        delete child;
4377    }
4378    #endif
4379    
4380    void MainWindow::add_instrument(gig::Instrument* instrument) {
4381        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
4382    
4383        // update instrument tree view
4384        instrument_name_connection.block();
4385        Gtk::TreeModel::iterator iterInstr = m_refInstrumentsTreeModel->append();
4386        Gtk::TreeModel::Row rowInstr = *iterInstr;
4387        const int index = m_refInstrumentsTreeModel->children().size() - 1;
4388        const int iScriptSlots = instrument->ScriptSlotCount();
4389        rowInstr[m_InstrumentsModel.m_col_nr] = index;
4390        rowInstr[m_InstrumentsModel.m_col_name] = name;
4391        rowInstr[m_InstrumentsModel.m_col_instr] = instrument;
4392        rowInstr[m_InstrumentsModel.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
4393        rowInstr[m_InstrumentsModel.m_col_tooltip] = scriptTooltipFor(instrument, index);
4394        instrument_name_connection.unblock();
4395    
4396    #if !USE_GTKMM_BUILDER
4397        add_instrument_to_menu(name);
4398    #endif
4399        select_instrument(instrument);
4400        file_changed();
4401  }  }
4402    
4403  void MainWindow::on_action_add_instrument() {  void MainWindow::on_action_add_instrument() {
# Line 1311  void MainWindow::on_action_add_instrumen Line 4405  void MainWindow::on_action_add_instrumen
4405      if (!file) return;      if (!file) return;
4406      gig::Instrument* instrument = file->AddInstrument();      gig::Instrument* instrument = file->AddInstrument();
4407      __instrument_indexer++;      __instrument_indexer++;
4408      instrument->pInfo->Name =      instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
4409          _("Unnamed Instrument ") + ToString(__instrument_indexer);                                              ToString(__instrument_indexer));
4410      // update instrument tree view  
4411      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      add_instrument(instrument);
4412      Gtk::TreeModel::Row rowInstr = *iterInstr;  }
4413      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();  
4414      rowInstr[m_Columns.m_col_instr] = instrument;  void MainWindow::on_action_duplicate_instrument() {
4415      file_changed();      if (!file) return;
4416    
4417        // retrieve the currently selected instrument
4418        // (being the original instrument to be duplicated)
4419        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewInstruments.get_selection();
4420        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4421        for (int r = 0; r < rows.size(); ++r) {
4422            // convert index of visual selection (i.e. if filtered) to index of model
4423            Gtk::TreeModel::Path path = m_refInstrumentsModelFilter->convert_path_to_child_path(rows[r]);
4424            Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(path);
4425            if (it) {
4426                Gtk::TreeModel::Row row = *it;
4427                gig::Instrument* instrOrig = row[m_InstrumentsModel.m_col_instr];
4428                if (instrOrig) {
4429                    // duplicate the orginal instrument
4430                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
4431                    instrNew->pInfo->Name =
4432                        instrOrig->pInfo->Name +
4433                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
4434    
4435                    add_instrument(instrNew);
4436                }
4437            }
4438        }
4439  }  }
4440    
4441  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1334  void MainWindow::on_action_remove_instru Line 4451  void MainWindow::on_action_remove_instru
4451          return;          return;
4452      }      }
4453    
4454      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewInstruments.get_selection();
4455      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4456      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4457            Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(rows[r]);
4458            if (!it) continue;
4459          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4460          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_InstrumentsModel.m_col_instr];
4461          try {          try {
4462                Gtk::TreePath path(it);
4463                int index = path[0];
4464    
4465              // remove instrument from the gig file              // remove instrument from the gig file
4466              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
4467              file_changed();              file_changed();
4468    
4469    #if !USE_GTKMM_BUILDER
4470                remove_instrument_from_menu(index);
4471    #endif
4472    
4473                // remove row from instruments tree view
4474                m_refInstrumentsTreeModel->erase(it);
4475                // update "Nr" column of all instrument rows
4476                {
4477                    int index = 0;
4478                    for (Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->children().begin();
4479                         it != m_refInstrumentsTreeModel->children().end(); ++it, ++index)
4480                    {
4481                        Gtk::TreeModel::Row row = *it;
4482                        gig::Instrument* instrument = row[m_InstrumentsModel.m_col_instr];
4483                        row[m_InstrumentsModel.m_col_nr] = index;
4484                        row[m_InstrumentsModel.m_col_tooltip] = scriptTooltipFor(instrument, index);
4485                    }
4486                }
4487    
4488    #if GTKMM_MAJOR_VERSION < 3
4489                // select another instrument (in gtk3 this is done
4490                // automatically)
4491                if (!m_refInstrumentsTreeModel->children().empty()) {
4492                    if (index == m_refInstrumentsTreeModel->children().size()) {
4493                        index--;
4494                    }
4495                    m_TreeViewInstruments.get_selection()->select(
4496                        Gtk::TreePath(ToString(index)));
4497                }
4498    #endif
4499                instr_props_set_instrument();
4500                instr = get_instrument();
4501                if (instr) {
4502                    midiRules.set_instrument(instr);
4503                } else {
4504                    midiRules.hide();
4505                }
4506          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
4507              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4508              msg.run();              msg.run();
# Line 1353  void MainWindow::on_action_remove_instru Line 4511  void MainWindow::on_action_remove_instru
4511  }  }
4512    
4513  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
4514      //TODO: show a dialog where the selected sample's properties can be edited      show_sample_props();
4515      Gtk::MessageDialog msg(  }
4516          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO  
4517    void MainWindow::on_action_add_script_group() {
4518        static int __script_indexer = 0;
4519        if (!file) return;
4520        gig::ScriptGroup* group = file->AddScriptGroup();
4521        group->Name = gig_from_utf8(_("Unnamed Group"));
4522        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
4523        __script_indexer++;
4524        // update sample tree view
4525        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
4526        Gtk::TreeModel::Row rowGroup = *iterGroup;
4527        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
4528        rowGroup[m_ScriptsModel.m_col_script] = NULL;
4529        rowGroup[m_ScriptsModel.m_col_group] = group;
4530        file_changed();
4531    }
4532    
4533    void MainWindow::on_action_add_script() {
4534        if (!file) return;
4535        // get selected group
4536        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4537        Gtk::TreeModel::iterator it = sel->get_selected();
4538        if (!it) return;
4539        Gtk::TreeModel::Row row = *it;
4540        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4541        if (!group) { // not a group, but a script is selected (probably)
4542            gig::Script* script = row[m_ScriptsModel.m_col_script];
4543            if (!script) return;
4544            it = row.parent(); // resolve parent (that is the script's group)
4545            if (!it) return;
4546            row = *it;
4547            group = row[m_ScriptsModel.m_col_group];
4548            if (!group) return;
4549        }
4550    
4551        // add a new script to the .gig file
4552        gig::Script* script = group->AddScript();    
4553        Glib::ustring name = _("Unnamed Script");
4554        script->Name = gig_from_utf8(name);
4555    
4556        // add script to the tree view
4557        Gtk::TreeModel::iterator iterScript =
4558            m_refScriptsTreeModel->append(row.children());
4559        Gtk::TreeModel::Row rowScript = *iterScript;
4560        rowScript[m_ScriptsModel.m_col_name] = name;
4561        rowScript[m_ScriptsModel.m_col_script] = script;
4562        rowScript[m_ScriptsModel.m_col_group]  = NULL;
4563    
4564        // unfold group of new script item in treeview
4565        Gtk::TreeModel::Path path(iterScript);
4566        m_TreeViewScripts.expand_to_path(path);
4567    }
4568    
4569    void MainWindow::on_action_edit_script() {
4570        if (!file) return;
4571        // get selected script
4572        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4573        Gtk::TreeModel::iterator it = sel->get_selected();
4574        if (!it) return;
4575        Gtk::TreeModel::Row row = *it;
4576        gig::Script* script = row[m_ScriptsModel.m_col_script];
4577        editScript(script);
4578    }
4579    
4580    void MainWindow::editScript(gig::Script* script) {
4581        if (!script) return;
4582        ScriptEditor* editor = new ScriptEditor;
4583        editor->signal_script_to_be_changed.connect(
4584            signal_script_to_be_changed.make_slot()
4585      );      );
4586      msg.run();      editor->signal_script_changed.connect([this](gig::Script* script) {
4587            // signal to sampler (which will reload the script due to this)
4588            signal_script_changed.emit(script);
4589            // force script 'patch' variables editor ("Script" tab) to be refreshed
4590            gig::Instrument* instr = get_instrument();
4591            dimreg_edit.scriptVars.setInstrument(instr, true/*force update*/);
4592        });
4593        editor->setScript(script);
4594        //editor->reparent(*this);
4595        editor->show();
4596    }
4597    
4598    void MainWindow::on_action_remove_script() {
4599        if (!file) return;
4600        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4601        Gtk::TreeModel::iterator it = sel->get_selected();
4602        if (it) {
4603            Gtk::TreeModel::Row row = *it;
4604            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4605            gig::Script* script     = row[m_ScriptsModel.m_col_script];
4606            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
4607            try {
4608                // remove script group or script from the gig file
4609                if (group) {
4610                    // notify everybody that we're going to remove these samples
4611    //TODO:         scripts_to_be_removed_signal.emit(members);
4612                    // delete the group in the .gig file including the
4613                    // samples that belong to the group
4614                    file->DeleteScriptGroup(group);
4615                    // notify that we're done with removal
4616    //TODO:         scripts_removed_signal.emit();
4617                    file_changed();
4618                } else if (script) {
4619                    // notify everybody that we're going to remove this sample
4620    //TODO:         std::list<gig::Script*> lscripts;
4621    //TODO:         lscripts.push_back(script);
4622    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
4623                    // remove sample from the .gig file
4624                    script->GetGroup()->DeleteScript(script);
4625                    // notify that we're done with removal
4626    //TODO:         scripts_removed_signal.emit();
4627                    dimreg_changed();
4628                    file_changed();
4629                }
4630                // remove respective row(s) from samples tree view
4631                m_refScriptsTreeModel->erase(it);
4632            } catch (RIFF::Exception e) {
4633                // pretend we're done with removal (i.e. to avoid dead locks)
4634    //TODO:     scripts_removed_signal.emit();
4635                // show error message
4636                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4637                msg.run();
4638            }
4639        }
4640  }  }
4641    
4642  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
4643      static int __sample_indexer = 0;      static int __sample_indexer = 0;
4644      if (!file) return;      if (!file) return;
4645      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
4646      group->Name = _("Unnamed Group");      group->Name = gig_from_utf8(_("Unnamed Group"));
4647      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
4648      __sample_indexer++;      __sample_indexer++;
4649      // update sample tree view      // update sample tree view
4650      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
4651      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
4652      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
4653      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
4654      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
4655      file_changed();      file_changed();
4656  }  }
4657    
4658    void MainWindow::on_action_replace_sample() {
4659        add_or_replace_sample(true);
4660    }
4661    
4662  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
4663        add_or_replace_sample(false);
4664    }
4665    
4666    void MainWindow::add_or_replace_sample(bool replace) {
4667      if (!file) return;      if (!file) return;
4668      // get selected group  
4669        // get selected group (and probably selected sample)
4670      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4671      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4672        if (rows.empty()) return;
4673        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4674      if (!it) return;      if (!it) return;
4675      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
4676        gig::Sample* sample = NULL;
4677      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
4678      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
4679          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
4680          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
4681          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
4682          if (!it) return;          if (!it) return;
4683          row = *it;          if (!replace) row = *it;
4684          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
4685          if (!group) return;          if (!group) return;
4686      }      }
4687        if (replace && !sample) return;
4688    
4689      // show 'browse for file' dialog      // show 'browse for file' dialog
4690      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
4691    #if HAS_GTKMM_STOCK
4692      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4693      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
4694      dialog.set_select_multiple(true);  #else
4695        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4696        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
4697    #endif
4698        dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
4699    
4700      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
4701  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
# Line 1439  void MainWindow::on_action_add_sample() Line 4737  void MainWindow::on_action_add_sample()
4737          dialog.set_current_folder(current_sample_dir);          dialog.set_current_folder(current_sample_dir);
4738      }      }
4739      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
4740            dialog.hide();
4741          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4742          Glib::ustring error_files;          Glib::ustring error_files;
4743          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
4744          for (std::vector<std::string>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
4745               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
4746              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
4747              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file information
4748              SF_INFO info;              SF_INFO info;
4749              info.format = 0;              info.format = 0;
4750              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
# Line 1468  void MainWindow::on_action_add_sample() Line 4767  void MainWindow::on_action_add_sample()
4767                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
4768                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
4769                  }                  }
4770                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
4771                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
4772                  // file name without path                  // file name without path
4773                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
4774                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1479  void MainWindow::on_action_add_sample() Line 4778  void MainWindow::on_action_add_sample()
4778                          break;                          break;
4779                      }                      }
4780                  }                  }
4781                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
4782                  sample->Channels = info.channels;                  sample->Channels = info.channels;
4783                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
4784                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1493  void MainWindow::on_action_add_sample() Line 4792  void MainWindow::on_action_add_sample()
4792                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
4793                  {                  {
4794                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
4795                        sample->FineTune      = instrument.detune;
4796    
 #if HAVE_SF_INSTRUMENT_LOOPS  
4797                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
4798                          sample->Loops = 1;                          sample->Loops = 1;
4799    
# Line 1514  void MainWindow::on_action_add_sample() Line 4813  void MainWindow::on_action_add_sample()
4813                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
4814                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
4815                      }                      }
 #endif  
4816                  }                  }
4817    
4818                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
4819                  // physically when File::Save() is called)                  // physically when File::Save() is called)
4820                  sample->Resize(info.frames);                  sample->Resize(info.frames);
4821                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
4822                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
4823                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
4824                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
4825                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4826                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4827                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
4828                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4829                  // add sample to the tree view                  // add sample to the tree view
4830                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
4831                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
4832                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
4833                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
4834                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
4835                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
4836                        rowSample[m_SamplesModel.m_col_name] =
4837                            gig_to_utf8(sample->pInfo->Name);
4838                        rowSample[m_SamplesModel.m_col_sample] = sample;
4839                        rowSample[m_SamplesModel.m_col_group]  = NULL;
4840                    }
4841                  // close sound file                  // close sound file
4842                  sf_close(hFile);                  sf_close(hFile);
4843                  file_changed();                  file_changed();
4844              } 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)
4845                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4846                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
4847              }              }
4848          }          }
4849          // 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
4850          if (error_files.size()) {          if (!error_files.empty()) {
4851              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
4852                    (replace
4853                        ? _("Failed to replace sample with:\n")
4854                        : _("Could not add the following sample(s):\n"))
4855                    + error_files;
4856              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4857              msg.run();              msg.run();
4858          }          }
# Line 1557  void MainWindow::on_action_replace_all_s Line 4864  void MainWindow::on_action_replace_all_s
4864      if (!file) return;      if (!file) return;
4865      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
4866                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
4867      view::WrapLabel description(      const char* str =
4868          _("This is a very specific function. It tries to replace all samples "          _("This is a very specific function. It tries to replace all samples "
4869            "in the current gig file by samples located in the chosen "            "in the current gig file by samples located in the chosen "
4870            "directory.\n\n"            "directory.\n\n"
# Line 1571  void MainWindow::on_action_replace_all_s Line 4878  void MainWindow::on_action_replace_all_s
4878            "the sample in the gig file accordingly. If you don't need an "            "the sample in the gig file accordingly. If you don't need an "
4879            "extension, blank the field below. Any gig sample where no "            "extension, blank the field below. Any gig sample where no "
4880            "appropriate sample file could be found will be reported and left "            "appropriate sample file could be found will be reported and left "
4881            "untouched.\n")            "untouched.\n");
4882      );  #if GTKMM_MAJOR_VERSION < 3
4883      Gtk::HBox entryArea;      view::WrapLabel description(str);
4884    #else
4885        Gtk::Label description(str);
4886        description.set_line_wrap();
4887    #endif
4888        HBox entryArea;
4889      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
4890      Gtk::Entry postfixEntryBox;      Gtk::Entry postfixEntryBox;
4891      postfixEntryBox.set_text(".wav");      postfixEntryBox.set_text(".wav");
4892      entryArea.pack_start(entryLabel);      entryArea.pack_start(entryLabel);
4893      entryArea.pack_start(postfixEntryBox);      entryArea.pack_start(postfixEntryBox);
4894    #if USE_GTKMM_BOX
4895        dialog.get_content_area()->pack_start(description, Gtk::PACK_SHRINK);
4896        dialog.get_content_area()->pack_start(entryArea, Gtk::PACK_SHRINK);
4897    #else
4898      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
4899      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
4900    #endif
4901      description.show();      description.show();
4902    
4903    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4904      entryArea.show_all();      entryArea.show_all();
4905    #else
4906        entryArea.show();
4907    #endif
4908    
4909    #if HAS_GTKMM_STOCK
4910      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4911    #else
4912        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4913    #endif
4914      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
4915      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
4916      if (current_sample_dir != "") {      if (current_sample_dir != "") {
# Line 1591  void MainWindow::on_action_replace_all_s Line 4918  void MainWindow::on_action_replace_all_s
4918      }      }
4919      if (dialog.run() == Gtk::RESPONSE_OK)      if (dialog.run() == Gtk::RESPONSE_OK)
4920      {      {
4921            dialog.hide();
4922          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4923          Glib::ustring error_files;          Glib::ustring error_files;
4924          std::string folder = dialog.get_filename();          std::string folder = dialog.get_filename();
# Line 1598  void MainWindow::on_action_replace_all_s Line 4926  void MainWindow::on_action_replace_all_s
4926               sample; sample = file->GetNextSample())               sample; sample = file->GetNextSample())
4927          {          {
4928              std::string filename =              std::string filename =
4929                  folder + G_DIR_SEPARATOR_S + sample->pInfo->Name +                  folder + G_DIR_SEPARATOR_S +
4930                  postfixEntryBox.get_text().raw();                  Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
4931                                             postfixEntryBox.get_text());
4932              SF_INFO info;              SF_INFO info;
4933              info.format = 0;              info.format = 0;
4934              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
4935              try              try
4936              {              {
4937                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
4938                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
4939                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
4940                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
4941                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
4942                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
4943                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
4944                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
4945                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
4946                          break;                          break;
4947                      default:                      default:
4948                          sf_close(hFile);                          sf_close(hFile);
# Line 1626  void MainWindow::on_action_replace_all_s Line 4951  void MainWindow::on_action_replace_all_s
4951                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4952                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4953                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
4954                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4955                  sf_close(hFile);                  sf_close(hFile);
4956                  file_changed();                  file_changed();
4957              }              }
4958              catch (std::string what)              catch (std::string what)
4959              {              {
4960                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4961                      error_files += filename += " (" + what + ")";                  error_files += Glib::filename_to_utf8(filename) +
4962                        " (" + what + ")";
4963              }              }
4964          }          }
4965          // 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
4966          if (error_files.size()) {          if (!error_files.empty()) {
4967              Glib::ustring txt =              Glib::ustring txt =
4968                  _("Could not replace the following sample(s):\n") + error_files;                  _("Could not replace the following sample(s):\n") + error_files;
4969              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
# Line 1649  void MainWindow::on_action_replace_all_s Line 4975  void MainWindow::on_action_replace_all_s
4975  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
4976      if (!file) return;      if (!file) return;
4977      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4978      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4979      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4980            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4981            if (!it) continue;
4982          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4983          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
4984          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1658  void MainWindow::on_action_remove_sample Line 4986  void MainWindow::on_action_remove_sample
4986          try {          try {
4987              // remove group or sample from the gig file              // remove group or sample from the gig file
4988              if (group) {              if (group) {
4989                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
4990                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
4991                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
4992                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1675  void MainWindow::on_action_remove_sample Line 5003  void MainWindow::on_action_remove_sample
5003                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
5004                  // them from the import queue                  // them from the import queue
5005                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
5006                       member != members.end(); ++member) {                       member != members.end(); ++member)
5007                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
5008                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
5009                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
5010                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
5011                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
5012                      }                      }
5013                  }                  }
5014                  file_changed();                  file_changed();
# Line 1698  void MainWindow::on_action_remove_sample Line 5023  void MainWindow::on_action_remove_sample
5023                  samples_removed_signal.emit();                  samples_removed_signal.emit();
5024                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
5025                  // the import queue                  // the import queue
5026                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
5027                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
5028                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
5029                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
5030                  }                  }
5031                  dimreg_changed();                  dimreg_changed();
5032                  file_changed();                  file_changed();
# Line 1722  void MainWindow::on_action_remove_sample Line 5043  void MainWindow::on_action_remove_sample
5043      }      }
5044  }  }
5045    
5046    void MainWindow::on_action_remove_unused_samples() {
5047        if (!file) return;
5048    
5049        // collect all samples that are not referenced by any instrument
5050        std::list<gig::Sample*> lsamples;
5051        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
5052            gig::Sample* sample = file->GetSample(iSample);
5053            bool isUsed = false;
5054            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
5055                                  instrument = file->GetNextInstrument())
5056            {
5057                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
5058                                  rgn = instrument->GetNextRegion())
5059                {
5060                    for (int i = 0; i < 256; ++i) {
5061                        if (!rgn->pDimensionRegions[i]) continue;
5062                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
5063                        isUsed = true;
5064                        goto endOfRefSearch;
5065                    }
5066                }
5067            }
5068            endOfRefSearch:
5069            if (!isUsed) lsamples.push_back(sample);
5070        }
5071    
5072        if (lsamples.empty()) return;
5073    
5074        // notify everybody that we're going to remove these samples
5075        samples_to_be_removed_signal.emit(lsamples);
5076    
5077        // remove collected samples
5078        try {
5079            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
5080                 itSample != lsamples.end(); ++itSample)
5081            {
5082                gig::Sample* sample = *itSample;
5083                // remove sample from the .gig file
5084                file->DeleteSample(sample);
5085                // if sample was just previously added, remove it from the import queue
5086                if (m_SampleImportQueue.count(sample)) {
5087                    printf("Removing previously added sample '%s'\n",
5088                           m_SampleImportQueue[sample].sample_path.c_str());
5089                    m_SampleImportQueue.erase(sample);
5090                }
5091            }
5092        } catch (RIFF::Exception e) {
5093            // show error message
5094            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
5095            msg.run();
5096        }
5097    
5098        // notify everybody that we're done with removal
5099        samples_removed_signal.emit();
5100    
5101        dimreg_changed();
5102        file_changed();
5103        __refreshEntireGUI();
5104    }
5105    
5106    // see comment on on_sample_treeview_drag_begin()
5107    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
5108    {
5109        first_call_to_drag_data_get = true;
5110    }
5111    
5112    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
5113                                                       Gtk::SelectionData& selection_data, guint, guint)
5114    {
5115        if (!first_call_to_drag_data_get) return;
5116        first_call_to_drag_data_get = false;
5117    
5118        // get selected script
5119        gig::Script* script = NULL;
5120        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
5121        Gtk::TreeModel::iterator it = sel->get_selected();
5122        if (it) {
5123            Gtk::TreeModel::Row row = *it;
5124            script = row[m_ScriptsModel.m_col_script];
5125        }
5126        // pass the gig::Script as pointer
5127        selection_data.set(selection_data.get_target(), 0/*unused*/,
5128                           (const guchar*)&script,
5129                           sizeof(script)/*length of data in bytes*/);
5130    }
5131    
5132    // see comment on on_sample_treeview_drag_begin()
5133    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
5134    {
5135        first_call_to_drag_data_get = true;
5136    }
5137    
5138    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
5139                                                           Gtk::SelectionData& selection_data, guint, guint)
5140    {
5141        if (!first_call_to_drag_data_get) return;
5142        first_call_to_drag_data_get = false;
5143    
5144        // get selected source instrument
5145        gig::Instrument* src = NULL;
5146        {
5147            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewInstruments.get_selection();
5148            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5149            if (!rows.empty()) {
5150                Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(rows[0]);
5151                if (it) {
5152                    Gtk::TreeModel::Row row = *it;
5153                    src = row[m_InstrumentsModel.m_col_instr];
5154                }
5155            }
5156        }
5157        if (!src) return;
5158    
5159        // pass the source gig::Instrument as pointer
5160        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
5161                           sizeof(src)/*length of data in bytes*/);
5162    }
5163    
5164    void MainWindow::on_instruments_treeview_drop_drag_data_received(
5165        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
5166        const Gtk::SelectionData& selection_data, guint, guint time)
5167    {
5168        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
5169        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
5170            return;
5171    
5172        gig::Instrument* dst = NULL;
5173        {
5174            Gtk::TreeModel::Path path;
5175            const bool found = m_TreeViewInstruments.get_path_at_pos(x, y, path);
5176            if (!found) return;
5177    
5178            Gtk::TreeModel::iterator iter = m_refInstrumentsTreeModel->get_iter(path);
5179            if (!iter) return;
5180            Gtk::TreeModel::Row row = *iter;
5181            dst = row[m_InstrumentsModel.m_col_instr];
5182        }
5183        if (!dst) return;
5184    
5185        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
5186        src->MoveTo(dst);
5187        __refreshEntireGUI();
5188        select_instrument(src);
5189    }
5190    
5191  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
5192  // 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
5193  // 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 1740  void MainWindow::on_sample_treeview_drag Line 5206  void MainWindow::on_sample_treeview_drag
5206      // get selected sample      // get selected sample
5207      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
5208      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
5209      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5210      if (it) {      if (!rows.empty()) {
5211          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
5212          sample = row[m_SamplesModel.m_col_sample];          if (it) {
5213                Gtk::TreeModel::Row row = *it;
5214                sample = row[m_SamplesModel.m_col_sample];
5215            }
5216      }      }
5217      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
5218      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 1780  void MainWindow::on_sample_label_drop_dr Line 5249  void MainWindow::on_sample_label_drop_dr
5249          bool channels_changed = false;          bool channels_changed = false;
5250          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
5251              // remove the samplechannel dimension              // remove the samplechannel dimension
5252    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
5253              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
5254              channels_changed = true;              channels_changed = true;
5255              region_changed();              region_changed();
5256    */
5257          }          }
5258          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
5259                sample,
5260                is_copy_samples_unity_note_enabled(),
5261                is_copy_samples_fine_tune_enabled(),
5262                is_copy_samples_loop_enabled()
5263            );
5264    
5265          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
5266              // add samplechannel dimension              // add samplechannel dimension
# Line 1827  void MainWindow::sample_name_changed(con Line 5303  void MainWindow::sample_name_changed(con
5303      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
5304      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
5305      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
5306        gig::String gigname(gig_from_utf8(name));
5307      if (group) {      if (group) {
5308          if (group->Name != name) {          if (group->Name != gigname) {
5309              group->Name = name;              group->Name = gigname;
5310              printf("group name changed\n");              printf("group name changed\n");
5311              file_changed();              file_changed();
5312          }          }
5313      } else if (sample) {      } else if (sample) {
5314          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
5315              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
5316              printf("sample name changed\n");              printf("sample name changed\n");
5317              file_changed();              file_changed();
5318          }          }
5319      }      }
5320        // change name in the sample properties window
5321        if (sampleProps.get_sample() == sample && sample) {
5322            sampleProps.set_sample(sample);
5323        }
5324    }
5325    
5326    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
5327                                         const Gtk::TreeModel::iterator& iter) {
5328        if (!iter) return;
5329        Gtk::TreeModel::Row row = *iter;
5330        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
5331        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
5332        gig::Script* script     = row[m_ScriptsModel.m_col_script];
5333        gig::String gigname(gig_from_utf8(name));
5334        if (group) {
5335            if (group->Name != gigname) {
5336                group->Name = gigname;
5337                printf("script group name changed\n");
5338                file_changed();
5339            }
5340        } else if (script) {
5341            if (script->Name != gigname) {
5342                script->Name = gigname;
5343                printf("script name changed\n");
5344                file_changed();
5345            }
5346        }
5347    }
5348    
5349    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
5350                                           Gtk::TreeViewColumn* column)
5351    {
5352        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
5353        if (!iter) return;
5354        Gtk::TreeModel::Row row = *iter;
5355        gig::Script* script = row[m_ScriptsModel.m_col_script];
5356        editScript(script);
5357  }  }
5358    
5359  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
5360                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
5361      if (!iter) return;      if (!iter) return;
5362      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
5363      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_InstrumentsModel.m_col_name];
5364      gig::Instrument* instrument = row[m_Columns.m_col_instr];  
5365      if (instrument && instrument->pInfo->Name != name.raw()) {  #if !USE_GTKMM_BUILDER
5366          instrument->pInfo->Name = name.raw();      // change name in instrument menu
5367        int index = path[0];
5368        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
5369        if (index < children.size()) {
5370    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
5371            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
5372    #else
5373            remove_instrument_from_menu(index);
5374            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
5375            item->set_active();
5376    #endif
5377        }
5378    #endif
5379    
5380        // change name in gig
5381        gig::Instrument* instrument = row[m_InstrumentsModel.m_col_instr];
5382        gig::String gigname(gig_from_utf8(name));
5383        if (instrument && instrument->pInfo->Name != gigname) {
5384            instrument->pInfo->Name = gigname;
5385    
5386            // change name in the instrument properties window
5387            if (instrumentProps.get_instrument() == instrument) {
5388                instrumentProps.update_name();
5389            }
5390    
5391          file_changed();          file_changed();
5392      }      }
5393  }  }
5394    
5395    bool MainWindow::instrument_row_visible(const Gtk::TreeModel::const_iterator& iter) {
5396        if (!iter)
5397            return true;
5398    
5399        Glib::ustring pattern = m_searchText.get_text().lowercase();
5400        trim(pattern);
5401        if (pattern.empty()) return true;
5402    
5403    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
5404        //HACK: on GTKMM4 development branch const_iterator cannot be easily converted to iterator, probably going to be fixed before final GTKMM4 release though.
5405        Gtk::TreeModel::Row row = **(Gtk::TreeModel::iterator*)(&iter);
5406    #else
5407        Gtk::TreeModel::Row row = *iter;
5408    #endif
5409        Glib::ustring name = row[m_InstrumentsModel.m_col_name];
5410        name = name.lowercase();
5411    
5412        std::vector<Glib::ustring> tokens = Glib::Regex::split_simple(" ", pattern);
5413        for (int t = 0; t < tokens.size(); ++t)
5414            if (name.find(tokens[t]) == Glib::ustring::npos)
5415                return false;
5416    
5417        return true;
5418    }
5419    
5420    void MainWindow::on_action_combine_instruments() {
5421        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
5422    
5423        // take over selection from instruments list view for the combine dialog's
5424        // list view as pre-selection
5425        std::set<int> indeces;
5426        {
5427            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewInstruments.get_selection();
5428            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5429            for (int r = 0; r < rows.size(); ++r) {
5430                Gtk::TreeModel::iterator it = m_refInstrumentsTreeModel->get_iter(rows[r]);
5431                if (it) {
5432                    Gtk::TreeModel::Row row = *it;
5433                    int index = row[m_InstrumentsModel.m_col_nr];
5434                    indeces.insert(index);
5435                }
5436            }
5437        }
5438        d->setSelectedInstruments(indeces);
5439    
5440    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5441        d->show_all();
5442    #else
5443        d->show();
5444    #endif
5445        d->run();
5446        if (d->fileWasChanged()) {
5447            // update GUI with new instrument just created
5448            add_instrument(d->newCombinedInstrument());
5449        }
5450        delete d;
5451    }
5452    
5453    void MainWindow::on_action_view_references() {
5454        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
5455        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5456        if (rows.empty()) return;
5457        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
5458        if (!it) return;
5459        Gtk::TreeModel::Row row = *it;
5460        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
5461        if (!sample) return;
5462    
5463        ReferencesView* d = new ReferencesView(*this);
5464        d->setSample(sample);
5465        d->dimension_region_selected.connect(
5466            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
5467        );
5468    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5469        d->show_all();
5470    #else
5471        d->show();
5472    #endif
5473        d->resize(500, 400);
5474        d->run();
5475        delete d;
5476    }
5477    
5478    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
5479        struct _Source {
5480            std::vector<RIFF::File*> riffs;
5481            std::vector<gig::File*> gigs;
5482            
5483            ~_Source() {
5484                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
5485                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
5486                riffs.clear();
5487                gigs.clear();
5488            }
5489        } sources;
5490    
5491        if (filenames.empty())
5492            throw RIFF::Exception(_("No files selected, so nothing done."));
5493    
5494        // first open all input files (to avoid output file corruption)
5495        int i;
5496        try {
5497            for (i = 0; i < filenames.size(); ++i) {
5498                const std::string& filename = filenames[i];
5499                printf("opening file=%s\n", filename.c_str());
5500    
5501                RIFF::File* riff = new RIFF::File(filename);
5502                sources.riffs.push_back(riff);
5503    
5504                gig::File* gig = new gig::File(riff);
5505                sources.gigs.push_back(gig);
5506            }
5507        } catch (RIFF::Exception e) {
5508            throw RIFF::Exception(
5509                _("Error occurred while opening '") +
5510                filenames[i] +
5511                "': " +
5512                e.Message
5513            );
5514        } catch (...) {
5515            throw RIFF::Exception(
5516                _("Unknown exception occurred while opening '") +
5517                filenames[i] + "'"
5518            );
5519        }
5520    
5521        // now merge the opened .gig files to the main .gig file currently being
5522        // open in gigedit
5523        try {
5524            for (i = 0; i < filenames.size(); ++i) {
5525                const std::string& filename = filenames[i];
5526                printf("merging file=%s\n", filename.c_str());
5527                assert(i < sources.gigs.size());
5528    
5529                this->file->AddContentOf(sources.gigs[i]);
5530            }
5531        } catch (RIFF::Exception e) {
5532            throw RIFF::Exception(
5533                _("Error occurred while merging '") +
5534                filenames[i] +
5535                "': " +
5536                e.Message
5537            );
5538        } catch (...) {
5539            throw RIFF::Exception(
5540                _("Unknown exception occurred while merging '") +
5541                filenames[i] + "'"
5542            );
5543        }
5544    
5545        // Finally save gig file persistently to disk ...
5546        //NOTE: requires that this gig file already has a filename !
5547        {
5548            std::cout << "Saving file\n" << std::flush;
5549            file_structure_to_be_changed_signal.emit(this->file);
5550    
5551            progress_dialog = new ProgressDialog( //FIXME: memory leak!
5552                _("Saving") +  Glib::ustring(" '") +
5553                Glib::filename_display_basename(this->filename) + "' ...",
5554                *this
5555            );
5556    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5557            progress_dialog->show_all();
5558    #else
5559            progress_dialog->show();
5560    #endif
5561            saver = new Saver(this->file); //FIXME: memory leak!
5562            saver->signal_progress().connect(
5563                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
5564            saver->signal_finished().connect(
5565                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
5566            saver->signal_error().connect(
5567                sigc::mem_fun(*this, &MainWindow::on_saver_error));
5568            saver->launch();
5569        }
5570    }
5571    
5572    void MainWindow::on_action_merge_files() {
5573        if (this->file->GetFileName().empty()) {
5574            Glib::ustring txt = _(
5575                "You seem to have a new .gig file open that has not been saved "
5576                "yet. You must save it somewhere before starting to merge it with "
5577                "other .gig files though, because during the merge operation the "
5578                "other files' sample data must be written on file level to the "
5579                "target .gig file."
5580            );
5581            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5582            msg.run();
5583            return;
5584        }
5585    
5586        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
5587    #if HAS_GTKMM_STOCK
5588        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
5589    #else
5590        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
5591    #endif
5592        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
5593        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
5594    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
5595        Gtk::FileFilter filter;
5596        filter.add_pattern("*.gig");
5597    #else
5598        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
5599        filter->add_pattern("*.gig");
5600    #endif
5601        dialog.set_filter(filter);
5602        if (current_gig_dir != "") {
5603            dialog.set_current_folder(current_gig_dir);
5604        }
5605        dialog.set_select_multiple(true);
5606    
5607        // show warning in the file picker dialog
5608        HBox descriptionArea;
5609        descriptionArea.set_spacing(15);
5610        Gtk::Image warningIcon;
5611        warningIcon.set_from_icon_name("dialog-warning",
5612                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
5613        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
5614    #if GTKMM_MAJOR_VERSION < 3
5615        view::WrapLabel description;
5616    #else
5617        Gtk::Label description;
5618        description.set_line_wrap();
5619    #endif
5620        description.set_markup(_(
5621            "\nSelect at least one .gig file that shall be merged to the .gig file "
5622            "currently being open in gigedit.\n\n"
5623            "<b>Please Note:</b> Merging with other files will modify your "
5624            "currently open .gig file on file level! And be aware that the current "
5625            "merge algorithm does not detect duplicate samples yet. So if you are "
5626            "merging files which are using equivalent sample data, those "
5627            "equivalent samples will currently be treated as separate samples and "
5628            "will accordingly be stored separately in the target .gig file!"
5629        ));
5630        descriptionArea.pack_start(description);
5631    #if USE_GTKMM_BOX
5632    # warning No description area implemented for dialog on GTKMM 3
5633    #else
5634        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
5635    #endif
5636    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5637        descriptionArea.show_all();
5638    #else
5639        descriptionArea.show();
5640    #endif
5641    
5642        if (dialog.run() == Gtk::RESPONSE_OK) {
5643            dialog.hide();
5644    #ifdef GLIB_THREADS
5645            printf("on_action_merge_files self=%p\n",
5646                   static_cast<void*>(Glib::Threads::Thread::self()));
5647    #else
5648            std::cout << "on_action_merge_files self=" <<
5649                std::this_thread::get_id() << "\n";
5650    #endif
5651            std::vector<std::string> filenames = dialog.get_filenames();
5652    
5653            // merge the selected files to the currently open .gig file
5654            try {
5655                mergeFiles(filenames);
5656            } catch (RIFF::Exception e) {
5657                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
5658                msg.run();
5659            }
5660    
5661            // update GUI
5662            __refreshEntireGUI();
5663        }
5664    }
5665    
5666  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
5667      this->file_is_shared = b;      this->file_is_shared = b;
5668    
# Line 1868  void MainWindow::set_file_is_shared(bool Line 5677  void MainWindow::set_file_is_shared(bool
5677              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
5678          );          );
5679      }      }
5680    
5681        {
5682    #if USE_GTKMM_BUILDER
5683            m_actionToggleSyncSamplerSelection->property_enabled() = b;
5684    #else
5685            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
5686                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
5687            if (item) item->set_sensitive(b);
5688    #endif
5689        }
5690    }
5691    
5692    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
5693        if (!sample) return;
5694        sample_ref_count[sample] += offset;
5695        const int refcount = sample_ref_count[sample];
5696    
5697        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
5698        for (int g = 0; g < model->children().size(); ++g) {
5699            Gtk::TreeModel::Row rowGroup = model->children()[g];
5700            for (int s = 0; s < rowGroup.children().size(); ++s) {
5701                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
5702                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
5703                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
5704                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
5705            }
5706        }
5707    }
5708    
5709    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
5710        on_sample_ref_count_incremented(oldSample, -1);
5711        on_sample_ref_count_incremented(newSample, +1);
5712    }
5713    
5714    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
5715        // just in case a new sample is added later with exactly the same memory
5716        // address, which would lead to incorrect refcount if not deleted here
5717        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
5718             it != samples.end(); ++it)
5719        {
5720            sample_ref_count.erase(*it);
5721        }
5722    }
5723    
5724    void MainWindow::show_samples_tab() {
5725        m_TreeViewNotebook.set_current_page(0);
5726    }
5727    
5728    void MainWindow::show_intruments_tab() {
5729        m_TreeViewNotebook.set_current_page(1);
5730    }
5731    
5732    void MainWindow::show_scripts_tab() {
5733        m_TreeViewNotebook.set_current_page(2);
5734    }
5735    
5736    void MainWindow::select_instrument_by_dir(int dir) {
5737        if (!file) return;
5738        gig::Instrument* pInstrument = get_instrument();
5739        if (!pInstrument) {
5740            select_instrument( file->GetInstrument(0) );
5741            return;
5742        }
5743        for (int i = 0; file->GetInstrument(i); ++i) {
5744            if (file->GetInstrument(i) == pInstrument) {
5745                select_instrument( file->GetInstrument(i + dir) );
5746                return;
5747            }
5748        }
5749    }
5750    
5751    void MainWindow::select_prev_instrument() {
5752        select_instrument_by_dir(-1);
5753    }
5754    
5755    void MainWindow::select_next_instrument() {
5756        select_instrument_by_dir(1);
5757    }
5758    
5759    void MainWindow::select_prev_region() {
5760        m_RegionChooser.select_prev_region();
5761    }
5762    
5763    void MainWindow::select_next_region() {
5764        m_RegionChooser.select_next_region();
5765    }
5766    
5767    void MainWindow::select_next_dim_rgn_zone() {
5768        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5769        m_DimRegionChooser.select_next_dimzone();
5770    }
5771    
5772    void MainWindow::select_prev_dim_rgn_zone() {
5773        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5774        m_DimRegionChooser.select_prev_dimzone();
5775    }
5776    
5777    void MainWindow::select_add_next_dim_rgn_zone() {
5778        m_DimRegionChooser.select_next_dimzone(true);
5779    }
5780    
5781    void MainWindow::select_add_prev_dim_rgn_zone() {
5782        m_DimRegionChooser.select_prev_dimzone(true);
5783    }
5784    
5785    void MainWindow::select_prev_dimension() {
5786        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5787        m_DimRegionChooser.select_prev_dimension();
5788    }
5789    
5790    void MainWindow::select_next_dimension() {
5791        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5792        m_DimRegionChooser.select_next_dimension();
5793    }
5794    
5795    #define CLIPBOARD_DIMENSIONREGION_TARGET \
5796        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
5797    
5798    void MainWindow::copy_selected_dimrgn() {
5799        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5800        if (!pDimRgn) {
5801            updateClipboardPasteAvailable();
5802            updateClipboardCopyAvailable();
5803            return;
5804        }
5805    
5806        std::vector<Gtk::TargetEntry> targets;
5807        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
5808    
5809        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5810        clipboard->set(
5811            targets,
5812            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
5813            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
5814        );
5815    
5816        m_serializationArchive.serialize(pDimRgn);
5817    
5818        updateClipboardPasteAvailable();
5819    }
5820    
5821    void MainWindow::paste_copied_dimrgn() {
5822        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5823        clipboard->request_contents(
5824            CLIPBOARD_DIMENSIONREGION_TARGET,
5825            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
5826        );
5827        updateClipboardPasteAvailable();
5828    }
5829    
5830    void MainWindow::adjust_clipboard_content() {
5831        MacroEditor* editor = new MacroEditor();
5832        editor->setMacro(&m_serializationArchive, true);
5833        editor->show();
5834    }
5835    
5836    void MainWindow::updateClipboardPasteAvailable() {
5837        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5838        clipboard->request_targets(
5839            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
5840        );
5841    }
5842    
5843    void MainWindow::updateClipboardCopyAvailable() {
5844        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
5845    #if USE_GTKMM_BUILDER
5846        m_actionCopyDimRgn->property_enabled() = bDimensionRegionCopyIsPossible;
5847    #else
5848        static_cast<Gtk::MenuItem*>(
5849            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
5850        )->set_sensitive(bDimensionRegionCopyIsPossible);
5851    #endif
5852    }
5853    
5854    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && (GTKMM_MINOR_VERSION > 91 || (GTKMM_MINOR_VERSION == 91 && GTKMM_MICRO_VERSION >= 2))) // GTKMM >= 3.91.2
5855    void MainWindow::on_clipboard_owner_change(Gdk::EventOwnerChange& event) {
5856    #else
5857    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
5858    #endif
5859        updateClipboardPasteAvailable();
5860    }
5861    
5862    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
5863        const std::string target = selection_data.get_target();
5864        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5865            selection_data.set(
5866                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
5867                &m_serializationArchive.rawData()[0],
5868                m_serializationArchive.rawData().size()
5869            );
5870        } else {
5871            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
5872        }
5873    }
5874    
5875    void MainWindow::on_clipboard_clear() {
5876        m_serializationArchive.clear();
5877        updateClipboardPasteAvailable();
5878        updateClipboardCopyAvailable();
5879    }
5880    
5881    //NOTE: Might throw exception !!!
5882    void MainWindow::applyMacro(Serialization::Archive& macro) {
5883        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5884        if (!pDimRgn) return;
5885    
5886        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
5887             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
5888        {
5889            gig::DimensionRegion* pDimRgn = *itDimReg;
5890            DimRegionChangeGuard(this, pDimRgn);
5891            macro.deserialize(pDimRgn);
5892        }
5893        //region_changed()
5894        file_changed();
5895        dimreg_changed();
5896    }
5897    
5898    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
5899        const std::string target = selection_data.get_target();
5900        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5901            Glib::ustring errorText;
5902            try {
5903                m_serializationArchive.decode(
5904                    selection_data.get_data(), selection_data.get_length()
5905                );
5906                applyMacro(m_serializationArchive);
5907            } catch (Serialization::Exception e) {
5908                errorText = e.Message;
5909            } catch (...) {
5910                errorText = _("Unknown exception while pasting DimensionRegion");
5911            }
5912            if (!errorText.empty()) {
5913                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
5914                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5915                msg.run();
5916            }
5917        }
5918    }
5919    
5920    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
5921        const bool bDimensionRegionPasteIsPossible =
5922            std::find(targets.begin(), targets.end(),
5923                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
5924    
5925    #if USE_GTKMM_BUILDER
5926        m_actionPasteDimRgn->property_enabled() = bDimensionRegionPasteIsPossible;
5927        m_actionAdjustClipboard->property_enabled() = bDimensionRegionPasteIsPossible;
5928    #else
5929        static_cast<Gtk::MenuItem*>(
5930            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
5931        )->set_sensitive(bDimensionRegionPasteIsPossible);
5932    
5933        static_cast<Gtk::MenuItem*>(
5934            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
5935        )->set_sensitive(bDimensionRegionPasteIsPossible);
5936    #endif
5937  }  }
5938    
5939  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 1925  sigc::signal<void, int/*key*/, int/*velo Line 5991  sigc::signal<void, int/*key*/, int/*velo
5991  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
5992      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
5993  }  }
5994    
5995    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
5996        return switch_sampler_instrument_signal;
5997    }

Legend:
Removed from v.2332  
changed lines
  Added in v.3811

  ViewVC Help
Powered by ViewVC