/[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 2398 by persson, Sun Jan 13 09:14:29 2013 UTC revision 3643 by schoenebeck, Sat Dec 7 15:04:51 2019 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006-2013 Andreas Persson   * Copyright (C) 2006-2019 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  #if GTKMM_MAJOR_VERSION < 3
43  #include "wrapLabel.hh"  #include "wrapLabel.hh"
44  #endif  #endif
# Line 40  Line 47 
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(960, 600);
100    #else
101            set_default_size(865, 600);
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_TreeView.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_TreeView.set_reorderable();
113    
114    #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_TreeView.signal_button_press_event().connect(
116            sigc::mem_fun(*this, &MainWindow::on_button_release));
117    #else
118      m_TreeView.signal_button_press_event().connect_notify(      m_TreeView.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_TreeView);
# Line 108  MainWindow::MainWindow() : Line 127  MainWindow::MainWindow() :
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 119  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 155  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("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      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  #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_actionToggleShowTooltips = m_actionGroup->add_action_bool(
455            "ShowTooltips", sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips),
456            Settings::singleton()->showTooltips
457        );
458        m_actionToggleSaveWithTempFile =
459            m_actionGroup->add_action_bool("SaveWithTemporaryFile", sigc::mem_fun(*this, &MainWindow::on_save_with_temporary_file), Settings::singleton()->saveWithTemporaryFile);
460        m_actionGroup->add_action("RefreshAll", sigc::mem_fun(*this, &MainWindow::on_action_refresh_all));
461    #else
462        actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
463    
464    
465        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
466        toggle_action =
467          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
468      toggle_action->set_active(true);      toggle_action->set_active(true);
469      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
470                       sigc::mem_fun(                       sigc::mem_fun(
471                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
472    
473        toggle_action =
474            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
475        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
476        actionGroup->add(toggle_action,
477                         sigc::mem_fun(
478                             *this, &MainWindow::on_auto_restore_win_dim));
479    
480        toggle_action =
481            Gtk::ToggleAction::create("ShowTooltips", _("Tooltips for Beginners"));
482        toggle_action->set_active(Settings::singleton()->showTooltips);
483        actionGroup->add(
484            toggle_action,
485            sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips)
486        );
487    
488        toggle_action =
489            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
490        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
491        actionGroup->add(toggle_action,
492                         sigc::mem_fun(
493                             *this, &MainWindow::on_save_with_temporary_file));
494    
495        actionGroup->add(
496            Gtk::Action::create("RefreshAll", _("_Refresh All")),
497            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
498        );                
499    #endif
500    
501    #if USE_GLIB_ACTION
502        m_actionGroup->add_action(
503            "About", sigc::mem_fun(*this, &MainWindow::on_action_help_about)
504        );
505        m_actionGroup->add_action(
506            "AddInstrument", sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
507        );
508        m_actionGroup->add_action(
509            "DupInstrument", sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
510        );
511        m_actionGroup->add_action(
512            "CombInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
513        );
514        m_actionGroup->add_action(
515            "RemoveInstrument", sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
516        );
517    #else
518      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
519      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
520                                           action->property_label()));                                           action->property_label()));
# Line 183  MainWindow::MainWindow() : Line 530  MainWindow::MainWindow() :
530          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
531      );      );
532      actionGroup->add(      actionGroup->add(
533            Gtk::Action::create("CombInstruments", _("_Combine Instruments ...")),
534            Gtk::AccelKey(GDK_KEY_j, primaryModifierKey),
535            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
536        );
537        actionGroup->add(
538          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
539          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
540      );      );
541    #endif
542    
543    #if USE_GLIB_ACTION
544        m_actionToggleWarnOnExtensions = m_actionGroup->add_action_bool(
545            "WarnUserOnExtensions", sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions),
546            Settings::singleton()->warnUserOnExtensions
547        );
548        m_actionToggleSyncSamplerSelection = m_actionGroup->add_action_bool(
549            "SyncSamplerInstrumentSelection", sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection),
550            Settings::singleton()->syncSamplerInstrumentSelection
551        );
552        m_actionToggleMoveRootNoteWithRegion = m_actionGroup->add_action_bool(
553            "MoveRootNoteWithRegionMoved", sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved),
554            Settings::singleton()->moveRootNoteWithRegionMoved
555        );
556    #else
557        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
558        
559        toggle_action =
560            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
561        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
562        actionGroup->add(
563            toggle_action,
564            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
565        );
566    
567        toggle_action =
568            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
569        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
570        actionGroup->add(
571            toggle_action,
572            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
573        );
574    
575        toggle_action =
576            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
577        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
578        actionGroup->add(
579            toggle_action,
580            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
581        );
582    #endif
583    
584    #if USE_GLIB_ACTION
585        m_actionGroup->add_action(
586            "CombineInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
587        );
588        m_actionGroup->add_action(
589            "MergeFiles", sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
590        );
591    #else
592        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
593    
594        actionGroup->add(
595            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
596            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
597        );
598    
599        actionGroup->add(
600            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
601            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
602        );
603    #endif
604    
605      // sample right-click popup actions      // sample right-click popup actions
606    #if USE_GLIB_ACTION
607        m_actionSampleProperties = m_actionGroup->add_action(
608            "SampleProperties", sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
609        );
610        m_actionAddSampleGroup = m_actionGroup->add_action(
611            "AddGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_group)
612        );
613        m_actionAddSample = m_actionGroup->add_action(
614            "AddSample", sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
615        );
616        m_actionRemoveSample = m_actionGroup->add_action(
617            "RemoveSample", sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
618        );
619        m_actionGroup->add_action(
620            "RemoveUnusedSamples", sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
621        );
622        m_actionViewSampleRefs = m_actionGroup->add_action(
623            "ShowSampleRefs", sigc::mem_fun(*this, &MainWindow::on_action_view_references)
624        );
625        m_actionReplaceSample = m_actionGroup->add_action(
626            "ReplaceSample", sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
627        );
628        m_actionGroup->add_action(
629            "ReplaceAllSamplesInAllGroups", sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
630        );
631    #else
632      actionGroup->add(      actionGroup->add(
633          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
634          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
# Line 205  MainWindow::MainWindow() : Line 646  MainWindow::MainWindow() :
646          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
647      );      );
648      actionGroup->add(      actionGroup->add(
649            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
650            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
651        );
652        actionGroup->add(
653            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
654            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
655        );
656        actionGroup->add(
657            Gtk::Action::create("ReplaceSample",
658                                _("Replace Sample...")),
659            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
660        );
661        actionGroup->add(
662          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
663                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
664          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)
665      );      );
666    #endif
667        
668        // script right-click popup actions
669    #if USE_GLIB_ACTION
670        m_actionAddScriptGroup = m_actionGroup->add_action(
671            "AddScriptGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
672        );
673        m_actionAddScript = m_actionGroup->add_action(
674            "AddScript", sigc::mem_fun(*this, &MainWindow::on_action_add_script)
675        );
676        m_actionEditScript = m_actionGroup->add_action(
677            "EditScript", sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
678        );
679        m_actionRemoveScript = m_actionGroup->add_action(
680            "RemoveScript", sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
681        );
682    #else
683        actionGroup->add(
684            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
685            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
686        );
687        actionGroup->add(
688            Gtk::Action::create("AddScript", _("Add _Script")),
689            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
690        );
691        actionGroup->add(
692            Gtk::Action::create("EditScript", _("_Edit Script...")),
693            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
694        );
695        actionGroup->add(
696            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
697            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
698        );
699    #endif
700    
701    #if USE_GTKMM_BUILDER
702        insert_action_group("AppMenu", m_actionGroup);
703        
704        m_uiManager = Gtk::Builder::create();
705        Glib::ustring ui_info =
706            "<interface>"
707            "  <menubar id='MenuBar'>"
708            "    <menu id='MenuFile'>"
709            "      <attribute name='label' translatable='yes'>_File</attribute>"
710            "      <section>"
711            "        <item id='New'>"
712            "          <attribute name='label' translatable='yes'>New</attribute>"
713            "          <attribute name='action'>AppMenu.New</attribute>"
714            "        </item>"
715            "        <item id='Open'>"
716            "          <attribute name='label' translatable='yes'>Open</attribute>"
717            "          <attribute name='action'>AppMenu.Open</attribute>"
718            "        </item>"
719            "      </section>"
720            "      <section>"
721            "        <item id='Save'>"
722            "          <attribute name='label' translatable='yes'>Save</attribute>"
723            "          <attribute name='action'>AppMenu.Save</attribute>"
724            "        </item>"
725            "        <item id='SaveAs'>"
726            "          <attribute name='label' translatable='yes'>Save As</attribute>"
727            "          <attribute name='action'>AppMenu.SaveAs</attribute>"
728            "        </item>"
729            "      </section>"
730            "      <section>"
731            "        <item id='Properties'>"
732            "          <attribute name='label' translatable='yes'>Properties</attribute>"
733            "          <attribute name='action'>AppMenu.Properties</attribute>"
734            "        </item>"
735            "      </section>"
736            "      <section>"
737            "        <item id='Quit'>"
738            "          <attribute name='label' translatable='yes'>Quit</attribute>"
739            "          <attribute name='action'>AppMenu.Quit</attribute>"
740            "        </item>"
741            "      </section>"
742            "    </menu>"
743            "    <menu id='MenuEdit'>"
744            "      <attribute name='label' translatable='yes'>Edit</attribute>"
745            "      <section>"
746            "        <item id='CopyDimRgn'>"
747            "          <attribute name='label' translatable='yes'>Copy Dimension Region</attribute>"
748            "          <attribute name='action'>AppMenu.CopyDimRgn</attribute>"
749            "        </item>"
750            "        <item id='AdjustClipboard'>"
751            "          <attribute name='label' translatable='yes'>Adjust Clipboard</attribute>"
752            "          <attribute name='action'>AppMenu.AdjustClipboard</attribute>"
753            "        </item>"
754            "        <item id='PasteDimRgn'>"
755            "          <attribute name='label' translatable='yes'>Paste Dimension Region</attribute>"
756            "          <attribute name='action'>AppMenu.PasteDimRgn</attribute>"
757            "        </item>"
758            "      </section>"
759            "        <item id='SelectPrevInstr'>"
760            "          <attribute name='label' translatable='yes'>Previous Instrument</attribute>"
761            "          <attribute name='action'>AppMenu.SelectPrevInstr</attribute>"
762            "        </item>"
763            "        <item id='SelectNextInstr'>"
764            "          <attribute name='label' translatable='yes'>Next Instrument</attribute>"
765            "          <attribute name='action'>AppMenu.SelectNextInstr</attribute>"
766            "        </item>"
767            "      <section>"
768            "        <item id='SelectPrevRegion'>"
769            "          <attribute name='label' translatable='yes'>Previous Region</attribute>"
770            "          <attribute name='action'>AppMenu.SelectPrevRegion</attribute>"
771            "        </item>"
772            "        <item id='SelectNextRegion'>"
773            "          <attribute name='label' translatable='yes'>Next Region</attribute>"
774            "          <attribute name='action'>AppMenu.SelectNextRegion</attribute>"
775            "        </item>"
776            "      </section>"
777            "        <item id='SelectPrevDimension'>"
778            "          <attribute name='label' translatable='yes'>Previous Dimension</attribute>"
779            "          <attribute name='action'>AppMenu.SelectPrevDimension</attribute>"
780            "        </item>"
781            "        <item id='SelectNextDimension'>"
782            "          <attribute name='label' translatable='yes'>Next Dimension</attribute>"
783            "          <attribute name='action'>AppMenu.SelectNextDimension</attribute>"
784            "        </item>"
785            "        <item id='SelectPrevDimRgnZone'>"
786            "          <attribute name='label' translatable='yes'>Previous Dimension Region Zone</attribute>"
787            "          <attribute name='action'>AppMenu.SelectPrevDimRgnZone</attribute>"
788            "        </item>"
789            "        <item id='SelectNextDimRgnZone'>"
790            "          <attribute name='label' translatable='yes'>Next Dimension Region Zone</attribute>"
791            "          <attribute name='action'>AppMenu.SelectNextDimRgnZone</attribute>"
792            "        </item>"
793            "        <item id='SelectAddPrevDimRgnZone'>"
794            "          <attribute name='label' translatable='yes'>Add Previous Dimension Region Zone</attribute>"
795            "          <attribute name='action'>AppMenu.SelectAddPrevDimRgnZone</attribute>"
796            "        </item>"
797            "        <item id='SelectAddNextDimRgnZone'>"
798            "          <attribute name='label' translatable='yes'>Add Next Dimension Region Zone</attribute>"
799            "          <attribute name='action'>AppMenu.SelectAddNextDimRgnZone</attribute>"
800            "        </item>"
801            "      <section>"
802            "        <item id='CopySampleUnity'>"
803            "          <attribute name='label' translatable='yes'>Copy Sample Unity</attribute>"
804            "          <attribute name='action'>AppMenu.CopySampleUnity</attribute>"
805            "        </item>"
806            "        <item id='CopySampleTune'>"
807            "          <attribute name='label' translatable='yes'>Copy Sample Tune</attribute>"
808            "          <attribute name='action'>AppMenu.CopySampleTune</attribute>"
809            "        </item>"
810            "        <item id='CopySampleLoop'>"
811            "          <attribute name='label' translatable='yes'>Copy Sample Loop</attribute>"
812            "          <attribute name='action'>AppMenu.CopySampleLoop</attribute>"
813            "        </item>"
814            "      </section>"
815            "    </menu>"
816            "    <menu id='MenuMacro'>"
817            "      <attribute name='label' translatable='yes'>Macro</attribute>"
818            "      <section>"
819            "      </section>"
820            "    </menu>"
821            "    <menu id='MenuSample'>"
822            "      <attribute name='label' translatable='yes'>Sample</attribute>"
823            "      <section>"
824            "        <item id='SampleProperties'>"
825            "          <attribute name='label' translatable='yes'>Properties</attribute>"
826            "          <attribute name='action'>AppMenu.SampleProperties</attribute>"
827            "        </item>"
828            "        <item id='AddGroup'>"
829            "          <attribute name='label' translatable='yes'>Add Group</attribute>"
830            "          <attribute name='action'>AppMenu.AddGroup</attribute>"
831            "        </item>"
832            "        <item id='AddSample'>"
833            "          <attribute name='label' translatable='yes'>Add Sample</attribute>"
834            "          <attribute name='action'>AppMenu.AddSample</attribute>"
835            "        </item>"
836            "        <item id='ShowSampleRefs'>"
837            "          <attribute name='label' translatable='yes'>Show Sample References</attribute>"
838            "          <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
839            "        </item>"
840            "        <item id='ReplaceSample'>"
841            "          <attribute name='label' translatable='yes'>Replace Sample</attribute>"
842            "          <attribute name='action'>AppMenu.ReplaceSample</attribute>"
843            "        </item>"
844            "        <item id='ReplaceAllSamplesInAllGroups'>"
845            "          <attribute name='label' translatable='yes'>Replace all Samples in all Groups</attribute>"
846            "          <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
847            "        </item>"
848            "      </section>"
849            "      <section>"
850            "        <item id='RemoveSample'>"
851            "          <attribute name='label' translatable='yes'>Remove Sample</attribute>"
852            "          <attribute name='action'>AppMenu.RemoveSample</attribute>"
853            "        </item>"
854            "        <item id='RemoveUnusedSamples'>"
855            "          <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
856            "          <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
857            "        </item>"
858            "      </section>"
859            "    </menu>"
860            "    <menu id='MenuInstrument'>"
861            "      <attribute name='label' translatable='yes'>Instrument</attribute>"
862            "      <section>"
863            "        <item id='InstrProperties'>"
864            "          <attribute name='label' translatable='yes'>Properties</attribute>"
865            "          <attribute name='action'>AppMenu.InstrProperties</attribute>"
866            "        </item>"
867            "        <item id='MidiRules'>"
868            "          <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
869            "          <attribute name='action'>AppMenu.MidiRules</attribute>"
870            "        </item>"
871            "        <item id='ScriptSlots'>"
872            "          <attribute name='label' translatable='yes'>Script Slots</attribute>"
873            "          <attribute name='action'>AppMenu.ScriptSlots</attribute>"
874            "        </item>"
875            "      </section>"
876            "      <submenu id='AssignScripts'>"
877            "        <attribute name='label' translatable='yes'>Assign Scripts</attribute>"
878            "      </submenu>"
879            "      <section>"
880            "        <item id='AddInstrument'>"
881            "          <attribute name='label' translatable='yes'>Add Instrument</attribute>"
882            "          <attribute name='action'>AppMenu.AddInstrument</attribute>"
883            "        </item>"
884            "        <item id='DupInstrument'>"
885            "          <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
886            "          <attribute name='action'>AppMenu.DupInstrument</attribute>"
887            "        </item>"
888            "        <item id='CombInstruments'>"
889            "          <attribute name='label' translatable='yes'>Combine Instrument</attribute>"
890            "          <attribute name='action'>AppMenu.CombInstruments</attribute>"
891            "        </item>"
892            "      </section>"
893            "      <section>"
894            "        <item id='RemoveInstrument'>"
895            "          <attribute name='label' translatable='yes'>Remove Instrument</attribute>"
896            "          <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
897            "        </item>"
898            "      </section>"
899            "    </menu>"
900            "    <menu id='MenuScript'>"
901            "      <attribute name='label' translatable='yes'>Script</attribute>"
902            "      <section>"
903            "        <item id='AddScriptGroup'>"
904            "          <attribute name='label' translatable='yes'>Add Script Group</attribute>"
905            "          <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
906            "        </item>"
907            "        <item id='AddScript'>"
908            "          <attribute name='label' translatable='yes'>Add Script</attribute>"
909            "          <attribute name='action'>AppMenu.AddScript</attribute>"
910            "        </item>"
911            "        <item id='EditScript'>"
912            "          <attribute name='label' translatable='yes'>Edit Script</attribute>"
913            "          <attribute name='action'>AppMenu.EditScript</attribute>"
914            "        </item>"
915            "      </section>"
916            "      <section>"
917            "        <item id='RemoveScript'>"
918            "          <attribute name='label' translatable='yes'>Remove Script</attribute>"
919            "          <attribute name='action'>AppMenu.RemoveScript</attribute>"
920            "        </item>"
921            "      </section>"
922            "    </menu>"
923            "    <menu id='MenuView'>"
924            "      <attribute name='label' translatable='yes'>View</attribute>"
925            "      <section>"
926            "        <item id='Statusbar'>"
927            "          <attribute name='label' translatable='yes'>Statusbar</attribute>"
928            "          <attribute name='action'>AppMenu.Statusbar</attribute>"
929            "        </item>"
930            "        <item id='ShowTooltips'>"
931            "          <attribute name='label' translatable='yes'>Tooltips for Beginners</attribute>"
932            "          <attribute name='action'>AppMenu.ShowTooltips</attribute>"
933            "        </item>"
934            "        <item id='AutoRestoreWinDim'>"
935            "          <attribute name='label' translatable='yes'>Auto restore Window Dimensions</attribute>"
936            "          <attribute name='action'>AppMenu.AutoRestoreWinDim</attribute>"
937            "        </item>"
938            "      </section>"
939            "      <section>"
940            "        <item id='RefreshAll'>"
941            "          <attribute name='label' translatable='yes'>Refresh All</attribute>"
942            "          <attribute name='action'>AppMenu.RefreshAll</attribute>"
943            "        </item>"
944            "      </section>"
945            "    </menu>"
946            "    <menu id='MenuTools'>"
947            "      <attribute name='label' translatable='yes'>Tools</attribute>"
948            "      <section>"
949            "        <item id='CombineInstruments'>"
950            "          <attribute name='label' translatable='yes'>Combine Instruments ...</attribute>"
951            "          <attribute name='action'>AppMenu.CombineInstruments</attribute>"
952            "        </item>"
953            "        <item id='MergeFiles'>"
954            "          <attribute name='label' translatable='yes'>Merge Files ...</attribute>"
955            "          <attribute name='action'>AppMenu.MergeFiles</attribute>"
956            "        </item>"
957            "      </section>"
958            "    </menu>"
959            "    <menu id='MenuSettings'>"
960            "      <attribute name='label' translatable='yes'>Settings</attribute>"
961            "      <section>"
962            "        <item id='WarnUserOnExtensions'>"
963            "          <attribute name='label' translatable='yes'>Warning on Format Extensions</attribute>"
964            "          <attribute name='action'>AppMenu.WarnUserOnExtensions</attribute>"
965            "        </item>"
966            "        <item id='SyncSamplerInstrumentSelection'>"
967            "          <attribute name='label' translatable='yes'>Synchronize Sampler Selection</attribute>"
968            "          <attribute name='action'>AppMenu.SyncSamplerInstrumentSelection</attribute>"
969            "        </item>"
970            "        <item id='MoveRootNoteWithRegionMoved'>"
971            "          <attribute name='label' translatable='yes'>Move Root Note with Region moved</attribute>"
972            "          <attribute name='action'>AppMenu.MoveRootNoteWithRegionMoved</attribute>"
973            "        </item>"
974            "        <item id='SaveWithTemporaryFile'>"
975            "          <attribute name='label' translatable='yes'>Save with temporary file</attribute>"
976            "          <attribute name='action'>AppMenu.SaveWithTemporaryFile</attribute>"
977            "        </item>"
978            "      </section>"
979            "    </menu>"
980            "    <menu id='MenuHelp'>"
981            "      <attribute name='label' translatable='yes'>Help</attribute>"
982            "      <section>"
983            "        <item id='About'>"
984            "          <attribute name='label' translatable='yes'>About ...</attribute>"
985            "          <attribute name='action'>AppMenu.About</attribute>"
986            "        </item>"
987            "      </section>"
988            "    </menu>"
989            "  </menubar>"
990            // popups
991            "  <menu id='PopupMenu'>"
992            "    <section>"
993            "      <item id='InstrProperties'>"
994            "        <attribute name='label' translatable='yes'>Instrument Properties</attribute>"
995            "        <attribute name='action'>AppMenu.InstrProperties</attribute>"
996            "      </item>"
997            "      <item id='MidiRules'>"
998            "        <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
999            "        <attribute name='action'>AppMenu.MidiRules</attribute>"
1000            "      </item>"
1001            "      <item id='ScriptSlots'>"
1002            "        <attribute name='label' translatable='yes'>Script Slots</attribute>"
1003            "        <attribute name='action'>AppMenu.ScriptSlots</attribute>"
1004            "      </item>"
1005            "      <item id='AddInstrument'>"
1006            "        <attribute name='label' translatable='yes'>Add Instrument</attribute>"
1007            "        <attribute name='action'>AppMenu.AddInstrument</attribute>"
1008            "      </item>"
1009            "      <item id='DupInstrument'>"
1010            "        <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
1011            "        <attribute name='action'>AppMenu.DupInstrument</attribute>"
1012            "      </item>"
1013            "      <item id='CombInstruments'>"
1014            "        <attribute name='label' translatable='yes'>Combine Instruments</attribute>"
1015            "        <attribute name='action'>AppMenu.CombInstruments</attribute>"
1016            "      </item>"
1017            "    </section>"
1018            "    <section>"
1019            "      <item id='RemoveInstrument'>"
1020            "        <attribute name='label' translatable='yes'>Remove Instruments</attribute>"
1021            "        <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
1022            "      </item>"
1023            "    </section>"
1024            "  </menu>"
1025            "  <menu id='SamplePopupMenu'>"
1026            "    <section>"
1027            "      <item id='SampleProperties'>"
1028            "        <attribute name='label' translatable='yes'>Sample Properties</attribute>"
1029            "        <attribute name='action'>AppMenu.SampleProperties</attribute>"
1030            "      </item>"
1031            "      <item id='AddGroup'>"
1032            "        <attribute name='label' translatable='yes'>Add Sample Group</attribute>"
1033            "        <attribute name='action'>AppMenu.AddGroup</attribute>"
1034            "      </item>"
1035            "      <item id='AddSample'>"
1036            "        <attribute name='label' translatable='yes'>Add Sample</attribute>"
1037            "        <attribute name='action'>AppMenu.AddSample</attribute>"
1038            "      </item>"
1039            "      <item id='ShowSampleRefs'>"
1040            "        <attribute name='label' translatable='yes'>Show Sample References ...</attribute>"
1041            "        <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
1042            "      </item>"
1043            "      <item id='ReplaceSample'>"
1044            "        <attribute name='label' translatable='yes'>Replace Sample</attribute>"
1045            "        <attribute name='action'>AppMenu.ReplaceSample</attribute>"
1046            "      </item>"
1047            "      <item id='ReplaceAllSamplesInAllGroups'>"
1048            "        <attribute name='label' translatable='yes'>Replace all Samples ...</attribute>"
1049            "        <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
1050            "      </item>"
1051            "    </section>"
1052            "    <section>"
1053            "      <item id='RemoveSample'>"
1054            "        <attribute name='label' translatable='yes'>Remove Sample</attribute>"
1055            "        <attribute name='action'>AppMenu.RemoveSample</attribute>"
1056            "      </item>"
1057            "      <item id='RemoveUnusedSamples'>"
1058            "        <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
1059            "        <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
1060            "      </item>"
1061            "    </section>"
1062            "  </menu>"
1063            "  <menu id='ScriptPopupMenu'>"
1064            "    <section>"
1065            "      <item id='AddScriptGroup'>"
1066            "        <attribute name='label' translatable='yes'>Add Script Group</attribute>"
1067            "        <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
1068            "      </item>"
1069            "      <item id='AddScript'>"
1070            "        <attribute name='label' translatable='yes'>Add Script</attribute>"
1071            "        <attribute name='action'>AppMenu.AddScript</attribute>"
1072            "      </item>"
1073            "      <item id='EditScript'>"
1074            "        <attribute name='label' translatable='yes'>Edit Script</attribute>"
1075            "        <attribute name='action'>AppMenu.EditScript</attribute>"
1076            "      </item>"
1077            "    </section>"
1078            "    <section>"
1079            "      <item id='RemoveScript'>"
1080            "        <attribute name='label' translatable='yes'>Remove Script</attribute>"
1081            "        <attribute name='action'>AppMenu.RemoveScript</attribute>"
1082            "      </item>"
1083            "    </section>"
1084            "  </menu>"
1085            "</interface>";
1086        m_uiManager->add_from_string(ui_info);
1087    #else
1088      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
1089      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
1090      add_accel_group(uiManager->get_accel_group());      add_accel_group(uiManager->get_accel_group());
# Line 228  MainWindow::MainWindow() : Line 1103  MainWindow::MainWindow() :
1103          "      <separator/>"          "      <separator/>"
1104          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
1105          "    </menu>"          "    </menu>"
1106            "    <menu action='MenuEdit'>"
1107            "      <menuitem action='CopyDimRgn'/>"
1108            "      <menuitem action='AdjustClipboard'/>"
1109            "      <menuitem action='PasteDimRgn'/>"
1110            "      <separator/>"
1111            "      <menuitem action='SelectPrevInstr'/>"
1112            "      <menuitem action='SelectNextInstr'/>"
1113            "      <separator/>"
1114            "      <menuitem action='SelectPrevRegion'/>"
1115            "      <menuitem action='SelectNextRegion'/>"
1116            "      <separator/>"
1117            "      <menuitem action='SelectPrevDimension'/>"
1118            "      <menuitem action='SelectNextDimension'/>"
1119            "      <menuitem action='SelectPrevDimRgnZone'/>"
1120            "      <menuitem action='SelectNextDimRgnZone'/>"
1121            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
1122            "      <menuitem action='SelectAddNextDimRgnZone'/>"
1123            "      <separator/>"
1124            "      <menuitem action='CopySampleUnity'/>"
1125            "      <menuitem action='CopySampleTune'/>"
1126            "      <menuitem action='CopySampleLoop'/>"
1127            "    </menu>"
1128            "    <menu action='MenuMacro'>"
1129            "    </menu>"
1130            "    <menu action='MenuSample'>"
1131            "      <menuitem action='SampleProperties'/>"
1132            "      <menuitem action='AddGroup'/>"
1133            "      <menuitem action='AddSample'/>"
1134            "      <menuitem action='ShowSampleRefs'/>"
1135            "      <menuitem action='ReplaceSample' />"
1136            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
1137            "      <separator/>"
1138            "      <menuitem action='RemoveSample'/>"
1139            "      <menuitem action='RemoveUnusedSamples'/>"
1140            "    </menu>"
1141          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
1142            "      <menu action='AllInstruments'>"
1143            "      </menu>"
1144            "      <separator/>"
1145            "      <menuitem action='InstrProperties'/>"
1146            "      <menuitem action='MidiRules'/>"
1147            "      <menuitem action='ScriptSlots'/>"
1148            "      <menu action='AssignScripts'/>"
1149            "      <menuitem action='AddInstrument'/>"
1150            "      <menuitem action='DupInstrument'/>"
1151            "      <menuitem action='CombInstruments'/>"
1152            "      <separator/>"
1153            "      <menuitem action='RemoveInstrument'/>"
1154            "    </menu>"
1155            "    <menu action='MenuScript'>"
1156            "      <menuitem action='AddScriptGroup'/>"
1157            "      <menuitem action='AddScript'/>"
1158            "      <menuitem action='EditScript'/>"
1159            "      <separator/>"
1160            "      <menuitem action='RemoveScript'/>"
1161          "    </menu>"          "    </menu>"
1162          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
1163          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
1164            "      <menuitem action='ShowTooltips'/>"
1165            "      <menuitem action='AutoRestoreWinDim'/>"
1166            "      <separator/>"
1167            "      <menuitem action='RefreshAll'/>"
1168            "    </menu>"
1169            "    <menu action='MenuTools'>"
1170            "      <menuitem action='CombineInstruments'/>"
1171            "      <menuitem action='MergeFiles'/>"
1172            "    </menu>"
1173            "    <menu action='MenuSettings'>"
1174            "      <menuitem action='WarnUserOnExtensions'/>"
1175            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
1176            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
1177            "      <menuitem action='SaveWithTemporaryFile'/>"
1178          "    </menu>"          "    </menu>"
1179          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
1180          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 239  MainWindow::MainWindow() : Line 1182  MainWindow::MainWindow() :
1182          "  </menubar>"          "  </menubar>"
1183          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
1184          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
1185            "    <menuitem action='MidiRules'/>"
1186            "    <menuitem action='ScriptSlots'/>"
1187          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
1188          "    <menuitem action='DupInstrument'/>"          "    <menuitem action='DupInstrument'/>"
1189            "    <menuitem action='CombInstruments'/>"
1190          "    <separator/>"          "    <separator/>"
1191          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
1192          "  </popup>"          "  </popup>"
# Line 248  MainWindow::MainWindow() : Line 1194  MainWindow::MainWindow() :
1194          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
1195          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
1196          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
1197          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ShowSampleRefs'/>"
1198            "    <menuitem action='ReplaceSample' />"
1199            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
1200          "    <separator/>"          "    <separator/>"
1201          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
1202            "    <menuitem action='RemoveUnusedSamples'/>"
1203            "  </popup>"
1204            "  <popup name='ScriptPopupMenu'>"
1205            "    <menuitem action='AddScriptGroup'/>"
1206            "    <menuitem action='AddScript'/>"
1207            "    <menuitem action='EditScript'/>"
1208            "    <separator/>"
1209            "    <menuitem action='RemoveScript'/>"
1210          "  </popup>"          "  </popup>"
1211          "</ui>";          "</ui>";
1212      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
1213    #endif
1214    
1215    #if USE_GTKMM_BUILDER
1216        popup_menu = new Gtk::Menu(
1217            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1218                m_uiManager->get_object("PopupMenu")
1219            )
1220        );
1221        sample_popup = new Gtk::Menu(
1222            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1223                m_uiManager->get_object("SamplePopupMenu")
1224            )
1225        );
1226        script_popup = new Gtk::Menu(
1227            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1228                m_uiManager->get_object("ScriptPopupMenu")
1229            )
1230        );
1231    #else
1232      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
1233        
1234        // Set tooltips for menu items (for some reason, setting a tooltip on the
1235        // respective Gtk::Action objects above will simply be ignored, no matter
1236        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
1237        // Gtk::Action::create()).
1238        {
1239            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1240                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1241            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."));
1242        }
1243        {
1244            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1245                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
1246            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."));
1247        }
1248        {
1249            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1250                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
1251            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."));
1252        }
1253        {
1254            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1255                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
1256            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."));
1257        }
1258        {
1259            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1260                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
1261            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)."));
1262        }
1263        {
1264            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1265                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
1266            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."));
1267        }
1268        {
1269            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1270                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
1271            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
1272            // copy tooltip to popup menu
1273            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
1274                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
1275            item2->set_tooltip_text(item->get_tooltip_text());
1276        }
1277        {
1278            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1279                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
1280            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
1281        }
1282        {
1283            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1284                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
1285            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
1286        }
1287        {
1288            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1289                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
1290            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
1291        }
1292        {
1293            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1294                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
1295            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
1296        }
1297    #endif
1298    
1299    #if USE_GTKMM_BUILDER
1300        assign_scripts_menu = new Gtk::Menu(
1301            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1302                m_uiManager->get_object("AssignScripts")
1303            )
1304        );
1305    #else
1306        instrument_menu = static_cast<Gtk::MenuItem*>(
1307            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
1308    
1309        assign_scripts_menu = static_cast<Gtk::MenuItem*>(
1310            uiManager->get_widget("/MenuBar/MenuInstrument/AssignScripts"))->get_submenu();
1311    #endif
1312    
1313    #if USE_GTKMM_BUILDER
1314        Gtk::Widget* menuBar = NULL;
1315        m_uiManager->get_widget("MenuBar", menuBar);
1316    #else
1317      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
1318    #endif
1319    
1320      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
1321      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
1322      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
# Line 268  MainWindow::MainWindow() : Line 1327  MainWindow::MainWindow() :
1327      set_file_is_shared(false);      set_file_is_shared(false);
1328    
1329      // Status Bar:      // Status Bar:
1330    #if USE_GTKMM_BOX
1331    # warning No status bar layout for GTKMM 4 yet
1332    #else
1333      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
1334      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
1335    #endif
1336      m_StatusBar.show();      m_StatusBar.show();
1337    
1338      m_RegionChooser.signal_region_selected().connect(      m_RegionChooser.signal_region_selected().connect(
# Line 280  MainWindow::MainWindow() : Line 1343  MainWindow::MainWindow() :
1343    
1344      // Create the Tree model:      // Create the Tree model:
1345      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
1346      m_TreeView.set_model(m_refTreeModel);      m_refTreeModelFilter = Gtk::TreeModelFilter::create(m_refTreeModel);
1347      m_refTreeModel->signal_row_changed().connect(      m_refTreeModelFilter->set_visible_func(
1348            sigc::mem_fun(*this, &MainWindow::instrument_row_visible)
1349        );
1350        m_TreeView.set_model(m_refTreeModelFilter);
1351    
1352        m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1353        m_TreeView.set_has_tooltip(true);
1354        m_TreeView.signal_query_tooltip().connect(
1355            sigc::mem_fun(*this, &MainWindow::onQueryTreeViewTooltip)
1356        );
1357        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
1358          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
1359      );      );
1360    
1361      // Add the TreeView's view columns:      // Add the TreeView's view columns:
1362      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
1363      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
1364        m_TreeView.append_column(_("Scripts"), m_Columns.m_col_scripts);
1365        m_TreeView.set_headers_visible(true);
1366        
1367        // establish drag&drop within the instrument tree view, allowing to reorder
1368        // the sequence of instruments within the gig file
1369        {
1370            std::vector<Gtk::TargetEntry> drag_target_instrument;
1371            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
1372            m_TreeView.drag_source_set(drag_target_instrument);
1373            m_TreeView.drag_dest_set(drag_target_instrument);
1374            m_TreeView.signal_drag_begin().connect(
1375                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
1376            );
1377            m_TreeView.signal_drag_data_get().connect(
1378                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
1379            );
1380            m_TreeView.signal_drag_data_received().connect(
1381                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
1382            );
1383        }
1384    
1385      // create samples treeview (including its data model)      // create samples treeview (including its data model)
1386      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
1387      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
1388        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1389        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."));
1390      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
1391      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
1392      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
1393        {
1394            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
1395            Gtk::CellRendererText* cellrenderer =
1396                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1397            column->add_attribute(
1398                cellrenderer->property_foreground(), m_SamplesModel.m_color
1399            );
1400        }
1401        {
1402            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
1403            Gtk::CellRendererText* cellrenderer =
1404                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1405            column->add_attribute(
1406                cellrenderer->property_foreground(), m_SamplesModel.m_color
1407            );
1408        }
1409        m_TreeViewSamples.set_headers_visible(true);
1410    #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
1411        m_TreeViewSamples.signal_button_press_event().connect(
1412            sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1413        );
1414    #else
1415      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
1416          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1417      );      );
1418    #endif
1419      m_refSamplesTreeModel->signal_row_changed().connect(      m_refSamplesTreeModel->signal_row_changed().connect(
1420          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
1421      );      );
1422    
1423        // create scripts treeview (including its data model)
1424        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
1425        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
1426        m_TreeViewScripts.set_tooltip_text(_(
1427            "Use CTRL + double click for editing a script."
1428            "\n\n"
1429            "Note: instrument scripts are a LinuxSampler extension of the gig "
1430            "format. This feature will not work with the GigaStudio software!"
1431        ));
1432        // m_TreeViewScripts.set_reorderable();
1433        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
1434        m_TreeViewScripts.set_headers_visible(false);
1435    #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
1436        m_TreeViewScripts.signal_button_press_event().connect(
1437            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1438        );
1439    #else
1440        m_TreeViewScripts.signal_button_press_event().connect_notify(
1441            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1442        );
1443    #endif
1444        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
1445        m_TreeViewScripts.signal_row_activated().connect(
1446            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
1447        );
1448        m_refScriptsTreeModel->signal_row_changed().connect(
1449            sigc::mem_fun(*this, &MainWindow::script_name_changed)
1450        );
1451    
1452        // establish drag&drop between scripts tree view and ScriptSlots window
1453        std::vector<Gtk::TargetEntry> drag_target_gig_script;
1454        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
1455        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
1456        m_TreeViewScripts.signal_drag_begin().connect(
1457            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
1458        );
1459        m_TreeViewScripts.signal_drag_data_get().connect(
1460            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
1461        );
1462    
1463      // 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
1464      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
1465      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
# Line 320  MainWindow::MainWindow() : Line 1478  MainWindow::MainWindow() :
1478          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
1479      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
1480          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1481        m_RegionChooser.signal_instrument_changed().connect(
1482            sigc::mem_fun(*this, &MainWindow::region_changed));
1483      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
1484          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1485      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
1486            sigc::mem_fun(*this, &MainWindow::file_changed));
1487        sampleProps.signal_changed().connect(
1488          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1489      propDialog.signal_info_changed().connect(      fileProps.signal_changed().connect(
1490            sigc::mem_fun(*this, &MainWindow::file_changed));
1491        midiRules.signal_changed().connect(
1492          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1493    
1494      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 333  MainWindow::MainWindow() : Line 1497  MainWindow::MainWindow() :
1497          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
1498      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
1499          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
1500        sample_ref_changed_signal.connect(
1501            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
1502        );
1503        samples_to_be_removed_signal.connect(
1504            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
1505        );
1506    
1507        dimreg_edit.signal_select_sample().connect(
1508            sigc::mem_fun(*this, &MainWindow::select_sample)
1509        );
1510    
1511      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
1512          sigc::hide(          sigc::hide(
1513              sigc::bind(              sigc::bind(
1514                  file_structure_to_be_changed_signal.make_slot(),                  file_structure_to_be_changed_signal.make_slot(),
1515    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1516                    std::ref(this->file)
1517    #else
1518                  sigc::ref(this->file)                  sigc::ref(this->file)
1519    #endif
1520              )              )
1521          )          )
1522      );      );
# Line 346  MainWindow::MainWindow() : Line 1524  MainWindow::MainWindow() :
1524          sigc::hide(          sigc::hide(
1525              sigc::bind(              sigc::bind(
1526                  file_structure_changed_signal.make_slot(),                  file_structure_changed_signal.make_slot(),
1527    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1528                    std::ref(this->file)
1529    #else
1530                  sigc::ref(this->file)                  sigc::ref(this->file)
1531    #endif
1532              )              )
1533          )          )
1534      );      );
# Line 367  MainWindow::MainWindow() : Line 1549  MainWindow::MainWindow() :
1549      dimreg_stereo.signal_toggled().connect(      dimreg_stereo.signal_toggled().connect(
1550          sigc::mem_fun(*this, &MainWindow::update_dimregs));          sigc::mem_fun(*this, &MainWindow::update_dimregs));
1551    
1552        m_searchText.signal_changed().connect(
1553            sigc::mem_fun(*m_refTreeModelFilter.operator->(), &Gtk::TreeModelFilter::refilter)
1554        );
1555    
1556      file = 0;      file = 0;
1557      file_is_changed = false;      file_is_changed = false;
1558    
1559    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1560      show_all_children();      show_all_children();
1561    #endif
1562    
1563      // start with a new gig file by default      // start with a new gig file by default
1564      on_action_file_new();      on_action_file_new();
1565    
1566        m_TreeViewNotebook.signal_switch_page().connect(
1567            sigc::mem_fun(*this, &MainWindow::on_notebook_tab_switched)
1568        );
1569    
1570        // select 'Instruments' tab by default
1571        // (gtk allows this only if the tab childs are visible, thats why it's here)
1572        m_TreeViewNotebook.set_current_page(1);
1573    
1574        Gtk::Clipboard::get()->signal_owner_change().connect(
1575            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
1576        );
1577        updateClipboardPasteAvailable();
1578        updateClipboardCopyAvailable();
1579    
1580        // setup macros and their keyboard accelerators
1581        {
1582    #if USE_GTKMM_BUILDER
1583            menuMacro = new Gtk::Menu(
1584                Glib::RefPtr<Gio::Menu>::cast_dynamic(
1585                    m_uiManager->get_object("MenuMacro")
1586                )
1587            );
1588    #else
1589            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1590                uiManager->get_widget("/MenuBar/MenuMacro")
1591            )->get_submenu();
1592    #endif
1593    
1594            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
1595            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
1596            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
1597            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
1598            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
1599            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
1600            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
1601            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
1602            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
1603            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
1604            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
1605            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
1606            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
1607            Gtk::AccelMap::add_entry("<Macros>/macro_12", GDK_KEY_F13, noModifier);
1608            Gtk::AccelMap::add_entry("<Macros>/macro_13", GDK_KEY_F14, noModifier);
1609            Gtk::AccelMap::add_entry("<Macros>/macro_14", GDK_KEY_F15, noModifier);
1610            Gtk::AccelMap::add_entry("<Macros>/macro_15", GDK_KEY_F16, noModifier);
1611            Gtk::AccelMap::add_entry("<Macros>/macro_16", GDK_KEY_F17, noModifier);
1612            Gtk::AccelMap::add_entry("<Macros>/macro_17", GDK_KEY_F18, noModifier);
1613            Gtk::AccelMap::add_entry("<Macros>/macro_18", GDK_KEY_F19, noModifier);
1614            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
1615    
1616            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1617            menuMacro->set_accel_group(accelGroup);
1618    
1619            updateMacroMenu();
1620        }
1621    
1622        // setup "Assign Scripts" keyboard accelerators
1623        {
1624            Gtk::AccelMap::add_entry("<Scripts>/script_0", GDK_KEY_F1, Gdk::SHIFT_MASK);
1625            Gtk::AccelMap::add_entry("<Scripts>/script_1", GDK_KEY_F2, Gdk::SHIFT_MASK);
1626            Gtk::AccelMap::add_entry("<Scripts>/script_2", GDK_KEY_F3, Gdk::SHIFT_MASK);
1627            Gtk::AccelMap::add_entry("<Scripts>/script_3", GDK_KEY_F4, Gdk::SHIFT_MASK);
1628            Gtk::AccelMap::add_entry("<Scripts>/script_4", GDK_KEY_F5, Gdk::SHIFT_MASK);
1629            Gtk::AccelMap::add_entry("<Scripts>/script_5", GDK_KEY_F6, Gdk::SHIFT_MASK);
1630            Gtk::AccelMap::add_entry("<Scripts>/script_6", GDK_KEY_F7, Gdk::SHIFT_MASK);
1631            Gtk::AccelMap::add_entry("<Scripts>/script_7", GDK_KEY_F8, Gdk::SHIFT_MASK);
1632            Gtk::AccelMap::add_entry("<Scripts>/script_8", GDK_KEY_F9, Gdk::SHIFT_MASK);
1633            Gtk::AccelMap::add_entry("<Scripts>/script_9", GDK_KEY_F10, Gdk::SHIFT_MASK);
1634            Gtk::AccelMap::add_entry("<Scripts>/script_10", GDK_KEY_F11, Gdk::SHIFT_MASK);
1635            Gtk::AccelMap::add_entry("<Scripts>/script_11", GDK_KEY_F12, Gdk::SHIFT_MASK);
1636            Gtk::AccelMap::add_entry("<Scripts>/script_12", GDK_KEY_F13, Gdk::SHIFT_MASK);
1637            Gtk::AccelMap::add_entry("<Scripts>/script_13", GDK_KEY_F14, Gdk::SHIFT_MASK);
1638            Gtk::AccelMap::add_entry("<Scripts>/script_14", GDK_KEY_F15, Gdk::SHIFT_MASK);
1639            Gtk::AccelMap::add_entry("<Scripts>/script_15", GDK_KEY_F16, Gdk::SHIFT_MASK);
1640            Gtk::AccelMap::add_entry("<Scripts>/script_16", GDK_KEY_F17, Gdk::SHIFT_MASK);
1641            Gtk::AccelMap::add_entry("<Scripts>/script_17", GDK_KEY_F18, Gdk::SHIFT_MASK);
1642            Gtk::AccelMap::add_entry("<Scripts>/script_18", GDK_KEY_F19, Gdk::SHIFT_MASK);
1643            Gtk::AccelMap::add_entry("<Scripts>/DropAllScriptSlots", GDK_KEY_BackSpace, Gdk::SHIFT_MASK);
1644    
1645            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1646            assign_scripts_menu->set_accel_group(accelGroup);
1647        }
1648    
1649        on_show_tooltips_changed();
1650    
1651        Glib::signal_idle().connect_once(
1652            sigc::mem_fun(*this, &MainWindow::bringToFront),
1653            200
1654        );
1655  }  }
1656    
1657  MainWindow::~MainWindow()  MainWindow::~MainWindow()
1658  {  {
1659  }  }
1660    
1661    void MainWindow::bringToFront() {
1662        #if defined(__APPLE__)
1663        macRaiseAppWindow();
1664        #endif
1665        raise();
1666        present();
1667    }
1668    
1669    void MainWindow::updateMacroMenu() {
1670    #if !USE_GTKMM_BUILDER
1671        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1672            uiManager->get_widget("/MenuBar/MenuMacro")
1673        )->get_submenu();
1674    #endif
1675    
1676        // remove all entries from "Macro" menu
1677        {
1678            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
1679            for (int i = 0; i < children.size(); ++i) {
1680                Gtk::Widget* child = children[i];
1681                menuMacro->remove(*child);
1682                delete child;
1683            }
1684        }
1685    
1686        // (re)load all macros from config file
1687        try {
1688            Settings::singleton()->loadMacros(m_macros);
1689        } catch (Serialization::Exception e) {
1690            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
1691        } catch (...) {
1692            std::cerr << "Unknown exception while loading macros!" << std::endl;
1693        }
1694    
1695        // add all configured macros as menu items to the "Macro" menu
1696        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
1697            const Serialization::Archive& macro = m_macros[iMacro];
1698            std::string name =
1699                macro.name().empty() ?
1700                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
1701            Gtk::MenuItem* item = new Gtk::MenuItem(name);
1702            item->signal_activate().connect(
1703                sigc::bind(
1704                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
1705                )
1706            );
1707            menuMacro->append(*item);
1708            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
1709            Glib::ustring comment = macro.comment();
1710            if (!comment.empty())
1711                item->set_tooltip_text(comment);
1712        }
1713        // if there are no macros configured at all, then show a dummy entry instead
1714        if (m_macros.empty()) {
1715            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
1716            item->set_sensitive(false);
1717            menuMacro->append(*item);
1718        }
1719    
1720        // add separator line to menu
1721        menuMacro->append(*new Gtk::SeparatorMenuItem);
1722    
1723        {
1724            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
1725            item->signal_activate().connect(
1726                sigc::mem_fun(*this, &MainWindow::setupMacros)
1727            );
1728            menuMacro->append(*item);
1729            item->set_accel_path("<Macros>/SetupMacros");
1730        }
1731    
1732    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1733        menuMacro->show_all_children();
1734    #endif
1735    }
1736    
1737    void MainWindow::onMacroSelected(int iMacro) {
1738        printf("onMacroSelected(%d)\n", iMacro);
1739        if (iMacro < 0 || iMacro >= m_macros.size()) return;
1740        Glib::ustring errorText;
1741        try {
1742            applyMacro(m_macros[iMacro]);
1743        } catch (Serialization::Exception e) {
1744            errorText = e.Message;
1745        } catch (...) {
1746            errorText = _("Unknown exception while applying macro");
1747        }
1748        if (!errorText.empty()) {
1749            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
1750            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1751            msg.run();
1752        }
1753    }
1754    
1755    void MainWindow::setupMacros() {
1756        MacrosSetup* setup = new MacrosSetup();
1757        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
1758        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
1759        setup->signal_macros_changed().connect(
1760            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
1761        );
1762        setup->show();
1763    }
1764    
1765    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
1766        m_macros = macros;
1767        Settings::singleton()->saveMacros(m_macros);
1768        updateMacroMenu();
1769    }
1770    
1771    //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.
1772    void MainWindow::on_notebook_tab_switched(void* page, guint page_num) {
1773        bool isInstrumentsPage = (page_num == 1);
1774        // so far we only support filtering for the instruments list, so hide the
1775        // filter text entry field if another tab is selected
1776        m_searchField.set_visible(isInstrumentsPage);
1777    }
1778    
1779  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
1780  {  {
1781      return !file_is_shared && file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
# Line 399  void MainWindow::region_changed() Line 1795  void MainWindow::region_changed()
1795  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1796  {  {
1797      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
1798      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1799        if (rows.empty()) return NULL;
1800      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
1801        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1802      if (it) {      if (it) {
1803          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1804          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 444  void MainWindow::update_dimregs() Line 1841  void MainWindow::update_dimregs()
1841              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1842          }          }
1843      }      }
1844    
1845        m_RegionChooser.setModifyAllRegions(all_regions);
1846        m_DimRegionChooser.setModifyAllRegions(all_regions);
1847        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1848        m_DimRegionChooser.setModifyBothChannels(stereo);
1849    
1850        updateClipboardCopyAvailable();
1851  }  }
1852    
1853  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 455  void MainWindow::dimreg_all_dimregs_togg Line 1859  void MainWindow::dimreg_all_dimregs_togg
1859  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1860  {  {
1861      update_dimregs();      update_dimregs();
1862      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1863  }  }
1864    
1865  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1866  {  {
1867    #if !USE_GTKMM_BUILDER
1868        // select item in instrument menu
1869        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1870        if (!rows.empty()) {
1871            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1872            if (it) {
1873                Gtk::TreePath path(it);
1874                int index = path[0];
1875                const std::vector<Gtk::Widget*> children =
1876                    instrument_menu->get_children();
1877                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1878            }
1879        }
1880    #endif
1881    
1882        updateScriptListOfMenu();
1883    
1884      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1885    
1886        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1887            switch_sampler_instrument_signal.emit(get_instrument());
1888        }
1889    }
1890    
1891    
1892    LoaderSaverBase::LoaderSaverBase(const Glib::ustring filename, gig::File* gig) :
1893        filename(filename), gig(gig),
1894    #ifdef GLIB_THREADS
1895        thread(0),
1896    #endif
1897        progress(0.f)
1898    {
1899  }  }
1900    
1901  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
1902  {  {
1903      Loader* loader = static_cast<Loader*>(progress->custom);      LoaderSaverBase* loader = static_cast<LoaderSaverBase*>(progress->custom);
1904      loader->progress_callback(progress->factor);      loader->progress_callback(progress->factor);
1905  }  }
1906    
1907  void Loader::progress_callback(float fraction)  void LoaderSaverBase::progress_callback(float fraction)
1908  {  {
1909      {      {
1910    #ifdef GLIB_THREADS
1911          Glib::Threads::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1912    #else
1913            std::lock_guard<std::mutex> lock(progressMutex);
1914    #endif
1915          progress = fraction;          progress = fraction;
1916      }      }
1917      progress_dispatcher();      progress_dispatcher();
1918  }  }
1919    
1920  void Loader::thread_function()  #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1921    // make sure stack is 16-byte aligned for SSE instructions
1922    __attribute__((force_align_arg_pointer))
1923    #endif
1924    void LoaderSaverBase::thread_function()
1925  {  {
1926      printf("thread_function self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
1927      printf("Start %s\n", filename);      printf("thread_function self=%p\n",
1928      RIFF::File* riff = new RIFF::File(filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1929      gig = new gig::File(riff);  #else
1930      gig::progress_t progress;      std::cout << "thread_function self=" << std::this_thread::get_id() << "\n";
1931      progress.callback = loader_progress_callback;  #endif
1932      progress.custom = this;      printf("Start %s\n", filename.c_str());
1933        try {
1934            gig::progress_t progress;
1935            progress.callback = loader_progress_callback;
1936            progress.custom = this;
1937    
1938            thread_function_sub(progress);
1939            printf("End\n");
1940            finished_dispatcher();
1941        } catch (RIFF::Exception e) {
1942            error_message = e.Message;
1943            error_dispatcher.emit();
1944        } catch (...) {
1945            error_message = _("Unknown exception occurred");
1946            error_dispatcher.emit();
1947        }
1948    }
1949    
1950      gig->GetInstrument(0, &progress);  void LoaderSaverBase::launch()
1951      printf("End\n");  {
1952      finished_dispatcher();  #ifdef GLIB_THREADS
1953    #ifdef OLD_THREADS
1954        thread = Glib::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function), true);
1955    #else
1956        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function));
1957    #endif
1958        printf("launch thread=%p\n", static_cast<void*>(thread));
1959    #else
1960        thread = std::thread([this](){ thread_function(); });
1961        std::cout << "launch thread=" << thread.get_id() << "\n";
1962    #endif
1963  }  }
1964    
1965  Loader::Loader(const char* filename)  float LoaderSaverBase::get_progress()
     : filename(filename), thread(0)  
1966  {  {
1967    #ifdef GLIB_THREADS
1968        Glib::Threads::Mutex::Lock lock(progressMutex);
1969    #else
1970        std::lock_guard<std::mutex> lock(progressMutex);
1971    #endif
1972        return progress;
1973  }  }
1974    
1975  void Loader::launch()  Glib::Dispatcher& LoaderSaverBase::signal_progress()
1976  {  {
1977  #ifdef OLD_THREADS      return progress_dispatcher;
1978      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);  }
1979    
1980    Glib::Dispatcher& LoaderSaverBase::signal_finished()
1981    {
1982        return finished_dispatcher;
1983    }
1984    
1985    Glib::Dispatcher& LoaderSaverBase::signal_error()
1986    {
1987        return error_dispatcher;
1988    }
1989    
1990    void LoaderSaverBase::join() {
1991    #ifdef GLIB_THREADS
1992        thread->join();
1993  #else  #else
1994      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread.join();
1995  #endif  #endif
     printf("launch thread=%x\n", thread);  
1996  }  }
1997    
1998  float Loader::get_progress()  
1999    Loader::Loader(const char* filename) :
2000        LoaderSaverBase(filename, 0)
2001  {  {
     float res;  
     {  
         Glib::Threads::Mutex::Lock lock(progressMutex);  
         res = progress;  
     }  
     return res;  
2002  }  }
2003    
2004  Glib::Dispatcher& Loader::signal_progress()  void Loader::thread_function_sub(gig::progress_t& progress)
2005  {  {
2006      return progress_dispatcher;      RIFF::File* riff = new RIFF::File(filename);
2007        gig = new gig::File(riff);
2008    
2009        gig->GetInstrument(0, &progress);
2010  }  }
2011    
2012  Glib::Dispatcher& Loader::signal_finished()  
2013    Saver::Saver(gig::File* file, Glib::ustring filename) :
2014        LoaderSaverBase(filename, file)
2015  {  {
     return finished_dispatcher;  
2016  }  }
2017    
2018  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  void Saver::thread_function_sub(gig::progress_t& progress)
2019    {
2020        // if no filename was provided, that means "save", if filename was provided means "save as"
2021        if (filename.empty()) {
2022            if (!Settings::singleton()->saveWithTemporaryFile) {
2023                // save directly over the existing .gig file
2024                // (requires less disk space than solution below
2025                // but may be slower)
2026                gig->Save(&progress);
2027            } else {
2028                // save the file as separate temporary file first,
2029                // then move the saved file over the old file
2030                // (may result in performance speedup during save)
2031                gig::String tmpname = filename + ".TMP";
2032                gig->Save(tmpname, &progress);
2033    #if defined(WIN32)
2034                if (!DeleteFile(filename.c_str())) {
2035                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
2036                }
2037    #else // POSIX ...
2038                if (unlink(filename.c_str())) {
2039                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
2040                }
2041    #endif
2042                if (rename(tmpname.c_str(), filename.c_str())) {
2043    #if defined(WIN32)
2044                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
2045    #else
2046                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
2047    #endif
2048                }
2049            }
2050        } else {
2051            gig->Save(filename, &progress);
2052        }
2053    }
2054    
2055    
2056    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
2057      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
2058  {  {
2059    #if USE_GTKMM_BOX
2060        get_content_area()->pack_start(progressBar);
2061    #else
2062      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
2063    #endif
2064    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2065      show_all_children();      show_all_children();
2066    #endif
2067        resize(600,50);
2068  }  }
2069    
2070  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
2071  // 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.
2072  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;  
     }  
2073      // forget all samples that ought to be imported      // forget all samples that ought to be imported
2074      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
2075      // clear the samples and instruments tree views      // clear the samples and instruments tree views
2076      m_refTreeModel->clear();      m_refTreeModel->clear();
2077      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
2078        m_refScriptsTreeModel->clear();
2079    #if !USE_GTKMM_BUILDER
2080        // remove all entries from "Instrument" menu
2081        while (!instrument_menu->get_children().empty()) {
2082            remove_instrument_from_menu(0);
2083        }
2084    #endif
2085      // free libgig's gig::File instance      // free libgig's gig::File instance
2086      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
2087      file = NULL;      file = NULL;
2088      set_file_is_shared(false);      set_file_is_shared(false);
2089  }  }
2090    
2091    void MainWindow::__refreshEntireGUI() {
2092        // clear the samples and instruments tree views
2093        m_refTreeModel->clear();
2094        m_refSamplesTreeModel->clear();
2095        m_refScriptsTreeModel->clear();
2096    #if !USE_GTKMM_BUILDER
2097        // remove all entries from "Instrument" menu
2098        while (!instrument_menu->get_children().empty()) {
2099            remove_instrument_from_menu(0);
2100        }
2101    #endif
2102    
2103        if (!this->file) return;
2104    
2105        load_gig(
2106            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
2107        );
2108    }
2109    
2110  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
2111  {  {
2112      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 571  void MainWindow::on_action_file_new() Line 2119  void MainWindow::on_action_file_new()
2119      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
2120      // already add one new instrument by default      // already add one new instrument by default
2121      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
2122      pInstrument->pInfo->Name = _("Unnamed Instrument");      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
2123      // update GUI with that new gig::File      // update GUI with that new gig::File
2124      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
2125  }  }
# Line 584  bool MainWindow::close_confirmation_dial Line 2132  bool MainWindow::close_confirmation_dial
2132      g_free(msg);      g_free(msg);
2133      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."));
2134      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
2135    #if HAS_GTKMM_STOCK
2136      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2137      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);
2138    #else
2139        dialog.add_button(_("_OK"), Gtk::RESPONSE_OK);
2140        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2141    #endif
2142      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
2143      int response = dialog.run();      int response = dialog.run();
2144      dialog.hide();      dialog.hide();
2145      if (response == Gtk::RESPONSE_YES) return file_save();  
2146      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
2147        if (response == Gtk::RESPONSE_NO) return true;
2148    
2149        // user cancelled dialog, thus don't close app
2150        if (response == Gtk::RESPONSE_CANCEL) return false;
2151    
2152        // TODO: the following return valid is disabled and hard coded instead for
2153        // now, due to the fact that saving with progress bar is now implemented
2154        // asynchronously, as a result the app does not close automatically anymore
2155        // after saving the file has completed
2156        //
2157        //   if (response == Gtk::RESPONSE_YES) return file_save();
2158        //   return response != Gtk::RESPONSE_CANCEL;
2159        //
2160        if (response == Gtk::RESPONSE_YES) file_save();
2161        return false; // always prevent closing the app for now (see comment above)
2162  }  }
2163    
2164  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 601  bool MainWindow::leaving_shared_mode_dia Line 2169  bool MainWindow::leaving_shared_mode_dia
2169            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
2170            "load it."));            "load it."));
2171      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
2172    #if HAS_GTKMM_STOCK
2173      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2174    #else
2175        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2176    #endif
2177      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
2178      int response = dialog.run();      int response = dialog.run();
2179      dialog.hide();      dialog.hide();
# Line 615  void MainWindow::on_action_file_open() Line 2187  void MainWindow::on_action_file_open()
2187      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
2188    
2189      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
2190    #if HAS_GTKMM_STOCK
2191      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2192      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2193    #else
2194        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2195        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2196    #endif
2197      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2198  #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
2199      Gtk::FileFilter filter;      Gtk::FileFilter filter;
# Line 630  void MainWindow::on_action_file_open() Line 2207  void MainWindow::on_action_file_open()
2207          dialog.set_current_folder(current_gig_dir);          dialog.set_current_folder(current_gig_dir);
2208      }      }
2209      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2210            dialog.hide();
2211          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
2212          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
2213          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2214            printf("on_action_file_open self=%p\n",
2215                   static_cast<void*>(Glib::Threads::Thread::self()));
2216    #else
2217            std::cout << "on_action_file_open self=" <<
2218                std::this_thread::get_id() << "\n";
2219    #endif
2220          load_file(filename.c_str());          load_file(filename.c_str());
2221          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
2222      }      }
# Line 641  void MainWindow::on_action_file_open() Line 2225  void MainWindow::on_action_file_open()
2225  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
2226  {  {
2227      __clear();      __clear();
2228      load_dialog = new LoadDialog(_("Loading..."), *this);  
2229      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2230      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
2231            Glib::filename_display_basename(name) + "' ...",
2232            *this
2233        );
2234    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2235        progress_dialog->show_all();
2236    #endif
2237        loader = new Loader(name); //FIXME: memory leak!
2238      loader->signal_progress().connect(      loader->signal_progress().connect(
2239          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
2240      loader->signal_finished().connect(      loader->signal_finished().connect(
2241          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
2242        loader->signal_error().connect(
2243            sigc::mem_fun(*this, &MainWindow::on_loader_error));
2244      loader->launch();      loader->launch();
2245  }  }
2246    
# Line 663  void MainWindow::load_instrument(gig::In Line 2256  void MainWindow::load_instrument(gig::In
2256      // load the instrument      // load the instrument
2257      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
2258      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
2259      //TODO: automatically select the given instrument      // automatically select the given instrument
2260        int i = 0;
2261        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
2262             instrument = pFile->GetNextInstrument(), ++i)
2263        {
2264            if (instrument == instr) {
2265                // select item in "instruments" tree view
2266                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
2267                // make sure the selected item in the "instruments" tree view is
2268                // visible (scroll to it)
2269                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
2270    #if !USE_GTKMM_BUILDER
2271                // select item in instrument menu
2272                {
2273                    const std::vector<Gtk::Widget*> children =
2274                        instrument_menu->get_children();
2275                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
2276                }
2277    #endif
2278                // update region chooser and dimension region chooser
2279                m_RegionChooser.set_instrument(instr);
2280                break;
2281            }
2282        }
2283  }  }
2284    
2285  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
2286  {  {
2287      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
2288  }  }
2289    
2290  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
2291  {  {
2292        loader->join();
2293      printf("Loader finished!\n");      printf("Loader finished!\n");
2294      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2295      load_gig(loader->gig, loader->filename);      printf("on_loader_finished self=%p\n",
2296      load_dialog->hide();             static_cast<void*>(Glib::Threads::Thread::self()));
2297    #else
2298        std::cout << "on_loader_finished self=" <<
2299            std::this_thread::get_id() << "\n";
2300    #endif
2301        load_gig(loader->gig, loader->filename.c_str());
2302        progress_dialog->hide();
2303    }
2304    
2305    void MainWindow::on_loader_error()
2306    {
2307        loader->join();
2308        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
2309        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2310        msg.run();
2311        progress_dialog->hide();
2312  }  }
2313    
2314  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 715  bool MainWindow::file_save() Line 2347  bool MainWindow::file_save()
2347    
2348      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
2349      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
2350      try {  
2351          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2352          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
2353              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
2354              file_is_changed = false;          *this
2355          }      );
2356      } catch (RIFF::Exception e) {  #if HAS_GTKMM_SHOW_ALL_CHILDREN
2357          file_structure_changed_signal.emit(this->file);      progress_dialog->show_all();
2358          Glib::ustring txt = _("Could not save file: ") + e.Message;  #endif
2359          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);      saver = new Saver(this->file); //FIXME: memory leak!
2360          msg.run();      saver->signal_progress().connect(
2361          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2362      }      saver->signal_finished().connect(
2363      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2364        saver->signal_error().connect(
2365            sigc::mem_fun(*this, &MainWindow::on_saver_error));
2366        saver->launch();
2367    
2368        return true;
2369    }
2370    
2371    void MainWindow::on_saver_progress()
2372    {
2373        progress_dialog->set_fraction(saver->get_progress());
2374    }
2375    
2376    void MainWindow::on_saver_error()
2377    {
2378        saver->join();
2379        file_structure_changed_signal.emit(this->file);
2380        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
2381        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2382        msg.run();
2383    }
2384    
2385    void MainWindow::on_saver_finished()
2386    {
2387        saver->join();
2388        this->file = saver->gig;
2389        this->filename = saver->filename;
2390        current_gig_dir = Glib::path_get_dirname(filename);
2391        set_title(Glib::filename_display_basename(filename));
2392        file_has_name = true;
2393        file_is_changed = false;
2394        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
2395      __import_queued_samples();      __import_queued_samples();
2396        std::cout << "Importing queued samples done.\n" << std::flush;
2397    
2398      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
2399      return true;  
2400        __refreshEntireGUI();
2401        progress_dialog->hide();
2402  }  }
2403    
2404  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 743  void MainWindow::on_action_file_save_as( Line 2410  void MainWindow::on_action_file_save_as(
2410  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
2411  {  {
2412      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
2413    #if HAS_GTKMM_STOCK
2414      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2415      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
2416    #else
2417        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2418        dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
2419    #endif
2420      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2421      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
2422    
# Line 773  bool MainWindow::file_save_as() Line 2445  bool MainWindow::file_save_as()
2445      }      }
2446    
2447      // show warning in the dialog      // show warning in the dialog
2448      Gtk::HBox descriptionArea;      HBox descriptionArea;
2449      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
2450      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
2451        warningIcon.set_from_icon_name("dialog-warning",
2452                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
2453      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
2454  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2455      view::WrapLabel description;      view::WrapLabel description;
# Line 792  bool MainWindow::file_save_as() Line 2466  bool MainWindow::file_save_as()
2466            "same .gig file will end up in corrupted sample wave data!\n")            "same .gig file will end up in corrupted sample wave data!\n")
2467      );      );
2468      descriptionArea.pack_start(description);      descriptionArea.pack_start(description);
2469    #if USE_GTKMM_BOX
2470        dialog.get_content_area()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2471    #else
2472      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2473    #endif
2474    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2475      descriptionArea.show_all();      descriptionArea.show_all();
2476    #endif
2477    
2478      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2479          file_structure_to_be_changed_signal.emit(this->file);          dialog.hide();
2480          try {          std::string filename = dialog.get_filename();
2481              std::string filename = dialog.get_filename();          if (!Glib::str_has_suffix(filename, ".gig")) {
2482              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;  
2483          }          }
2484          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
2485          file_structure_changed_signal.emit(this->file);  
2486            progress_dialog = new ProgressDialog( //FIXME: memory leak!
2487                _("Saving") +  Glib::ustring(" '") +
2488                Glib::filename_display_basename(filename) + "' ...",
2489                *this
2490            );
2491    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2492            progress_dialog->show_all();
2493    #endif
2494    
2495            saver = new Saver(file, filename); //FIXME: memory leak!
2496            saver->signal_progress().connect(
2497                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2498            saver->signal_finished().connect(
2499                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2500            saver->signal_error().connect(
2501                sigc::mem_fun(*this, &MainWindow::on_saver_error));
2502            saver->launch();
2503    
2504          return true;          return true;
2505      }      }
2506      return false;      return false;
# Line 827  bool MainWindow::file_save_as() Line 2510  bool MainWindow::file_save_as()
2510  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
2511      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
2512      Glib::ustring error_files;      Glib::ustring error_files;
2513      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
2514      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2515           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
2516          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
2517          SF_INFO info;          SF_INFO info;
2518          info.format = 0;          info.format = 0;
2519          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);
2520          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
2521          try {          try {
2522              if (!hFile) throw std::string(_("could not open file"));              if (!hFile) throw std::string(_("could not open file"));
# Line 856  void MainWindow::__import_queued_samples Line 2539  void MainWindow::__import_queued_samples
2539                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
2540              }              }
2541    
2542                // reset write position for sample
2543                iter->first->SetPos(0);
2544    
2545              const int bufsize = 10000;              const int bufsize = 10000;
2546              switch (bitdepth) {              switch (bitdepth) {
2547                  case 16: {                  case 16: {
# Line 865  void MainWindow::__import_queued_samples Line 2551  void MainWindow::__import_queued_samples
2551                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
2552                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
2553                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2554                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
2555                          cnt -= n;                          cnt -= n;
2556                      }                      }
2557                      delete[] buffer;                      delete[] buffer;
# Line 885  void MainWindow::__import_queued_samples Line 2571  void MainWindow::__import_queued_samples
2571                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
2572                          }                          }
2573                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2574                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
2575                          cnt -= n;                          cnt -= n;
2576                      }                      }
2577                      delete[] srcbuf;                      delete[] srcbuf;
# Line 896  void MainWindow::__import_queued_samples Line 2582  void MainWindow::__import_queued_samples
2582              // cleanup              // cleanup
2583              sf_close(hFile);              sf_close(hFile);
2584              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
2585              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
2586              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
2587              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
2588              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
2589              ++iter;              ++iter;
2590              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
2591          } catch (std::string what) {          } catch (std::string what) {
2592              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
2593              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
2594              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
2595              ++iter;              ++iter;
2596          }          }
2597      }      }
2598      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
2599      if (error_files.size()) {      if (!error_files.empty()) {
2600          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;
2601          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2602          msg.run();          msg.run();
# Line 919  void MainWindow::__import_queued_samples Line 2605  void MainWindow::__import_queued_samples
2605    
2606  void MainWindow::on_action_file_properties()  void MainWindow::on_action_file_properties()
2607  {  {
2608      propDialog.show();      fileProps.show();
2609      propDialog.deiconify();      fileProps.deiconify();
2610    }
2611    
2612    void MainWindow::on_action_warn_user_on_extensions() {
2613        Settings::singleton()->warnUserOnExtensions =
2614            !Settings::singleton()->warnUserOnExtensions;
2615    }
2616    
2617    void MainWindow::on_action_show_tooltips() {
2618        Settings::singleton()->showTooltips =
2619            !Settings::singleton()->showTooltips;
2620    
2621        on_show_tooltips_changed();
2622    }
2623    
2624    void MainWindow::on_show_tooltips_changed() {
2625        const bool b = Settings::singleton()->showTooltips;
2626    
2627        dimreg_label.set_has_tooltip(b);
2628        dimreg_all_regions.set_has_tooltip(b);
2629        dimreg_all_dimregs.set_has_tooltip(b);
2630        dimreg_stereo.set_has_tooltip(b);
2631    
2632        // Not doing this here, we let onQueryTreeViewTooltip() handle this per cell
2633        //m_TreeView.set_has_tooltip(b);
2634    
2635        m_TreeViewSamples.set_has_tooltip(b);
2636        m_TreeViewScripts.set_has_tooltip(b);
2637    
2638        set_has_tooltip(b);
2639    }
2640    
2641    void MainWindow::on_action_sync_sampler_instrument_selection() {
2642        Settings::singleton()->syncSamplerInstrumentSelection =
2643            !Settings::singleton()->syncSamplerInstrumentSelection;
2644    }
2645    
2646    void MainWindow::on_action_move_root_note_with_region_moved() {
2647        Settings::singleton()->moveRootNoteWithRegionMoved =
2648            !Settings::singleton()->moveRootNoteWithRegionMoved;
2649  }  }
2650    
2651  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
# Line 932  void MainWindow::on_action_help_about() Line 2657  void MainWindow::on_action_help_about()
2657      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
2658  #endif  #endif
2659      dialog.set_version(VERSION);      dialog.set_version(VERSION);
2660      dialog.set_copyright("Copyright (C) 2006-2013 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2019 Andreas Persson");
2661      dialog.set_comments(_(      const std::string sComment =
2662          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
2663          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
2664          "Please notice that this is still a very young instrument editor. "          _(
2665          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
2666          "this application.\n"              "\n"
2667          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
2668          "Please report bugs to: http://bugs.linuxsampler.org")              "backup your Gigasampler/GigaStudio files before editing them with "
2669      );              "this application.\n"
2670      dialog.set_website("http://www.linuxsampler.org");              "\n"
2671      dialog.set_website_label("http://www.linuxsampler.org");              "Please report bugs to: https://bugs.linuxsampler.org"
2672            );
2673        dialog.set_comments(sComment.c_str());
2674        dialog.set_website("https://www.linuxsampler.org");
2675        dialog.set_website_label("https://www.linuxsampler.org");
2676        dialog.set_position(Gtk::WIN_POS_CENTER);
2677      dialog.run();      dialog.run();
2678  }  }
2679    
2680  PropDialog::PropDialog()  FilePropDialog::FilePropDialog()
2681      : eName(_("Name")),      : eFileFormat(_("File Format")),
2682          eName(_("Name")),
2683        eCreationDate(_("Creation date")),        eCreationDate(_("Creation date")),
2684        eComments(_("Comments")),        eComments(_("Comments")),
2685        eProduct(_("Product")),        eProduct(_("Product")),
# Line 964  PropDialog::PropDialog() Line 2695  PropDialog::PropDialog()
2695        eSourceForm(_("Source form")),        eSourceForm(_("Source form")),
2696        eCommissioned(_("Commissioned")),        eCommissioned(_("Commissioned")),
2697        eSubject(_("Subject")),        eSubject(_("Subject")),
2698    #if HAS_GTKMM_STOCK
2699        quitButton(Gtk::Stock::CLOSE),        quitButton(Gtk::Stock::CLOSE),
2700    #else
2701          quitButton(_("_Close")),
2702    #endif
2703        table(2, 1),        table(2, 1),
2704        update_model(0)        m_file(NULL)
2705  {  {
2706        if (!Settings::singleton()->autoRestoreWindowDimension) {
2707            set_default_size(470, 390);
2708            set_position(Gtk::WIN_POS_MOUSE);
2709        }
2710    
2711      set_title(_("File Properties"));      set_title(_("File Properties"));
2712      eName.set_width_chars(50);      eName.set_width_chars(50);
2713    
2714        connect(eFileFormat, &FilePropDialog::set_FileFormat);
2715      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
2716      connect(eCreationDate, &DLS::Info::CreationDate);      connect(eCreationDate, &DLS::Info::CreationDate);
2717      connect(eComments, &DLS::Info::Comments);      connect(eComments, &DLS::Info::Comments);
# Line 988  PropDialog::PropDialog() Line 2729  PropDialog::PropDialog()
2729      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
2730      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
2731    
2732        table.add(eFileFormat);
2733      table.add(eName);      table.add(eName);
2734      table.add(eCreationDate);      table.add(eCreationDate);
2735      table.add(eComments);      table.add(eComments);
# Line 1005  PropDialog::PropDialog() Line 2747  PropDialog::PropDialog()
2747      table.add(eCommissioned);      table.add(eCommissioned);
2748      table.add(eSubject);      table.add(eSubject);
2749    
2750    #if USE_GTKMM_GRID
2751        table.set_column_spacing(5);
2752    #else
2753      table.set_col_spacings(5);      table.set_col_spacings(5);
2754    #endif
2755    
2756      add(vbox);      add(vbox);
2757    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2758        table.set_margin(5);
2759    #else
2760      table.set_border_width(5);      table.set_border_width(5);
2761    #endif
2762      vbox.add(table);      vbox.add(table);
2763      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
2764      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
2765    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2766        buttonBox.set_margin(5);
2767    #else
2768      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2769    #endif
2770      buttonBox.show();      buttonBox.show();
2771      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2772      quitButton.set_can_default();      quitButton.set_can_default();
2773      quitButton.grab_focus();      quitButton.grab_focus();
2774      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
2775          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &FilePropDialog::hide));
2776    
2777      quitButton.show();      quitButton.show();
2778      vbox.show();      vbox.show();
2779    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2780      show_all_children();      show_all_children();
2781    #endif
2782  }  }
2783    
2784  void PropDialog::set_info(DLS::Info* info)  void FilePropDialog::set_file(gig::File* file)
2785  {  {
2786      this->info = info;      m_file = file;
2787        update(file->pInfo);
2788    
2789        // update file format version combo box
2790        const std::string sGiga = "Gigasampler/GigaStudio v";
2791        const int major = file->pVersion->major;
2792        std::vector<std::string> txts;
2793        std::vector<int> values;
2794        txts.push_back(sGiga + "2"); values.push_back(2);
2795        txts.push_back(sGiga + "3"); values.push_back(3);
2796        txts.push_back(sGiga + "4"); values.push_back(4);
2797        if (major < 2 || major > 4) {
2798            txts.push_back(sGiga + ToString(major)); values.push_back(major);
2799        }
2800        std::vector<const char*> texts;
2801        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
2802        texts.push_back(NULL); values.push_back(0);
2803    
2804      update_model++;      update_model++;
2805      eName.set_value(info->Name);      eFileFormat.set_choices(&texts[0], &values[0]);
2806      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);  
2807      update_model--;      update_model--;
2808  }  }
2809    
2810  sigc::signal<void>& PropDialog::signal_info_changed()  void FilePropDialog::set_FileFormat(int value)
2811  {  {
2812      return info_changed;      m_file->pVersion->major = value;
2813  }  }
2814    
2815  void InstrumentProps::set_IsDrum(bool value)  
2816    void InstrumentProps::set_Name(const gig::String& name)
2817  {  {
2818      instrument->IsDrum = value;      m->pInfo->Name = name;
2819  }  }
2820    
2821  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
2822  {  {
2823      instrument->MIDIBank = value;      update_model++;
2824        eName.set_value(m->pInfo->Name);
2825        update_model--;
2826  }  }
2827    
2828  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
2829  {  {
2830      instrument->MIDIProgram = value;      m->IsDrum = value;
2831  }  }
2832    
2833  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
2834  {  {
2835      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
2836  }  }
2837    
2838  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
2839  {  {
2840      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
2841  }  }
2842    
2843  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
2844      : update_model(0),  #if HAS_GTKMM_STOCK
2845        quitButton(Gtk::Stock::CLOSE),      quitButton(Gtk::Stock::CLOSE),
2846        table(2,1),  #else
2847        eName(_("Name")),      quitButton(_("_Close")),
2848        eIsDrum(_("Is drum")),  #endif
2849        eMIDIBank(_("MIDI bank"), 0, 16383),      table(2,1),
2850        eMIDIProgram(_("MIDI program")),      eName(_("Name")),
2851        eAttenuation(_("Attenuation"), 0, 96, 0, 1),      eIsDrum(_("Is drum")),
2852        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),      eMIDIBank(_("MIDI bank"), 0, 16383),
2853        eEffectSend(_("Effect send"), 0, 65535),      eMIDIProgram(_("MIDI program")),
2854        eFineTune(_("Fine tune"), -8400, 8400),      eAttenuation(_("Attenuation (dB)"), -96, +96, 0, 1),
2855        ePitchbendRange(_("Pitchbend range"), 0, 12),      eEffectSend(_("Effect send"), 0, 65535),
2856        ePianoReleaseMode(_("Piano release mode")),      eFineTune(_("Fine tune"), -8400, 8400),
2857        eDimensionKeyRangeLow(_("Keyswitching range low")),      ePitchbendRange(_("Pitchbend range (halftones)"), 0, 48),
2858        eDimensionKeyRangeHigh(_("Keyswitching range high"))      ePianoReleaseMode(_("Piano release mode")),
2859  {      eDimensionKeyRangeLow(_("Keyswitching range low")),
2860        eDimensionKeyRangeHigh(_("Keyswitching range high")),
2861        table2(2,1),
2862        eName2(_("Name")),
2863        eCreationDate(_("Creation date")),
2864        eComments(_("Comments")),
2865        eProduct(_("Product")),
2866        eCopyright(_("Copyright")),
2867        eArtists(_("Artists")),
2868        eGenre(_("Genre")),
2869        eKeywords(_("Keywords")),
2870        eEngineer(_("Engineer")),
2871        eTechnician(_("Technician")),
2872        eSoftware(_("Software")),
2873        eMedium(_("Medium")),
2874        eSource(_("Source")),
2875        eSourceForm(_("Source form")),
2876        eCommissioned(_("Commissioned")),
2877        eSubject(_("Subject"))
2878    {
2879        if (!Settings::singleton()->autoRestoreWindowDimension) {
2880            //set_default_size(470, 390);
2881            set_position(Gtk::WIN_POS_MOUSE);
2882        }
2883    
2884      set_title(_("Instrument Properties"));      set_title(_("Instrument Properties"));
2885    
2886        tabs.append_page(vbox[1], _("Settings"));
2887        tabs.append_page(vbox[2], _("Info"));
2888    
2889      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
2890          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
2891            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
# Line 1111  InstrumentProps::InstrumentProps() Line 2895  InstrumentProps::InstrumentProps()
2895            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
2896      );      );
2897    
2898        connect(eName, &InstrumentProps::set_Name);
2899      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
2900      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
2901      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
2902      connect(eAttenuation, &gig::Instrument::Attenuation);      connect(eAttenuation, &gig::Instrument::Attenuation);
     connect(eGainPlus6, &gig::Instrument::Attenuation);  
2903      connect(eEffectSend, &gig::Instrument::EffectSend);      connect(eEffectSend, &gig::Instrument::EffectSend);
2904      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
2905      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
2906      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
2907      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
2908              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
     connect(eDimensionKeyRangeHigh,  
             &InstrumentProps::set_DimensionKeyRange_high);  
2909    
2910      table.set_col_spacings(5);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
2911    
2912        connect(eName2, &InstrumentProps::set_Name);
2913        connectLambda(eCreationDate, [this](gig::String s) {
2914            m->pInfo->CreationDate = s;
2915        });
2916        connectLambda(eComments, [this](gig::String s) {
2917            m->pInfo->Comments = s;
2918        });
2919        connectLambda(eProduct, [this](gig::String s) {
2920            m->pInfo->Product = s;
2921        });
2922        connectLambda(eCopyright, [this](gig::String s) {
2923            m->pInfo->Copyright = s;
2924        });
2925        connectLambda(eArtists, [this](gig::String s) {
2926            m->pInfo->Artists = s;
2927        });
2928        connectLambda(eGenre, [this](gig::String s) {
2929            m->pInfo->Genre = s;
2930        });
2931        connectLambda(eKeywords, [this](gig::String s) {
2932            m->pInfo->Keywords = s;
2933        });
2934        connectLambda(eEngineer, [this](gig::String s) {
2935            m->pInfo->Engineer = s;
2936        });
2937        connectLambda(eTechnician, [this](gig::String s) {
2938            m->pInfo->Technician = s;
2939        });
2940        connectLambda(eSoftware, [this](gig::String s) {
2941            m->pInfo->Software = s;
2942        });
2943        connectLambda(eMedium, [this](gig::String s) {
2944            m->pInfo->Medium = s;
2945        });
2946        connectLambda(eSource, [this](gig::String s) {
2947            m->pInfo->Source = s;
2948        });
2949        connectLambda(eSourceForm, [this](gig::String s) {
2950            m->pInfo->SourceForm = s;
2951        });
2952        connectLambda(eCommissioned, [this](gig::String s) {
2953            m->pInfo->Commissioned = s;
2954        });
2955        connectLambda(eSubject, [this](gig::String s) {
2956            m->pInfo->Subject = s;
2957        });
2958    
2959        // tab 1
2960    #if USE_GTKMM_GRID
2961        table.set_column_spacing(5);
2962    #else
2963        table.set_col_spacings(5);
2964    #endif
2965      table.add(eName);      table.add(eName);
2966      table.add(eIsDrum);      table.add(eIsDrum);
2967      table.add(eMIDIBank);      table.add(eMIDIBank);
2968      table.add(eMIDIProgram);      table.add(eMIDIProgram);
2969      table.add(eAttenuation);      table.add(eAttenuation);
     table.add(eGainPlus6);  
2970      table.add(eEffectSend);      table.add(eEffectSend);
2971      table.add(eFineTune);      table.add(eFineTune);
2972      table.add(ePitchbendRange);      table.add(ePitchbendRange);
# Line 1140  InstrumentProps::InstrumentProps() Line 2974  InstrumentProps::InstrumentProps()
2974      table.add(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
2975      table.add(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
2976    
2977      add(vbox);      // tab 2
2978    #if USE_GTKMM_GRID
2979        table2.set_column_spacing(5);
2980    #else
2981        table2.set_col_spacings(5);
2982    #endif
2983        table2.add(eName2);
2984        table2.add(eCreationDate);
2985        table2.add(eComments);
2986        table2.add(eProduct);
2987        table2.add(eCopyright);
2988        table2.add(eArtists);
2989        table2.add(eGenre);
2990        table2.add(eKeywords);
2991        table2.add(eEngineer);
2992        table2.add(eTechnician);
2993        table2.add(eSoftware);
2994        table2.add(eMedium);
2995        table2.add(eSource);
2996        table2.add(eSourceForm);
2997        table2.add(eCommissioned);
2998        table2.add(eSubject);
2999    
3000        add(vbox[0]);
3001    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3002        table.set_margin(5);
3003    #else
3004      table.set_border_width(5);      table.set_border_width(5);
3005      vbox.pack_start(table);  #endif
3006        vbox[1].pack_start(table);
3007        vbox[2].pack_start(table2);
3008      table.show();      table.show();
3009      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      table2.show();
3010        vbox[0].pack_start(tabs);
3011        vbox[0].pack_start(buttonBox, Gtk::PACK_SHRINK);
3012      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
3013    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3014        buttonBox.set_margin(5);
3015    #else
3016      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
3017    #endif
3018      buttonBox.show();      buttonBox.show();
3019      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
3020      quitButton.set_can_default();      quitButton.set_can_default();
# Line 1156  InstrumentProps::InstrumentProps() Line 3024  InstrumentProps::InstrumentProps()
3024          sigc::mem_fun(*this, &InstrumentProps::hide));          sigc::mem_fun(*this, &InstrumentProps::hide));
3025    
3026      quitButton.show();      quitButton.show();
3027      vbox.show();      vbox[0].show();
3028    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3029      show_all_children();      show_all_children();
3030    #endif
3031  }  }
3032    
3033  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
3034  {  {
3035      this->instrument = instrument;      update(instrument);
3036    
3037      update_model++;      update_model++;
3038    
3039        // tab 1
3040      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
3041      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
3042      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
3043      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
3044      eAttenuation.set_value(instrument->Attenuation);      // tab 2
3045      eGainPlus6.set_value(instrument->Attenuation);      eName2.set_value(instrument->pInfo->Name);
3046      eEffectSend.set_value(instrument->EffectSend);      eCreationDate.set_value(instrument->pInfo->CreationDate);
3047      eFineTune.set_value(instrument->FineTune);      eComments.set_value(instrument->pInfo->Comments);
3048      ePitchbendRange.set_value(instrument->PitchbendRange);      eProduct.set_value(instrument->pInfo->Product);
3049      ePianoReleaseMode.set_value(instrument->PianoReleaseMode);      eCopyright.set_value(instrument->pInfo->Copyright);
3050      eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);      eArtists.set_value(instrument->pInfo->Artists);
3051      eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);      eGenre.set_value(instrument->pInfo->Genre);
3052        eKeywords.set_value(instrument->pInfo->Keywords);
3053        eEngineer.set_value(instrument->pInfo->Engineer);
3054        eTechnician.set_value(instrument->pInfo->Technician);
3055        eSoftware.set_value(instrument->pInfo->Software);
3056        eMedium.set_value(instrument->pInfo->Medium);
3057        eSource.set_value(instrument->pInfo->Source);
3058        eSourceForm.set_value(instrument->pInfo->SourceForm);
3059        eCommissioned.set_value(instrument->pInfo->Commissioned);
3060        eSubject.set_value(instrument->pInfo->Subject);
3061    
3062        update_model--;
3063    }
3064    
3065    
3066    SampleProps::SampleProps() :
3067    #if HAS_GTKMM_STOCK
3068        quitButton(Gtk::Stock::CLOSE),
3069    #else
3070        quitButton(_("_Close")),
3071    #endif
3072        table(2,1),
3073        eName(_("Name")),
3074        eUnityNote(_("Unity Note")),
3075        eSampleGroup(_("Sample Group")),
3076        eSampleFormatInfo(_("Sample Format")),
3077        eSampleID("Sample ID"),
3078        eChecksum("Wave Data CRC-32"),
3079        eLoopsCount(_("Loops"), 0, 1), // we might support more than 1 loop in future
3080        eLoopStart(_("Loop start position"), 0, 9999999),
3081        eLoopLength(_("Loop size"), 0, 9999999),
3082        eLoopType(_("Loop type")),
3083        eLoopPlayCount(_("Playback count")),
3084        table2(2,1),
3085        eName2(_("Name")),
3086        eCreationDate(_("Creation date")),
3087        eComments(_("Comments")),
3088        eProduct(_("Product")),
3089        eCopyright(_("Copyright")),
3090        eArtists(_("Artists")),
3091        eGenre(_("Genre")),
3092        eKeywords(_("Keywords")),
3093        eEngineer(_("Engineer")),
3094        eTechnician(_("Technician")),
3095        eSoftware(_("Software")),
3096        eMedium(_("Medium")),
3097        eSource(_("Source")),
3098        eSourceForm(_("Source form")),
3099        eCommissioned(_("Commissioned")),
3100        eSubject(_("Subject"))
3101    {
3102        if (!Settings::singleton()->autoRestoreWindowDimension) {
3103            //set_default_size(470, 390);
3104            set_position(Gtk::WIN_POS_MOUSE);
3105        }
3106    
3107        set_title(_("Sample Properties"));
3108    
3109        tabs.append_page(vbox[1], _("Settings"));
3110        tabs.append_page(vbox[2], _("Info"));
3111    
3112        connect(eName, &SampleProps::set_Name);
3113        connect(eUnityNote, &gig::Sample::MIDIUnityNote);
3114        connect(eLoopsCount, &gig::Sample::Loops);
3115        connectLambda(eLoopStart, [this](uint32_t start){
3116            m->LoopStart = start;
3117            m->LoopEnd = start + m->LoopSize;
3118        });
3119        connectLambda(eLoopLength, [this](uint32_t length){
3120            m->LoopSize = length;
3121            m->LoopEnd = m->LoopStart + length;
3122        });
3123        {
3124            const char* choices[] = { _("normal"), _("bidirectional"), _("backward"), 0 };
3125            static const gig::loop_type_t values[] = {
3126                gig::loop_type_normal,
3127                gig::loop_type_bidirectional,
3128                gig::loop_type_backward
3129            };
3130            eLoopType.set_choices(choices, values);
3131        }
3132        connect(eLoopType, &gig::Sample::LoopType);
3133        connect(eLoopPlayCount, &gig::Sample::LoopPlayCount);
3134    
3135        eName.signal_value_changed().connect(sig_name_changed.make_slot());
3136    
3137        connect(eName2, &SampleProps::set_Name);
3138        connectLambda(eCreationDate, [this](gig::String s) {
3139            m->pInfo->CreationDate = s;
3140        });
3141        connectLambda(eComments, [this](gig::String s) {
3142            m->pInfo->Comments = s;
3143        });
3144        connectLambda(eProduct, [this](gig::String s) {
3145            m->pInfo->Product = s;
3146        });
3147        connectLambda(eCopyright, [this](gig::String s) {
3148            m->pInfo->Copyright = s;
3149        });
3150        connectLambda(eArtists, [this](gig::String s) {
3151            m->pInfo->Artists = s;
3152        });
3153        connectLambda(eGenre, [this](gig::String s) {
3154            m->pInfo->Genre = s;
3155        });
3156        connectLambda(eKeywords, [this](gig::String s) {
3157            m->pInfo->Keywords = s;
3158        });
3159        connectLambda(eEngineer, [this](gig::String s) {
3160            m->pInfo->Engineer = s;
3161        });
3162        connectLambda(eTechnician, [this](gig::String s) {
3163            m->pInfo->Technician = s;
3164        });
3165        connectLambda(eSoftware, [this](gig::String s) {
3166            m->pInfo->Software = s;
3167        });
3168        connectLambda(eMedium, [this](gig::String s) {
3169            m->pInfo->Medium = s;
3170        });
3171        connectLambda(eSource, [this](gig::String s) {
3172            m->pInfo->Source = s;
3173        });
3174        connectLambda(eSourceForm, [this](gig::String s) {
3175            m->pInfo->SourceForm = s;
3176        });
3177        connectLambda(eCommissioned, [this](gig::String s) {
3178            m->pInfo->Commissioned = s;
3179        });
3180        connectLambda(eSubject, [this](gig::String s) {
3181            m->pInfo->Subject = s;
3182        });
3183    
3184        // tab 1
3185    #if USE_GTKMM_GRID
3186        table.set_column_spacing(5);
3187    #else
3188        table.set_col_spacings(5);
3189    #endif
3190        table.add(eName);
3191        table.add(eUnityNote);
3192        table.add(eSampleGroup);
3193        table.add(eSampleFormatInfo);
3194        table.add(eSampleID);
3195        table.add(eChecksum);
3196        table.add(eLoopsCount);
3197        table.add(eLoopStart);
3198        table.add(eLoopLength);
3199        table.add(eLoopType);
3200        table.add(eLoopPlayCount);
3201    
3202        // tab 2
3203    #if USE_GTKMM_GRID
3204        table2.set_column_spacing(5);
3205    #else
3206        table2.set_col_spacings(5);
3207    #endif
3208        table2.add(eName2);
3209        table2.add(eCreationDate);
3210        table2.add(eComments);
3211        table2.add(eProduct);
3212        table2.add(eCopyright);
3213        table2.add(eArtists);
3214        table2.add(eGenre);
3215        table2.add(eKeywords);
3216        table2.add(eEngineer);
3217        table2.add(eTechnician);
3218        table2.add(eSoftware);
3219        table2.add(eMedium);
3220        table2.add(eSource);
3221        table2.add(eSourceForm);
3222        table2.add(eCommissioned);
3223        table2.add(eSubject);
3224    
3225        add(vbox[0]);
3226    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3227        table.set_margin(5);
3228    #else
3229        table.set_border_width(5);
3230    #endif
3231        vbox[1].pack_start(table);
3232        vbox[2].pack_start(table2);
3233        table.show();
3234        table2.show();
3235        vbox[0].pack_start(tabs);
3236        vbox[0].pack_start(buttonBox, Gtk::PACK_SHRINK);
3237        buttonBox.set_layout(Gtk::BUTTONBOX_END);
3238    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3239        buttonBox.set_margin(5);
3240    #else
3241        buttonBox.set_border_width(5);
3242    #endif
3243        buttonBox.show();
3244        buttonBox.pack_start(quitButton);
3245        quitButton.set_can_default();
3246        quitButton.grab_focus();
3247    
3248        quitButton.signal_clicked().connect(
3249            sigc::mem_fun(*this, &SampleProps::hide));
3250    
3251        quitButton.show();
3252        vbox[0].show();
3253    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3254        show_all_children();
3255    #endif
3256    }
3257    
3258    void SampleProps::set_sample(gig::Sample* sample)
3259    {
3260        update(sample);
3261    
3262        update_model++;
3263    
3264        // tab 1
3265        eName.set_value(sample->pInfo->Name);
3266        eUnityNote.set_value(sample->MIDIUnityNote);
3267        // show sample group name
3268        {
3269            Glib::ustring s = "---";
3270            if (sample && sample->GetGroup())
3271                s = sample->GetGroup()->Name;
3272            eSampleGroup.text.set_text(s);
3273        }
3274        // assemble sample format info string
3275        {
3276            Glib::ustring s;
3277            if (sample) {
3278                switch (sample->Channels) {
3279                    case 1: s = _("Mono"); break;
3280                    case 2: s = _("Stereo"); break;
3281                    default:
3282                        s = ToString(sample->Channels) + _(" audio channels");
3283                        break;
3284                }
3285                s += " " + ToString(sample->BitDepth) + " Bits";
3286                s += " " + ToString(sample->SamplesPerSecond/1000) + "."
3287                         + ToString((sample->SamplesPerSecond%1000)/100) + " kHz";
3288            } else {
3289                s = _("No sample assigned to this dimension region.");
3290            }
3291            eSampleFormatInfo.text.set_text(s);
3292        }
3293        // generate sample's memory address pointer string
3294        {
3295            Glib::ustring s;
3296            if (sample) {
3297                char buf[64] = {};
3298                snprintf(buf, sizeof(buf), "%p", sample);
3299                s = buf;
3300            } else {
3301                s = "---";
3302            }
3303            eSampleID.text.set_text(s);
3304        }
3305        // generate raw wave form data CRC-32 checksum string
3306        {
3307            Glib::ustring s = "---";
3308            if (sample) {
3309                char buf[64] = {};
3310                snprintf(buf, sizeof(buf), "%x", sample->GetWaveDataCRC32Checksum());
3311                s = buf;
3312            }
3313            eChecksum.text.set_text(s);
3314        }
3315        eLoopsCount.set_value(sample->Loops);
3316        eLoopStart.set_value(sample->LoopStart);
3317        eLoopLength.set_value(sample->LoopSize);
3318        eLoopType.set_value(sample->LoopType);
3319        eLoopPlayCount.set_value(sample->LoopPlayCount);
3320        // tab 2
3321        eName2.set_value(sample->pInfo->Name);
3322        eCreationDate.set_value(sample->pInfo->CreationDate);
3323        eComments.set_value(sample->pInfo->Comments);
3324        eProduct.set_value(sample->pInfo->Product);
3325        eCopyright.set_value(sample->pInfo->Copyright);
3326        eArtists.set_value(sample->pInfo->Artists);
3327        eGenre.set_value(sample->pInfo->Genre);
3328        eKeywords.set_value(sample->pInfo->Keywords);
3329        eEngineer.set_value(sample->pInfo->Engineer);
3330        eTechnician.set_value(sample->pInfo->Technician);
3331        eSoftware.set_value(sample->pInfo->Software);
3332        eMedium.set_value(sample->pInfo->Medium);
3333        eSource.set_value(sample->pInfo->Source);
3334        eSourceForm.set_value(sample->pInfo->SourceForm);
3335        eCommissioned.set_value(sample->pInfo->Commissioned);
3336        eSubject.set_value(sample->pInfo->Subject);
3337    
3338      update_model--;      update_model--;
3339  }  }
3340    
3341  sigc::signal<void>& InstrumentProps::signal_instrument_changed()  void SampleProps::set_Name(const gig::String& name)
3342  {  {
3343      return instrument_changed;      m->pInfo->Name = name;
3344  }  }
3345    
3346    void SampleProps::update_name()
3347    {
3348        update_model++;
3349        eName.set_value(m->pInfo->Name);
3350        update_model--;
3351    }
3352    
3353    
3354  void MainWindow::file_changed()  void MainWindow::file_changed()
3355  {  {
3356      if (file && !file_is_changed) {      if (file && !file_is_changed) {
# Line 1193  void MainWindow::file_changed() Line 3359  void MainWindow::file_changed()
3359      }      }
3360  }  }
3361    
3362    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
3363        sample_ref_count.clear();
3364        
3365        if (!gig) return;
3366    
3367        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
3368             instrument = gig->GetNextInstrument())
3369        {
3370            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3371                 rgn = instrument->GetNextRegion())
3372            {
3373                for (int i = 0; i < 256; ++i) {
3374                    if (!rgn->pDimensionRegions[i]) continue;
3375                    if (rgn->pDimensionRegions[i]->pSample) {
3376                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
3377                    }
3378                }
3379            }
3380        }
3381    }
3382    
3383    bool MainWindow::onQueryTreeViewTooltip(int x, int y, bool keyboardTip, const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
3384        Gtk::TreeModel::iterator iter;
3385        if (!m_TreeView.get_tooltip_context_iter(x, y, keyboardTip, iter)) {
3386            return false;
3387        }
3388        Gtk::TreeModel::Path path(iter);
3389        Gtk::TreeModel::Row row = *iter;
3390        Gtk::TreeViewColumn* pointedColumn = NULL;
3391        // resolve the precise table column the mouse points to
3392        {
3393            Gtk::TreeModel::Path path; // unused
3394            int cellX, cellY; // unused
3395            m_TreeView.get_path_at_pos(x, y, path, pointedColumn, cellX, cellY);
3396        }
3397        Gtk::TreeViewColumn* scriptsColumn = m_TreeView.get_column(2);
3398        if (pointedColumn == scriptsColumn) { // mouse hovers scripts column ...
3399            // show the script(s) assigned to the hovered instrument as tooltip
3400            tooltip->set_markup( row[m_Columns.m_col_tooltip] );
3401            m_TreeView.set_tooltip_cell(tooltip, &path, scriptsColumn, NULL);
3402        } else {
3403            // if beginners' tooltips is disabled then don't show the following one
3404            if (!Settings::singleton()->showTooltips)
3405                return false;
3406            // yeah, a beginners tooltip
3407            tooltip->set_text(_(
3408                "Right click here for actions on instruments & MIDI Rules. "
3409                "Drag & drop to change the order of instruments."
3410            ));
3411            m_TreeView.set_tooltip_cell(tooltip, &path, pointedColumn, NULL);
3412        }
3413        return true;
3414    }
3415    
3416    static Glib::ustring scriptTooltipFor(gig::Instrument* instrument, int index) {
3417        Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3418        const int iScriptSlots = instrument->ScriptSlotCount();
3419        Glib::ustring tooltip = "<u>(" + ToString(index) + ") “"  + name + "”</u>\n\n";
3420        if (!iScriptSlots)
3421            tooltip += "<span foreground='red'><i>No script assigned</i></span>";
3422        else {
3423            for (int i = 0; i < iScriptSlots; ++i) {
3424                tooltip += "• " + ToString(i+1) + ". Script: “<span foreground='#46DEFF'><b>" +
3425                           instrument->GetScriptOfSlot(i)->Name + "</b></span>”";
3426                if (i + 1 < iScriptSlots) tooltip += "\n\n";
3427            }
3428        }
3429        return tooltip;
3430    }
3431    
3432  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
3433  {  {
3434      file = 0;      file = 0;
3435      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
3436    
3437      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
3438            (filename && strlen(filename) > 0) ?
3439                filename : (!gig->GetFileName().empty()) ?
3440                    gig->GetFileName() : _("Unsaved Gig File");
3441      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
3442      file_has_name = filename;      file_has_name = filename;
3443      file_is_changed = false;      file_is_changed = false;
3444    
3445      propDialog.set_info(gig->pInfo);      fileProps.set_file(gig);
3446    
3447      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
3448          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));      int index = 0;
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
3449      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
3450           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
3451            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3452            const int iScriptSlots = instrument->ScriptSlotCount();
3453    
3454          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
3455          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
3456          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
3457            row[m_Columns.m_col_name] = name;
3458          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
3459          // create a menu item for this instrument          row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3460          Gtk::RadioMenuItem* item =          row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3461              new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());  
3462          instrument_menu->get_submenu()->append(*item);  #if !USE_GTKMM_BUILDER
3463          item->signal_activate().connect(          add_instrument_to_menu(name);
3464              sigc::bind(  #endif
                 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  
                 instrument_index  
             )  
         );  
         instrument_index++;  
3465      }      }
3466      instrument_menu->show();      instrument_name_connection.unblock();
3467      instrument_menu->get_submenu()->show_all_children();  #if !USE_GTKMM_BUILDER
3468        uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
3469    #endif
3470    
3471        updateSampleRefCountMap(gig);
3472    
3473      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
3474          if (group->Name != "") {          if (group->Name != "") {
3475              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
3476              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
3477              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
3478              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
3479              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
3480              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1243  void MainWindow::load_gig(gig::File* gig Line 3482  void MainWindow::load_gig(gig::File* gig
3482                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
3483                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
3484                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
3485                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
3486                        gig_to_utf8(sample->pInfo->Name);
3487                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
3488                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
3489                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
3490                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3491                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3492              }              }
3493          }          }
3494      }      }
3495        
3496        for (int i = 0; gig->GetScriptGroup(i); ++i) {
3497            gig::ScriptGroup* group = gig->GetScriptGroup(i);
3498    
3499            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
3500            Gtk::TreeModel::Row rowGroup = *iterGroup;
3501            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
3502            rowGroup[m_ScriptsModel.m_col_group]  = group;
3503            rowGroup[m_ScriptsModel.m_col_script] = NULL;
3504            for (int s = 0; group->GetScript(s); ++s) {
3505                gig::Script* script = group->GetScript(s);
3506    
3507                Gtk::TreeModel::iterator iterScript =
3508                    m_refScriptsTreeModel->append(rowGroup.children());
3509                Gtk::TreeModel::Row rowScript = *iterScript;
3510                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
3511                rowScript[m_ScriptsModel.m_col_script] = script;
3512                rowScript[m_ScriptsModel.m_col_group]  = NULL;
3513            }
3514        }
3515        // unfold all sample groups & script groups by default
3516        m_TreeViewSamples.expand_all();
3517        m_TreeViewScripts.expand_all();
3518    
3519      file = gig;      file = gig;
3520    
3521      // select the first instrument      // select the first instrument
3522      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
3523      tree_sel_ref->select(Gtk::TreePath("0"));  
3524        instr_props_set_instrument();
3525        gig::Instrument* instrument = get_instrument();
3526        if (instrument) {
3527            midiRules.set_instrument(instrument);
3528        }
3529  }  }
3530    
3531  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
3532  {  {
3533      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
3534      if (instrument)  
3535      {      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3536        if (rows.empty()) {
3537            instrumentProps.hide();
3538            return false;
3539        }
3540        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3541        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3542        if (it) {
3543            Gtk::TreeModel::Row row = *it;
3544            gig::Instrument* instrument = row[m_Columns.m_col_instr];
3545    
3546          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
3547    
3548            // make sure instrument tree is updated when user changes the
3549            // instrument name in instrument properties window
3550            instrumentProps.signal_name_changed().connect(
3551                sigc::bind(
3552                    sigc::mem_fun(*this,
3553                                  &MainWindow::instr_name_changed_by_instr_props),
3554                    it));
3555        } else {
3556            instrumentProps.hide();
3557        }
3558        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3559        return it ? true : false;
3560    }
3561    
3562    void MainWindow::show_instr_props()
3563    {
3564        if (instr_props_set_instrument()) {
3565          instrumentProps.show();          instrumentProps.show();
3566          instrumentProps.deiconify();          instrumentProps.deiconify();
3567      }      }
3568  }  }
3569    
3570    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
3571    {
3572        Gtk::TreeModel::Row row = *it;
3573        Glib::ustring name = row[m_Columns.m_col_name];
3574    
3575        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3576        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
3577        if (gigname != name) {
3578            Gtk::TreeModel::Path path(*it);
3579            const int index = path[0];
3580            row[m_Columns.m_col_name] = gigname;
3581            row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3582        }
3583    }
3584    
3585    bool MainWindow::sample_props_set_sample()
3586    {
3587        sampleProps.signal_name_changed().clear();
3588    
3589        std::vector<Gtk::TreeModel::Path> rows = m_TreeViewSamples.get_selection()->get_selected_rows();
3590        if (rows.empty()) {
3591            sampleProps.hide();
3592            return false;
3593        }
3594        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3595        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3596        if (it) {
3597            Gtk::TreeModel::Row row = *it;
3598            gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3599    
3600            sampleProps.set_sample(sample);
3601    
3602            // make sure sample tree is updated when user changes the
3603            // sample name in sample properties window
3604            sampleProps.signal_name_changed().connect(
3605                sigc::bind(
3606                    sigc::mem_fun(*this,
3607                        &MainWindow::sample_name_changed_by_sample_props
3608                    ), it
3609                )
3610            );
3611        } else {
3612            sampleProps.hide();
3613        }
3614        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3615        return it ? true : false;
3616    }
3617    
3618    void MainWindow::show_sample_props()
3619    {
3620        if (sample_props_set_sample()) {
3621            sampleProps.show();
3622            sampleProps.deiconify();
3623        }
3624    }
3625    
3626    void MainWindow::sample_name_changed_by_sample_props(Gtk::TreeModel::iterator& it)
3627    {
3628        Gtk::TreeModel::Row row = *it;
3629        Glib::ustring name = row[m_SamplesModel.m_col_name];
3630    
3631        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3632        Glib::ustring gigname(gig_to_utf8(sample->pInfo->Name));
3633        if (gigname != name) {
3634            Gtk::TreeModel::Path path(*it);
3635            row[m_SamplesModel.m_col_name] = gigname;
3636        }
3637    }
3638    
3639    void MainWindow::show_midi_rules()
3640    {
3641        if (gig::Instrument* instrument = get_instrument())
3642        {
3643            midiRules.set_instrument(instrument);
3644            midiRules.show();
3645            midiRules.deiconify();
3646        }
3647    }
3648    
3649    void MainWindow::show_script_slots() {
3650        if (!file) return;
3651        // get selected instrument
3652        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3653        if (rows.empty()) return;
3654        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3655        if (!it) return;
3656        Gtk::TreeModel::Row row = *it;
3657        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3658        if (!instrument) return;
3659    
3660        ScriptSlots* window = new ScriptSlots;
3661        window->setInstrument(instrument);
3662        window->signal_script_slots_changed().connect(
3663            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
3664        );
3665        //window->reparent(*this);
3666        window->show();
3667    }
3668    
3669    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
3670        if (!pInstrument) return;
3671        const int iScriptSlots = pInstrument->ScriptSlotCount();
3672    
3673        //NOTE: This is a big mess! Sometimes GTK requires m_TreeView.get_model(), here we need m_refTreeModelFilter->get_model(), otherwise accessing children below causes an error!
3674        //Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3675        Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3676    
3677        for (int i = 0; i < model->children().size(); ++i) {
3678            Gtk::TreeModel::Row row = model->children()[i];
3679            if (row[m_Columns.m_col_instr] != pInstrument) continue;
3680            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3681            row[m_Columns.m_col_tooltip] = scriptTooltipFor(pInstrument, i);
3682            break;
3683        }
3684    
3685        // causes the sampler to reload the instrument with the new script
3686        on_sel_change();
3687    }
3688    
3689    void MainWindow::assignScript(gig::Script* pScript) {
3690        if (!pScript) {
3691            printf("assignScript() : !script\n");
3692            return;
3693        }
3694        printf("assignScript('%s')\n", pScript->Name.c_str());
3695    
3696        gig::Instrument* pInstrument = get_instrument();
3697        if (!pInstrument) {
3698            printf("!instrument\n");
3699            return;
3700        }
3701    
3702        pInstrument->AddScriptSlot(pScript);
3703    
3704        onScriptSlotsModified(pInstrument);
3705    }
3706    
3707    void MainWindow::dropAllScriptSlots() {
3708        gig::Instrument* pInstrument = get_instrument();
3709        if (!pInstrument) {
3710            printf("!instrument\n");
3711            return;
3712        }
3713    
3714        const int iScriptSlots = pInstrument->ScriptSlotCount();
3715        for (int i = iScriptSlots - 1; i >= 0; --i)
3716            pInstrument->RemoveScriptSlot(i);
3717    
3718        onScriptSlotsModified(pInstrument);
3719    }
3720    
3721    void MainWindow::on_action_refresh_all() {
3722        __refreshEntireGUI();
3723    }
3724    
3725  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
3726    #if USE_GLIB_ACTION
3727        bool active = false;
3728        m_actionToggleStatusBar->get_state(active);
3729        // for some reason toggle state does not change automatically
3730        active = !active;
3731        m_actionToggleStatusBar->change_state(active);
3732        if (active)
3733            m_StatusBar.show();
3734        else
3735            m_StatusBar.hide();
3736    #else
3737      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
3738          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
3739      if (!item) {      if (!item) {
# Line 1277  void MainWindow::on_action_view_status_b Line 3742  void MainWindow::on_action_view_status_b
3742      }      }
3743      if (item->get_active()) m_StatusBar.show();      if (item->get_active()) m_StatusBar.show();
3744      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
3745    #endif
3746  }  }
3747    
3748  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_auto_restore_win_dim() {
3749  {  #if USE_GLIB_ACTION
3750        bool active = false;
3751        m_actionToggleRestoreWinDim->get_state(active);
3752        // for some reason toggle state does not change automatically
3753        active = !active;
3754        m_actionToggleRestoreWinDim->change_state(active);
3755        Settings::singleton()->autoRestoreWindowDimension = active;
3756    #else
3757        Gtk::CheckMenuItem* item =
3758            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
3759        if (!item) {
3760            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
3761            return;
3762        }
3763        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
3764    #endif
3765    }
3766    
3767    void MainWindow::on_save_with_temporary_file() {
3768    #if USE_GLIB_ACTION
3769        bool active = false;
3770        m_actionToggleSaveWithTempFile->get_state(active);
3771        // for some reason toggle state does not change automatically
3772        active = !active;
3773        m_actionToggleSaveWithTempFile->change_state(active);
3774        Settings::singleton()->saveWithTemporaryFile = active;
3775    #else
3776        Gtk::CheckMenuItem* item =
3777            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
3778        if (!item) {
3779            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
3780            return;
3781        }
3782        Settings::singleton()->saveWithTemporaryFile = item->get_active();
3783    #endif
3784    }
3785    
3786    bool MainWindow::is_copy_samples_unity_note_enabled() const {
3787    #if USE_GLIB_ACTION
3788        bool active = false;
3789        m_actionToggleCopySampleUnity->get_state(active);
3790        return active;
3791    #else
3792        Gtk::CheckMenuItem* item =
3793            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
3794        if (!item) {
3795            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
3796            return true;
3797        }
3798        return item->get_active();
3799    #endif
3800    }
3801    
3802    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
3803    #if USE_GLIB_ACTION
3804        bool active = false;
3805        m_actionToggleCopySampleTune->get_state(active);
3806        return active;
3807    #else
3808        Gtk::CheckMenuItem* item =
3809            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
3810        if (!item) {
3811            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
3812            return true;
3813        }
3814        return item->get_active();
3815    #endif
3816    }
3817    
3818    bool MainWindow::is_copy_samples_loop_enabled() const {
3819    #if USE_GLIB_ACTION
3820        bool active = false;
3821        m_actionToggleCopySampleLoop->get_state(active);
3822        return active;
3823    #else
3824        Gtk::CheckMenuItem* item =
3825            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
3826        if (!item) {
3827            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
3828            return true;
3829        }
3830        return item->get_active();
3831    #endif
3832    }
3833    
3834    #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
3835    bool MainWindow::on_button_release(Gdk::EventButton& _button) {
3836        GdkEventButton* button = _button.gobj();
3837    #else
3838    void MainWindow::on_button_release(GdkEventButton* button) {
3839    #endif
3840      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
3841          show_instr_props();          show_instr_props();
3842      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3843            // gig v2 files have no midi rules
3844            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
3845    #if USE_GTKMM_BUILDER
3846            m_actionMIDIRules->property_enabled() = bEnabled;
3847    #else
3848            static_cast<Gtk::MenuItem*>(
3849                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
3850                    bEnabled
3851                );
3852            static_cast<Gtk::MenuItem*>(
3853                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
3854                    bEnabled
3855                );
3856    #endif
3857          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
3858      }      }
3859    #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
3860        return false;
3861    #endif
3862    }
3863    
3864    #if !USE_GTKMM_BUILDER
3865    void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
3866        if (item->get_active()) {
3867            const std::vector<Gtk::Widget*> children =
3868                instrument_menu->get_children();
3869            std::vector<Gtk::Widget*>::const_iterator it =
3870                find(children.begin(), children.end(), item);
3871            if (it != children.end()) {
3872                int index = it - children.begin();
3873                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
3874    
3875                m_RegionChooser.set_instrument(file->GetInstrument(index));
3876            }
3877        }
3878  }  }
3879    #endif
3880    
3881    void MainWindow::select_instrument(gig::Instrument* instrument) {
3882        if (!instrument) return;
3883    
3884  void MainWindow::on_instrument_selection_change(int index) {      //NOTE: This is a big mess! Sometimes GTK requires m_refTreeModelFilter->get_model(), here we need m_TreeView.get_model(), otherwise treeview selection below causes an error!
3885      m_RegionChooser.set_instrument(file->GetInstrument(index));      Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3886        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3887    
3888        for (int i = 0; i < model->children().size(); ++i) {
3889            Gtk::TreeModel::Row row = model->children()[i];
3890            if (row[m_Columns.m_col_instr] == instrument) {
3891                // select and show the respective instrument in the list view
3892                show_intruments_tab();
3893                m_TreeView.get_selection()->unselect_all();
3894                
3895    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3896                auto iterSel = model->children()[i].get_iter();
3897                m_TreeView.get_selection()->select(iterSel);
3898    #else
3899                m_TreeView.get_selection()->select(model->children()[i]);
3900    #endif
3901                std::vector<Gtk::TreeModel::Path> rows =
3902                    m_TreeView.get_selection()->get_selected_rows();
3903                if (!rows.empty())
3904                    m_TreeView.scroll_to_row(rows[0]);
3905                on_sel_change(); // the regular instrument selection change callback
3906            }
3907        }
3908  }  }
3909    
3910    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
3911    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
3912        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
3913        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
3914    
3915        //NOTE: This is a big mess! Sometimes GTK requires m_refTreeModelFilter->get_model(), here we need m_TreeView.get_model(), otherwise treeview selection below causes an error!
3916        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3917        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3918    
3919        for (int i = 0; i < model->children().size(); ++i) {
3920            Gtk::TreeModel::Row row = model->children()[i];
3921            if (row[m_Columns.m_col_instr] == pInstrument) {
3922                // select and show the respective instrument in the list view
3923                show_intruments_tab();
3924                m_TreeView.get_selection()->unselect_all();
3925    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3926                auto iterSel = model->children()[i].get_iter();
3927                m_TreeView.get_selection()->select(iterSel);
3928    #else
3929                m_TreeView.get_selection()->select(model->children()[i]);
3930    #endif
3931                std::vector<Gtk::TreeModel::Path> rows =
3932                    m_TreeView.get_selection()->get_selected_rows();
3933                if (!rows.empty())
3934                    m_TreeView.scroll_to_row(rows[0]);
3935                on_sel_change(); // the regular instrument selection change callback
3936    
3937                // select respective region in the region selector
3938                m_RegionChooser.set_region(pRegion);
3939    
3940                // select and show the respective dimension region in the editor
3941                //update_dimregs();
3942                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
3943                //dimreg_edit.set_dim_region(dimRgn);
3944    
3945                return true;
3946            }
3947        }
3948    
3949        return false;
3950    }
3951    
3952    void MainWindow::select_sample(gig::Sample* sample) {
3953        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3954        for (int g = 0; g < model->children().size(); ++g) {
3955            Gtk::TreeModel::Row rowGroup = model->children()[g];
3956            for (int s = 0; s < rowGroup.children().size(); ++s) {
3957                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3958                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
3959                    show_samples_tab();
3960                    m_TreeViewSamples.get_selection()->unselect_all();
3961    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3962                    auto iterSel = rowGroup.children()[s].get_iter();
3963                    m_TreeViewSamples.get_selection()->select(iterSel);
3964    #else
3965                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
3966    #endif
3967                    std::vector<Gtk::TreeModel::Path> rows =
3968                        m_TreeViewSamples.get_selection()->get_selected_rows();
3969                    if (rows.empty()) return;
3970                    m_TreeViewSamples.scroll_to_row(rows[0]);
3971                    return;
3972                }
3973            }
3974        }
3975    }
3976    
3977    #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
3978    bool MainWindow::on_sample_treeview_button_release(Gdk::EventButton& _button) {
3979        GdkEventButton* button = _button.gobj();
3980    #else
3981  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
3982    #endif
3983      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3984            // by default if Ctrl keys is pressed down, then a mouse right-click
3985            // does not select the respective row, so we must assure this
3986            // programmatically ...
3987            /*{
3988                Gtk::TreeModel::Path path;
3989                Gtk::TreeViewColumn* pColumn = NULL;
3990                int cellX, cellY;
3991                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
3992                    (int)button->x, (int)button->y,
3993                    path, pColumn, cellX, cellY
3994                );
3995                if (bSuccess) {
3996                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
3997                        printf("not selected !!!\n");
3998                        m_TreeViewSamples.get_selection()->select(path);
3999                    }
4000                }
4001            }*/
4002    
4003    #if !USE_GTKMM_BUILDER
4004          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
4005              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
4006    #endif
4007    
4008          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
4009          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4010          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4011          bool group_selected  = false;          const int n = rows.size();
4012          bool sample_selected = false;          int nGroups  = 0;
4013          if (it) {          int nSamples = 0;
4014            for (int r = 0; r < n; ++r) {
4015                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4016                if (!it) continue;
4017              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
4018              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
4019              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
4020          }          }
4021    
4022    #if USE_GTKMM_BUILDER
4023            m_actionSampleProperties->property_enabled() = (n == 1);
4024            m_actionAddSample->property_enabled() = (n);
4025            m_actionAddSampleGroup->property_enabled() = (file);
4026            m_actionViewSampleRefs->property_enabled() = (nSamples == 1);
4027            m_actionRemoveSample->property_enabled() = (n);
4028            m_actionReplaceSample->property_enabled() = (nSamples == 1);
4029    #else
4030          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
4031              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
4032          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
4033              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
4034          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
4035              set_sensitive(file);              set_sensitive(file);
4036            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
4037                set_sensitive(nSamples == 1);
4038          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
4039              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
4040    #endif
4041          // show sample popup          // show sample popup
4042          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
4043    
4044    #if !USE_GTKMM_BUILDER
4045            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
4046                set_sensitive(n == 1);
4047            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
4048                set_sensitive(n);
4049            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
4050                set_sensitive(file);
4051            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
4052                set_sensitive(nSamples == 1);
4053            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
4054                set_sensitive(n);
4055    #endif
4056      }      }
4057        
4058    #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
4059        return false;
4060    #endif
4061  }  }
4062    
4063  void MainWindow::on_action_add_instrument() {  #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
4064      static int __instrument_indexer = 0;  bool MainWindow::on_script_treeview_button_release(Gdk::EventButton& _button) {
4065      if (!file) return;      GdkEventButton* button = _button.gobj();
4066      gig::Instrument* instrument = file->AddInstrument();  #else
4067      __instrument_indexer++;  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
4068      instrument->pInfo->Name =  #endif
4069          _("Unnamed Instrument ") + ToString(__instrument_indexer);      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
4070    #if !USE_GTKMM_BUILDER
4071            Gtk::Menu* script_popup =
4072                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
4073    #endif
4074            // update enabled/disabled state of sample popup items
4075            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4076            Gtk::TreeModel::iterator it = sel->get_selected();
4077            bool group_selected  = false;
4078            bool script_selected = false;
4079            if (it) {
4080                Gtk::TreeModel::Row row = *it;
4081                group_selected  = row[m_ScriptsModel.m_col_group];
4082                script_selected = row[m_ScriptsModel.m_col_script];
4083            }
4084    #if USE_GTKMM_BUILDER
4085            m_actionAddScript->property_enabled() = (group_selected || script_selected);
4086            m_actionAddScriptGroup->property_enabled() = (file);
4087            m_actionEditScript->property_enabled() = (script_selected);
4088            m_actionRemoveScript->property_enabled() = (group_selected || script_selected);
4089    #else
4090            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
4091                set_sensitive(group_selected || script_selected);
4092            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
4093                set_sensitive(file);
4094            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
4095                set_sensitive(script_selected);    
4096            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
4097                set_sensitive(group_selected || script_selected);
4098    #endif
4099            // show sample popup
4100            script_popup->popup(button->button, button->time);
4101    
4102    #if !USE_GTKMM_BUILDER
4103            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
4104                set_sensitive(group_selected || script_selected);
4105            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
4106                set_sensitive(file);
4107            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
4108                set_sensitive(script_selected);    
4109            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
4110                set_sensitive(group_selected || script_selected);
4111    #endif
4112        }
4113    #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
4114        return false;
4115    #endif
4116    }
4117    
4118    void MainWindow::updateScriptListOfMenu() {
4119        // remove all entries from "Assign Script" menu
4120        {
4121            const std::vector<Gtk::Widget*> children = assign_scripts_menu->get_children();
4122            for (int i = 0; i < children.size(); ++i) {
4123                Gtk::Widget* child = children[i];
4124                assign_scripts_menu->remove(*child);
4125                delete child;
4126            }
4127        }
4128    
4129        int iTotalScripts = 0;
4130    
4131        if (!file) goto noScripts;
4132    
4133        // add all configured macros as menu items to the "Macro" menu
4134        for (int iGroup = 0; file->GetScriptGroup(iGroup); ++iGroup) {
4135            gig::ScriptGroup* pGroup = file->GetScriptGroup(iGroup);
4136            for (int iScript = 0; pGroup->GetScript(iScript); ++iScript, ++iTotalScripts) {
4137                gig::Script* pScript = pGroup->GetScript(iScript);
4138                std::string name = pScript->Name;
4139    
4140                Gtk::MenuItem* item = new Gtk::MenuItem(name);
4141                item->signal_activate().connect(
4142                    sigc::bind(
4143                        sigc::mem_fun(*this, &MainWindow::assignScript), pScript
4144                    )
4145                );
4146                assign_scripts_menu->append(*item);
4147                item->set_accel_path("<Scripts>/script_" + ToString(iTotalScripts));
4148                //item->set_tooltip_text(comment);
4149            }
4150        }
4151    
4152        noScripts:
4153    
4154        // if there are no macros configured at all, then show a dummy entry instead
4155        if (!iTotalScripts) {
4156            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Scripts"));
4157            item->set_sensitive(false);
4158            assign_scripts_menu->append(*item);
4159        }
4160    
4161        // add separator line to menu
4162        assign_scripts_menu->append(*new Gtk::SeparatorMenuItem);
4163    
4164        {
4165            Gtk::MenuItem* item = new Gtk::MenuItem(_("Unassign All Scripts"));
4166            item->signal_activate().connect(
4167                sigc::mem_fun(*this, &MainWindow::dropAllScriptSlots)
4168            );
4169            assign_scripts_menu->append(*item);
4170            item->set_accel_path("<Scripts>/DropAllScriptSlots");
4171        }
4172    
4173    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4174        assign_scripts_menu->show_all_children();
4175    #endif
4176    }
4177    
4178    #if !USE_GTKMM_BUILDER
4179    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
4180        const Glib::ustring& name, int position) {
4181    
4182        Gtk::RadioMenuItem::Group instrument_group;
4183        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
4184        if (!children.empty()) {
4185            instrument_group =
4186                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
4187        }
4188        Gtk::RadioMenuItem* item =
4189            new Gtk::RadioMenuItem(instrument_group, name);
4190        if (position < 0) {
4191            instrument_menu->append(*item);
4192        } else {
4193            instrument_menu->insert(*item, position);
4194        }
4195        item->show();
4196        item->signal_activate().connect(
4197            sigc::bind(
4198                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
4199                item));
4200        return item;
4201    }
4202    #endif
4203    
4204    #if !USE_GTKMM_BUILDER
4205    void MainWindow::remove_instrument_from_menu(int index) {
4206        const std::vector<Gtk::Widget*> children =
4207            instrument_menu->get_children();
4208        Gtk::Widget* child = children[index];
4209        instrument_menu->remove(*child);
4210        delete child;
4211    }
4212    #endif
4213    
4214    void MainWindow::add_instrument(gig::Instrument* instrument) {
4215        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
4216    
4217      // update instrument tree view      // update instrument tree view
4218        instrument_name_connection.block();
4219      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
4220      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
4221      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      const int index = m_refTreeModel->children().size() - 1;
4222        rowInstr[m_Columns.m_col_nr] = index;
4223        rowInstr[m_Columns.m_col_name] = name;
4224      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
4225        rowInstr[m_Columns.m_col_scripts] = "";
4226        rowInstr[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
4227        instrument_name_connection.unblock();
4228    
4229    #if !USE_GTKMM_BUILDER
4230        add_instrument_to_menu(name);
4231    #endif
4232        select_instrument(instrument);
4233      file_changed();      file_changed();
4234  }  }
4235    
4236    void MainWindow::on_action_add_instrument() {
4237        static int __instrument_indexer = 0;
4238        if (!file) return;
4239        gig::Instrument* instrument = file->AddInstrument();
4240        __instrument_indexer++;
4241        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
4242                                                ToString(__instrument_indexer));
4243    
4244        add_instrument(instrument);
4245    }
4246    
4247  void MainWindow::on_action_duplicate_instrument() {  void MainWindow::on_action_duplicate_instrument() {
4248      if (!file) return;      if (!file) return;
4249        
4250      // retrieve the currently selected instrument      // retrieve the currently selected instrument
4251      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
4252      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4253      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4254      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
4255      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
4256      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
4257      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
4258                    gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
4259      // duplicate the orginal instrument              if (instrOrig) {
4260      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
4261      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
4262          instrOrig->pInfo->Name + " (" + _("Copy") + ")";                  instrNew->pInfo->Name =
4263                                instrOrig->pInfo->Name +
4264      // update instrument tree view                      gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
4265      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();  
4266      Gtk::TreeModel::Row rowInstr = *iterInstr;                  add_instrument(instrNew);
4267      rowInstr[m_Columns.m_col_name] = instrNew->pInfo->Name.c_str();              }
4268      rowInstr[m_Columns.m_col_instr] = instrNew;          }
4269      file_changed();      }
4270  }  }
4271    
4272  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1373  void MainWindow::on_action_remove_instru Line 4283  void MainWindow::on_action_remove_instru
4283      }      }
4284    
4285      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4286      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4287      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4288            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
4289            if (!it) continue;
4290          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4291          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
4292          try {          try {
4293                Gtk::TreePath path(it);
4294                int index = path[0];
4295    
4296              // remove instrument from the gig file              // remove instrument from the gig file
4297              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
4298              file_changed();              file_changed();
4299    
4300    #if !USE_GTKMM_BUILDER
4301                remove_instrument_from_menu(index);
4302    #endif
4303    
4304                // remove row from instruments tree view
4305                m_refTreeModel->erase(it);
4306                // update "Nr" column of all instrument rows
4307                {
4308                    int index = 0;
4309                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
4310                         it != m_refTreeModel->children().end(); ++it, ++index)
4311                    {
4312                        Gtk::TreeModel::Row row = *it;
4313                        gig::Instrument* instrument = row[m_Columns.m_col_instr];
4314                        row[m_Columns.m_col_nr] = index;
4315                        row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
4316                    }
4317                }
4318    
4319    #if GTKMM_MAJOR_VERSION < 3
4320                // select another instrument (in gtk3 this is done
4321                // automatically)
4322                if (!m_refTreeModel->children().empty()) {
4323                    if (index == m_refTreeModel->children().size()) {
4324                        index--;
4325                    }
4326                    m_TreeView.get_selection()->select(
4327                        Gtk::TreePath(ToString(index)));
4328                }
4329    #endif
4330                instr_props_set_instrument();
4331                instr = get_instrument();
4332                if (instr) {
4333                    midiRules.set_instrument(instr);
4334                } else {
4335                    midiRules.hide();
4336                }
4337          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
4338              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4339              msg.run();              msg.run();
# Line 1391  void MainWindow::on_action_remove_instru Line 4342  void MainWindow::on_action_remove_instru
4342  }  }
4343    
4344  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
4345      //TODO: show a dialog where the selected sample's properties can be edited      show_sample_props();
4346      Gtk::MessageDialog msg(  }
4347          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO  
4348    void MainWindow::on_action_add_script_group() {
4349        static int __script_indexer = 0;
4350        if (!file) return;
4351        gig::ScriptGroup* group = file->AddScriptGroup();
4352        group->Name = gig_from_utf8(_("Unnamed Group"));
4353        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
4354        __script_indexer++;
4355        // update sample tree view
4356        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
4357        Gtk::TreeModel::Row rowGroup = *iterGroup;
4358        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
4359        rowGroup[m_ScriptsModel.m_col_script] = NULL;
4360        rowGroup[m_ScriptsModel.m_col_group] = group;
4361        file_changed();
4362    }
4363    
4364    void MainWindow::on_action_add_script() {
4365        if (!file) return;
4366        // get selected group
4367        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4368        Gtk::TreeModel::iterator it = sel->get_selected();
4369        if (!it) return;
4370        Gtk::TreeModel::Row row = *it;
4371        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4372        if (!group) { // not a group, but a script is selected (probably)
4373            gig::Script* script = row[m_ScriptsModel.m_col_script];
4374            if (!script) return;
4375            it = row.parent(); // resolve parent (that is the script's group)
4376            if (!it) return;
4377            row = *it;
4378            group = row[m_ScriptsModel.m_col_group];
4379            if (!group) return;
4380        }
4381    
4382        // add a new script to the .gig file
4383        gig::Script* script = group->AddScript();    
4384        Glib::ustring name = _("Unnamed Script");
4385        script->Name = gig_from_utf8(name);
4386    
4387        // add script to the tree view
4388        Gtk::TreeModel::iterator iterScript =
4389            m_refScriptsTreeModel->append(row.children());
4390        Gtk::TreeModel::Row rowScript = *iterScript;
4391        rowScript[m_ScriptsModel.m_col_name] = name;
4392        rowScript[m_ScriptsModel.m_col_script] = script;
4393        rowScript[m_ScriptsModel.m_col_group]  = NULL;
4394    
4395        // unfold group of new script item in treeview
4396        Gtk::TreeModel::Path path(iterScript);
4397        m_TreeViewScripts.expand_to_path(path);
4398    }
4399    
4400    void MainWindow::on_action_edit_script() {
4401        if (!file) return;
4402        // get selected script
4403        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4404        Gtk::TreeModel::iterator it = sel->get_selected();
4405        if (!it) return;
4406        Gtk::TreeModel::Row row = *it;
4407        gig::Script* script = row[m_ScriptsModel.m_col_script];
4408        if (!script) return;
4409    
4410        ScriptEditor* editor = new ScriptEditor;
4411        editor->signal_script_to_be_changed.connect(
4412            signal_script_to_be_changed.make_slot()
4413      );      );
4414      msg.run();      editor->signal_script_changed.connect(
4415            signal_script_changed.make_slot()
4416        );
4417        editor->setScript(script);
4418        //editor->reparent(*this);
4419        editor->show();
4420    }
4421    
4422    void MainWindow::on_action_remove_script() {
4423        if (!file) return;
4424        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4425        Gtk::TreeModel::iterator it = sel->get_selected();
4426        if (it) {
4427            Gtk::TreeModel::Row row = *it;
4428            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4429            gig::Script* script     = row[m_ScriptsModel.m_col_script];
4430            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
4431            try {
4432                // remove script group or script from the gig file
4433                if (group) {
4434                    // notify everybody that we're going to remove these samples
4435    //TODO:         scripts_to_be_removed_signal.emit(members);
4436                    // delete the group in the .gig file including the
4437                    // samples that belong to the group
4438                    file->DeleteScriptGroup(group);
4439                    // notify that we're done with removal
4440    //TODO:         scripts_removed_signal.emit();
4441                    file_changed();
4442                } else if (script) {
4443                    // notify everybody that we're going to remove this sample
4444    //TODO:         std::list<gig::Script*> lscripts;
4445    //TODO:         lscripts.push_back(script);
4446    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
4447                    // remove sample from the .gig file
4448                    script->GetGroup()->DeleteScript(script);
4449                    // notify that we're done with removal
4450    //TODO:         scripts_removed_signal.emit();
4451                    dimreg_changed();
4452                    file_changed();
4453                }
4454                // remove respective row(s) from samples tree view
4455                m_refScriptsTreeModel->erase(it);
4456            } catch (RIFF::Exception e) {
4457                // pretend we're done with removal (i.e. to avoid dead locks)
4458    //TODO:     scripts_removed_signal.emit();
4459                // show error message
4460                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4461                msg.run();
4462            }
4463        }
4464  }  }
4465    
4466  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
4467      static int __sample_indexer = 0;      static int __sample_indexer = 0;
4468      if (!file) return;      if (!file) return;
4469      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
4470      group->Name = _("Unnamed Group");      group->Name = gig_from_utf8(_("Unnamed Group"));
4471      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
4472      __sample_indexer++;      __sample_indexer++;
4473      // update sample tree view      // update sample tree view
4474      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
4475      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
4476      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
4477      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
4478      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
4479      file_changed();      file_changed();
4480  }  }
4481    
4482    void MainWindow::on_action_replace_sample() {
4483        add_or_replace_sample(true);
4484    }
4485    
4486  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
4487        add_or_replace_sample(false);
4488    }
4489    
4490    void MainWindow::add_or_replace_sample(bool replace) {
4491      if (!file) return;      if (!file) return;
4492      // get selected group  
4493        // get selected group (and probably selected sample)
4494      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4495      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4496        if (rows.empty()) return;
4497        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4498      if (!it) return;      if (!it) return;
4499      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
4500        gig::Sample* sample = NULL;
4501      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
4502      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
4503          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
4504          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
4505          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
4506          if (!it) return;          if (!it) return;
4507          row = *it;          if (!replace) row = *it;
4508          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
4509          if (!group) return;          if (!group) return;
4510      }      }
4511        if (replace && !sample) return;
4512    
4513      // show 'browse for file' dialog      // show 'browse for file' dialog
4514      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
4515    #if HAS_GTKMM_STOCK
4516      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4517      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
4518      dialog.set_select_multiple(true);  #else
4519        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4520        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
4521    #endif
4522        dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
4523    
4524      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
4525  #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 1477  void MainWindow::on_action_add_sample() Line 4561  void MainWindow::on_action_add_sample()
4561          dialog.set_current_folder(current_sample_dir);          dialog.set_current_folder(current_sample_dir);
4562      }      }
4563      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
4564            dialog.hide();
4565          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4566          Glib::ustring error_files;          Glib::ustring error_files;
4567          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
4568          for (std::vector<std::string>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
4569               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
4570              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
4571              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file information
4572              SF_INFO info;              SF_INFO info;
4573              info.format = 0;              info.format = 0;
4574              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
# Line 1506  void MainWindow::on_action_add_sample() Line 4591  void MainWindow::on_action_add_sample()
4591                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
4592                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
4593                  }                  }
4594                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
4595                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
4596                  // file name without path                  // file name without path
4597                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
4598                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1517  void MainWindow::on_action_add_sample() Line 4602  void MainWindow::on_action_add_sample()
4602                          break;                          break;
4603                      }                      }
4604                  }                  }
4605                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
4606                  sample->Channels = info.channels;                  sample->Channels = info.channels;
4607                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
4608                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1531  void MainWindow::on_action_add_sample() Line 4616  void MainWindow::on_action_add_sample()
4616                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
4617                  {                  {
4618                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
4619                        sample->FineTune      = instrument.detune;
4620    
4621                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
4622                          sample->Loops = 1;                          sample->Loops = 1;
# Line 1557  void MainWindow::on_action_add_sample() Line 4643  void MainWindow::on_action_add_sample()
4643                  // physically when File::Save() is called)                  // physically when File::Save() is called)
4644                  sample->Resize(info.frames);                  sample->Resize(info.frames);
4645                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
4646                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
4647                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
4648                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
4649                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4650                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4651                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
4652                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4653                  // add sample to the tree view                  // add sample to the tree view
4654                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
4655                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
4656                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
4657                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
4658                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
4659                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
4660                        rowSample[m_SamplesModel.m_col_name] =
4661                            gig_to_utf8(sample->pInfo->Name);
4662                        rowSample[m_SamplesModel.m_col_sample] = sample;
4663                        rowSample[m_SamplesModel.m_col_group]  = NULL;
4664                    }
4665                  // close sound file                  // close sound file
4666                  sf_close(hFile);                  sf_close(hFile);
4667                  file_changed();                  file_changed();
4668              } 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)
4669                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4670                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
4671              }              }
4672          }          }
4673          // 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
4674          if (error_files.size()) {          if (!error_files.empty()) {
4675              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
4676                    (replace
4677                        ? _("Failed to replace sample with:\n")
4678                        : _("Could not add the following sample(s):\n"))
4679                    + error_files;
4680              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4681              msg.run();              msg.run();
4682          }          }
# Line 1593  void MainWindow::on_action_replace_all_s Line 4688  void MainWindow::on_action_replace_all_s
4688      if (!file) return;      if (!file) return;
4689      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
4690                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
4691      const char* str =      const char* str =
4692          _("This is a very specific function. It tries to replace all samples "          _("This is a very specific function. It tries to replace all samples "
4693            "in the current gig file by samples located in the chosen "            "in the current gig file by samples located in the chosen "
4694            "directory.\n\n"            "directory.\n\n"
# Line 1614  void MainWindow::on_action_replace_all_s Line 4709  void MainWindow::on_action_replace_all_s
4709      Gtk::Label description(str);      Gtk::Label description(str);
4710      description.set_line_wrap();      description.set_line_wrap();
4711  #endif  #endif
4712      Gtk::HBox entryArea;      HBox entryArea;
4713      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
4714      Gtk::Entry postfixEntryBox;      Gtk::Entry postfixEntryBox;
4715      postfixEntryBox.set_text(".wav");      postfixEntryBox.set_text(".wav");
4716      entryArea.pack_start(entryLabel);      entryArea.pack_start(entryLabel);
4717      entryArea.pack_start(postfixEntryBox);      entryArea.pack_start(postfixEntryBox);
4718    #if USE_GTKMM_BOX
4719        dialog.get_content_area()->pack_start(description, Gtk::PACK_SHRINK);
4720        dialog.get_content_area()->pack_start(entryArea, Gtk::PACK_SHRINK);
4721    #else
4722      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
4723      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
4724    #endif
4725      description.show();      description.show();
4726    
4727    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4728      entryArea.show_all();      entryArea.show_all();
4729    #else
4730        entryArea.show();
4731    #endif
4732    
4733    #if HAS_GTKMM_STOCK
4734      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4735    #else
4736        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4737    #endif
4738      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
4739      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
4740      if (current_sample_dir != "") {      if (current_sample_dir != "") {
# Line 1632  void MainWindow::on_action_replace_all_s Line 4742  void MainWindow::on_action_replace_all_s
4742      }      }
4743      if (dialog.run() == Gtk::RESPONSE_OK)      if (dialog.run() == Gtk::RESPONSE_OK)
4744      {      {
4745            dialog.hide();
4746          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4747          Glib::ustring error_files;          Glib::ustring error_files;
4748          std::string folder = dialog.get_filename();          std::string folder = dialog.get_filename();
# Line 1639  void MainWindow::on_action_replace_all_s Line 4750  void MainWindow::on_action_replace_all_s
4750               sample; sample = file->GetNextSample())               sample; sample = file->GetNextSample())
4751          {          {
4752              std::string filename =              std::string filename =
4753                  folder + G_DIR_SEPARATOR_S + sample->pInfo->Name +                  folder + G_DIR_SEPARATOR_S +
4754                  postfixEntryBox.get_text().raw();                  Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
4755                                             postfixEntryBox.get_text());
4756              SF_INFO info;              SF_INFO info;
4757              info.format = 0;              info.format = 0;
4758              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
4759              try              try
4760              {              {
4761                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
4762                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
4763                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
4764                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
4765                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
4766                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
4767                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
4768                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
4769                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
4770                          break;                          break;
4771                      default:                      default:
4772                          sf_close(hFile);                          sf_close(hFile);
# Line 1667  void MainWindow::on_action_replace_all_s Line 4775  void MainWindow::on_action_replace_all_s
4775                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4776                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4777                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
4778                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4779                  sf_close(hFile);                  sf_close(hFile);
4780                  file_changed();                  file_changed();
4781              }              }
4782              catch (std::string what)              catch (std::string what)
4783              {              {
4784                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4785                      error_files += filename += " (" + what + ")";                  error_files += Glib::filename_to_utf8(filename) +
4786                        " (" + what + ")";
4787              }              }
4788          }          }
4789          // 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
4790          if (error_files.size()) {          if (!error_files.empty()) {
4791              Glib::ustring txt =              Glib::ustring txt =
4792                  _("Could not replace the following sample(s):\n") + error_files;                  _("Could not replace the following sample(s):\n") + error_files;
4793              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
# Line 1690  void MainWindow::on_action_replace_all_s Line 4799  void MainWindow::on_action_replace_all_s
4799  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
4800      if (!file) return;      if (!file) return;
4801      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4802      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4803      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4804            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4805            if (!it) continue;
4806          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4807          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
4808          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1699  void MainWindow::on_action_remove_sample Line 4810  void MainWindow::on_action_remove_sample
4810          try {          try {
4811              // remove group or sample from the gig file              // remove group or sample from the gig file
4812              if (group) {              if (group) {
4813                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
4814                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
4815                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
4816                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1716  void MainWindow::on_action_remove_sample Line 4827  void MainWindow::on_action_remove_sample
4827                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
4828                  // them from the import queue                  // them from the import queue
4829                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
4830                       member != members.end(); ++member) {                       member != members.end(); ++member)
4831                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
4832                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
4833                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
4834                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
4835                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
4836                      }                      }
4837                  }                  }
4838                  file_changed();                  file_changed();
# Line 1739  void MainWindow::on_action_remove_sample Line 4847  void MainWindow::on_action_remove_sample
4847                  samples_removed_signal.emit();                  samples_removed_signal.emit();
4848                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
4849                  // the import queue                  // the import queue
4850                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
4851                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
4852                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
4853                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
4854                  }                  }
4855                  dimreg_changed();                  dimreg_changed();
4856                  file_changed();                  file_changed();
# Line 1763  void MainWindow::on_action_remove_sample Line 4867  void MainWindow::on_action_remove_sample
4867      }      }
4868  }  }
4869    
4870    void MainWindow::on_action_remove_unused_samples() {
4871        if (!file) return;
4872    
4873        // collect all samples that are not referenced by any instrument
4874        std::list<gig::Sample*> lsamples;
4875        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
4876            gig::Sample* sample = file->GetSample(iSample);
4877            bool isUsed = false;
4878            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
4879                                  instrument = file->GetNextInstrument())
4880            {
4881                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
4882                                  rgn = instrument->GetNextRegion())
4883                {
4884                    for (int i = 0; i < 256; ++i) {
4885                        if (!rgn->pDimensionRegions[i]) continue;
4886                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
4887                        isUsed = true;
4888                        goto endOfRefSearch;
4889                    }
4890                }
4891            }
4892            endOfRefSearch:
4893            if (!isUsed) lsamples.push_back(sample);
4894        }
4895    
4896        if (lsamples.empty()) return;
4897    
4898        // notify everybody that we're going to remove these samples
4899        samples_to_be_removed_signal.emit(lsamples);
4900    
4901        // remove collected samples
4902        try {
4903            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
4904                 itSample != lsamples.end(); ++itSample)
4905            {
4906                gig::Sample* sample = *itSample;
4907                // remove sample from the .gig file
4908                file->DeleteSample(sample);
4909                // if sample was just previously added, remove it from the import queue
4910                if (m_SampleImportQueue.count(sample)) {
4911                    printf("Removing previously added sample '%s'\n",
4912                           m_SampleImportQueue[sample].sample_path.c_str());
4913                    m_SampleImportQueue.erase(sample);
4914                }
4915            }
4916        } catch (RIFF::Exception e) {
4917            // show error message
4918            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4919            msg.run();
4920        }
4921    
4922        // notify everybody that we're done with removal
4923        samples_removed_signal.emit();
4924    
4925        dimreg_changed();
4926        file_changed();
4927        __refreshEntireGUI();
4928    }
4929    
4930    // see comment on on_sample_treeview_drag_begin()
4931    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4932    {
4933        first_call_to_drag_data_get = true;
4934    }
4935    
4936    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4937                                                       Gtk::SelectionData& selection_data, guint, guint)
4938    {
4939        if (!first_call_to_drag_data_get) return;
4940        first_call_to_drag_data_get = false;
4941    
4942        // get selected script
4943        gig::Script* script = NULL;
4944        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4945        Gtk::TreeModel::iterator it = sel->get_selected();
4946        if (it) {
4947            Gtk::TreeModel::Row row = *it;
4948            script = row[m_ScriptsModel.m_col_script];
4949        }
4950        // pass the gig::Script as pointer
4951        selection_data.set(selection_data.get_target(), 0/*unused*/,
4952                           (const guchar*)&script,
4953                           sizeof(script)/*length of data in bytes*/);
4954    }
4955    
4956    // see comment on on_sample_treeview_drag_begin()
4957    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4958    {
4959        first_call_to_drag_data_get = true;
4960    }
4961    
4962    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4963                                                           Gtk::SelectionData& selection_data, guint, guint)
4964    {
4965        if (!first_call_to_drag_data_get) return;
4966        first_call_to_drag_data_get = false;
4967    
4968        // get selected source instrument
4969        gig::Instrument* src = NULL;
4970        {
4971            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4972            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4973            if (!rows.empty()) {
4974                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
4975                if (it) {
4976                    Gtk::TreeModel::Row row = *it;
4977                    src = row[m_Columns.m_col_instr];
4978                }
4979            }
4980        }
4981        if (!src) return;
4982    
4983        // pass the source gig::Instrument as pointer
4984        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
4985                           sizeof(src)/*length of data in bytes*/);
4986    }
4987    
4988    void MainWindow::on_instruments_treeview_drop_drag_data_received(
4989        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
4990        const Gtk::SelectionData& selection_data, guint, guint time)
4991    {
4992        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
4993        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
4994            return;
4995    
4996        gig::Instrument* dst = NULL;
4997        {
4998            Gtk::TreeModel::Path path;
4999            const bool found = m_TreeView.get_path_at_pos(x, y, path);
5000            if (!found) return;
5001    
5002            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
5003            if (!iter) return;
5004            Gtk::TreeModel::Row row = *iter;
5005            dst = row[m_Columns.m_col_instr];
5006        }
5007        if (!dst) return;
5008    
5009        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
5010        src->MoveTo(dst);
5011        __refreshEntireGUI();
5012        select_instrument(src);
5013    }
5014    
5015  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
5016  // 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
5017  // 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 1781  void MainWindow::on_sample_treeview_drag Line 5030  void MainWindow::on_sample_treeview_drag
5030      // get selected sample      // get selected sample
5031      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
5032      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
5033      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5034      if (it) {      if (!rows.empty()) {
5035          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
5036          sample = row[m_SamplesModel.m_col_sample];          if (it) {
5037                Gtk::TreeModel::Row row = *it;
5038                sample = row[m_SamplesModel.m_col_sample];
5039            }
5040      }      }
5041      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
5042      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 1821  void MainWindow::on_sample_label_drop_dr Line 5073  void MainWindow::on_sample_label_drop_dr
5073          bool channels_changed = false;          bool channels_changed = false;
5074          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
5075              // remove the samplechannel dimension              // remove the samplechannel dimension
5076    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
5077              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
5078              channels_changed = true;              channels_changed = true;
5079              region_changed();              region_changed();
5080    */
5081          }          }
5082          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
5083                sample,
5084                is_copy_samples_unity_note_enabled(),
5085                is_copy_samples_fine_tune_enabled(),
5086                is_copy_samples_loop_enabled()
5087            );
5088    
5089          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
5090              // add samplechannel dimension              // add samplechannel dimension
# Line 1868  void MainWindow::sample_name_changed(con Line 5127  void MainWindow::sample_name_changed(con
5127      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
5128      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
5129      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
5130        gig::String gigname(gig_from_utf8(name));
5131      if (group) {      if (group) {
5132          if (group->Name != name) {          if (group->Name != gigname) {
5133              group->Name = name;              group->Name = gigname;
5134              printf("group name changed\n");              printf("group name changed\n");
5135              file_changed();              file_changed();
5136          }          }
5137      } else if (sample) {      } else if (sample) {
5138          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
5139              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
5140              printf("sample name changed\n");              printf("sample name changed\n");
5141              file_changed();              file_changed();
5142          }          }
5143      }      }
5144        // change name in the sample properties window
5145        if (sampleProps.get_sample() == sample && sample) {
5146            sampleProps.set_sample(sample);
5147        }
5148    }
5149    
5150    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
5151                                         const Gtk::TreeModel::iterator& iter) {
5152        if (!iter) return;
5153        Gtk::TreeModel::Row row = *iter;
5154        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
5155        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
5156        gig::Script* script     = row[m_ScriptsModel.m_col_script];
5157        gig::String gigname(gig_from_utf8(name));
5158        if (group) {
5159            if (group->Name != gigname) {
5160                group->Name = gigname;
5161                printf("script group name changed\n");
5162                file_changed();
5163            }
5164        } else if (script) {
5165            if (script->Name != gigname) {
5166                script->Name = gigname;
5167                printf("script name changed\n");
5168                file_changed();
5169            }
5170        }
5171    }
5172    
5173    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
5174                                           Gtk::TreeViewColumn* column)
5175    {
5176        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
5177        if (!iter) return;
5178        Gtk::TreeModel::Row row = *iter;
5179        gig::Script* script = row[m_ScriptsModel.m_col_script];
5180        if (!script) return;
5181    
5182        ScriptEditor* editor = new ScriptEditor;
5183        editor->signal_script_to_be_changed.connect(
5184            signal_script_to_be_changed.make_slot()
5185        );
5186        editor->signal_script_changed.connect(
5187            signal_script_changed.make_slot()
5188        );
5189        editor->setScript(script);
5190        //editor->reparent(*this);
5191        editor->show();
5192  }  }
5193    
5194  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
# Line 1888  void MainWindow::instrument_name_changed Line 5196  void MainWindow::instrument_name_changed
5196      if (!iter) return;      if (!iter) return;
5197      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
5198      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
5199    
5200    #if !USE_GTKMM_BUILDER
5201        // change name in instrument menu
5202        int index = path[0];
5203        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
5204        if (index < children.size()) {
5205    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
5206            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
5207    #else
5208            remove_instrument_from_menu(index);
5209            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
5210            item->set_active();
5211    #endif
5212        }
5213    #endif
5214    
5215        // change name in gig
5216      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
5217      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
5218          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
5219            instrument->pInfo->Name = gigname;
5220    
5221            // change name in the instrument properties window
5222            if (instrumentProps.get_instrument() == instrument) {
5223                instrumentProps.update_name();
5224            }
5225    
5226          file_changed();          file_changed();
5227      }      }
5228  }  }
5229    
5230    bool MainWindow::instrument_row_visible(const Gtk::TreeModel::const_iterator& iter) {
5231        if (!iter)
5232            return true;
5233    
5234        Glib::ustring pattern = m_searchText.get_text().lowercase();
5235        trim(pattern);
5236        if (pattern.empty()) return true;
5237    
5238    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
5239        //HACK: on GTKMM4 development branch const_iterator cannot be easily converted to iterator, probably going to be fixed before final GTKMM4 release though.
5240        Gtk::TreeModel::Row row = **(Gtk::TreeModel::iterator*)(&iter);
5241    #else
5242        Gtk::TreeModel::Row row = *iter;
5243    #endif
5244        Glib::ustring name = row[m_Columns.m_col_name];
5245        name = name.lowercase();
5246    
5247        std::vector<Glib::ustring> tokens = Glib::Regex::split_simple(" ", pattern);
5248        for (int t = 0; t < tokens.size(); ++t)
5249            if (name.find(tokens[t]) == Glib::ustring::npos)
5250                return false;
5251    
5252        return true;
5253    }
5254    
5255    void MainWindow::on_action_combine_instruments() {
5256        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
5257    
5258        // take over selection from instruments list view for the combine dialog's
5259        // list view as pre-selection
5260        std::set<int> indeces;
5261        {
5262            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
5263            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5264            for (int r = 0; r < rows.size(); ++r) {
5265                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
5266                if (it) {
5267                    Gtk::TreeModel::Row row = *it;
5268                    int index = row[m_Columns.m_col_nr];
5269                    indeces.insert(index);
5270                }
5271            }
5272        }
5273        d->setSelectedInstruments(indeces);
5274    
5275    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5276        d->show_all();
5277    #else
5278        d->show();
5279    #endif
5280        d->run();
5281        if (d->fileWasChanged()) {
5282            // update GUI with new instrument just created
5283            add_instrument(d->newCombinedInstrument());
5284        }
5285        delete d;
5286    }
5287    
5288    void MainWindow::on_action_view_references() {
5289        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
5290        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
5291        if (rows.empty()) return;
5292        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
5293        if (!it) return;
5294        Gtk::TreeModel::Row row = *it;
5295        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
5296        if (!sample) return;
5297    
5298        ReferencesView* d = new ReferencesView(*this);
5299        d->setSample(sample);
5300        d->dimension_region_selected.connect(
5301            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
5302        );
5303    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5304        d->show_all();
5305    #else
5306        d->show();
5307    #endif
5308        d->resize(500, 400);
5309        d->run();
5310        delete d;
5311    }
5312    
5313    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
5314        struct _Source {
5315            std::vector<RIFF::File*> riffs;
5316            std::vector<gig::File*> gigs;
5317            
5318            ~_Source() {
5319                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
5320                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
5321                riffs.clear();
5322                gigs.clear();
5323            }
5324        } sources;
5325    
5326        if (filenames.empty())
5327            throw RIFF::Exception(_("No files selected, so nothing done."));
5328    
5329        // first open all input files (to avoid output file corruption)
5330        int i;
5331        try {
5332            for (i = 0; i < filenames.size(); ++i) {
5333                const std::string& filename = filenames[i];
5334                printf("opening file=%s\n", filename.c_str());
5335    
5336                RIFF::File* riff = new RIFF::File(filename);
5337                sources.riffs.push_back(riff);
5338    
5339                gig::File* gig = new gig::File(riff);
5340                sources.gigs.push_back(gig);
5341            }
5342        } catch (RIFF::Exception e) {
5343            throw RIFF::Exception(
5344                _("Error occurred while opening '") +
5345                filenames[i] +
5346                "': " +
5347                e.Message
5348            );
5349        } catch (...) {
5350            throw RIFF::Exception(
5351                _("Unknown exception occurred while opening '") +
5352                filenames[i] + "'"
5353            );
5354        }
5355    
5356        // now merge the opened .gig files to the main .gig file currently being
5357        // open in gigedit
5358        try {
5359            for (i = 0; i < filenames.size(); ++i) {
5360                const std::string& filename = filenames[i];
5361                printf("merging file=%s\n", filename.c_str());
5362                assert(i < sources.gigs.size());
5363    
5364                this->file->AddContentOf(sources.gigs[i]);
5365            }
5366        } catch (RIFF::Exception e) {
5367            throw RIFF::Exception(
5368                _("Error occurred while merging '") +
5369                filenames[i] +
5370                "': " +
5371                e.Message
5372            );
5373        } catch (...) {
5374            throw RIFF::Exception(
5375                _("Unknown exception occurred while merging '") +
5376                filenames[i] + "'"
5377            );
5378        }
5379    
5380        // Finally save gig file persistently to disk ...
5381        //NOTE: requires that this gig file already has a filename !
5382        {
5383            std::cout << "Saving file\n" << std::flush;
5384            file_structure_to_be_changed_signal.emit(this->file);
5385    
5386            progress_dialog = new ProgressDialog( //FIXME: memory leak!
5387                _("Saving") +  Glib::ustring(" '") +
5388                Glib::filename_display_basename(this->filename) + "' ...",
5389                *this
5390            );
5391    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5392            progress_dialog->show_all();
5393    #else
5394            progress_dialog->show();
5395    #endif
5396            saver = new Saver(this->file); //FIXME: memory leak!
5397            saver->signal_progress().connect(
5398                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
5399            saver->signal_finished().connect(
5400                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
5401            saver->signal_error().connect(
5402                sigc::mem_fun(*this, &MainWindow::on_saver_error));
5403            saver->launch();
5404        }
5405    }
5406    
5407    void MainWindow::on_action_merge_files() {
5408        if (this->file->GetFileName().empty()) {
5409            Glib::ustring txt = _(
5410                "You seem to have a new .gig file open that has not been saved "
5411                "yet. You must save it somewhere before starting to merge it with "
5412                "other .gig files though, because during the merge operation the "
5413                "other files' sample data must be written on file level to the "
5414                "target .gig file."
5415            );
5416            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5417            msg.run();
5418            return;
5419        }
5420    
5421        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
5422    #if HAS_GTKMM_STOCK
5423        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
5424    #else
5425        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
5426    #endif
5427        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
5428        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
5429    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
5430        Gtk::FileFilter filter;
5431        filter.add_pattern("*.gig");
5432    #else
5433        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
5434        filter->add_pattern("*.gig");
5435    #endif
5436        dialog.set_filter(filter);
5437        if (current_gig_dir != "") {
5438            dialog.set_current_folder(current_gig_dir);
5439        }
5440        dialog.set_select_multiple(true);
5441    
5442        // show warning in the file picker dialog
5443        HBox descriptionArea;
5444        descriptionArea.set_spacing(15);
5445        Gtk::Image warningIcon;
5446        warningIcon.set_from_icon_name("dialog-warning",
5447                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
5448        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
5449    #if GTKMM_MAJOR_VERSION < 3
5450        view::WrapLabel description;
5451    #else
5452        Gtk::Label description;
5453        description.set_line_wrap();
5454    #endif
5455        description.set_markup(_(
5456            "\nSelect at least one .gig file that shall be merged to the .gig file "
5457            "currently being open in gigedit.\n\n"
5458            "<b>Please Note:</b> Merging with other files will modify your "
5459            "currently open .gig file on file level! And be aware that the current "
5460            "merge algorithm does not detect duplicate samples yet. So if you are "
5461            "merging files which are using equivalent sample data, those "
5462            "equivalent samples will currently be treated as separate samples and "
5463            "will accordingly be stored separately in the target .gig file!"
5464        ));
5465        descriptionArea.pack_start(description);
5466    #if USE_GTKMM_BOX
5467    # warning No description area implemented for dialog on GTKMM 3
5468    #else
5469        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
5470    #endif
5471    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5472        descriptionArea.show_all();
5473    #else
5474        descriptionArea.show();
5475    #endif
5476    
5477        if (dialog.run() == Gtk::RESPONSE_OK) {
5478            dialog.hide();
5479    #ifdef GLIB_THREADS
5480            printf("on_action_merge_files self=%p\n",
5481                   static_cast<void*>(Glib::Threads::Thread::self()));
5482    #else
5483            std::cout << "on_action_merge_files self=" <<
5484                std::this_thread::get_id() << "\n";
5485    #endif
5486            std::vector<std::string> filenames = dialog.get_filenames();
5487    
5488            // merge the selected files to the currently open .gig file
5489            try {
5490                mergeFiles(filenames);
5491            } catch (RIFF::Exception e) {
5492                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
5493                msg.run();
5494            }
5495    
5496            // update GUI
5497            __refreshEntireGUI();
5498        }
5499    }
5500    
5501  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
5502      this->file_is_shared = b;      this->file_is_shared = b;
5503    
# Line 1909  void MainWindow::set_file_is_shared(bool Line 5512  void MainWindow::set_file_is_shared(bool
5512              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
5513          );          );
5514      }      }
5515    
5516        {
5517    #if USE_GTKMM_BUILDER
5518            m_actionToggleSyncSamplerSelection->property_enabled() = b;
5519    #else
5520            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
5521                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
5522            if (item) item->set_sensitive(b);
5523    #endif
5524        }
5525    }
5526    
5527    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
5528        if (!sample) return;
5529        sample_ref_count[sample] += offset;
5530        const int refcount = sample_ref_count[sample];
5531    
5532        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
5533        for (int g = 0; g < model->children().size(); ++g) {
5534            Gtk::TreeModel::Row rowGroup = model->children()[g];
5535            for (int s = 0; s < rowGroup.children().size(); ++s) {
5536                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
5537                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
5538                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
5539                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
5540            }
5541        }
5542    }
5543    
5544    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
5545        on_sample_ref_count_incremented(oldSample, -1);
5546        on_sample_ref_count_incremented(newSample, +1);
5547    }
5548    
5549    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
5550        // just in case a new sample is added later with exactly the same memory
5551        // address, which would lead to incorrect refcount if not deleted here
5552        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
5553             it != samples.end(); ++it)
5554        {
5555            sample_ref_count.erase(*it);
5556        }
5557    }
5558    
5559    void MainWindow::show_samples_tab() {
5560        m_TreeViewNotebook.set_current_page(0);
5561    }
5562    
5563    void MainWindow::show_intruments_tab() {
5564        m_TreeViewNotebook.set_current_page(1);
5565    }
5566    
5567    void MainWindow::show_scripts_tab() {
5568        m_TreeViewNotebook.set_current_page(2);
5569    }
5570    
5571    void MainWindow::select_instrument_by_dir(int dir) {
5572        if (!file) return;
5573        gig::Instrument* pInstrument = get_instrument();
5574        if (!pInstrument) {
5575            select_instrument( file->GetInstrument(0) );
5576            return;
5577        }
5578        for (int i = 0; file->GetInstrument(i); ++i) {
5579            if (file->GetInstrument(i) == pInstrument) {
5580                select_instrument( file->GetInstrument(i + dir) );
5581                return;
5582            }
5583        }
5584    }
5585    
5586    void MainWindow::select_prev_instrument() {
5587        select_instrument_by_dir(-1);
5588    }
5589    
5590    void MainWindow::select_next_instrument() {
5591        select_instrument_by_dir(1);
5592    }
5593    
5594    void MainWindow::select_prev_region() {
5595        m_RegionChooser.select_prev_region();
5596    }
5597    
5598    void MainWindow::select_next_region() {
5599        m_RegionChooser.select_next_region();
5600    }
5601    
5602    void MainWindow::select_next_dim_rgn_zone() {
5603        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5604        m_DimRegionChooser.select_next_dimzone();
5605    }
5606    
5607    void MainWindow::select_prev_dim_rgn_zone() {
5608        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5609        m_DimRegionChooser.select_prev_dimzone();
5610    }
5611    
5612    void MainWindow::select_add_next_dim_rgn_zone() {
5613        m_DimRegionChooser.select_next_dimzone(true);
5614    }
5615    
5616    void MainWindow::select_add_prev_dim_rgn_zone() {
5617        m_DimRegionChooser.select_prev_dimzone(true);
5618    }
5619    
5620    void MainWindow::select_prev_dimension() {
5621        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5622        m_DimRegionChooser.select_prev_dimension();
5623    }
5624    
5625    void MainWindow::select_next_dimension() {
5626        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5627        m_DimRegionChooser.select_next_dimension();
5628    }
5629    
5630    #define CLIPBOARD_DIMENSIONREGION_TARGET \
5631        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
5632    
5633    void MainWindow::copy_selected_dimrgn() {
5634        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5635        if (!pDimRgn) {
5636            updateClipboardPasteAvailable();
5637            updateClipboardCopyAvailable();
5638            return;
5639        }
5640    
5641        std::vector<Gtk::TargetEntry> targets;
5642        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
5643    
5644        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5645        clipboard->set(
5646            targets,
5647            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
5648            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
5649        );
5650    
5651        m_serializationArchive.serialize(pDimRgn);
5652    
5653        updateClipboardPasteAvailable();
5654    }
5655    
5656    void MainWindow::paste_copied_dimrgn() {
5657        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5658        clipboard->request_contents(
5659            CLIPBOARD_DIMENSIONREGION_TARGET,
5660            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
5661        );
5662        updateClipboardPasteAvailable();
5663    }
5664    
5665    void MainWindow::adjust_clipboard_content() {
5666        MacroEditor* editor = new MacroEditor();
5667        editor->setMacro(&m_serializationArchive, true);
5668        editor->show();
5669    }
5670    
5671    void MainWindow::updateClipboardPasteAvailable() {
5672        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5673        clipboard->request_targets(
5674            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
5675        );
5676    }
5677    
5678    void MainWindow::updateClipboardCopyAvailable() {
5679        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
5680    #if USE_GTKMM_BUILDER
5681        m_actionCopyDimRgn->property_enabled() = bDimensionRegionCopyIsPossible;
5682    #else
5683        static_cast<Gtk::MenuItem*>(
5684            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
5685        )->set_sensitive(bDimensionRegionCopyIsPossible);
5686    #endif
5687    }
5688    
5689    #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
5690    void MainWindow::on_clipboard_owner_change(Gdk::EventOwnerChange& event) {
5691    #else
5692    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
5693    #endif
5694        updateClipboardPasteAvailable();
5695    }
5696    
5697    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
5698        const std::string target = selection_data.get_target();
5699        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5700            selection_data.set(
5701                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
5702                &m_serializationArchive.rawData()[0],
5703                m_serializationArchive.rawData().size()
5704            );
5705        } else {
5706            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
5707        }
5708    }
5709    
5710    void MainWindow::on_clipboard_clear() {
5711        m_serializationArchive.clear();
5712        updateClipboardPasteAvailable();
5713        updateClipboardCopyAvailable();
5714    }
5715    
5716    //NOTE: Might throw exception !!!
5717    void MainWindow::applyMacro(Serialization::Archive& macro) {
5718        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5719        if (!pDimRgn) return;
5720    
5721        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
5722             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
5723        {
5724            gig::DimensionRegion* pDimRgn = *itDimReg;
5725            DimRegionChangeGuard(this, pDimRgn);
5726            macro.deserialize(pDimRgn);
5727        }
5728        //region_changed()
5729        file_changed();
5730        dimreg_changed();
5731    }
5732    
5733    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
5734        const std::string target = selection_data.get_target();
5735        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5736            Glib::ustring errorText;
5737            try {
5738                m_serializationArchive.decode(
5739                    selection_data.get_data(), selection_data.get_length()
5740                );
5741                applyMacro(m_serializationArchive);
5742            } catch (Serialization::Exception e) {
5743                errorText = e.Message;
5744            } catch (...) {
5745                errorText = _("Unknown exception while pasting DimensionRegion");
5746            }
5747            if (!errorText.empty()) {
5748                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
5749                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5750                msg.run();
5751            }
5752        }
5753    }
5754    
5755    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
5756        const bool bDimensionRegionPasteIsPossible =
5757            std::find(targets.begin(), targets.end(),
5758                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
5759    
5760    #if USE_GTKMM_BUILDER
5761        m_actionPasteDimRgn->property_enabled() = bDimensionRegionPasteIsPossible;
5762        m_actionAdjustClipboard->property_enabled() = bDimensionRegionPasteIsPossible;
5763    #else
5764        static_cast<Gtk::MenuItem*>(
5765            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
5766        )->set_sensitive(bDimensionRegionPasteIsPossible);
5767    
5768        static_cast<Gtk::MenuItem*>(
5769            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
5770        )->set_sensitive(bDimensionRegionPasteIsPossible);
5771    #endif
5772  }  }
5773    
5774  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 1966  sigc::signal<void, int/*key*/, int/*velo Line 5826  sigc::signal<void, int/*key*/, int/*velo
5826  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
5827      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
5828  }  }
5829    
5830    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
5831        return switch_sampler_instrument_signal;
5832    }

Legend:
Removed from v.2398  
changed lines
  Added in v.3643

  ViewVC Help
Powered by ViewVC