/[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 3635 by schoenebeck, Thu Oct 24 11:16:26 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      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));      const Gdk::ModifierType primaryModifierKey =
315    #if defined(__APPLE__)
316        Gdk::META_MASK; // Cmd key on Mac
317    #else
318        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
319    #endif
320    
321    #if USE_GLIB_ACTION
322        m_actionCopyDimRgn = m_actionGroup->add_action(
323            "CopyDimRgn", sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn)
324        );
325        m_actionPasteDimRgn = m_actionGroup->add_action(
326            "PasteDimRgn", sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn)
327        );
328        m_actionAdjustClipboard = m_actionGroup->add_action(
329            "AdjustClipboard", sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content)
330        );
331        m_actionGroup->add_action(
332            "SelectPrevInstr", sigc::mem_fun(*this, &MainWindow::select_prev_instrument)
333        );
334        m_actionGroup->add_action(
335            "SelectNextInstr", sigc::mem_fun(*this, &MainWindow::select_next_instrument)
336        );
337        m_actionGroup->add_action(
338            "SelectPrevRegion", sigc::mem_fun(*this, &MainWindow::select_prev_region)
339        );
340        m_actionGroup->add_action(
341            "SelectNextRegion", sigc::mem_fun(*this, &MainWindow::select_next_region)
342        );
343        m_actionGroup->add_action(
344            "SelectPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone)
345        );
346        m_actionGroup->add_action(
347            "SelectNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone)
348        );
349        m_actionGroup->add_action(
350            "SelectPrevDimension", sigc::mem_fun(*this, &MainWindow::select_prev_dimension)
351        );
352        m_actionGroup->add_action(
353            "SelectNextDimension", sigc::mem_fun(*this, &MainWindow::select_next_dimension)
354        );
355        m_actionGroup->add_action(
356            "SelectAddPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone)
357        );
358        m_actionGroup->add_action(
359            "SelectAddNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone)
360        );
361    #else
362        actionGroup->add(Gtk::Action::create("CopyDimRgn",
363                                             _("Copy selected dimension region")),
364                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
365                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
366    
367        actionGroup->add(Gtk::Action::create("PasteDimRgn",
368                                             _("Paste dimension region")),
369                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
370                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
371    
372        actionGroup->add(Gtk::Action::create("AdjustClipboard",
373                                             _("Adjust Clipboard Content")),
374                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
375                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
376    
377        actionGroup->add(Gtk::Action::create("SelectPrevInstr",
378                                             _("Select Previous Instrument")),
379                         Gtk::AccelKey(GDK_KEY_Up, primaryModifierKey),
380                         sigc::mem_fun(*this, &MainWindow::select_prev_instrument));
381    
382        actionGroup->add(Gtk::Action::create("SelectNextInstr",
383                                             _("Select Next Instrument")),
384                         Gtk::AccelKey(GDK_KEY_Down, primaryModifierKey),
385                         sigc::mem_fun(*this, &MainWindow::select_next_instrument));
386    
387        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
388                                             _("Select Previous Region")),
389                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
390                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
391    
392        actionGroup->add(Gtk::Action::create("SelectNextRegion",
393                                             _("Select Next Region")),
394                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
395                         sigc::mem_fun(*this, &MainWindow::select_next_region));
396    
397        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
398                                             _("Select Previous Dimension Region Zone")),
399                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
400                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
401    
402        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
403                                             _("Select Next Dimension Region Zone")),
404                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
405                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
406    
407        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
408                                             _("Select Previous Dimension")),
409                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
410                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
411    
412        actionGroup->add(Gtk::Action::create("SelectNextDimension",
413                                             _("Select Next Dimension")),
414                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
415                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
416    
417        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
418                                             _("Add Previous Dimension Region Zone to Selection")),
419                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
420                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
421    
422        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
423                                             _("Add Next Dimension Region Zone to Selection")),
424                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
425                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
426    #endif
427    
428    #if USE_GLIB_ACTION
429        m_actionToggleCopySampleUnity = m_actionGroup->add_action_bool("CopySampleUnity", true);
430        m_actionToggleCopySampleTune  = m_actionGroup->add_action_bool("CopySampleTune", true);
431        m_actionToggleCopySampleLoop  = m_actionGroup->add_action_bool("CopySampleLoop", true);
432    #else
433      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
434            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
435        toggle_action->set_active(true);
436        actionGroup->add(toggle_action);
437    
438        toggle_action =
439            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
440        toggle_action->set_active(true);
441        actionGroup->add(toggle_action);
442    
443        toggle_action =
444            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
445        toggle_action->set_active(true);
446        actionGroup->add(toggle_action);
447    #endif
448    
449    #if USE_GLIB_ACTION
450        m_actionToggleStatusBar =
451            m_actionGroup->add_action_bool("Statusbar", sigc::mem_fun(*this, &MainWindow::on_action_view_status_bar), true);
452        m_actionToggleRestoreWinDim =
453            m_actionGroup->add_action_bool("AutoRestoreWinDim", sigc::mem_fun(*this, &MainWindow::on_auto_restore_win_dim), Settings::singleton()->autoRestoreWindowDimension);
454        m_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));          sigc::mem_fun(*this, &MainWindow::file_changed));
1487      propDialog.signal_info_changed().connect(      propDialog.signal_changed().connect(
1488            sigc::mem_fun(*this, &MainWindow::file_changed));
1489        midiRules.signal_changed().connect(
1490          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1491    
1492      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 333  MainWindow::MainWindow() : Line 1495  MainWindow::MainWindow() :
1495          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
1496      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
1497          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
1498        sample_ref_changed_signal.connect(
1499            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
1500        );
1501        samples_to_be_removed_signal.connect(
1502            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
1503        );
1504    
1505        dimreg_edit.signal_select_sample().connect(
1506            sigc::mem_fun(*this, &MainWindow::select_sample)
1507        );
1508    
1509      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
1510          sigc::hide(          sigc::hide(
1511              sigc::bind(              sigc::bind(
1512                  file_structure_to_be_changed_signal.make_slot(),                  file_structure_to_be_changed_signal.make_slot(),
1513    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1514                    std::ref(this->file)
1515    #else
1516                  sigc::ref(this->file)                  sigc::ref(this->file)
1517    #endif
1518              )              )
1519          )          )
1520      );      );
# Line 346  MainWindow::MainWindow() : Line 1522  MainWindow::MainWindow() :
1522          sigc::hide(          sigc::hide(
1523              sigc::bind(              sigc::bind(
1524                  file_structure_changed_signal.make_slot(),                  file_structure_changed_signal.make_slot(),
1525    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1526                    std::ref(this->file)
1527    #else
1528                  sigc::ref(this->file)                  sigc::ref(this->file)
1529    #endif
1530              )              )
1531          )          )
1532      );      );
# Line 367  MainWindow::MainWindow() : Line 1547  MainWindow::MainWindow() :
1547      dimreg_stereo.signal_toggled().connect(      dimreg_stereo.signal_toggled().connect(
1548          sigc::mem_fun(*this, &MainWindow::update_dimregs));          sigc::mem_fun(*this, &MainWindow::update_dimregs));
1549    
1550        m_searchText.signal_changed().connect(
1551            sigc::mem_fun(*m_refTreeModelFilter.operator->(), &Gtk::TreeModelFilter::refilter)
1552        );
1553    
1554      file = 0;      file = 0;
1555      file_is_changed = false;      file_is_changed = false;
1556    
1557    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1558      show_all_children();      show_all_children();
1559    #endif
1560    
1561      // start with a new gig file by default      // start with a new gig file by default
1562      on_action_file_new();      on_action_file_new();
1563    
1564        m_TreeViewNotebook.signal_switch_page().connect(
1565            sigc::mem_fun(*this, &MainWindow::on_notebook_tab_switched)
1566        );
1567    
1568        // select 'Instruments' tab by default
1569        // (gtk allows this only if the tab childs are visible, thats why it's here)
1570        m_TreeViewNotebook.set_current_page(1);
1571    
1572        Gtk::Clipboard::get()->signal_owner_change().connect(
1573            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
1574        );
1575        updateClipboardPasteAvailable();
1576        updateClipboardCopyAvailable();
1577    
1578        // setup macros and their keyboard accelerators
1579        {
1580    #if USE_GTKMM_BUILDER
1581            menuMacro = new Gtk::Menu(
1582                Glib::RefPtr<Gio::Menu>::cast_dynamic(
1583                    m_uiManager->get_object("MenuMacro")
1584                )
1585            );
1586    #else
1587            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1588                uiManager->get_widget("/MenuBar/MenuMacro")
1589            )->get_submenu();
1590    #endif
1591    
1592            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
1593            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
1594            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
1595            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
1596            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
1597            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
1598            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
1599            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
1600            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
1601            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
1602            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
1603            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
1604            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
1605            Gtk::AccelMap::add_entry("<Macros>/macro_12", GDK_KEY_F13, noModifier);
1606            Gtk::AccelMap::add_entry("<Macros>/macro_13", GDK_KEY_F14, noModifier);
1607            Gtk::AccelMap::add_entry("<Macros>/macro_14", GDK_KEY_F15, noModifier);
1608            Gtk::AccelMap::add_entry("<Macros>/macro_15", GDK_KEY_F16, noModifier);
1609            Gtk::AccelMap::add_entry("<Macros>/macro_16", GDK_KEY_F17, noModifier);
1610            Gtk::AccelMap::add_entry("<Macros>/macro_17", GDK_KEY_F18, noModifier);
1611            Gtk::AccelMap::add_entry("<Macros>/macro_18", GDK_KEY_F19, noModifier);
1612            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
1613    
1614            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1615            menuMacro->set_accel_group(accelGroup);
1616    
1617            updateMacroMenu();
1618        }
1619    
1620        // setup "Assign Scripts" keyboard accelerators
1621        {
1622            Gtk::AccelMap::add_entry("<Scripts>/script_0", GDK_KEY_F1, Gdk::SHIFT_MASK);
1623            Gtk::AccelMap::add_entry("<Scripts>/script_1", GDK_KEY_F2, Gdk::SHIFT_MASK);
1624            Gtk::AccelMap::add_entry("<Scripts>/script_2", GDK_KEY_F3, Gdk::SHIFT_MASK);
1625            Gtk::AccelMap::add_entry("<Scripts>/script_3", GDK_KEY_F4, Gdk::SHIFT_MASK);
1626            Gtk::AccelMap::add_entry("<Scripts>/script_4", GDK_KEY_F5, Gdk::SHIFT_MASK);
1627            Gtk::AccelMap::add_entry("<Scripts>/script_5", GDK_KEY_F6, Gdk::SHIFT_MASK);
1628            Gtk::AccelMap::add_entry("<Scripts>/script_6", GDK_KEY_F7, Gdk::SHIFT_MASK);
1629            Gtk::AccelMap::add_entry("<Scripts>/script_7", GDK_KEY_F8, Gdk::SHIFT_MASK);
1630            Gtk::AccelMap::add_entry("<Scripts>/script_8", GDK_KEY_F9, Gdk::SHIFT_MASK);
1631            Gtk::AccelMap::add_entry("<Scripts>/script_9", GDK_KEY_F10, Gdk::SHIFT_MASK);
1632            Gtk::AccelMap::add_entry("<Scripts>/script_10", GDK_KEY_F11, Gdk::SHIFT_MASK);
1633            Gtk::AccelMap::add_entry("<Scripts>/script_11", GDK_KEY_F12, Gdk::SHIFT_MASK);
1634            Gtk::AccelMap::add_entry("<Scripts>/script_12", GDK_KEY_F13, Gdk::SHIFT_MASK);
1635            Gtk::AccelMap::add_entry("<Scripts>/script_13", GDK_KEY_F14, Gdk::SHIFT_MASK);
1636            Gtk::AccelMap::add_entry("<Scripts>/script_14", GDK_KEY_F15, Gdk::SHIFT_MASK);
1637            Gtk::AccelMap::add_entry("<Scripts>/script_15", GDK_KEY_F16, Gdk::SHIFT_MASK);
1638            Gtk::AccelMap::add_entry("<Scripts>/script_16", GDK_KEY_F17, Gdk::SHIFT_MASK);
1639            Gtk::AccelMap::add_entry("<Scripts>/script_17", GDK_KEY_F18, Gdk::SHIFT_MASK);
1640            Gtk::AccelMap::add_entry("<Scripts>/script_18", GDK_KEY_F19, Gdk::SHIFT_MASK);
1641            Gtk::AccelMap::add_entry("<Scripts>/DropAllScriptSlots", GDK_KEY_BackSpace, Gdk::SHIFT_MASK);
1642    
1643            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1644            assign_scripts_menu->set_accel_group(accelGroup);
1645        }
1646    
1647        on_show_tooltips_changed();
1648    
1649        Glib::signal_idle().connect_once(
1650            sigc::mem_fun(*this, &MainWindow::bringToFront),
1651            200
1652        );
1653  }  }
1654    
1655  MainWindow::~MainWindow()  MainWindow::~MainWindow()
1656  {  {
1657  }  }
1658    
1659    void MainWindow::bringToFront() {
1660        #if defined(__APPLE__)
1661        macRaiseAppWindow();
1662        #endif
1663        raise();
1664        present();
1665    }
1666    
1667    void MainWindow::updateMacroMenu() {
1668    #if !USE_GTKMM_BUILDER
1669        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1670            uiManager->get_widget("/MenuBar/MenuMacro")
1671        )->get_submenu();
1672    #endif
1673    
1674        // remove all entries from "Macro" menu
1675        {
1676            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
1677            for (int i = 0; i < children.size(); ++i) {
1678                Gtk::Widget* child = children[i];
1679                menuMacro->remove(*child);
1680                delete child;
1681            }
1682        }
1683    
1684        // (re)load all macros from config file
1685        try {
1686            Settings::singleton()->loadMacros(m_macros);
1687        } catch (Serialization::Exception e) {
1688            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
1689        } catch (...) {
1690            std::cerr << "Unknown exception while loading macros!" << std::endl;
1691        }
1692    
1693        // add all configured macros as menu items to the "Macro" menu
1694        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
1695            const Serialization::Archive& macro = m_macros[iMacro];
1696            std::string name =
1697                macro.name().empty() ?
1698                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
1699            Gtk::MenuItem* item = new Gtk::MenuItem(name);
1700            item->signal_activate().connect(
1701                sigc::bind(
1702                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
1703                )
1704            );
1705            menuMacro->append(*item);
1706            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
1707            Glib::ustring comment = macro.comment();
1708            if (!comment.empty())
1709                item->set_tooltip_text(comment);
1710        }
1711        // if there are no macros configured at all, then show a dummy entry instead
1712        if (m_macros.empty()) {
1713            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
1714            item->set_sensitive(false);
1715            menuMacro->append(*item);
1716        }
1717    
1718        // add separator line to menu
1719        menuMacro->append(*new Gtk::SeparatorMenuItem);
1720    
1721        {
1722            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
1723            item->signal_activate().connect(
1724                sigc::mem_fun(*this, &MainWindow::setupMacros)
1725            );
1726            menuMacro->append(*item);
1727            item->set_accel_path("<Macros>/SetupMacros");
1728        }
1729    
1730    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1731        menuMacro->show_all_children();
1732    #endif
1733    }
1734    
1735    void MainWindow::onMacroSelected(int iMacro) {
1736        printf("onMacroSelected(%d)\n", iMacro);
1737        if (iMacro < 0 || iMacro >= m_macros.size()) return;
1738        Glib::ustring errorText;
1739        try {
1740            applyMacro(m_macros[iMacro]);
1741        } catch (Serialization::Exception e) {
1742            errorText = e.Message;
1743        } catch (...) {
1744            errorText = _("Unknown exception while applying macro");
1745        }
1746        if (!errorText.empty()) {
1747            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
1748            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1749            msg.run();
1750        }
1751    }
1752    
1753    void MainWindow::setupMacros() {
1754        MacrosSetup* setup = new MacrosSetup();
1755        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
1756        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
1757        setup->signal_macros_changed().connect(
1758            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
1759        );
1760        setup->show();
1761    }
1762    
1763    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
1764        m_macros = macros;
1765        Settings::singleton()->saveMacros(m_macros);
1766        updateMacroMenu();
1767    }
1768    
1769    //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.
1770    void MainWindow::on_notebook_tab_switched(void* page, guint page_num) {
1771        bool isInstrumentsPage = (page_num == 1);
1772        // so far we only support filtering for the instruments list, so hide the
1773        // filter text entry field if another tab is selected
1774        m_searchField.set_visible(isInstrumentsPage);
1775    }
1776    
1777  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
1778  {  {
1779      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 1793  void MainWindow::region_changed()
1793  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1794  {  {
1795      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
1796      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1797        if (rows.empty()) return NULL;
1798      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.
1799        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1800      if (it) {      if (it) {
1801          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1802          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 444  void MainWindow::update_dimregs() Line 1839  void MainWindow::update_dimregs()
1839              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1840          }          }
1841      }      }
1842    
1843        m_RegionChooser.setModifyAllRegions(all_regions);
1844        m_DimRegionChooser.setModifyAllRegions(all_regions);
1845        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1846        m_DimRegionChooser.setModifyBothChannels(stereo);
1847    
1848        updateClipboardCopyAvailable();
1849  }  }
1850    
1851  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 455  void MainWindow::dimreg_all_dimregs_togg Line 1857  void MainWindow::dimreg_all_dimregs_togg
1857  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1858  {  {
1859      update_dimregs();      update_dimregs();
1860      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1861  }  }
1862    
1863  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1864  {  {
1865    #if !USE_GTKMM_BUILDER
1866        // select item in instrument menu
1867        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1868        if (!rows.empty()) {
1869            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1870            if (it) {
1871                Gtk::TreePath path(it);
1872                int index = path[0];
1873                const std::vector<Gtk::Widget*> children =
1874                    instrument_menu->get_children();
1875                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1876            }
1877        }
1878    #endif
1879    
1880        updateScriptListOfMenu();
1881    
1882      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1883    
1884        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1885            switch_sampler_instrument_signal.emit(get_instrument());
1886        }
1887    }
1888    
1889    
1890    LoaderSaverBase::LoaderSaverBase(const Glib::ustring filename, gig::File* gig) :
1891        filename(filename), gig(gig),
1892    #ifdef GLIB_THREADS
1893        thread(0),
1894    #endif
1895        progress(0.f)
1896    {
1897  }  }
1898    
1899  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
1900  {  {
1901      Loader* loader = static_cast<Loader*>(progress->custom);      LoaderSaverBase* loader = static_cast<LoaderSaverBase*>(progress->custom);
1902      loader->progress_callback(progress->factor);      loader->progress_callback(progress->factor);
1903  }  }
1904    
1905  void Loader::progress_callback(float fraction)  void LoaderSaverBase::progress_callback(float fraction)
1906  {  {
1907      {      {
1908    #ifdef GLIB_THREADS
1909          Glib::Threads::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1910    #else
1911            std::lock_guard<std::mutex> lock(progressMutex);
1912    #endif
1913          progress = fraction;          progress = fraction;
1914      }      }
1915      progress_dispatcher();      progress_dispatcher();
1916  }  }
1917    
1918  void Loader::thread_function()  #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1919    // make sure stack is 16-byte aligned for SSE instructions
1920    __attribute__((force_align_arg_pointer))
1921    #endif
1922    void LoaderSaverBase::thread_function()
1923  {  {
1924      printf("thread_function self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
1925      printf("Start %s\n", filename);      printf("thread_function self=%p\n",
1926      RIFF::File* riff = new RIFF::File(filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1927      gig = new gig::File(riff);  #else
1928      gig::progress_t progress;      std::cout << "thread_function self=" << std::this_thread::get_id() << "\n";
1929      progress.callback = loader_progress_callback;  #endif
1930      progress.custom = this;      printf("Start %s\n", filename.c_str());
1931        try {
1932            gig::progress_t progress;
1933            progress.callback = loader_progress_callback;
1934            progress.custom = this;
1935    
1936            thread_function_sub(progress);
1937            printf("End\n");
1938            finished_dispatcher();
1939        } catch (RIFF::Exception e) {
1940            error_message = e.Message;
1941            error_dispatcher.emit();
1942        } catch (...) {
1943            error_message = _("Unknown exception occurred");
1944            error_dispatcher.emit();
1945        }
1946    }
1947    
1948      gig->GetInstrument(0, &progress);  void LoaderSaverBase::launch()
1949      printf("End\n");  {
1950      finished_dispatcher();  #ifdef GLIB_THREADS
1951    #ifdef OLD_THREADS
1952        thread = Glib::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function), true);
1953    #else
1954        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function));
1955    #endif
1956        printf("launch thread=%p\n", static_cast<void*>(thread));
1957    #else
1958        thread = std::thread([this](){ thread_function(); });
1959        std::cout << "launch thread=" << thread.get_id() << "\n";
1960    #endif
1961    }
1962    
1963    float LoaderSaverBase::get_progress()
1964    {
1965    #ifdef GLIB_THREADS
1966        Glib::Threads::Mutex::Lock lock(progressMutex);
1967    #else
1968        std::lock_guard<std::mutex> lock(progressMutex);
1969    #endif
1970        return progress;
1971  }  }
1972    
1973  Loader::Loader(const char* filename)  Glib::Dispatcher& LoaderSaverBase::signal_progress()
     : filename(filename), thread(0)  
1974  {  {
1975        return progress_dispatcher;
1976  }  }
1977    
1978  void Loader::launch()  Glib::Dispatcher& LoaderSaverBase::signal_finished()
1979  {  {
1980  #ifdef OLD_THREADS      return finished_dispatcher;
1981      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);  }
1982    
1983    Glib::Dispatcher& LoaderSaverBase::signal_error()
1984    {
1985        return error_dispatcher;
1986    }
1987    
1988    void LoaderSaverBase::join() {
1989    #ifdef GLIB_THREADS
1990        thread->join();
1991  #else  #else
1992      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread.join();
1993  #endif  #endif
     printf("launch thread=%x\n", thread);  
1994  }  }
1995    
1996  float Loader::get_progress()  
1997    Loader::Loader(const char* filename) :
1998        LoaderSaverBase(filename, 0)
1999  {  {
     float res;  
     {  
         Glib::Threads::Mutex::Lock lock(progressMutex);  
         res = progress;  
     }  
     return res;  
2000  }  }
2001    
2002  Glib::Dispatcher& Loader::signal_progress()  void Loader::thread_function_sub(gig::progress_t& progress)
2003  {  {
2004      return progress_dispatcher;      RIFF::File* riff = new RIFF::File(filename);
2005        gig = new gig::File(riff);
2006    
2007        gig->GetInstrument(0, &progress);
2008  }  }
2009    
2010  Glib::Dispatcher& Loader::signal_finished()  
2011    Saver::Saver(gig::File* file, Glib::ustring filename) :
2012        LoaderSaverBase(filename, file)
2013  {  {
     return finished_dispatcher;  
2014  }  }
2015    
2016  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  void Saver::thread_function_sub(gig::progress_t& progress)
2017    {
2018        // if no filename was provided, that means "save", if filename was provided means "save as"
2019        if (filename.empty()) {
2020            if (!Settings::singleton()->saveWithTemporaryFile) {
2021                // save directly over the existing .gig file
2022                // (requires less disk space than solution below
2023                // but may be slower)
2024                gig->Save(&progress);
2025            } else {
2026                // save the file as separate temporary file first,
2027                // then move the saved file over the old file
2028                // (may result in performance speedup during save)
2029                gig::String tmpname = filename + ".TMP";
2030                gig->Save(tmpname, &progress);
2031    #if defined(WIN32)
2032                if (!DeleteFile(filename.c_str())) {
2033                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
2034                }
2035    #else // POSIX ...
2036                if (unlink(filename.c_str())) {
2037                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
2038                }
2039    #endif
2040                if (rename(tmpname.c_str(), filename.c_str())) {
2041    #if defined(WIN32)
2042                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
2043    #else
2044                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
2045    #endif
2046                }
2047            }
2048        } else {
2049            gig->Save(filename, &progress);
2050        }
2051    }
2052    
2053    
2054    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
2055      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
2056  {  {
2057    #if USE_GTKMM_BOX
2058        get_content_area()->pack_start(progressBar);
2059    #else
2060      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
2061    #endif
2062    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2063      show_all_children();      show_all_children();
2064    #endif
2065        resize(600,50);
2066  }  }
2067    
2068  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
2069  // 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.
2070  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;  
     }  
2071      // forget all samples that ought to be imported      // forget all samples that ought to be imported
2072      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
2073      // clear the samples and instruments tree views      // clear the samples and instruments tree views
2074      m_refTreeModel->clear();      m_refTreeModel->clear();
2075      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
2076        m_refScriptsTreeModel->clear();
2077    #if !USE_GTKMM_BUILDER
2078        // remove all entries from "Instrument" menu
2079        while (!instrument_menu->get_children().empty()) {
2080            remove_instrument_from_menu(0);
2081        }
2082    #endif
2083      // free libgig's gig::File instance      // free libgig's gig::File instance
2084      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
2085      file = NULL;      file = NULL;
2086      set_file_is_shared(false);      set_file_is_shared(false);
2087  }  }
2088    
2089    void MainWindow::__refreshEntireGUI() {
2090        // clear the samples and instruments tree views
2091        m_refTreeModel->clear();
2092        m_refSamplesTreeModel->clear();
2093        m_refScriptsTreeModel->clear();
2094    #if !USE_GTKMM_BUILDER
2095        // remove all entries from "Instrument" menu
2096        while (!instrument_menu->get_children().empty()) {
2097            remove_instrument_from_menu(0);
2098        }
2099    #endif
2100    
2101        if (!this->file) return;
2102    
2103        load_gig(
2104            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
2105        );
2106    }
2107    
2108  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
2109  {  {
2110      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 2117  void MainWindow::on_action_file_new()
2117      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
2118      // already add one new instrument by default      // already add one new instrument by default
2119      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
2120      pInstrument->pInfo->Name = _("Unnamed Instrument");      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
2121      // update GUI with that new gig::File      // update GUI with that new gig::File
2122      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
2123  }  }
# Line 584  bool MainWindow::close_confirmation_dial Line 2130  bool MainWindow::close_confirmation_dial
2130      g_free(msg);      g_free(msg);
2131      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."));
2132      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
2133    #if HAS_GTKMM_STOCK
2134      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2135      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);
2136    #else
2137        dialog.add_button(_("_OK"), Gtk::RESPONSE_OK);
2138        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2139    #endif
2140      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
2141      int response = dialog.run();      int response = dialog.run();
2142      dialog.hide();      dialog.hide();
2143      if (response == Gtk::RESPONSE_YES) return file_save();  
2144      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
2145        if (response == Gtk::RESPONSE_NO) return true;
2146    
2147        // user cancelled dialog, thus don't close app
2148        if (response == Gtk::RESPONSE_CANCEL) return false;
2149    
2150        // TODO: the following return valid is disabled and hard coded instead for
2151        // now, due to the fact that saving with progress bar is now implemented
2152        // asynchronously, as a result the app does not close automatically anymore
2153        // after saving the file has completed
2154        //
2155        //   if (response == Gtk::RESPONSE_YES) return file_save();
2156        //   return response != Gtk::RESPONSE_CANCEL;
2157        //
2158        if (response == Gtk::RESPONSE_YES) file_save();
2159        return false; // always prevent closing the app for now (see comment above)
2160  }  }
2161    
2162  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 601  bool MainWindow::leaving_shared_mode_dia Line 2167  bool MainWindow::leaving_shared_mode_dia
2167            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
2168            "load it."));            "load it."));
2169      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
2170    #if HAS_GTKMM_STOCK
2171      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2172    #else
2173        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2174    #endif
2175      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
2176      int response = dialog.run();      int response = dialog.run();
2177      dialog.hide();      dialog.hide();
# Line 615  void MainWindow::on_action_file_open() Line 2185  void MainWindow::on_action_file_open()
2185      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
2186    
2187      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
2188    #if HAS_GTKMM_STOCK
2189      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2190      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2191    #else
2192        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2193        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2194    #endif
2195      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2196  #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
2197      Gtk::FileFilter filter;      Gtk::FileFilter filter;
# Line 630  void MainWindow::on_action_file_open() Line 2205  void MainWindow::on_action_file_open()
2205          dialog.set_current_folder(current_gig_dir);          dialog.set_current_folder(current_gig_dir);
2206      }      }
2207      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2208            dialog.hide();
2209          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
2210          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
2211          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2212            printf("on_action_file_open self=%p\n",
2213                   static_cast<void*>(Glib::Threads::Thread::self()));
2214    #else
2215            std::cout << "on_action_file_open self=" <<
2216                std::this_thread::get_id() << "\n";
2217    #endif
2218          load_file(filename.c_str());          load_file(filename.c_str());
2219          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
2220      }      }
# Line 641  void MainWindow::on_action_file_open() Line 2223  void MainWindow::on_action_file_open()
2223  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
2224  {  {
2225      __clear();      __clear();
2226      load_dialog = new LoadDialog(_("Loading..."), *this);  
2227      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2228      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
2229            Glib::filename_display_basename(name) + "' ...",
2230            *this
2231        );
2232    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2233        progress_dialog->show_all();
2234    #endif
2235        loader = new Loader(name); //FIXME: memory leak!
2236      loader->signal_progress().connect(      loader->signal_progress().connect(
2237          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
2238      loader->signal_finished().connect(      loader->signal_finished().connect(
2239          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
2240        loader->signal_error().connect(
2241            sigc::mem_fun(*this, &MainWindow::on_loader_error));
2242      loader->launch();      loader->launch();
2243  }  }
2244    
# Line 663  void MainWindow::load_instrument(gig::In Line 2254  void MainWindow::load_instrument(gig::In
2254      // load the instrument      // load the instrument
2255      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
2256      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
2257      //TODO: automatically select the given instrument      // automatically select the given instrument
2258        int i = 0;
2259        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
2260             instrument = pFile->GetNextInstrument(), ++i)
2261        {
2262            if (instrument == instr) {
2263                // select item in "instruments" tree view
2264                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
2265                // make sure the selected item in the "instruments" tree view is
2266                // visible (scroll to it)
2267                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
2268    #if !USE_GTKMM_BUILDER
2269                // select item in instrument menu
2270                {
2271                    const std::vector<Gtk::Widget*> children =
2272                        instrument_menu->get_children();
2273                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
2274                }
2275    #endif
2276                // update region chooser and dimension region chooser
2277                m_RegionChooser.set_instrument(instr);
2278                break;
2279            }
2280        }
2281  }  }
2282    
2283  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
2284  {  {
2285      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
2286  }  }
2287    
2288  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
2289  {  {
2290        loader->join();
2291      printf("Loader finished!\n");      printf("Loader finished!\n");
2292      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());  #ifdef GLIB_THREADS
2293      load_gig(loader->gig, loader->filename);      printf("on_loader_finished self=%p\n",
2294      load_dialog->hide();             static_cast<void*>(Glib::Threads::Thread::self()));
2295    #else
2296        std::cout << "on_loader_finished self=" <<
2297            std::this_thread::get_id() << "\n";
2298    #endif
2299        load_gig(loader->gig, loader->filename.c_str());
2300        progress_dialog->hide();
2301    }
2302    
2303    void MainWindow::on_loader_error()
2304    {
2305        loader->join();
2306        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
2307        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2308        msg.run();
2309        progress_dialog->hide();
2310  }  }
2311    
2312  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 715  bool MainWindow::file_save() Line 2345  bool MainWindow::file_save()
2345    
2346      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
2347      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
2348      try {  
2349          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2350          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
2351              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
2352              file_is_changed = false;          *this
2353          }      );
2354      } catch (RIFF::Exception e) {  #if HAS_GTKMM_SHOW_ALL_CHILDREN
2355          file_structure_changed_signal.emit(this->file);      progress_dialog->show_all();
2356          Glib::ustring txt = _("Could not save file: ") + e.Message;  #endif
2357          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);      saver = new Saver(this->file); //FIXME: memory leak!
2358          msg.run();      saver->signal_progress().connect(
2359          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2360      }      saver->signal_finished().connect(
2361      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2362        saver->signal_error().connect(
2363            sigc::mem_fun(*this, &MainWindow::on_saver_error));
2364        saver->launch();
2365    
2366        return true;
2367    }
2368    
2369    void MainWindow::on_saver_progress()
2370    {
2371        progress_dialog->set_fraction(saver->get_progress());
2372    }
2373    
2374    void MainWindow::on_saver_error()
2375    {
2376        saver->join();
2377        file_structure_changed_signal.emit(this->file);
2378        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
2379        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2380        msg.run();
2381    }
2382    
2383    void MainWindow::on_saver_finished()
2384    {
2385        saver->join();
2386        this->file = saver->gig;
2387        this->filename = saver->filename;
2388        current_gig_dir = Glib::path_get_dirname(filename);
2389        set_title(Glib::filename_display_basename(filename));
2390        file_has_name = true;
2391        file_is_changed = false;
2392        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
2393      __import_queued_samples();      __import_queued_samples();
2394        std::cout << "Importing queued samples done.\n" << std::flush;
2395    
2396      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
2397      return true;  
2398        __refreshEntireGUI();
2399        progress_dialog->hide();
2400  }  }
2401    
2402  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 743  void MainWindow::on_action_file_save_as( Line 2408  void MainWindow::on_action_file_save_as(
2408  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
2409  {  {
2410      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
2411    #if HAS_GTKMM_STOCK
2412      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2413      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
2414    #else
2415        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2416        dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
2417    #endif
2418      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2419      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
2420    
# Line 773  bool MainWindow::file_save_as() Line 2443  bool MainWindow::file_save_as()
2443      }      }
2444    
2445      // show warning in the dialog      // show warning in the dialog
2446      Gtk::HBox descriptionArea;      HBox descriptionArea;
2447      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
2448      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
2449        warningIcon.set_from_icon_name("dialog-warning",
2450                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
2451      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
2452  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2453      view::WrapLabel description;      view::WrapLabel description;
# Line 792  bool MainWindow::file_save_as() Line 2464  bool MainWindow::file_save_as()
2464            "same .gig file will end up in corrupted sample wave data!\n")            "same .gig file will end up in corrupted sample wave data!\n")
2465      );      );
2466      descriptionArea.pack_start(description);      descriptionArea.pack_start(description);
2467    #if USE_GTKMM_BOX
2468        dialog.get_content_area()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2469    #else
2470      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2471    #endif
2472    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2473      descriptionArea.show_all();      descriptionArea.show_all();
2474    #endif
2475    
2476      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2477          file_structure_to_be_changed_signal.emit(this->file);          dialog.hide();
2478          try {          std::string filename = dialog.get_filename();
2479              std::string filename = dialog.get_filename();          if (!Glib::str_has_suffix(filename, ".gig")) {
2480              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;  
2481          }          }
2482          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
2483          file_structure_changed_signal.emit(this->file);  
2484            progress_dialog = new ProgressDialog( //FIXME: memory leak!
2485                _("Saving") +  Glib::ustring(" '") +
2486                Glib::filename_display_basename(filename) + "' ...",
2487                *this
2488            );
2489    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2490            progress_dialog->show_all();
2491    #endif
2492    
2493            saver = new Saver(file, filename); //FIXME: memory leak!
2494            saver->signal_progress().connect(
2495                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2496            saver->signal_finished().connect(
2497                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2498            saver->signal_error().connect(
2499                sigc::mem_fun(*this, &MainWindow::on_saver_error));
2500            saver->launch();
2501    
2502          return true;          return true;
2503      }      }
2504      return false;      return false;
# Line 827  bool MainWindow::file_save_as() Line 2508  bool MainWindow::file_save_as()
2508  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
2509      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
2510      Glib::ustring error_files;      Glib::ustring error_files;
2511      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
2512      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2513           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
2514          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
2515          SF_INFO info;          SF_INFO info;
2516          info.format = 0;          info.format = 0;
2517          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);
2518          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
2519          try {          try {
2520              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 2537  void MainWindow::__import_queued_samples
2537                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
2538              }              }
2539    
2540                // reset write position for sample
2541                iter->first->SetPos(0);
2542    
2543              const int bufsize = 10000;              const int bufsize = 10000;
2544              switch (bitdepth) {              switch (bitdepth) {
2545                  case 16: {                  case 16: {
# Line 865  void MainWindow::__import_queued_samples Line 2549  void MainWindow::__import_queued_samples
2549                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
2550                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
2551                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2552                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
2553                          cnt -= n;                          cnt -= n;
2554                      }                      }
2555                      delete[] buffer;                      delete[] buffer;
# Line 885  void MainWindow::__import_queued_samples Line 2569  void MainWindow::__import_queued_samples
2569                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
2570                          }                          }
2571                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2572                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
2573                          cnt -= n;                          cnt -= n;
2574                      }                      }
2575                      delete[] srcbuf;                      delete[] srcbuf;
# Line 896  void MainWindow::__import_queued_samples Line 2580  void MainWindow::__import_queued_samples
2580              // cleanup              // cleanup
2581              sf_close(hFile);              sf_close(hFile);
2582              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
2583              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
2584              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
2585              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
2586              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
2587              ++iter;              ++iter;
2588              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
2589          } catch (std::string what) {          } catch (std::string what) {
2590              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
2591              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
2592              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
2593              ++iter;              ++iter;
2594          }          }
2595      }      }
2596      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
2597      if (error_files.size()) {      if (!error_files.empty()) {
2598          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;
2599          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2600          msg.run();          msg.run();
# Line 923  void MainWindow::on_action_file_properti Line 2607  void MainWindow::on_action_file_properti
2607      propDialog.deiconify();      propDialog.deiconify();
2608  }  }
2609    
2610    void MainWindow::on_action_warn_user_on_extensions() {
2611        Settings::singleton()->warnUserOnExtensions =
2612            !Settings::singleton()->warnUserOnExtensions;
2613    }
2614    
2615    void MainWindow::on_action_show_tooltips() {
2616        Settings::singleton()->showTooltips =
2617            !Settings::singleton()->showTooltips;
2618    
2619        on_show_tooltips_changed();
2620    }
2621    
2622    void MainWindow::on_show_tooltips_changed() {
2623        const bool b = Settings::singleton()->showTooltips;
2624    
2625        dimreg_label.set_has_tooltip(b);
2626        dimreg_all_regions.set_has_tooltip(b);
2627        dimreg_all_dimregs.set_has_tooltip(b);
2628        dimreg_stereo.set_has_tooltip(b);
2629    
2630        // Not doing this here, we let onQueryTreeViewTooltip() handle this per cell
2631        //m_TreeView.set_has_tooltip(b);
2632    
2633        m_TreeViewSamples.set_has_tooltip(b);
2634        m_TreeViewScripts.set_has_tooltip(b);
2635    
2636        set_has_tooltip(b);
2637    }
2638    
2639    void MainWindow::on_action_sync_sampler_instrument_selection() {
2640        Settings::singleton()->syncSamplerInstrumentSelection =
2641            !Settings::singleton()->syncSamplerInstrumentSelection;
2642    }
2643    
2644    void MainWindow::on_action_move_root_note_with_region_moved() {
2645        Settings::singleton()->moveRootNoteWithRegionMoved =
2646            !Settings::singleton()->moveRootNoteWithRegionMoved;
2647    }
2648    
2649  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
2650  {  {
2651      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
# Line 932  void MainWindow::on_action_help_about() Line 2655  void MainWindow::on_action_help_about()
2655      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
2656  #endif  #endif
2657      dialog.set_version(VERSION);      dialog.set_version(VERSION);
2658      dialog.set_copyright("Copyright (C) 2006-2013 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2019 Andreas Persson");
2659      dialog.set_comments(_(      const std::string sComment =
2660          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
2661          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
2662          "Please notice that this is still a very young instrument editor. "          _(
2663          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
2664          "this application.\n"              "\n"
2665          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
2666          "Please report bugs to: http://bugs.linuxsampler.org")              "backup your Gigasampler/GigaStudio files before editing them with "
2667      );              "this application.\n"
2668      dialog.set_website("http://www.linuxsampler.org");              "\n"
2669      dialog.set_website_label("http://www.linuxsampler.org");              "Please report bugs to: https://bugs.linuxsampler.org"
2670            );
2671        dialog.set_comments(sComment.c_str());
2672        dialog.set_website("https://www.linuxsampler.org");
2673        dialog.set_website_label("https://www.linuxsampler.org");
2674        dialog.set_position(Gtk::WIN_POS_CENTER);
2675      dialog.run();      dialog.run();
2676  }  }
2677    
2678  PropDialog::PropDialog()  PropDialog::PropDialog()
2679      : eName(_("Name")),      : eFileFormat(_("File Format")),
2680          eName(_("Name")),
2681        eCreationDate(_("Creation date")),        eCreationDate(_("Creation date")),
2682        eComments(_("Comments")),        eComments(_("Comments")),
2683        eProduct(_("Product")),        eProduct(_("Product")),
# Line 964  PropDialog::PropDialog() Line 2693  PropDialog::PropDialog()
2693        eSourceForm(_("Source form")),        eSourceForm(_("Source form")),
2694        eCommissioned(_("Commissioned")),        eCommissioned(_("Commissioned")),
2695        eSubject(_("Subject")),        eSubject(_("Subject")),
2696    #if HAS_GTKMM_STOCK
2697        quitButton(Gtk::Stock::CLOSE),        quitButton(Gtk::Stock::CLOSE),
2698    #else
2699          quitButton(_("_Close")),
2700    #endif
2701        table(2, 1),        table(2, 1),
2702        update_model(0)        m_file(NULL)
2703  {  {
2704        if (!Settings::singleton()->autoRestoreWindowDimension) {
2705            set_default_size(470, 390);
2706            set_position(Gtk::WIN_POS_MOUSE);
2707        }
2708    
2709      set_title(_("File Properties"));      set_title(_("File Properties"));
2710      eName.set_width_chars(50);      eName.set_width_chars(50);
2711    
2712        connect(eFileFormat, &PropDialog::set_FileFormat);
2713      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
2714      connect(eCreationDate, &DLS::Info::CreationDate);      connect(eCreationDate, &DLS::Info::CreationDate);
2715      connect(eComments, &DLS::Info::Comments);      connect(eComments, &DLS::Info::Comments);
# Line 988  PropDialog::PropDialog() Line 2727  PropDialog::PropDialog()
2727      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
2728      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
2729    
2730        table.add(eFileFormat);
2731      table.add(eName);      table.add(eName);
2732      table.add(eCreationDate);      table.add(eCreationDate);
2733      table.add(eComments);      table.add(eComments);
# Line 1005  PropDialog::PropDialog() Line 2745  PropDialog::PropDialog()
2745      table.add(eCommissioned);      table.add(eCommissioned);
2746      table.add(eSubject);      table.add(eSubject);
2747    
2748    #if USE_GTKMM_GRID
2749        table.set_column_spacing(5);
2750    #else
2751      table.set_col_spacings(5);      table.set_col_spacings(5);
2752    #endif
2753    
2754      add(vbox);      add(vbox);
2755    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2756        table.set_margin(5);
2757    #else
2758      table.set_border_width(5);      table.set_border_width(5);
2759    #endif
2760      vbox.add(table);      vbox.add(table);
2761      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
2762      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
2763    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2764        buttonBox.set_margin(5);
2765    #else
2766      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2767    #endif
2768      buttonBox.show();      buttonBox.show();
2769      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2770      quitButton.set_can_default();      quitButton.set_can_default();
# Line 1021  PropDialog::PropDialog() Line 2774  PropDialog::PropDialog()
2774    
2775      quitButton.show();      quitButton.show();
2776      vbox.show();      vbox.show();
2777    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2778      show_all_children();      show_all_children();
2779    #endif
2780  }  }
2781    
2782  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_file(gig::File* file)
2783  {  {
2784      this->info = info;      m_file = file;
2785        update(file->pInfo);
2786    
2787        // update file format version combo box
2788        const std::string sGiga = "Gigasampler/GigaStudio v";
2789        const int major = file->pVersion->major;
2790        std::vector<std::string> txts;
2791        std::vector<int> values;
2792        txts.push_back(sGiga + "2"); values.push_back(2);
2793        txts.push_back(sGiga + "3"); values.push_back(3);
2794        txts.push_back(sGiga + "4"); values.push_back(4);
2795        if (major < 2 || major > 4) {
2796            txts.push_back(sGiga + ToString(major)); values.push_back(major);
2797        }
2798        std::vector<const char*> texts;
2799        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
2800        texts.push_back(NULL); values.push_back(0);
2801    
2802      update_model++;      update_model++;
2803      eName.set_value(info->Name);      eFileFormat.set_choices(&texts[0], &values[0]);
2804      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);  
2805      update_model--;      update_model--;
2806  }  }
2807    
2808  sigc::signal<void>& PropDialog::signal_info_changed()  void PropDialog::set_FileFormat(int value)
2809  {  {
2810      return info_changed;      m_file->pVersion->major = value;
2811  }  }
2812    
2813  void InstrumentProps::set_IsDrum(bool value)  
2814    void InstrumentProps::set_Name(const gig::String& name)
2815  {  {
2816      instrument->IsDrum = value;      m->pInfo->Name = name;
2817  }  }
2818    
2819  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
2820  {  {
2821      instrument->MIDIBank = value;      update_model++;
2822        eName.set_value(m->pInfo->Name);
2823        update_model--;
2824  }  }
2825    
2826  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
2827  {  {
2828      instrument->MIDIProgram = value;      m->IsDrum = value;
2829  }  }
2830    
2831  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
2832  {  {
2833      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
2834  }  }
2835    
2836  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
2837  {  {
2838      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
2839  }  }
2840    
2841  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
2842      : update_model(0),  #if HAS_GTKMM_STOCK
2843        quitButton(Gtk::Stock::CLOSE),      quitButton(Gtk::Stock::CLOSE),
2844        table(2,1),  #else
2845        eName(_("Name")),      quitButton(_("_Close")),
2846        eIsDrum(_("Is drum")),  #endif
2847        eMIDIBank(_("MIDI bank"), 0, 16383),      table(2,1),
2848        eMIDIProgram(_("MIDI program")),      eName(_("Name")),
2849        eAttenuation(_("Attenuation"), 0, 96, 0, 1),      eIsDrum(_("Is drum")),
2850        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),      eMIDIBank(_("MIDI bank"), 0, 16383),
2851        eEffectSend(_("Effect send"), 0, 65535),      eMIDIProgram(_("MIDI program")),
2852        eFineTune(_("Fine tune"), -8400, 8400),      eAttenuation(_("Attenuation"), 0, 96, 0, 1),
2853        ePitchbendRange(_("Pitchbend range"), 0, 12),      eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
2854        ePianoReleaseMode(_("Piano release mode")),      eEffectSend(_("Effect send"), 0, 65535),
2855        eDimensionKeyRangeLow(_("Keyswitching range low")),      eFineTune(_("Fine tune"), -8400, 8400),
2856        eDimensionKeyRangeHigh(_("Keyswitching range high"))      ePitchbendRange(_("Pitchbend range"), 0, 48),
2857  {      ePianoReleaseMode(_("Piano release mode")),
2858        eDimensionKeyRangeLow(_("Keyswitching range low")),
2859        eDimensionKeyRangeHigh(_("Keyswitching range high")),
2860        table2(2,1),
2861        eName2(_("Name")),
2862        eCreationDate(_("Creation date")),
2863        eComments(_("Comments")),
2864        eProduct(_("Product")),
2865        eCopyright(_("Copyright")),
2866        eArtists(_("Artists")),
2867        eGenre(_("Genre")),
2868        eKeywords(_("Keywords")),
2869        eEngineer(_("Engineer")),
2870        eTechnician(_("Technician")),
2871        eSoftware(_("Software")),
2872        eMedium(_("Medium")),
2873        eSource(_("Source")),
2874        eSourceForm(_("Source form")),
2875        eCommissioned(_("Commissioned")),
2876        eSubject(_("Subject"))
2877    {
2878        if (!Settings::singleton()->autoRestoreWindowDimension) {
2879            //set_default_size(470, 390);
2880            set_position(Gtk::WIN_POS_MOUSE);
2881        }
2882    
2883      set_title(_("Instrument Properties"));      set_title(_("Instrument Properties"));
2884    
2885        tabs.append_page(vbox[1], _("Settings"));
2886        tabs.append_page(vbox[2], _("Info"));
2887    
2888      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
2889          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
2890            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
# Line 1111  InstrumentProps::InstrumentProps() Line 2894  InstrumentProps::InstrumentProps()
2894            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
2895      );      );
2896    
2897        connect(eName, &InstrumentProps::set_Name);
2898      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
2899      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
2900      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
# Line 1120  InstrumentProps::InstrumentProps() Line 2904  InstrumentProps::InstrumentProps()
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);
# Line 1140  InstrumentProps::InstrumentProps() Line 2975  InstrumentProps::InstrumentProps()
2975      table.add(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
2976      table.add(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
2977    
2978      add(vbox);      // tab 2
2979    #if USE_GTKMM_GRID
2980        table2.set_column_spacing(5);
2981    #else
2982        table2.set_col_spacings(5);
2983    #endif
2984        table2.add(eName2);
2985        table2.add(eCreationDate);
2986        table2.add(eComments);
2987        table2.add(eProduct);
2988        table2.add(eCopyright);
2989        table2.add(eArtists);
2990        table2.add(eGenre);
2991        table2.add(eKeywords);
2992        table2.add(eEngineer);
2993        table2.add(eTechnician);
2994        table2.add(eSoftware);
2995        table2.add(eMedium);
2996        table2.add(eSource);
2997        table2.add(eSourceForm);
2998        table2.add(eCommissioned);
2999        table2.add(eSubject);
3000    
3001        add(vbox[0]);
3002    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3003        table.set_margin(5);
3004    #else
3005      table.set_border_width(5);      table.set_border_width(5);
3006      vbox.pack_start(table);  #endif
3007        vbox[1].pack_start(table);
3008        vbox[2].pack_start(table2);
3009      table.show();      table.show();
3010      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      table2.show();
3011        vbox[0].pack_start(tabs);
3012        vbox[0].pack_start(buttonBox, Gtk::PACK_SHRINK);
3013      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
3014    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3015        buttonBox.set_margin(5);
3016    #else
3017      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
3018    #endif
3019      buttonBox.show();      buttonBox.show();
3020      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
3021      quitButton.set_can_default();      quitButton.set_can_default();
# Line 1156  InstrumentProps::InstrumentProps() Line 3025  InstrumentProps::InstrumentProps()
3025          sigc::mem_fun(*this, &InstrumentProps::hide));          sigc::mem_fun(*this, &InstrumentProps::hide));
3026    
3027      quitButton.show();      quitButton.show();
3028      vbox.show();      vbox[0].show();
3029    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3030      show_all_children();      show_all_children();
3031    #endif
3032  }  }
3033    
3034  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
3035  {  {
3036      this->instrument = instrument;      update(instrument);
3037    
3038      update_model++;      update_model++;
3039    
3040        // tab 1
3041      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
3042      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
3043      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
3044      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
3045      eAttenuation.set_value(instrument->Attenuation);      // tab 2
3046      eGainPlus6.set_value(instrument->Attenuation);      eName2.set_value(instrument->pInfo->Name);
3047      eEffectSend.set_value(instrument->EffectSend);      eCreationDate.set_value(instrument->pInfo->CreationDate);
3048      eFineTune.set_value(instrument->FineTune);      eComments.set_value(instrument->pInfo->Comments);
3049      ePitchbendRange.set_value(instrument->PitchbendRange);      eProduct.set_value(instrument->pInfo->Product);
3050      ePianoReleaseMode.set_value(instrument->PianoReleaseMode);      eCopyright.set_value(instrument->pInfo->Copyright);
3051      eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);      eArtists.set_value(instrument->pInfo->Artists);
3052      eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);      eGenre.set_value(instrument->pInfo->Genre);
3053        eKeywords.set_value(instrument->pInfo->Keywords);
3054        eEngineer.set_value(instrument->pInfo->Engineer);
3055        eTechnician.set_value(instrument->pInfo->Technician);
3056        eSoftware.set_value(instrument->pInfo->Software);
3057        eMedium.set_value(instrument->pInfo->Medium);
3058        eSource.set_value(instrument->pInfo->Source);
3059        eSourceForm.set_value(instrument->pInfo->SourceForm);
3060        eCommissioned.set_value(instrument->pInfo->Commissioned);
3061        eSubject.set_value(instrument->pInfo->Subject);
3062    
3063      update_model--;      update_model--;
3064  }  }
3065    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
3066    
3067  void MainWindow::file_changed()  void MainWindow::file_changed()
3068  {  {
# Line 1193  void MainWindow::file_changed() Line 3072  void MainWindow::file_changed()
3072      }      }
3073  }  }
3074    
3075    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
3076        sample_ref_count.clear();
3077        
3078        if (!gig) return;
3079    
3080        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
3081             instrument = gig->GetNextInstrument())
3082        {
3083            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3084                 rgn = instrument->GetNextRegion())
3085            {
3086                for (int i = 0; i < 256; ++i) {
3087                    if (!rgn->pDimensionRegions[i]) continue;
3088                    if (rgn->pDimensionRegions[i]->pSample) {
3089                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
3090                    }
3091                }
3092            }
3093        }
3094    }
3095    
3096    bool MainWindow::onQueryTreeViewTooltip(int x, int y, bool keyboardTip, const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
3097        Gtk::TreeModel::iterator iter;
3098        if (!m_TreeView.get_tooltip_context_iter(x, y, keyboardTip, iter)) {
3099            return false;
3100        }
3101        Gtk::TreeModel::Path path(iter);
3102        Gtk::TreeModel::Row row = *iter;
3103        Gtk::TreeViewColumn* pointedColumn = NULL;
3104        // resolve the precise table column the mouse points to
3105        {
3106            Gtk::TreeModel::Path path; // unused
3107            int cellX, cellY; // unused
3108            m_TreeView.get_path_at_pos(x, y, path, pointedColumn, cellX, cellY);
3109        }
3110        Gtk::TreeViewColumn* scriptsColumn = m_TreeView.get_column(2);
3111        if (pointedColumn == scriptsColumn) { // mouse hovers scripts column ...
3112            // show the script(s) assigned to the hovered instrument as tooltip
3113            tooltip->set_markup( row[m_Columns.m_col_tooltip] );
3114            m_TreeView.set_tooltip_cell(tooltip, &path, scriptsColumn, NULL);
3115        } else {
3116            // if beginners' tooltips is disabled then don't show the following one
3117            if (!Settings::singleton()->showTooltips)
3118                return false;
3119            // yeah, a beginners tooltip
3120            tooltip->set_text(_(
3121                "Right click here for actions on instruments & MIDI Rules. "
3122                "Drag & drop to change the order of instruments."
3123            ));
3124            m_TreeView.set_tooltip_cell(tooltip, &path, pointedColumn, NULL);
3125        }
3126        return true;
3127    }
3128    
3129    static Glib::ustring scriptTooltipFor(gig::Instrument* instrument, int index) {
3130        Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3131        const int iScriptSlots = instrument->ScriptSlotCount();
3132        Glib::ustring tooltip = "<u>(" + ToString(index) + ") “"  + name + "”</u>\n\n";
3133        if (!iScriptSlots)
3134            tooltip += "<span foreground='red'><i>No script assigned</i></span>";
3135        else {
3136            for (int i = 0; i < iScriptSlots; ++i) {
3137                tooltip += "• " + ToString(i+1) + ". Script: “<span foreground='#46DEFF'><b>" +
3138                           instrument->GetScriptOfSlot(i)->Name + "</b></span>”";
3139                if (i + 1 < iScriptSlots) tooltip += "\n\n";
3140            }
3141        }
3142        return tooltip;
3143    }
3144    
3145  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
3146  {  {
3147      file = 0;      file = 0;
3148      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
3149    
3150      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
3151            (filename && strlen(filename) > 0) ?
3152                filename : (!gig->GetFileName().empty()) ?
3153                    gig->GetFileName() : _("Unsaved Gig File");
3154      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
3155      file_has_name = filename;      file_has_name = filename;
3156      file_is_changed = false;      file_is_changed = false;
3157    
3158      propDialog.set_info(gig->pInfo);      propDialog.set_file(gig);
   
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
3159    
3160      int instrument_index = 0;      instrument_name_connection.block();
3161      Gtk::RadioMenuItem::Group instrument_group;      int index = 0;
3162      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
3163           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
3164            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3165            const int iScriptSlots = instrument->ScriptSlotCount();
3166    
3167          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
3168          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
3169          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
3170            row[m_Columns.m_col_name] = name;
3171          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
3172          // create a menu item for this instrument          row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3173          Gtk::RadioMenuItem* item =          row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3174              new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());  
3175          instrument_menu->get_submenu()->append(*item);  #if !USE_GTKMM_BUILDER
3176          item->signal_activate().connect(          add_instrument_to_menu(name);
3177              sigc::bind(  #endif
                 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  
                 instrument_index  
             )  
         );  
         instrument_index++;  
3178      }      }
3179      instrument_menu->show();      instrument_name_connection.unblock();
3180      instrument_menu->get_submenu()->show_all_children();  #if !USE_GTKMM_BUILDER
3181        uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
3182    #endif
3183    
3184        updateSampleRefCountMap(gig);
3185    
3186      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
3187          if (group->Name != "") {          if (group->Name != "") {
3188              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
3189              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
3190              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
3191              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
3192              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
3193              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1243  void MainWindow::load_gig(gig::File* gig Line 3195  void MainWindow::load_gig(gig::File* gig
3195                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
3196                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
3197                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
3198                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
3199                        gig_to_utf8(sample->pInfo->Name);
3200                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
3201                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
3202                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
3203                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3204                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3205              }              }
3206          }          }
3207      }      }
3208        
3209        for (int i = 0; gig->GetScriptGroup(i); ++i) {
3210            gig::ScriptGroup* group = gig->GetScriptGroup(i);
3211    
3212            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
3213            Gtk::TreeModel::Row rowGroup = *iterGroup;
3214            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
3215            rowGroup[m_ScriptsModel.m_col_group]  = group;
3216            rowGroup[m_ScriptsModel.m_col_script] = NULL;
3217            for (int s = 0; group->GetScript(s); ++s) {
3218                gig::Script* script = group->GetScript(s);
3219    
3220                Gtk::TreeModel::iterator iterScript =
3221                    m_refScriptsTreeModel->append(rowGroup.children());
3222                Gtk::TreeModel::Row rowScript = *iterScript;
3223                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
3224                rowScript[m_ScriptsModel.m_col_script] = script;
3225                rowScript[m_ScriptsModel.m_col_group]  = NULL;
3226            }
3227        }
3228        // unfold all sample groups & script groups by default
3229        m_TreeViewSamples.expand_all();
3230        m_TreeViewScripts.expand_all();
3231    
3232      file = gig;      file = gig;
3233    
3234      // select the first instrument      // select the first instrument
3235      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
3236      tree_sel_ref->select(Gtk::TreePath("0"));  
3237        instr_props_set_instrument();
3238        gig::Instrument* instrument = get_instrument();
3239        if (instrument) {
3240            midiRules.set_instrument(instrument);
3241        }
3242  }  }
3243    
3244  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
3245  {  {
3246      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
3247      if (instrument)  
3248      {      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3249        if (rows.empty()) {
3250            instrumentProps.hide();
3251            return false;
3252        }
3253        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3254        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3255        if (it) {
3256            Gtk::TreeModel::Row row = *it;
3257            gig::Instrument* instrument = row[m_Columns.m_col_instr];
3258    
3259          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
3260    
3261            // make sure instrument tree is updated when user changes the
3262            // instrument name in instrument properties window
3263            instrumentProps.signal_name_changed().connect(
3264                sigc::bind(
3265                    sigc::mem_fun(*this,
3266                                  &MainWindow::instr_name_changed_by_instr_props),
3267                    it));
3268        } else {
3269            instrumentProps.hide();
3270        }
3271        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3272        return it ? true : false;
3273    }
3274    
3275    void MainWindow::show_instr_props()
3276    {
3277        if (instr_props_set_instrument()) {
3278          instrumentProps.show();          instrumentProps.show();
3279          instrumentProps.deiconify();          instrumentProps.deiconify();
3280      }      }
3281  }  }
3282    
3283    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
3284    {
3285        Gtk::TreeModel::Row row = *it;
3286        Glib::ustring name = row[m_Columns.m_col_name];
3287    
3288        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3289        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
3290        if (gigname != name) {
3291            Gtk::TreeModel::Path path(*it);
3292            const int index = path[0];
3293            row[m_Columns.m_col_name] = gigname;
3294            row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3295        }
3296    }
3297    
3298    void MainWindow::show_midi_rules()
3299    {
3300        if (gig::Instrument* instrument = get_instrument())
3301        {
3302            midiRules.set_instrument(instrument);
3303            midiRules.show();
3304            midiRules.deiconify();
3305        }
3306    }
3307    
3308    void MainWindow::show_script_slots() {
3309        if (!file) return;
3310        // get selected instrument
3311        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3312        if (rows.empty()) return;
3313        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3314        if (!it) return;
3315        Gtk::TreeModel::Row row = *it;
3316        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3317        if (!instrument) return;
3318    
3319        ScriptSlots* window = new ScriptSlots;
3320        window->setInstrument(instrument);
3321        window->signal_script_slots_changed().connect(
3322            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
3323        );
3324        //window->reparent(*this);
3325        window->show();
3326    }
3327    
3328    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
3329        if (!pInstrument) return;
3330        const int iScriptSlots = pInstrument->ScriptSlotCount();
3331    
3332        //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!
3333        //Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3334        Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3335    
3336        for (int i = 0; i < model->children().size(); ++i) {
3337            Gtk::TreeModel::Row row = model->children()[i];
3338            if (row[m_Columns.m_col_instr] != pInstrument) continue;
3339            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3340            row[m_Columns.m_col_tooltip] = scriptTooltipFor(pInstrument, i);
3341            break;
3342        }
3343    
3344        // causes the sampler to reload the instrument with the new script
3345        on_sel_change();
3346    }
3347    
3348    void MainWindow::assignScript(gig::Script* pScript) {
3349        if (!pScript) {
3350            printf("assignScript() : !script\n");
3351            return;
3352        }
3353        printf("assignScript('%s')\n", pScript->Name.c_str());
3354    
3355        gig::Instrument* pInstrument = get_instrument();
3356        if (!pInstrument) {
3357            printf("!instrument\n");
3358            return;
3359        }
3360    
3361        pInstrument->AddScriptSlot(pScript);
3362    
3363        onScriptSlotsModified(pInstrument);
3364    }
3365    
3366    void MainWindow::dropAllScriptSlots() {
3367        gig::Instrument* pInstrument = get_instrument();
3368        if (!pInstrument) {
3369            printf("!instrument\n");
3370            return;
3371        }
3372    
3373        const int iScriptSlots = pInstrument->ScriptSlotCount();
3374        for (int i = iScriptSlots - 1; i >= 0; --i)
3375            pInstrument->RemoveScriptSlot(i);
3376    
3377        onScriptSlotsModified(pInstrument);
3378    }
3379    
3380    void MainWindow::on_action_refresh_all() {
3381        __refreshEntireGUI();
3382    }
3383    
3384  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
3385    #if USE_GLIB_ACTION
3386        bool active = false;
3387        m_actionToggleStatusBar->get_state(active);
3388        // for some reason toggle state does not change automatically
3389        active = !active;
3390        m_actionToggleStatusBar->change_state(active);
3391        if (active)
3392            m_StatusBar.show();
3393        else
3394            m_StatusBar.hide();
3395    #else
3396      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
3397          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
3398      if (!item) {      if (!item) {
# Line 1277  void MainWindow::on_action_view_status_b Line 3401  void MainWindow::on_action_view_status_b
3401      }      }
3402      if (item->get_active()) m_StatusBar.show();      if (item->get_active()) m_StatusBar.show();
3403      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
3404    #endif
3405  }  }
3406    
3407  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_auto_restore_win_dim() {
3408  {  #if USE_GLIB_ACTION
3409        bool active = false;
3410        m_actionToggleRestoreWinDim->get_state(active);
3411        // for some reason toggle state does not change automatically
3412        active = !active;
3413        m_actionToggleRestoreWinDim->change_state(active);
3414        Settings::singleton()->autoRestoreWindowDimension = active;
3415    #else
3416        Gtk::CheckMenuItem* item =
3417            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
3418        if (!item) {
3419            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
3420            return;
3421        }
3422        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
3423    #endif
3424    }
3425    
3426    void MainWindow::on_save_with_temporary_file() {
3427    #if USE_GLIB_ACTION
3428        bool active = false;
3429        m_actionToggleSaveWithTempFile->get_state(active);
3430        // for some reason toggle state does not change automatically
3431        active = !active;
3432        m_actionToggleSaveWithTempFile->change_state(active);
3433        Settings::singleton()->saveWithTemporaryFile = active;
3434    #else
3435        Gtk::CheckMenuItem* item =
3436            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
3437        if (!item) {
3438            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
3439            return;
3440        }
3441        Settings::singleton()->saveWithTemporaryFile = item->get_active();
3442    #endif
3443    }
3444    
3445    bool MainWindow::is_copy_samples_unity_note_enabled() const {
3446    #if USE_GLIB_ACTION
3447        bool active = false;
3448        m_actionToggleCopySampleUnity->get_state(active);
3449        return active;
3450    #else
3451        Gtk::CheckMenuItem* item =
3452            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
3453        if (!item) {
3454            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
3455            return true;
3456        }
3457        return item->get_active();
3458    #endif
3459    }
3460    
3461    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
3462    #if USE_GLIB_ACTION
3463        bool active = false;
3464        m_actionToggleCopySampleTune->get_state(active);
3465        return active;
3466    #else
3467        Gtk::CheckMenuItem* item =
3468            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
3469        if (!item) {
3470            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
3471            return true;
3472        }
3473        return item->get_active();
3474    #endif
3475    }
3476    
3477    bool MainWindow::is_copy_samples_loop_enabled() const {
3478    #if USE_GLIB_ACTION
3479        bool active = false;
3480        m_actionToggleCopySampleLoop->get_state(active);
3481        return active;
3482    #else
3483        Gtk::CheckMenuItem* item =
3484            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
3485        if (!item) {
3486            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
3487            return true;
3488        }
3489        return item->get_active();
3490    #endif
3491    }
3492    
3493    #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
3494    bool MainWindow::on_button_release(Gdk::EventButton& _button) {
3495        GdkEventButton* button = _button.gobj();
3496    #else
3497    void MainWindow::on_button_release(GdkEventButton* button) {
3498    #endif
3499      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
3500          show_instr_props();          show_instr_props();
3501      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3502            // gig v2 files have no midi rules
3503            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
3504    #if USE_GTKMM_BUILDER
3505            m_actionMIDIRules->property_enabled() = bEnabled;
3506    #else
3507            static_cast<Gtk::MenuItem*>(
3508                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
3509                    bEnabled
3510                );
3511            static_cast<Gtk::MenuItem*>(
3512                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
3513                    bEnabled
3514                );
3515    #endif
3516          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
3517      }      }
3518    #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
3519        return false;
3520    #endif
3521  }  }
3522    
3523  void MainWindow::on_instrument_selection_change(int index) {  #if !USE_GTKMM_BUILDER
3524      m_RegionChooser.set_instrument(file->GetInstrument(index));  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
3525        if (item->get_active()) {
3526            const std::vector<Gtk::Widget*> children =
3527                instrument_menu->get_children();
3528            std::vector<Gtk::Widget*>::const_iterator it =
3529                find(children.begin(), children.end(), item);
3530            if (it != children.end()) {
3531                int index = it - children.begin();
3532                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
3533    
3534                m_RegionChooser.set_instrument(file->GetInstrument(index));
3535            }
3536        }
3537  }  }
3538    #endif
3539    
3540    void MainWindow::select_instrument(gig::Instrument* instrument) {
3541        if (!instrument) return;
3542    
3543        //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!
3544        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3545        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3546    
3547        for (int i = 0; i < model->children().size(); ++i) {
3548            Gtk::TreeModel::Row row = model->children()[i];
3549            if (row[m_Columns.m_col_instr] == instrument) {
3550                // select and show the respective instrument in the list view
3551                show_intruments_tab();
3552                m_TreeView.get_selection()->unselect_all();
3553                
3554    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3555                auto iterSel = model->children()[i].get_iter();
3556                m_TreeView.get_selection()->select(iterSel);
3557    #else
3558                m_TreeView.get_selection()->select(model->children()[i]);
3559    #endif
3560                std::vector<Gtk::TreeModel::Path> rows =
3561                    m_TreeView.get_selection()->get_selected_rows();
3562                if (!rows.empty())
3563                    m_TreeView.scroll_to_row(rows[0]);
3564                on_sel_change(); // the regular instrument selection change callback
3565            }
3566        }
3567    }
3568    
3569    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
3570    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
3571        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
3572        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
3573    
3574        //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!
3575        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3576        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3577    
3578        for (int i = 0; i < model->children().size(); ++i) {
3579            Gtk::TreeModel::Row row = model->children()[i];
3580            if (row[m_Columns.m_col_instr] == pInstrument) {
3581                // select and show the respective instrument in the list view
3582                show_intruments_tab();
3583                m_TreeView.get_selection()->unselect_all();
3584    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3585                auto iterSel = model->children()[i].get_iter();
3586                m_TreeView.get_selection()->select(iterSel);
3587    #else
3588                m_TreeView.get_selection()->select(model->children()[i]);
3589    #endif
3590                std::vector<Gtk::TreeModel::Path> rows =
3591                    m_TreeView.get_selection()->get_selected_rows();
3592                if (!rows.empty())
3593                    m_TreeView.scroll_to_row(rows[0]);
3594                on_sel_change(); // the regular instrument selection change callback
3595    
3596                // select respective region in the region selector
3597                m_RegionChooser.set_region(pRegion);
3598    
3599                // select and show the respective dimension region in the editor
3600                //update_dimregs();
3601                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
3602                //dimreg_edit.set_dim_region(dimRgn);
3603    
3604                return true;
3605            }
3606        }
3607    
3608        return false;
3609    }
3610    
3611    void MainWindow::select_sample(gig::Sample* sample) {
3612        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3613        for (int g = 0; g < model->children().size(); ++g) {
3614            Gtk::TreeModel::Row rowGroup = model->children()[g];
3615            for (int s = 0; s < rowGroup.children().size(); ++s) {
3616                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3617                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
3618                    show_samples_tab();
3619                    m_TreeViewSamples.get_selection()->unselect_all();
3620    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3621                    auto iterSel = rowGroup.children()[s].get_iter();
3622                    m_TreeViewSamples.get_selection()->select(iterSel);
3623    #else
3624                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
3625    #endif
3626                    std::vector<Gtk::TreeModel::Path> rows =
3627                        m_TreeViewSamples.get_selection()->get_selected_rows();
3628                    if (rows.empty()) return;
3629                    m_TreeViewSamples.scroll_to_row(rows[0]);
3630                    return;
3631                }
3632            }
3633        }
3634    }
3635    
3636    #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
3637    bool MainWindow::on_sample_treeview_button_release(Gdk::EventButton& _button) {
3638        GdkEventButton* button = _button.gobj();
3639    #else
3640  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
3641    #endif
3642      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3643            // by default if Ctrl keys is pressed down, then a mouse right-click
3644            // does not select the respective row, so we must assure this
3645            // programmatically ...
3646            /*{
3647                Gtk::TreeModel::Path path;
3648                Gtk::TreeViewColumn* pColumn = NULL;
3649                int cellX, cellY;
3650                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
3651                    (int)button->x, (int)button->y,
3652                    path, pColumn, cellX, cellY
3653                );
3654                if (bSuccess) {
3655                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
3656                        printf("not selected !!!\n");
3657                        m_TreeViewSamples.get_selection()->select(path);
3658                    }
3659                }
3660            }*/
3661    
3662    #if !USE_GTKMM_BUILDER
3663          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
3664              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
3665    #endif
3666    
3667          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
3668          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3669          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3670          bool group_selected  = false;          const int n = rows.size();
3671          bool sample_selected = false;          int nGroups  = 0;
3672          if (it) {          int nSamples = 0;
3673            for (int r = 0; r < n; ++r) {
3674                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3675                if (!it) continue;
3676              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
3677              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
3678              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
3679          }          }
3680    
3681    #if USE_GTKMM_BUILDER
3682            m_actionSampleProperties->property_enabled() = (n == 1);
3683            m_actionAddSample->property_enabled() = (n);
3684            m_actionAddSampleGroup->property_enabled() = (file);
3685            m_actionViewSampleRefs->property_enabled() = (nSamples == 1);
3686            m_actionRemoveSample->property_enabled() = (n);
3687            m_actionReplaceSample->property_enabled() = (nSamples == 1);
3688    #else
3689          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
3690              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
3691          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
3692              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
3693          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
3694              set_sensitive(file);              set_sensitive(file);
3695            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
3696                set_sensitive(nSamples == 1);
3697          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
3698              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
3699    #endif
3700          // show sample popup          // show sample popup
3701          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
3702    
3703    #if !USE_GTKMM_BUILDER
3704            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
3705                set_sensitive(n == 1);
3706            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
3707                set_sensitive(n);
3708            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
3709                set_sensitive(file);
3710            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
3711                set_sensitive(nSamples == 1);
3712            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
3713                set_sensitive(n);
3714    #endif
3715      }      }
3716        
3717    #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
3718        return false;
3719    #endif
3720  }  }
3721    
3722  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
3723      static int __instrument_indexer = 0;  bool MainWindow::on_script_treeview_button_release(Gdk::EventButton& _button) {
3724      if (!file) return;      GdkEventButton* button = _button.gobj();
3725      gig::Instrument* instrument = file->AddInstrument();  #else
3726      __instrument_indexer++;  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
3727      instrument->pInfo->Name =  #endif
3728          _("Unnamed Instrument ") + ToString(__instrument_indexer);      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3729    #if !USE_GTKMM_BUILDER
3730            Gtk::Menu* script_popup =
3731                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
3732    #endif
3733            // update enabled/disabled state of sample popup items
3734            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3735            Gtk::TreeModel::iterator it = sel->get_selected();
3736            bool group_selected  = false;
3737            bool script_selected = false;
3738            if (it) {
3739                Gtk::TreeModel::Row row = *it;
3740                group_selected  = row[m_ScriptsModel.m_col_group];
3741                script_selected = row[m_ScriptsModel.m_col_script];
3742            }
3743    #if USE_GTKMM_BUILDER
3744            m_actionAddScript->property_enabled() = (group_selected || script_selected);
3745            m_actionAddScriptGroup->property_enabled() = (file);
3746            m_actionEditScript->property_enabled() = (script_selected);
3747            m_actionRemoveScript->property_enabled() = (group_selected || script_selected);
3748    #else
3749            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
3750                set_sensitive(group_selected || script_selected);
3751            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
3752                set_sensitive(file);
3753            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
3754                set_sensitive(script_selected);    
3755            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
3756                set_sensitive(group_selected || script_selected);
3757    #endif
3758            // show sample popup
3759            script_popup->popup(button->button, button->time);
3760    
3761    #if !USE_GTKMM_BUILDER
3762            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
3763                set_sensitive(group_selected || script_selected);
3764            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
3765                set_sensitive(file);
3766            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
3767                set_sensitive(script_selected);    
3768            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
3769                set_sensitive(group_selected || script_selected);
3770    #endif
3771        }
3772    #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
3773        return false;
3774    #endif
3775    }
3776    
3777    void MainWindow::updateScriptListOfMenu() {
3778        // remove all entries from "Assign Script" menu
3779        {
3780            const std::vector<Gtk::Widget*> children = assign_scripts_menu->get_children();
3781            for (int i = 0; i < children.size(); ++i) {
3782                Gtk::Widget* child = children[i];
3783                assign_scripts_menu->remove(*child);
3784                delete child;
3785            }
3786        }
3787    
3788        int iTotalScripts = 0;
3789    
3790        if (!file) goto noScripts;
3791    
3792        // add all configured macros as menu items to the "Macro" menu
3793        for (int iGroup = 0; file->GetScriptGroup(iGroup); ++iGroup) {
3794            gig::ScriptGroup* pGroup = file->GetScriptGroup(iGroup);
3795            for (int iScript = 0; pGroup->GetScript(iScript); ++iScript, ++iTotalScripts) {
3796                gig::Script* pScript = pGroup->GetScript(iScript);
3797                std::string name = pScript->Name;
3798    
3799                Gtk::MenuItem* item = new Gtk::MenuItem(name);
3800                item->signal_activate().connect(
3801                    sigc::bind(
3802                        sigc::mem_fun(*this, &MainWindow::assignScript), pScript
3803                    )
3804                );
3805                assign_scripts_menu->append(*item);
3806                item->set_accel_path("<Scripts>/script_" + ToString(iTotalScripts));
3807                //item->set_tooltip_text(comment);
3808            }
3809        }
3810    
3811        noScripts:
3812    
3813        // if there are no macros configured at all, then show a dummy entry instead
3814        if (!iTotalScripts) {
3815            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Scripts"));
3816            item->set_sensitive(false);
3817            assign_scripts_menu->append(*item);
3818        }
3819    
3820        // add separator line to menu
3821        assign_scripts_menu->append(*new Gtk::SeparatorMenuItem);
3822    
3823        {
3824            Gtk::MenuItem* item = new Gtk::MenuItem(_("Unassign All Scripts"));
3825            item->signal_activate().connect(
3826                sigc::mem_fun(*this, &MainWindow::dropAllScriptSlots)
3827            );
3828            assign_scripts_menu->append(*item);
3829            item->set_accel_path("<Scripts>/DropAllScriptSlots");
3830        }
3831    
3832    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3833        assign_scripts_menu->show_all_children();
3834    #endif
3835    }
3836    
3837    #if !USE_GTKMM_BUILDER
3838    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
3839        const Glib::ustring& name, int position) {
3840    
3841        Gtk::RadioMenuItem::Group instrument_group;
3842        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3843        if (!children.empty()) {
3844            instrument_group =
3845                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
3846        }
3847        Gtk::RadioMenuItem* item =
3848            new Gtk::RadioMenuItem(instrument_group, name);
3849        if (position < 0) {
3850            instrument_menu->append(*item);
3851        } else {
3852            instrument_menu->insert(*item, position);
3853        }
3854        item->show();
3855        item->signal_activate().connect(
3856            sigc::bind(
3857                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
3858                item));
3859        return item;
3860    }
3861    #endif
3862    
3863    #if !USE_GTKMM_BUILDER
3864    void MainWindow::remove_instrument_from_menu(int index) {
3865        const std::vector<Gtk::Widget*> children =
3866            instrument_menu->get_children();
3867        Gtk::Widget* child = children[index];
3868        instrument_menu->remove(*child);
3869        delete child;
3870    }
3871    #endif
3872    
3873    void MainWindow::add_instrument(gig::Instrument* instrument) {
3874        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3875    
3876      // update instrument tree view      // update instrument tree view
3877        instrument_name_connection.block();
3878      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
3879      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
3880      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      const int index = m_refTreeModel->children().size() - 1;
3881        rowInstr[m_Columns.m_col_nr] = index;
3882        rowInstr[m_Columns.m_col_name] = name;
3883      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
3884        rowInstr[m_Columns.m_col_scripts] = "";
3885        rowInstr[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3886        instrument_name_connection.unblock();
3887    
3888    #if !USE_GTKMM_BUILDER
3889        add_instrument_to_menu(name);
3890    #endif
3891        select_instrument(instrument);
3892      file_changed();      file_changed();
3893  }  }
3894    
3895    void MainWindow::on_action_add_instrument() {
3896        static int __instrument_indexer = 0;
3897        if (!file) return;
3898        gig::Instrument* instrument = file->AddInstrument();
3899        __instrument_indexer++;
3900        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
3901                                                ToString(__instrument_indexer));
3902    
3903        add_instrument(instrument);
3904    }
3905    
3906  void MainWindow::on_action_duplicate_instrument() {  void MainWindow::on_action_duplicate_instrument() {
3907      if (!file) return;      if (!file) return;
3908        
3909      // retrieve the currently selected instrument      // retrieve the currently selected instrument
3910      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
3911      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3912      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3913      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
3914      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
3915      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
3916      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
3917                    gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
3918      // duplicate the orginal instrument              if (instrOrig) {
3919      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
3920      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
3921          instrOrig->pInfo->Name + " (" + _("Copy") + ")";                  instrNew->pInfo->Name =
3922                                instrOrig->pInfo->Name +
3923      // update instrument tree view                      gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
3924      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();  
3925      Gtk::TreeModel::Row rowInstr = *iterInstr;                  add_instrument(instrNew);
3926      rowInstr[m_Columns.m_col_name] = instrNew->pInfo->Name.c_str();              }
3927      rowInstr[m_Columns.m_col_instr] = instrNew;          }
3928      file_changed();      }
3929  }  }
3930    
3931  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1373  void MainWindow::on_action_remove_instru Line 3942  void MainWindow::on_action_remove_instru
3942      }      }
3943    
3944      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3945      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3946      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3947            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
3948            if (!it) continue;
3949          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3950          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
3951          try {          try {
3952                Gtk::TreePath path(it);
3953                int index = path[0];
3954    
3955              // remove instrument from the gig file              // remove instrument from the gig file
3956              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
3957              file_changed();              file_changed();
3958    
3959    #if !USE_GTKMM_BUILDER
3960                remove_instrument_from_menu(index);
3961    #endif
3962    
3963                // remove row from instruments tree view
3964                m_refTreeModel->erase(it);
3965                // update "Nr" column of all instrument rows
3966                {
3967                    int index = 0;
3968                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
3969                         it != m_refTreeModel->children().end(); ++it, ++index)
3970                    {
3971                        Gtk::TreeModel::Row row = *it;
3972                        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3973                        row[m_Columns.m_col_nr] = index;
3974                        row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3975                    }
3976                }
3977    
3978    #if GTKMM_MAJOR_VERSION < 3
3979                // select another instrument (in gtk3 this is done
3980                // automatically)
3981                if (!m_refTreeModel->children().empty()) {
3982                    if (index == m_refTreeModel->children().size()) {
3983                        index--;
3984                    }
3985                    m_TreeView.get_selection()->select(
3986                        Gtk::TreePath(ToString(index)));
3987                }
3988    #endif
3989                instr_props_set_instrument();
3990                instr = get_instrument();
3991                if (instr) {
3992                    midiRules.set_instrument(instr);
3993                } else {
3994                    midiRules.hide();
3995                }
3996          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
3997              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3998              msg.run();              msg.run();
# Line 1398  void MainWindow::on_action_sample_proper Line 4008  void MainWindow::on_action_sample_proper
4008      msg.run();      msg.run();
4009  }  }
4010    
4011    void MainWindow::on_action_add_script_group() {
4012        static int __script_indexer = 0;
4013        if (!file) return;
4014        gig::ScriptGroup* group = file->AddScriptGroup();
4015        group->Name = gig_from_utf8(_("Unnamed Group"));
4016        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
4017        __script_indexer++;
4018        // update sample tree view
4019        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
4020        Gtk::TreeModel::Row rowGroup = *iterGroup;
4021        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
4022        rowGroup[m_ScriptsModel.m_col_script] = NULL;
4023        rowGroup[m_ScriptsModel.m_col_group] = group;
4024        file_changed();
4025    }
4026    
4027    void MainWindow::on_action_add_script() {
4028        if (!file) return;
4029        // get selected group
4030        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4031        Gtk::TreeModel::iterator it = sel->get_selected();
4032        if (!it) return;
4033        Gtk::TreeModel::Row row = *it;
4034        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4035        if (!group) { // not a group, but a script is selected (probably)
4036            gig::Script* script = row[m_ScriptsModel.m_col_script];
4037            if (!script) return;
4038            it = row.parent(); // resolve parent (that is the script's group)
4039            if (!it) return;
4040            row = *it;
4041            group = row[m_ScriptsModel.m_col_group];
4042            if (!group) return;
4043        }
4044    
4045        // add a new script to the .gig file
4046        gig::Script* script = group->AddScript();    
4047        Glib::ustring name = _("Unnamed Script");
4048        script->Name = gig_from_utf8(name);
4049    
4050        // add script to the tree view
4051        Gtk::TreeModel::iterator iterScript =
4052            m_refScriptsTreeModel->append(row.children());
4053        Gtk::TreeModel::Row rowScript = *iterScript;
4054        rowScript[m_ScriptsModel.m_col_name] = name;
4055        rowScript[m_ScriptsModel.m_col_script] = script;
4056        rowScript[m_ScriptsModel.m_col_group]  = NULL;
4057    
4058        // unfold group of new script item in treeview
4059        Gtk::TreeModel::Path path(iterScript);
4060        m_TreeViewScripts.expand_to_path(path);
4061    }
4062    
4063    void MainWindow::on_action_edit_script() {
4064        if (!file) return;
4065        // get selected script
4066        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4067        Gtk::TreeModel::iterator it = sel->get_selected();
4068        if (!it) return;
4069        Gtk::TreeModel::Row row = *it;
4070        gig::Script* script = row[m_ScriptsModel.m_col_script];
4071        if (!script) return;
4072    
4073        ScriptEditor* editor = new ScriptEditor;
4074        editor->signal_script_to_be_changed.connect(
4075            signal_script_to_be_changed.make_slot()
4076        );
4077        editor->signal_script_changed.connect(
4078            signal_script_changed.make_slot()
4079        );
4080        editor->setScript(script);
4081        //editor->reparent(*this);
4082        editor->show();
4083    }
4084    
4085    void MainWindow::on_action_remove_script() {
4086        if (!file) return;
4087        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4088        Gtk::TreeModel::iterator it = sel->get_selected();
4089        if (it) {
4090            Gtk::TreeModel::Row row = *it;
4091            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4092            gig::Script* script     = row[m_ScriptsModel.m_col_script];
4093            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
4094            try {
4095                // remove script group or script from the gig file
4096                if (group) {
4097                    // notify everybody that we're going to remove these samples
4098    //TODO:         scripts_to_be_removed_signal.emit(members);
4099                    // delete the group in the .gig file including the
4100                    // samples that belong to the group
4101                    file->DeleteScriptGroup(group);
4102                    // notify that we're done with removal
4103    //TODO:         scripts_removed_signal.emit();
4104                    file_changed();
4105                } else if (script) {
4106                    // notify everybody that we're going to remove this sample
4107    //TODO:         std::list<gig::Script*> lscripts;
4108    //TODO:         lscripts.push_back(script);
4109    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
4110                    // remove sample from the .gig file
4111                    script->GetGroup()->DeleteScript(script);
4112                    // notify that we're done with removal
4113    //TODO:         scripts_removed_signal.emit();
4114                    dimreg_changed();
4115                    file_changed();
4116                }
4117                // remove respective row(s) from samples tree view
4118                m_refScriptsTreeModel->erase(it);
4119            } catch (RIFF::Exception e) {
4120                // pretend we're done with removal (i.e. to avoid dead locks)
4121    //TODO:     scripts_removed_signal.emit();
4122                // show error message
4123                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4124                msg.run();
4125            }
4126        }
4127    }
4128    
4129  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
4130      static int __sample_indexer = 0;      static int __sample_indexer = 0;
4131      if (!file) return;      if (!file) return;
4132      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
4133      group->Name = _("Unnamed Group");      group->Name = gig_from_utf8(_("Unnamed Group"));
4134      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
4135      __sample_indexer++;      __sample_indexer++;
4136      // update sample tree view      // update sample tree view
4137      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
4138      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
4139      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
4140      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
4141      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
4142      file_changed();      file_changed();
4143  }  }
4144    
4145    void MainWindow::on_action_replace_sample() {
4146        add_or_replace_sample(true);
4147    }
4148    
4149  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
4150        add_or_replace_sample(false);
4151    }
4152    
4153    void MainWindow::add_or_replace_sample(bool replace) {
4154      if (!file) return;      if (!file) return;
4155      // get selected group  
4156        // get selected group (and probably selected sample)
4157      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4158      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4159        if (rows.empty()) return;
4160        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4161      if (!it) return;      if (!it) return;
4162      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
4163        gig::Sample* sample = NULL;
4164      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
4165      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
4166          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
4167          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
4168          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
4169          if (!it) return;          if (!it) return;
4170          row = *it;          if (!replace) row = *it;
4171          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
4172          if (!group) return;          if (!group) return;
4173      }      }
4174        if (replace && !sample) return;
4175    
4176      // show 'browse for file' dialog      // show 'browse for file' dialog
4177      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
4178    #if HAS_GTKMM_STOCK
4179      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4180      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
4181      dialog.set_select_multiple(true);  #else
4182        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4183        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
4184    #endif
4185        dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
4186    
4187      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
4188  #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 4224  void MainWindow::on_action_add_sample()
4224          dialog.set_current_folder(current_sample_dir);          dialog.set_current_folder(current_sample_dir);
4225      }      }
4226      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
4227            dialog.hide();
4228          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4229          Glib::ustring error_files;          Glib::ustring error_files;
4230          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
4231          for (std::vector<std::string>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
4232               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
4233              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
4234              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file information
4235              SF_INFO info;              SF_INFO info;
4236              info.format = 0;              info.format = 0;
4237              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 4254  void MainWindow::on_action_add_sample()
4254                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
4255                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
4256                  }                  }
4257                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
4258                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
4259                  // file name without path                  // file name without path
4260                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
4261                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1517  void MainWindow::on_action_add_sample() Line 4265  void MainWindow::on_action_add_sample()
4265                          break;                          break;
4266                      }                      }
4267                  }                  }
4268                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
4269                  sample->Channels = info.channels;                  sample->Channels = info.channels;
4270                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
4271                  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 4279  void MainWindow::on_action_add_sample()
4279                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
4280                  {                  {
4281                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
4282                        sample->FineTune      = instrument.detune;
4283    
4284                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
4285                          sample->Loops = 1;                          sample->Loops = 1;
# Line 1557  void MainWindow::on_action_add_sample() Line 4306  void MainWindow::on_action_add_sample()
4306                  // physically when File::Save() is called)                  // physically when File::Save() is called)
4307                  sample->Resize(info.frames);                  sample->Resize(info.frames);
4308                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
4309                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
4310                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
4311                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
4312                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4313                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4314                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
4315                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4316                  // add sample to the tree view                  // add sample to the tree view
4317                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
4318                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
4319                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
4320                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
4321                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
4322                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
4323                        rowSample[m_SamplesModel.m_col_name] =
4324                            gig_to_utf8(sample->pInfo->Name);
4325                        rowSample[m_SamplesModel.m_col_sample] = sample;
4326                        rowSample[m_SamplesModel.m_col_group]  = NULL;
4327                    }
4328                  // close sound file                  // close sound file
4329                  sf_close(hFile);                  sf_close(hFile);
4330                  file_changed();                  file_changed();
4331              } 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)
4332                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4333                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
4334              }              }
4335          }          }
4336          // 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
4337          if (error_files.size()) {          if (!error_files.empty()) {
4338              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
4339                    (replace
4340                        ? _("Failed to replace sample with:\n")
4341                        : _("Could not add the following sample(s):\n"))
4342                    + error_files;
4343              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4344              msg.run();              msg.run();
4345          }          }
# Line 1593  void MainWindow::on_action_replace_all_s Line 4351  void MainWindow::on_action_replace_all_s
4351      if (!file) return;      if (!file) return;
4352      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),      Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
4353                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);                                    Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
4354      const char* str =      const char* str =
4355          _("This is a very specific function. It tries to replace all samples "          _("This is a very specific function. It tries to replace all samples "
4356            "in the current gig file by samples located in the chosen "            "in the current gig file by samples located in the chosen "
4357            "directory.\n\n"            "directory.\n\n"
# Line 1614  void MainWindow::on_action_replace_all_s Line 4372  void MainWindow::on_action_replace_all_s
4372      Gtk::Label description(str);      Gtk::Label description(str);
4373      description.set_line_wrap();      description.set_line_wrap();
4374  #endif  #endif
4375      Gtk::HBox entryArea;      HBox entryArea;
4376      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);      Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
4377      Gtk::Entry postfixEntryBox;      Gtk::Entry postfixEntryBox;
4378      postfixEntryBox.set_text(".wav");      postfixEntryBox.set_text(".wav");
4379      entryArea.pack_start(entryLabel);      entryArea.pack_start(entryLabel);
4380      entryArea.pack_start(postfixEntryBox);      entryArea.pack_start(postfixEntryBox);
4381    #if USE_GTKMM_BOX
4382        dialog.get_content_area()->pack_start(description, Gtk::PACK_SHRINK);
4383        dialog.get_content_area()->pack_start(entryArea, Gtk::PACK_SHRINK);
4384    #else
4385      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
4386      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
4387    #endif
4388      description.show();      description.show();
4389    
4390    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4391      entryArea.show_all();      entryArea.show_all();
4392    #else
4393        entryArea.show();
4394    #endif
4395    
4396    #if HAS_GTKMM_STOCK
4397      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4398    #else
4399        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4400    #endif
4401      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
4402      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
4403      if (current_sample_dir != "") {      if (current_sample_dir != "") {
# Line 1632  void MainWindow::on_action_replace_all_s Line 4405  void MainWindow::on_action_replace_all_s
4405      }      }
4406      if (dialog.run() == Gtk::RESPONSE_OK)      if (dialog.run() == Gtk::RESPONSE_OK)
4407      {      {
4408            dialog.hide();
4409          current_sample_dir = dialog.get_current_folder();          current_sample_dir = dialog.get_current_folder();
4410          Glib::ustring error_files;          Glib::ustring error_files;
4411          std::string folder = dialog.get_filename();          std::string folder = dialog.get_filename();
# Line 1639  void MainWindow::on_action_replace_all_s Line 4413  void MainWindow::on_action_replace_all_s
4413               sample; sample = file->GetNextSample())               sample; sample = file->GetNextSample())
4414          {          {
4415              std::string filename =              std::string filename =
4416                  folder + G_DIR_SEPARATOR_S + sample->pInfo->Name +                  folder + G_DIR_SEPARATOR_S +
4417                  postfixEntryBox.get_text().raw();                  Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
4418                                             postfixEntryBox.get_text());
4419              SF_INFO info;              SF_INFO info;
4420              info.format = 0;              info.format = 0;
4421              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
4422              try              try
4423              {              {
4424                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
4425                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
4426                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
4427                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
4428                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
4429                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
4430                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
4431                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
4432                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
4433                          break;                          break;
4434                      default:                      default:
4435                          sf_close(hFile);                          sf_close(hFile);
# Line 1667  void MainWindow::on_action_replace_all_s Line 4438  void MainWindow::on_action_replace_all_s
4438                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4439                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4440                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
4441                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4442                  sf_close(hFile);                  sf_close(hFile);
4443                  file_changed();                  file_changed();
4444              }              }
4445              catch (std::string what)              catch (std::string what)
4446              {              {
4447                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4448                      error_files += filename += " (" + what + ")";                  error_files += Glib::filename_to_utf8(filename) +
4449                        " (" + what + ")";
4450              }              }
4451          }          }
4452          // 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
4453          if (error_files.size()) {          if (!error_files.empty()) {
4454              Glib::ustring txt =              Glib::ustring txt =
4455                  _("Could not replace the following sample(s):\n") + error_files;                  _("Could not replace the following sample(s):\n") + error_files;
4456              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 4462  void MainWindow::on_action_replace_all_s
4462  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
4463      if (!file) return;      if (!file) return;
4464      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4465      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4466      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4467            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4468            if (!it) continue;
4469          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4470          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
4471          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 4473  void MainWindow::on_action_remove_sample
4473          try {          try {
4474              // remove group or sample from the gig file              // remove group or sample from the gig file
4475              if (group) {              if (group) {
4476                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
4477                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
4478                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
4479                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1716  void MainWindow::on_action_remove_sample Line 4490  void MainWindow::on_action_remove_sample
4490                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
4491                  // them from the import queue                  // them from the import queue
4492                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
4493                       member != members.end(); ++member) {                       member != members.end(); ++member)
4494                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
4495                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
4496                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
4497                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
4498                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
4499                      }                      }
4500                  }                  }
4501                  file_changed();                  file_changed();
# Line 1739  void MainWindow::on_action_remove_sample Line 4510  void MainWindow::on_action_remove_sample
4510                  samples_removed_signal.emit();                  samples_removed_signal.emit();
4511                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
4512                  // the import queue                  // the import queue
4513                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
4514                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
4515                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
4516                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
4517                  }                  }
4518                  dimreg_changed();                  dimreg_changed();
4519                  file_changed();                  file_changed();
# Line 1763  void MainWindow::on_action_remove_sample Line 4530  void MainWindow::on_action_remove_sample
4530      }      }
4531  }  }
4532    
4533    void MainWindow::on_action_remove_unused_samples() {
4534        if (!file) return;
4535    
4536        // collect all samples that are not referenced by any instrument
4537        std::list<gig::Sample*> lsamples;
4538        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
4539            gig::Sample* sample = file->GetSample(iSample);
4540            bool isUsed = false;
4541            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
4542                                  instrument = file->GetNextInstrument())
4543            {
4544                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
4545                                  rgn = instrument->GetNextRegion())
4546                {
4547                    for (int i = 0; i < 256; ++i) {
4548                        if (!rgn->pDimensionRegions[i]) continue;
4549                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
4550                        isUsed = true;
4551                        goto endOfRefSearch;
4552                    }
4553                }
4554            }
4555            endOfRefSearch:
4556            if (!isUsed) lsamples.push_back(sample);
4557        }
4558    
4559        if (lsamples.empty()) return;
4560    
4561        // notify everybody that we're going to remove these samples
4562        samples_to_be_removed_signal.emit(lsamples);
4563    
4564        // remove collected samples
4565        try {
4566            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
4567                 itSample != lsamples.end(); ++itSample)
4568            {
4569                gig::Sample* sample = *itSample;
4570                // remove sample from the .gig file
4571                file->DeleteSample(sample);
4572                // if sample was just previously added, remove it from the import queue
4573                if (m_SampleImportQueue.count(sample)) {
4574                    printf("Removing previously added sample '%s'\n",
4575                           m_SampleImportQueue[sample].sample_path.c_str());
4576                    m_SampleImportQueue.erase(sample);
4577                }
4578            }
4579        } catch (RIFF::Exception e) {
4580            // show error message
4581            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4582            msg.run();
4583        }
4584    
4585        // notify everybody that we're done with removal
4586        samples_removed_signal.emit();
4587    
4588        dimreg_changed();
4589        file_changed();
4590        __refreshEntireGUI();
4591    }
4592    
4593    // see comment on on_sample_treeview_drag_begin()
4594    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4595    {
4596        first_call_to_drag_data_get = true;
4597    }
4598    
4599    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4600                                                       Gtk::SelectionData& selection_data, guint, guint)
4601    {
4602        if (!first_call_to_drag_data_get) return;
4603        first_call_to_drag_data_get = false;
4604    
4605        // get selected script
4606        gig::Script* script = NULL;
4607        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4608        Gtk::TreeModel::iterator it = sel->get_selected();
4609        if (it) {
4610            Gtk::TreeModel::Row row = *it;
4611            script = row[m_ScriptsModel.m_col_script];
4612        }
4613        // pass the gig::Script as pointer
4614        selection_data.set(selection_data.get_target(), 0/*unused*/,
4615                           (const guchar*)&script,
4616                           sizeof(script)/*length of data in bytes*/);
4617    }
4618    
4619    // see comment on on_sample_treeview_drag_begin()
4620    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4621    {
4622        first_call_to_drag_data_get = true;
4623    }
4624    
4625    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4626                                                           Gtk::SelectionData& selection_data, guint, guint)
4627    {
4628        if (!first_call_to_drag_data_get) return;
4629        first_call_to_drag_data_get = false;
4630    
4631        // get selected source instrument
4632        gig::Instrument* src = NULL;
4633        {
4634            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4635            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4636            if (!rows.empty()) {
4637                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
4638                if (it) {
4639                    Gtk::TreeModel::Row row = *it;
4640                    src = row[m_Columns.m_col_instr];
4641                }
4642            }
4643        }
4644        if (!src) return;
4645    
4646        // pass the source gig::Instrument as pointer
4647        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
4648                           sizeof(src)/*length of data in bytes*/);
4649    }
4650    
4651    void MainWindow::on_instruments_treeview_drop_drag_data_received(
4652        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
4653        const Gtk::SelectionData& selection_data, guint, guint time)
4654    {
4655        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
4656        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
4657            return;
4658    
4659        gig::Instrument* dst = NULL;
4660        {
4661            Gtk::TreeModel::Path path;
4662            const bool found = m_TreeView.get_path_at_pos(x, y, path);
4663            if (!found) return;
4664    
4665            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
4666            if (!iter) return;
4667            Gtk::TreeModel::Row row = *iter;
4668            dst = row[m_Columns.m_col_instr];
4669        }
4670        if (!dst) return;
4671    
4672        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
4673        src->MoveTo(dst);
4674        __refreshEntireGUI();
4675        select_instrument(src);
4676    }
4677    
4678  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
4679  // 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
4680  // 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 4693  void MainWindow::on_sample_treeview_drag
4693      // get selected sample      // get selected sample
4694      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
4695      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4696      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4697      if (it) {      if (!rows.empty()) {
4698          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4699          sample = row[m_SamplesModel.m_col_sample];          if (it) {
4700                Gtk::TreeModel::Row row = *it;
4701                sample = row[m_SamplesModel.m_col_sample];
4702            }
4703      }      }
4704      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
4705      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 4736  void MainWindow::on_sample_label_drop_dr
4736          bool channels_changed = false;          bool channels_changed = false;
4737          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
4738              // remove the samplechannel dimension              // remove the samplechannel dimension
4739    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
4740              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
4741              channels_changed = true;              channels_changed = true;
4742              region_changed();              region_changed();
4743    */
4744          }          }
4745          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
4746                sample,
4747                is_copy_samples_unity_note_enabled(),
4748                is_copy_samples_fine_tune_enabled(),
4749                is_copy_samples_loop_enabled()
4750            );
4751    
4752          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
4753              // add samplechannel dimension              // add samplechannel dimension
# Line 1868  void MainWindow::sample_name_changed(con Line 4790  void MainWindow::sample_name_changed(con
4790      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
4791      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
4792      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
4793        gig::String gigname(gig_from_utf8(name));
4794      if (group) {      if (group) {
4795          if (group->Name != name) {          if (group->Name != gigname) {
4796              group->Name = name;              group->Name = gigname;
4797              printf("group name changed\n");              printf("group name changed\n");
4798              file_changed();              file_changed();
4799          }          }
4800      } else if (sample) {      } else if (sample) {
4801          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
4802              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
4803              printf("sample name changed\n");              printf("sample name changed\n");
4804              file_changed();              file_changed();
4805          }          }
4806      }      }
4807  }  }
4808    
4809    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
4810                                         const Gtk::TreeModel::iterator& iter) {
4811        if (!iter) return;
4812        Gtk::TreeModel::Row row = *iter;
4813        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
4814        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4815        gig::Script* script     = row[m_ScriptsModel.m_col_script];
4816        gig::String gigname(gig_from_utf8(name));
4817        if (group) {
4818            if (group->Name != gigname) {
4819                group->Name = gigname;
4820                printf("script group name changed\n");
4821                file_changed();
4822            }
4823        } else if (script) {
4824            if (script->Name != gigname) {
4825                script->Name = gigname;
4826                printf("script name changed\n");
4827                file_changed();
4828            }
4829        }
4830    }
4831    
4832    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
4833                                           Gtk::TreeViewColumn* column)
4834    {
4835        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
4836        if (!iter) return;
4837        Gtk::TreeModel::Row row = *iter;
4838        gig::Script* script = row[m_ScriptsModel.m_col_script];
4839        if (!script) return;
4840    
4841        ScriptEditor* editor = new ScriptEditor;
4842        editor->signal_script_to_be_changed.connect(
4843            signal_script_to_be_changed.make_slot()
4844        );
4845        editor->signal_script_changed.connect(
4846            signal_script_changed.make_slot()
4847        );
4848        editor->setScript(script);
4849        //editor->reparent(*this);
4850        editor->show();
4851    }
4852    
4853  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
4854                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
4855      if (!iter) return;      if (!iter) return;
4856      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
4857      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
4858    
4859    #if !USE_GTKMM_BUILDER
4860        // change name in instrument menu
4861        int index = path[0];
4862        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
4863        if (index < children.size()) {
4864    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
4865            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
4866    #else
4867            remove_instrument_from_menu(index);
4868            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
4869            item->set_active();
4870    #endif
4871        }
4872    #endif
4873    
4874        // change name in gig
4875      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
4876      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
4877          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
4878            instrument->pInfo->Name = gigname;
4879    
4880            // change name in the instrument properties window
4881            if (instrumentProps.get_instrument() == instrument) {
4882                instrumentProps.update_name();
4883            }
4884    
4885          file_changed();          file_changed();
4886      }      }
4887  }  }
4888    
4889    bool MainWindow::instrument_row_visible(const Gtk::TreeModel::const_iterator& iter) {
4890        if (!iter)
4891            return true;
4892    
4893        Glib::ustring pattern = m_searchText.get_text().lowercase();
4894        trim(pattern);
4895        if (pattern.empty()) return true;
4896    
4897    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
4898        //HACK: on GTKMM4 development branch const_iterator cannot be easily converted to iterator, probably going to be fixed before final GTKMM4 release though.
4899        Gtk::TreeModel::Row row = **(Gtk::TreeModel::iterator*)(&iter);
4900    #else
4901        Gtk::TreeModel::Row row = *iter;
4902    #endif
4903        Glib::ustring name = row[m_Columns.m_col_name];
4904        name = name.lowercase();
4905    
4906        std::vector<Glib::ustring> tokens = Glib::Regex::split_simple(" ", pattern);
4907        for (int t = 0; t < tokens.size(); ++t)
4908            if (name.find(tokens[t]) == Glib::ustring::npos)
4909                return false;
4910    
4911        return true;
4912    }
4913    
4914    void MainWindow::on_action_combine_instruments() {
4915        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
4916    
4917        // take over selection from instruments list view for the combine dialog's
4918        // list view as pre-selection
4919        std::set<int> indeces;
4920        {
4921            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4922            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4923            for (int r = 0; r < rows.size(); ++r) {
4924                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
4925                if (it) {
4926                    Gtk::TreeModel::Row row = *it;
4927                    int index = row[m_Columns.m_col_nr];
4928                    indeces.insert(index);
4929                }
4930            }
4931        }
4932        d->setSelectedInstruments(indeces);
4933    
4934    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4935        d->show_all();
4936    #else
4937        d->show();
4938    #endif
4939        d->run();
4940        if (d->fileWasChanged()) {
4941            // update GUI with new instrument just created
4942            add_instrument(d->newCombinedInstrument());
4943        }
4944        delete d;
4945    }
4946    
4947    void MainWindow::on_action_view_references() {
4948        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4949        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4950        if (rows.empty()) return;
4951        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4952        if (!it) return;
4953        Gtk::TreeModel::Row row = *it;
4954        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
4955        if (!sample) return;
4956    
4957        ReferencesView* d = new ReferencesView(*this);
4958        d->setSample(sample);
4959        d->dimension_region_selected.connect(
4960            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
4961        );
4962    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4963        d->show_all();
4964    #else
4965        d->show();
4966    #endif
4967        d->resize(500, 400);
4968        d->run();
4969        delete d;
4970    }
4971    
4972    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
4973        struct _Source {
4974            std::vector<RIFF::File*> riffs;
4975            std::vector<gig::File*> gigs;
4976            
4977            ~_Source() {
4978                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
4979                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
4980                riffs.clear();
4981                gigs.clear();
4982            }
4983        } sources;
4984    
4985        if (filenames.empty())
4986            throw RIFF::Exception(_("No files selected, so nothing done."));
4987    
4988        // first open all input files (to avoid output file corruption)
4989        int i;
4990        try {
4991            for (i = 0; i < filenames.size(); ++i) {
4992                const std::string& filename = filenames[i];
4993                printf("opening file=%s\n", filename.c_str());
4994    
4995                RIFF::File* riff = new RIFF::File(filename);
4996                sources.riffs.push_back(riff);
4997    
4998                gig::File* gig = new gig::File(riff);
4999                sources.gigs.push_back(gig);
5000            }
5001        } catch (RIFF::Exception e) {
5002            throw RIFF::Exception(
5003                _("Error occurred while opening '") +
5004                filenames[i] +
5005                "': " +
5006                e.Message
5007            );
5008        } catch (...) {
5009            throw RIFF::Exception(
5010                _("Unknown exception occurred while opening '") +
5011                filenames[i] + "'"
5012            );
5013        }
5014    
5015        // now merge the opened .gig files to the main .gig file currently being
5016        // open in gigedit
5017        try {
5018            for (i = 0; i < filenames.size(); ++i) {
5019                const std::string& filename = filenames[i];
5020                printf("merging file=%s\n", filename.c_str());
5021                assert(i < sources.gigs.size());
5022    
5023                this->file->AddContentOf(sources.gigs[i]);
5024            }
5025        } catch (RIFF::Exception e) {
5026            throw RIFF::Exception(
5027                _("Error occurred while merging '") +
5028                filenames[i] +
5029                "': " +
5030                e.Message
5031            );
5032        } catch (...) {
5033            throw RIFF::Exception(
5034                _("Unknown exception occurred while merging '") +
5035                filenames[i] + "'"
5036            );
5037        }
5038    
5039        // Finally save gig file persistently to disk ...
5040        //NOTE: requires that this gig file already has a filename !
5041        {
5042            std::cout << "Saving file\n" << std::flush;
5043            file_structure_to_be_changed_signal.emit(this->file);
5044    
5045            progress_dialog = new ProgressDialog( //FIXME: memory leak!
5046                _("Saving") +  Glib::ustring(" '") +
5047                Glib::filename_display_basename(this->filename) + "' ...",
5048                *this
5049            );
5050    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5051            progress_dialog->show_all();
5052    #else
5053            progress_dialog->show();
5054    #endif
5055            saver = new Saver(this->file); //FIXME: memory leak!
5056            saver->signal_progress().connect(
5057                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
5058            saver->signal_finished().connect(
5059                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
5060            saver->signal_error().connect(
5061                sigc::mem_fun(*this, &MainWindow::on_saver_error));
5062            saver->launch();
5063        }
5064    }
5065    
5066    void MainWindow::on_action_merge_files() {
5067        if (this->file->GetFileName().empty()) {
5068            Glib::ustring txt = _(
5069                "You seem to have a new .gig file open that has not been saved "
5070                "yet. You must save it somewhere before starting to merge it with "
5071                "other .gig files though, because during the merge operation the "
5072                "other files' sample data must be written on file level to the "
5073                "target .gig file."
5074            );
5075            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5076            msg.run();
5077            return;
5078        }
5079    
5080        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
5081    #if HAS_GTKMM_STOCK
5082        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
5083    #else
5084        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
5085    #endif
5086        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
5087        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
5088    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
5089        Gtk::FileFilter filter;
5090        filter.add_pattern("*.gig");
5091    #else
5092        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
5093        filter->add_pattern("*.gig");
5094    #endif
5095        dialog.set_filter(filter);
5096        if (current_gig_dir != "") {
5097            dialog.set_current_folder(current_gig_dir);
5098        }
5099        dialog.set_select_multiple(true);
5100    
5101        // show warning in the file picker dialog
5102        HBox descriptionArea;
5103        descriptionArea.set_spacing(15);
5104        Gtk::Image warningIcon;
5105        warningIcon.set_from_icon_name("dialog-warning",
5106                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
5107        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
5108    #if GTKMM_MAJOR_VERSION < 3
5109        view::WrapLabel description;
5110    #else
5111        Gtk::Label description;
5112        description.set_line_wrap();
5113    #endif
5114        description.set_markup(_(
5115            "\nSelect at least one .gig file that shall be merged to the .gig file "
5116            "currently being open in gigedit.\n\n"
5117            "<b>Please Note:</b> Merging with other files will modify your "
5118            "currently open .gig file on file level! And be aware that the current "
5119            "merge algorithm does not detect duplicate samples yet. So if you are "
5120            "merging files which are using equivalent sample data, those "
5121            "equivalent samples will currently be treated as separate samples and "
5122            "will accordingly be stored separately in the target .gig file!"
5123        ));
5124        descriptionArea.pack_start(description);
5125    #if USE_GTKMM_BOX
5126    # warning No description area implemented for dialog on GTKMM 3
5127    #else
5128        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
5129    #endif
5130    #if HAS_GTKMM_SHOW_ALL_CHILDREN
5131        descriptionArea.show_all();
5132    #else
5133        descriptionArea.show();
5134    #endif
5135    
5136        if (dialog.run() == Gtk::RESPONSE_OK) {
5137            dialog.hide();
5138    #ifdef GLIB_THREADS
5139            printf("on_action_merge_files self=%p\n",
5140                   static_cast<void*>(Glib::Threads::Thread::self()));
5141    #else
5142            std::cout << "on_action_merge_files self=" <<
5143                std::this_thread::get_id() << "\n";
5144    #endif
5145            std::vector<std::string> filenames = dialog.get_filenames();
5146    
5147            // merge the selected files to the currently open .gig file
5148            try {
5149                mergeFiles(filenames);
5150            } catch (RIFF::Exception e) {
5151                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
5152                msg.run();
5153            }
5154    
5155            // update GUI
5156            __refreshEntireGUI();
5157        }
5158    }
5159    
5160  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
5161      this->file_is_shared = b;      this->file_is_shared = b;
5162    
# Line 1909  void MainWindow::set_file_is_shared(bool Line 5171  void MainWindow::set_file_is_shared(bool
5171              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
5172          );          );
5173      }      }
5174    
5175        {
5176    #if USE_GTKMM_BUILDER
5177            m_actionToggleSyncSamplerSelection->property_enabled() = b;
5178    #else
5179            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
5180                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
5181            if (item) item->set_sensitive(b);
5182    #endif
5183        }
5184    }
5185    
5186    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
5187        if (!sample) return;
5188        sample_ref_count[sample] += offset;
5189        const int refcount = sample_ref_count[sample];
5190    
5191        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
5192        for (int g = 0; g < model->children().size(); ++g) {
5193            Gtk::TreeModel::Row rowGroup = model->children()[g];
5194            for (int s = 0; s < rowGroup.children().size(); ++s) {
5195                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
5196                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
5197                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
5198                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
5199            }
5200        }
5201    }
5202    
5203    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
5204        on_sample_ref_count_incremented(oldSample, -1);
5205        on_sample_ref_count_incremented(newSample, +1);
5206    }
5207    
5208    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
5209        // just in case a new sample is added later with exactly the same memory
5210        // address, which would lead to incorrect refcount if not deleted here
5211        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
5212             it != samples.end(); ++it)
5213        {
5214            sample_ref_count.erase(*it);
5215        }
5216    }
5217    
5218    void MainWindow::show_samples_tab() {
5219        m_TreeViewNotebook.set_current_page(0);
5220    }
5221    
5222    void MainWindow::show_intruments_tab() {
5223        m_TreeViewNotebook.set_current_page(1);
5224    }
5225    
5226    void MainWindow::show_scripts_tab() {
5227        m_TreeViewNotebook.set_current_page(2);
5228    }
5229    
5230    void MainWindow::select_instrument_by_dir(int dir) {
5231        if (!file) return;
5232        gig::Instrument* pInstrument = get_instrument();
5233        if (!pInstrument) {
5234            select_instrument( file->GetInstrument(0) );
5235            return;
5236        }
5237        for (int i = 0; file->GetInstrument(i); ++i) {
5238            if (file->GetInstrument(i) == pInstrument) {
5239                select_instrument( file->GetInstrument(i + dir) );
5240                return;
5241            }
5242        }
5243    }
5244    
5245    void MainWindow::select_prev_instrument() {
5246        select_instrument_by_dir(-1);
5247    }
5248    
5249    void MainWindow::select_next_instrument() {
5250        select_instrument_by_dir(1);
5251    }
5252    
5253    void MainWindow::select_prev_region() {
5254        m_RegionChooser.select_prev_region();
5255    }
5256    
5257    void MainWindow::select_next_region() {
5258        m_RegionChooser.select_next_region();
5259    }
5260    
5261    void MainWindow::select_next_dim_rgn_zone() {
5262        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5263        m_DimRegionChooser.select_next_dimzone();
5264    }
5265    
5266    void MainWindow::select_prev_dim_rgn_zone() {
5267        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5268        m_DimRegionChooser.select_prev_dimzone();
5269    }
5270    
5271    void MainWindow::select_add_next_dim_rgn_zone() {
5272        m_DimRegionChooser.select_next_dimzone(true);
5273    }
5274    
5275    void MainWindow::select_add_prev_dim_rgn_zone() {
5276        m_DimRegionChooser.select_prev_dimzone(true);
5277    }
5278    
5279    void MainWindow::select_prev_dimension() {
5280        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5281        m_DimRegionChooser.select_prev_dimension();
5282    }
5283    
5284    void MainWindow::select_next_dimension() {
5285        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5286        m_DimRegionChooser.select_next_dimension();
5287    }
5288    
5289    #define CLIPBOARD_DIMENSIONREGION_TARGET \
5290        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
5291    
5292    void MainWindow::copy_selected_dimrgn() {
5293        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5294        if (!pDimRgn) {
5295            updateClipboardPasteAvailable();
5296            updateClipboardCopyAvailable();
5297            return;
5298        }
5299    
5300        std::vector<Gtk::TargetEntry> targets;
5301        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
5302    
5303        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5304        clipboard->set(
5305            targets,
5306            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
5307            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
5308        );
5309    
5310        m_serializationArchive.serialize(pDimRgn);
5311    
5312        updateClipboardPasteAvailable();
5313    }
5314    
5315    void MainWindow::paste_copied_dimrgn() {
5316        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5317        clipboard->request_contents(
5318            CLIPBOARD_DIMENSIONREGION_TARGET,
5319            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
5320        );
5321        updateClipboardPasteAvailable();
5322    }
5323    
5324    void MainWindow::adjust_clipboard_content() {
5325        MacroEditor* editor = new MacroEditor();
5326        editor->setMacro(&m_serializationArchive, true);
5327        editor->show();
5328    }
5329    
5330    void MainWindow::updateClipboardPasteAvailable() {
5331        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5332        clipboard->request_targets(
5333            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
5334        );
5335    }
5336    
5337    void MainWindow::updateClipboardCopyAvailable() {
5338        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
5339    #if USE_GTKMM_BUILDER
5340        m_actionCopyDimRgn->property_enabled() = bDimensionRegionCopyIsPossible;
5341    #else
5342        static_cast<Gtk::MenuItem*>(
5343            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
5344        )->set_sensitive(bDimensionRegionCopyIsPossible);
5345    #endif
5346    }
5347    
5348    #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
5349    void MainWindow::on_clipboard_owner_change(Gdk::EventOwnerChange& event) {
5350    #else
5351    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
5352    #endif
5353        updateClipboardPasteAvailable();
5354    }
5355    
5356    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
5357        const std::string target = selection_data.get_target();
5358        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5359            selection_data.set(
5360                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
5361                &m_serializationArchive.rawData()[0],
5362                m_serializationArchive.rawData().size()
5363            );
5364        } else {
5365            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
5366        }
5367    }
5368    
5369    void MainWindow::on_clipboard_clear() {
5370        m_serializationArchive.clear();
5371        updateClipboardPasteAvailable();
5372        updateClipboardCopyAvailable();
5373    }
5374    
5375    //NOTE: Might throw exception !!!
5376    void MainWindow::applyMacro(Serialization::Archive& macro) {
5377        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5378        if (!pDimRgn) return;
5379    
5380        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
5381             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
5382        {
5383            gig::DimensionRegion* pDimRgn = *itDimReg;
5384            DimRegionChangeGuard(this, pDimRgn);
5385            macro.deserialize(pDimRgn);
5386        }
5387        //region_changed()
5388        file_changed();
5389        dimreg_changed();
5390    }
5391    
5392    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
5393        const std::string target = selection_data.get_target();
5394        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5395            Glib::ustring errorText;
5396            try {
5397                m_serializationArchive.decode(
5398                    selection_data.get_data(), selection_data.get_length()
5399                );
5400                applyMacro(m_serializationArchive);
5401            } catch (Serialization::Exception e) {
5402                errorText = e.Message;
5403            } catch (...) {
5404                errorText = _("Unknown exception while pasting DimensionRegion");
5405            }
5406            if (!errorText.empty()) {
5407                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
5408                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5409                msg.run();
5410            }
5411        }
5412    }
5413    
5414    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
5415        const bool bDimensionRegionPasteIsPossible =
5416            std::find(targets.begin(), targets.end(),
5417                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
5418    
5419    #if USE_GTKMM_BUILDER
5420        m_actionPasteDimRgn->property_enabled() = bDimensionRegionPasteIsPossible;
5421        m_actionAdjustClipboard->property_enabled() = bDimensionRegionPasteIsPossible;
5422    #else
5423        static_cast<Gtk::MenuItem*>(
5424            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
5425        )->set_sensitive(bDimensionRegionPasteIsPossible);
5426    
5427        static_cast<Gtk::MenuItem*>(
5428            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
5429        )->set_sensitive(bDimensionRegionPasteIsPossible);
5430    #endif
5431  }  }
5432    
5433  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 5485  sigc::signal<void, int/*key*/, int/*velo
5485  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
5486      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
5487  }  }
5488    
5489    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
5490        return switch_sampler_instrument_signal;
5491    }

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

  ViewVC Help
Powered by ViewVC