/[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 1661 by schoenebeck, Sun Feb 3 14:10:47 2008 UTC revision 3471 by persson, Sat Feb 16 19:13:37 2019 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006 - 2008 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 18  Line 18 
18   */   */
19    
20  #include <iostream>  #include <iostream>
21    #include <cstring>
22    
23    #include "compat.h"
24    // threads.h must be included first to be able to build with
25    // G_DISABLE_DEPRECATED
26    #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION == 31 && GLIBMM_MICRO_VERSION >= 2) || \
27        (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION > 31) || GLIBMM_MAJOR_VERSION > 2
28    #include <glibmm/threads.h>
29    #endif
30    
31    #include <glibmm/convert.h>
32    #include <glibmm/dispatcher.h>
33    #include <glibmm/miscutils.h>
34    #include <glibmm/stringutils.h>
35    #include <glibmm/regex.h>
36    #include <gtkmm/aboutdialog.h>
37  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
38  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
39  #include <gtkmm/stock.h>  #if HAS_GTKMM_STOCK
40    # include <gtkmm/stock.h>
41    #endif
42  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
43  #include <gtkmm/main.h>  #include <gtkmm/main.h>
44  #include <gtkmm/toggleaction.h>  #if GTKMM_MAJOR_VERSION < 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION < 89)
45    # include <gtkmm/toggleaction.h>
 #include "global.h"  
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
 #define ABOUT_DIALOG  
 #include <gtkmm/aboutdialog.h>  
46  #endif  #endif
47    #include <gtkmm/accelmap.h>
48  #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2  #if GTKMM_MAJOR_VERSION < 3
49  namespace Glib {  #include "wrapLabel.hh"
 Glib::ustring filename_display_basename(const std::string& filename)  
 {  
     gchar* gstr = g_path_get_basename(filename.c_str());  
     Glib::ustring str(gstr);  
     g_free(gstr);  
     return Glib::filename_to_utf8(str);  
 }  
 }  
50  #endif  #endif
51    
52    #include "global.h"
53    #include "compat.h"
54    
55  #include <stdio.h>  #include <stdio.h>
56  #include <sndfile.h>  #ifdef LIBSNDFILE_HEADER_FILE
57    # include LIBSNDFILE_HEADER_FILE(sndfile.h)
58    #else
59    # include <sndfile.h>
60    #endif
61    #include <assert.h>
62    
63  #include "mainwindow.h"  #include "mainwindow.h"
64    #include "Settings.h"
65    #include "CombineInstrumentsDialog.h"
66    #include "scripteditor.h"
67    #include "scriptslots.h"
68    #include "ReferencesView.h"
69  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
70  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
71    #include "gfx/builtinpix.h"
72    #include "MacroEditor.h"
73    #include "MacrosSetup.h"
74    #if defined(__APPLE__)
75    # include "MacHelper.h"
76    #endif
77    
78  template<class T> inline std::string ToString(T o) {  static const Gdk::ModifierType primaryModifierKey =
79      std::stringstream ss;      #if defined(__APPLE__)
80      ss << o;      Gdk::META_MASK; // Cmd key on Mac
81      return ss.str();      #else
82  }      Gdk::CONTROL_MASK; // Ctrl key on all other OSs
83        #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++;  
 }  
84    
85  MainWindow::MainWindow() :  MainWindow::MainWindow() :
86        m_DimRegionChooser(*this),
87      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
88      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
89      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
90      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
91        labelLegend(_("Legend:")),
92        labelNoSample(_(" No Sample")),
93        labelMissingSample(_(" Missing some Sample(s)")),
94        labelLooped(_(" Looped")),
95        labelSomeLoops(_(" Some Loop(s)"))
96  {  {
97        loadBuiltInPix();
98    
99        this->file = NULL;
100    
101  //    set_border_width(5);  //    set_border_width(5);
 //    set_default_size(400, 200);  
102    
103        if (!Settings::singleton()->autoRestoreWindowDimension) {
104    #if GTKMM_MAJOR_VERSION >= 3
105            set_default_size(895, 600);
106    #else
107            set_default_size(800, 600);
108    #endif
109            set_position(Gtk::WIN_POS_CENTER);
110        }
111    
112      add(m_VBox);      add(m_VBox);
113    
114      // Handle selection      // Handle selection
115      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
116          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
117    
118      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
119    
120    #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
121        m_TreeView.signal_button_press_event().connect(
122            sigc::mem_fun(*this, &MainWindow::on_button_release));
123    #else
124      m_TreeView.signal_button_press_event().connect_notify(      m_TreeView.signal_button_press_event().connect_notify(
125          sigc::mem_fun(*this, &MainWindow::on_button_release));          sigc::mem_fun(*this, &MainWindow::on_button_release));
126    #endif
127    
128      // Add the TreeView tab, inside a ScrolledWindow, with the button underneath:      // Add the TreeView tab, inside a ScrolledWindow, with the button underneath:
129      m_ScrolledWindow.add(m_TreeView);      m_ScrolledWindow.add(m_TreeView);
# Line 114  MainWindow::MainWindow() : Line 133  MainWindow::MainWindow() :
133      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
134      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
135    
136        m_ScrolledWindowScripts.add(m_TreeViewScripts);
137        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
138    
139    #if GTKMM_MAJOR_VERSION < 3
140      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
141    #endif
142    
143        m_searchLabel.set_text(Glib::ustring(" ") + _("Filter:"));
144        m_searchField.pack_start(m_searchLabel, Gtk::PACK_SHRINK);
145        m_searchField.pack_start(m_searchText);
146        m_searchField.set_spacing(5);
147    
148        m_left_vbox.pack_start(m_TreeViewNotebook);
149        m_left_vbox.pack_start(m_searchField, Gtk::PACK_SHRINK);
150    
151        m_HPaned.add1(m_left_vbox);
152    
     m_HPaned.add1(m_TreeViewNotebook);  
153      dimreg_hbox.add(dimreg_label);      dimreg_hbox.add(dimreg_label);
154      dimreg_hbox.add(dimreg_all_regions);      dimreg_hbox.add(dimreg_all_regions);
155      dimreg_hbox.add(dimreg_all_dimregs);      dimreg_hbox.add(dimreg_all_dimregs);
# Line 125  MainWindow::MainWindow() : Line 157  MainWindow::MainWindow() :
157      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
158      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
159      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
160      m_HPaned.add2(dimreg_vbox);      {
161            legend_hbox.add(labelLegend);
162    
163            imageNoSample.set(redDot);
164    #if HAS_GTKMM_ALIGNMENT
165            imageNoSample.set_alignment(Gtk::ALIGN_END);
166            labelNoSample.set_alignment(Gtk::ALIGN_START);
167    #else
168            imageNoSample.set_halign(Gtk::ALIGN_END);
169            labelNoSample.set_halign(Gtk::ALIGN_START);
170    #endif
171            legend_hbox.add(imageNoSample);
172            legend_hbox.add(labelNoSample);
173    
174            imageMissingSample.set(yellowDot);
175    #if HAS_GTKMM_ALIGNMENT
176            imageMissingSample.set_alignment(Gtk::ALIGN_END);
177            labelMissingSample.set_alignment(Gtk::ALIGN_START);
178    #else
179            imageMissingSample.set_halign(Gtk::ALIGN_END);
180            labelMissingSample.set_halign(Gtk::ALIGN_START);
181    #endif
182            legend_hbox.add(imageMissingSample);
183            legend_hbox.add(labelMissingSample);
184    
185            imageLooped.set(blackLoop);
186    #if HAS_GTKMM_ALIGNMENT
187            imageLooped.set_alignment(Gtk::ALIGN_END);
188            labelLooped.set_alignment(Gtk::ALIGN_START);
189    #else
190            imageLooped.set_halign(Gtk::ALIGN_END);
191            labelLooped.set_halign(Gtk::ALIGN_START);
192    #endif
193            legend_hbox.add(imageLooped);
194            legend_hbox.add(labelLooped);
195    
196      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");          imageSomeLoops.set(grayLoop);
197      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");  #if HAS_GTKMM_ALIGNMENT
198            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
199            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
200    #else
201            imageSomeLoops.set_halign(Gtk::ALIGN_END);
202            labelSomeLoops.set_halign(Gtk::ALIGN_START);
203    #endif
204            legend_hbox.add(imageSomeLoops);
205            legend_hbox.add(labelSomeLoops);
206    
207    #if HAS_GTKMM_SHOW_ALL_CHILDREN
208            legend_hbox.show_all_children();
209    #endif
210        }
211        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
212        m_HPaned.add2(dimreg_vbox);
213    
214        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
215        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."));
216        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."));
217        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)."));
218    
219        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
220        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
221        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
222    
223    #if USE_GLIB_ACTION
224        m_actionGroup = Gio::SimpleActionGroup::create();
225        m_actionGroup->add_action(
226            "New", sigc::mem_fun(*this, &MainWindow::on_action_file_new)
227        );
228        m_actionGroup->add_action(
229            "Open", sigc::mem_fun(*this, &MainWindow::on_action_file_open)
230        );
231        m_actionGroup->add_action(
232            "Save", sigc::mem_fun(*this, &MainWindow::on_action_file_save)
233        );
234        m_actionGroup->add_action(
235            "SaveAs", sigc::mem_fun(*this, &MainWindow::on_action_file_save_as)
236        );
237        m_actionGroup->add_action(
238            "Properties", sigc::mem_fun(*this, &MainWindow::on_action_file_properties)
239        );
240        m_actionGroup->add_action(
241            "InstrProperties", sigc::mem_fun(*this, &MainWindow::show_instr_props)
242        );
243        m_actionMIDIRules = m_actionGroup->add_action(
244            "MidiRules", sigc::mem_fun(*this, &MainWindow::show_midi_rules)
245        );
246        m_actionGroup->add_action(
247            "ScriptSlots", sigc::mem_fun(*this, &MainWindow::show_script_slots)
248        );
249        m_actionGroup->add_action(
250            "Quit", sigc::mem_fun(*this, &MainWindow::on_action_quit)
251        );
252        m_actionGroup->add_action(
253            "MenuSample", sigc::mem_fun(*this, &MainWindow::show_samples_tab)
254        );
255        m_actionGroup->add_action(
256            "MenuInstrument", sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
257        );
258        m_actionGroup->add_action(
259            "MenuScript", sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
260        );
261    #else
262      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
263    
264      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
# Line 161  MainWindow::MainWindow() : Line 288  MainWindow::MainWindow() :
288                                           Gtk::Stock::PROPERTIES),                                           Gtk::Stock::PROPERTIES),
289                       sigc::mem_fun(                       sigc::mem_fun(
290                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
291        actionGroup->add(Gtk::Action::create("MidiRules",
292                                             _("_Midi Rules...")),
293                         sigc::mem_fun(
294                             *this, &MainWindow::show_midi_rules));
295        actionGroup->add(Gtk::Action::create("ScriptSlots",
296                                             _("_Script Slots...")),
297                         sigc::mem_fun(
298                             *this, &MainWindow::show_script_slots));
299      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
300                       sigc::mem_fun(                       sigc::mem_fun(
301                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
302      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
303            Gtk::Action::create("MenuSample", _("_Sample")),
304            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
305        );
306        actionGroup->add(
307            Gtk::Action::create("MenuInstrument", _("_Instrument")),
308            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
309        );
310        actionGroup->add(
311            Gtk::Action::create("MenuScript", _("Scr_ipt")),
312            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
313        );
314        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
315        actionGroup->add(Gtk::Action::create("AssignScripts", _("Assign Script")));
316    
317        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
318    #endif
319    
320        const Gdk::ModifierType primaryModifierKey =
321    #if defined(__APPLE__)
322        Gdk::META_MASK; // Cmd key on Mac
323    #else
324        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
325    #endif
326    
327    #if USE_GLIB_ACTION
328        m_actionCopyDimRgn = m_actionGroup->add_action(
329            "CopyDimRgn", sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn)
330        );
331        m_actionPasteDimRgn = m_actionGroup->add_action(
332            "PasteDimRgn", sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn)
333        );
334        m_actionAdjustClipboard = m_actionGroup->add_action(
335            "AdjustClipboard", sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content)
336        );
337        m_actionGroup->add_action(
338            "SelectPrevInstr", sigc::mem_fun(*this, &MainWindow::select_prev_instrument)
339        );
340        m_actionGroup->add_action(
341            "SelectNextInstr", sigc::mem_fun(*this, &MainWindow::select_next_instrument)
342        );
343        m_actionGroup->add_action(
344            "SelectPrevRegion", sigc::mem_fun(*this, &MainWindow::select_prev_region)
345        );
346        m_actionGroup->add_action(
347            "SelectNextRegion", sigc::mem_fun(*this, &MainWindow::select_next_region)
348        );
349        m_actionGroup->add_action(
350            "SelectPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone)
351        );
352        m_actionGroup->add_action(
353            "SelectNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone)
354        );
355        m_actionGroup->add_action(
356            "SelectPrevDimension", sigc::mem_fun(*this, &MainWindow::select_prev_dimension)
357        );
358        m_actionGroup->add_action(
359            "SelectNextDimension", sigc::mem_fun(*this, &MainWindow::select_next_dimension)
360        );
361        m_actionGroup->add_action(
362            "SelectAddPrevDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone)
363        );
364        m_actionGroup->add_action(
365            "SelectAddNextDimRgnZone", sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone)
366        );
367    #else
368        actionGroup->add(Gtk::Action::create("CopyDimRgn",
369                                             _("Copy selected dimension region")),
370                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
371                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
372    
373        actionGroup->add(Gtk::Action::create("PasteDimRgn",
374                                             _("Paste dimension region")),
375                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
376                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
377    
378        actionGroup->add(Gtk::Action::create("AdjustClipboard",
379                                             _("Adjust Clipboard Content")),
380                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
381                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
382    
383        actionGroup->add(Gtk::Action::create("SelectPrevInstr",
384                                             _("Select Previous Instrument")),
385                         Gtk::AccelKey(GDK_KEY_Up, primaryModifierKey),
386                         sigc::mem_fun(*this, &MainWindow::select_prev_instrument));
387    
388        actionGroup->add(Gtk::Action::create("SelectNextInstr",
389                                             _("Select Next Instrument")),
390                         Gtk::AccelKey(GDK_KEY_Down, primaryModifierKey),
391                         sigc::mem_fun(*this, &MainWindow::select_next_instrument));
392    
393        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
394                                             _("Select Previous Region")),
395                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
396                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
397    
398        actionGroup->add(Gtk::Action::create("SelectNextRegion",
399                                             _("Select Next Region")),
400                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
401                         sigc::mem_fun(*this, &MainWindow::select_next_region));
402    
403        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
404                                             _("Select Previous Dimension Region Zone")),
405                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
406                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
407    
408        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
409                                             _("Select Next Dimension Region Zone")),
410                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
411                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
412    
413        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
414                                             _("Select Previous Dimension")),
415                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
416                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
417    
418        actionGroup->add(Gtk::Action::create("SelectNextDimension",
419                                             _("Select Next Dimension")),
420                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
421                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
422    
423        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
424                                             _("Add Previous Dimension Region Zone to Selection")),
425                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
426                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
427    
428        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
429                                             _("Add Next Dimension Region Zone to Selection")),
430                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
431                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
432    #endif
433    
434      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  #if USE_GLIB_ACTION
435        m_actionToggleCopySampleUnity = m_actionGroup->add_action_bool("CopySampleUnity", true);
436        m_actionToggleCopySampleTune  = m_actionGroup->add_action_bool("CopySampleTune", true);
437        m_actionToggleCopySampleLoop  = m_actionGroup->add_action_bool("CopySampleLoop", true);
438    #else
439      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
440            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
441        toggle_action->set_active(true);
442        actionGroup->add(toggle_action);
443    
444        toggle_action =
445            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
446        toggle_action->set_active(true);
447        actionGroup->add(toggle_action);
448    
449        toggle_action =
450            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
451        toggle_action->set_active(true);
452        actionGroup->add(toggle_action);
453    #endif
454    
455    #if USE_GLIB_ACTION
456        m_actionToggleStatusBar =
457            m_actionGroup->add_action_bool("Statusbar", sigc::mem_fun(*this, &MainWindow::on_action_view_status_bar), true);
458        m_actionToggleRestoreWinDim =
459            m_actionGroup->add_action_bool("AutoRestoreWinDim", sigc::mem_fun(*this, &MainWindow::on_auto_restore_win_dim), Settings::singleton()->autoRestoreWindowDimension);
460        m_actionToggleShowTooltips = m_actionGroup->add_action_bool(
461            "ShowTooltips", sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips),
462            Settings::singleton()->showTooltips
463        );
464        m_actionToggleSaveWithTempFile =
465            m_actionGroup->add_action_bool("SaveWithTemporaryFile", sigc::mem_fun(*this, &MainWindow::on_save_with_temporary_file), Settings::singleton()->saveWithTemporaryFile);
466        m_actionGroup->add_action("RefreshAll", sigc::mem_fun(*this, &MainWindow::on_action_refresh_all));
467    #else
468        actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
469    
470    
471        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
472        toggle_action =
473          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
474      toggle_action->set_active(true);      toggle_action->set_active(true);
475      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
476                       sigc::mem_fun(                       sigc::mem_fun(
477                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
478    
479        toggle_action =
480            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
481        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
482        actionGroup->add(toggle_action,
483                         sigc::mem_fun(
484                             *this, &MainWindow::on_auto_restore_win_dim));
485    
486        toggle_action =
487            Gtk::ToggleAction::create("ShowTooltips", _("Tooltips for Beginners"));
488        toggle_action->set_active(Settings::singleton()->showTooltips);
489        actionGroup->add(
490            toggle_action,
491            sigc::mem_fun(*this, &MainWindow::on_action_show_tooltips)
492        );
493    
494        toggle_action =
495            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
496        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
497        actionGroup->add(toggle_action,
498                         sigc::mem_fun(
499                             *this, &MainWindow::on_save_with_temporary_file));
500    
501        actionGroup->add(
502            Gtk::Action::create("RefreshAll", _("_Refresh All")),
503            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
504        );                
505    #endif
506    
507    #if USE_GLIB_ACTION
508        m_actionGroup->add_action(
509            "About", sigc::mem_fun(*this, &MainWindow::on_action_help_about)
510        );
511        m_actionGroup->add_action(
512            "AddInstrument", sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
513        );
514        m_actionGroup->add_action(
515            "DupInstrument", sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
516        );
517        m_actionGroup->add_action(
518            "CombInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
519        );
520        m_actionGroup->add_action(
521            "RemoveInstrument", sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
522        );
523    #else
524      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
525      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
526                                           action->property_label()));                                           action->property_label()));
 #ifdef ABOUT_DIALOG  
527      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),
528                       sigc::mem_fun(                       sigc::mem_fun(
529                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
530      actionGroup->add(      actionGroup->add(
531          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
532          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
533      );      );
534      actionGroup->add(      actionGroup->add(
535            Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
536            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
537        );
538        actionGroup->add(
539            Gtk::Action::create("CombInstruments", _("_Combine Instruments ...")),
540            Gtk::AccelKey(GDK_KEY_j, primaryModifierKey),
541            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
542        );
543        actionGroup->add(
544          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
545          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
546      );      );
547    #endif
548    
549    #if USE_GLIB_ACTION
550        m_actionToggleWarnOnExtensions = m_actionGroup->add_action_bool(
551            "WarnUserOnExtensions", sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions),
552            Settings::singleton()->warnUserOnExtensions
553        );
554        m_actionToggleSyncSamplerSelection = m_actionGroup->add_action_bool(
555            "SyncSamplerInstrumentSelection", sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection),
556            Settings::singleton()->syncSamplerInstrumentSelection
557        );
558        m_actionToggleMoveRootNoteWithRegion = m_actionGroup->add_action_bool(
559            "MoveRootNoteWithRegionMoved", sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved),
560            Settings::singleton()->moveRootNoteWithRegionMoved
561        );
562    #else
563        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
564        
565        toggle_action =
566            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
567        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
568        actionGroup->add(
569            toggle_action,
570            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
571        );
572    
573        toggle_action =
574            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
575        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
576        actionGroup->add(
577            toggle_action,
578            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
579        );
580    
581        toggle_action =
582            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
583        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
584        actionGroup->add(
585            toggle_action,
586            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
587        );
588    #endif
589    
590    #if USE_GLIB_ACTION
591        m_actionGroup->add_action(
592            "CombineInstruments", sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
593        );
594        m_actionGroup->add_action(
595            "MergeFiles", sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
596        );
597    #else
598        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
599    
600        actionGroup->add(
601            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
602            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
603        );
604    
605        actionGroup->add(
606            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
607            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
608        );
609    #endif
610    
611      // sample right-click popup actions      // sample right-click popup actions
612    #if USE_GLIB_ACTION
613        m_actionSampleProperties = m_actionGroup->add_action(
614            "SampleProperties", sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
615        );
616        m_actionAddSampleGroup = m_actionGroup->add_action(
617            "AddGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_group)
618        );
619        m_actionAddSample = m_actionGroup->add_action(
620            "AddSample", sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
621        );
622        m_actionRemoveSample = m_actionGroup->add_action(
623            "RemoveSample", sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
624        );
625        m_actionGroup->add_action(
626            "RemoveUnusedSamples", sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
627        );
628        m_actionViewSampleRefs = m_actionGroup->add_action(
629            "ShowSampleRefs", sigc::mem_fun(*this, &MainWindow::on_action_view_references)
630        );
631        m_actionReplaceSample = m_actionGroup->add_action(
632            "ReplaceSample", sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
633        );
634        m_actionGroup->add_action(
635            "ReplaceAllSamplesInAllGroups", sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
636        );
637    #else
638      actionGroup->add(      actionGroup->add(
639          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),
640          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
# Line 201  MainWindow::MainWindow() : Line 644  MainWindow::MainWindow() :
644          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
645      );      );
646      actionGroup->add(      actionGroup->add(
647          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
648          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
649      );      );
650      actionGroup->add(      actionGroup->add(
651          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),
652          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
653      );      );
654        actionGroup->add(
655            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
656            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
657        );
658        actionGroup->add(
659            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
660            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
661        );
662        actionGroup->add(
663            Gtk::Action::create("ReplaceSample",
664                                _("Replace Sample...")),
665            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
666        );
667        actionGroup->add(
668            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
669                                _("Replace All Samples in All Groups...")),
670            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
671        );
672    #endif
673        
674        // script right-click popup actions
675    #if USE_GLIB_ACTION
676        m_actionAddScriptGroup = m_actionGroup->add_action(
677            "AddScriptGroup", sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
678        );
679        m_actionAddScript = m_actionGroup->add_action(
680            "AddScript", sigc::mem_fun(*this, &MainWindow::on_action_add_script)
681        );
682        m_actionEditScript = m_actionGroup->add_action(
683            "EditScript", sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
684        );
685        m_actionRemoveScript = m_actionGroup->add_action(
686            "RemoveScript", sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
687        );
688    #else
689        actionGroup->add(
690            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
691            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
692        );
693        actionGroup->add(
694            Gtk::Action::create("AddScript", _("Add _Script")),
695            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
696        );
697        actionGroup->add(
698            Gtk::Action::create("EditScript", _("_Edit Script...")),
699            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
700        );
701        actionGroup->add(
702            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
703            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
704        );
705    #endif
706    
707    #if USE_GTKMM_BUILDER
708        insert_action_group("AppMenu", m_actionGroup);
709        
710        m_uiManager = Gtk::Builder::create();
711        Glib::ustring ui_info =
712            "<interface>"
713            "  <menubar id='MenuBar'>"
714            "    <menu id='MenuFile'>"
715            "      <attribute name='label' translatable='yes'>_File</attribute>"
716            "      <section>"
717            "        <item id='New'>"
718            "          <attribute name='label' translatable='yes'>New</attribute>"
719            "          <attribute name='action'>AppMenu.New</attribute>"
720            "        </item>"
721            "        <item id='Open'>"
722            "          <attribute name='label' translatable='yes'>Open</attribute>"
723            "          <attribute name='action'>AppMenu.Open</attribute>"
724            "        </item>"
725            "      </section>"
726            "      <section>"
727            "        <item id='Save'>"
728            "          <attribute name='label' translatable='yes'>Save</attribute>"
729            "          <attribute name='action'>AppMenu.Save</attribute>"
730            "        </item>"
731            "        <item id='SaveAs'>"
732            "          <attribute name='label' translatable='yes'>Save As</attribute>"
733            "          <attribute name='action'>AppMenu.SaveAs</attribute>"
734            "        </item>"
735            "      </section>"
736            "      <section>"
737            "        <item id='Properties'>"
738            "          <attribute name='label' translatable='yes'>Properties</attribute>"
739            "          <attribute name='action'>AppMenu.Properties</attribute>"
740            "        </item>"
741            "      </section>"
742            "      <section>"
743            "        <item id='Quit'>"
744            "          <attribute name='label' translatable='yes'>Quit</attribute>"
745            "          <attribute name='action'>AppMenu.Quit</attribute>"
746            "        </item>"
747            "      </section>"
748            "    </menu>"
749            "    <menu id='MenuEdit'>"
750            "      <attribute name='label' translatable='yes'>Edit</attribute>"
751            "      <section>"
752            "        <item id='CopyDimRgn'>"
753            "          <attribute name='label' translatable='yes'>Copy Dimension Region</attribute>"
754            "          <attribute name='action'>AppMenu.CopyDimRgn</attribute>"
755            "        </item>"
756            "        <item id='AdjustClipboard'>"
757            "          <attribute name='label' translatable='yes'>Adjust Clipboard</attribute>"
758            "          <attribute name='action'>AppMenu.AdjustClipboard</attribute>"
759            "        </item>"
760            "        <item id='PasteDimRgn'>"
761            "          <attribute name='label' translatable='yes'>Paste Dimension Region</attribute>"
762            "          <attribute name='action'>AppMenu.PasteDimRgn</attribute>"
763            "        </item>"
764            "      </section>"
765            "        <item id='SelectPrevInstr'>"
766            "          <attribute name='label' translatable='yes'>Previous Instrument</attribute>"
767            "          <attribute name='action'>AppMenu.SelectPrevInstr</attribute>"
768            "        </item>"
769            "        <item id='SelectNextInstr'>"
770            "          <attribute name='label' translatable='yes'>Next Instrument</attribute>"
771            "          <attribute name='action'>AppMenu.SelectNextInstr</attribute>"
772            "        </item>"
773            "      <section>"
774            "        <item id='SelectPrevRegion'>"
775            "          <attribute name='label' translatable='yes'>Previous Region</attribute>"
776            "          <attribute name='action'>AppMenu.SelectPrevRegion</attribute>"
777            "        </item>"
778            "        <item id='SelectNextRegion'>"
779            "          <attribute name='label' translatable='yes'>Next Region</attribute>"
780            "          <attribute name='action'>AppMenu.SelectNextRegion</attribute>"
781            "        </item>"
782            "      </section>"
783            "        <item id='SelectPrevDimension'>"
784            "          <attribute name='label' translatable='yes'>Previous Dimension</attribute>"
785            "          <attribute name='action'>AppMenu.SelectPrevDimension</attribute>"
786            "        </item>"
787            "        <item id='SelectNextDimension'>"
788            "          <attribute name='label' translatable='yes'>Next Dimension</attribute>"
789            "          <attribute name='action'>AppMenu.SelectNextDimension</attribute>"
790            "        </item>"
791            "        <item id='SelectPrevDimRgnZone'>"
792            "          <attribute name='label' translatable='yes'>Previous Dimension Region Zone</attribute>"
793            "          <attribute name='action'>AppMenu.SelectPrevDimRgnZone</attribute>"
794            "        </item>"
795            "        <item id='SelectNextDimRgnZone'>"
796            "          <attribute name='label' translatable='yes'>Next Dimension Region Zone</attribute>"
797            "          <attribute name='action'>AppMenu.SelectNextDimRgnZone</attribute>"
798            "        </item>"
799            "        <item id='SelectAddPrevDimRgnZone'>"
800            "          <attribute name='label' translatable='yes'>Add Previous Dimension Region Zone</attribute>"
801            "          <attribute name='action'>AppMenu.SelectAddPrevDimRgnZone</attribute>"
802            "        </item>"
803            "        <item id='SelectAddNextDimRgnZone'>"
804            "          <attribute name='label' translatable='yes'>Add Next Dimension Region Zone</attribute>"
805            "          <attribute name='action'>AppMenu.SelectAddNextDimRgnZone</attribute>"
806            "        </item>"
807            "      <section>"
808            "        <item id='CopySampleUnity'>"
809            "          <attribute name='label' translatable='yes'>Copy Sample Unity</attribute>"
810            "          <attribute name='action'>AppMenu.CopySampleUnity</attribute>"
811            "        </item>"
812            "        <item id='CopySampleTune'>"
813            "          <attribute name='label' translatable='yes'>Copy Sample Tune</attribute>"
814            "          <attribute name='action'>AppMenu.CopySampleTune</attribute>"
815            "        </item>"
816            "        <item id='CopySampleLoop'>"
817            "          <attribute name='label' translatable='yes'>Copy Sample Loop</attribute>"
818            "          <attribute name='action'>AppMenu.CopySampleLoop</attribute>"
819            "        </item>"
820            "      </section>"
821            "    </menu>"
822            "    <menu id='MenuMacro'>"
823            "      <attribute name='label' translatable='yes'>Macro</attribute>"
824            "      <section>"
825            "      </section>"
826            "    </menu>"
827            "    <menu id='MenuSample'>"
828            "      <attribute name='label' translatable='yes'>Sample</attribute>"
829            "      <section>"
830            "        <item id='SampleProperties'>"
831            "          <attribute name='label' translatable='yes'>Properties</attribute>"
832            "          <attribute name='action'>AppMenu.SampleProperties</attribute>"
833            "        </item>"
834            "        <item id='AddGroup'>"
835            "          <attribute name='label' translatable='yes'>Add Group</attribute>"
836            "          <attribute name='action'>AppMenu.AddGroup</attribute>"
837            "        </item>"
838            "        <item id='AddSample'>"
839            "          <attribute name='label' translatable='yes'>Add Sample</attribute>"
840            "          <attribute name='action'>AppMenu.AddSample</attribute>"
841            "        </item>"
842            "        <item id='ShowSampleRefs'>"
843            "          <attribute name='label' translatable='yes'>Show Sample References</attribute>"
844            "          <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
845            "        </item>"
846            "        <item id='ReplaceSample'>"
847            "          <attribute name='label' translatable='yes'>Replace Sample</attribute>"
848            "          <attribute name='action'>AppMenu.ReplaceSample</attribute>"
849            "        </item>"
850            "        <item id='ReplaceAllSamplesInAllGroups'>"
851            "          <attribute name='label' translatable='yes'>Replace all Samples in all Groups</attribute>"
852            "          <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
853            "        </item>"
854            "      </section>"
855            "      <section>"
856            "        <item id='RemoveSample'>"
857            "          <attribute name='label' translatable='yes'>Remove Sample</attribute>"
858            "          <attribute name='action'>AppMenu.RemoveSample</attribute>"
859            "        </item>"
860            "        <item id='RemoveUnusedSamples'>"
861            "          <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
862            "          <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
863            "        </item>"
864            "      </section>"
865            "    </menu>"
866            "    <menu id='MenuInstrument'>"
867            "      <attribute name='label' translatable='yes'>Instrument</attribute>"
868            "      <section>"
869            "        <item id='InstrProperties'>"
870            "          <attribute name='label' translatable='yes'>Properties</attribute>"
871            "          <attribute name='action'>AppMenu.InstrProperties</attribute>"
872            "        </item>"
873            "        <item id='MidiRules'>"
874            "          <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
875            "          <attribute name='action'>AppMenu.MidiRules</attribute>"
876            "        </item>"
877            "        <item id='ScriptSlots'>"
878            "          <attribute name='label' translatable='yes'>Script Slots</attribute>"
879            "          <attribute name='action'>AppMenu.ScriptSlots</attribute>"
880            "        </item>"
881            "      </section>"
882            "      <submenu id='AssignScripts'>"
883            "        <attribute name='label' translatable='yes'>Assign Scripts</attribute>"
884            "      </submenu>"
885            "      <section>"
886            "        <item id='AddInstrument'>"
887            "          <attribute name='label' translatable='yes'>Add Instrument</attribute>"
888            "          <attribute name='action'>AppMenu.AddInstrument</attribute>"
889            "        </item>"
890            "        <item id='DupInstrument'>"
891            "          <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
892            "          <attribute name='action'>AppMenu.DupInstrument</attribute>"
893            "        </item>"
894            "        <item id='CombInstruments'>"
895            "          <attribute name='label' translatable='yes'>Combine Instrument</attribute>"
896            "          <attribute name='action'>AppMenu.CombInstruments</attribute>"
897            "        </item>"
898            "      </section>"
899            "      <section>"
900            "        <item id='RemoveInstrument'>"
901            "          <attribute name='label' translatable='yes'>Remove Instrument</attribute>"
902            "          <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
903            "        </item>"
904            "      </section>"
905            "    </menu>"
906            "    <menu id='MenuScript'>"
907            "      <attribute name='label' translatable='yes'>Script</attribute>"
908            "      <section>"
909            "        <item id='AddScriptGroup'>"
910            "          <attribute name='label' translatable='yes'>Add Script Group</attribute>"
911            "          <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
912            "        </item>"
913            "        <item id='AddScript'>"
914            "          <attribute name='label' translatable='yes'>Add Script</attribute>"
915            "          <attribute name='action'>AppMenu.AddScript</attribute>"
916            "        </item>"
917            "        <item id='EditScript'>"
918            "          <attribute name='label' translatable='yes'>Edit Script</attribute>"
919            "          <attribute name='action'>AppMenu.EditScript</attribute>"
920            "        </item>"
921            "      </section>"
922            "      <section>"
923            "        <item id='RemoveScript'>"
924            "          <attribute name='label' translatable='yes'>Remove Script</attribute>"
925            "          <attribute name='action'>AppMenu.RemoveScript</attribute>"
926            "        </item>"
927            "      </section>"
928            "    </menu>"
929            "    <menu id='MenuView'>"
930            "      <attribute name='label' translatable='yes'>View</attribute>"
931            "      <section>"
932            "        <item id='Statusbar'>"
933            "          <attribute name='label' translatable='yes'>Statusbar</attribute>"
934            "          <attribute name='action'>AppMenu.Statusbar</attribute>"
935            "        </item>"
936            "        <item id='ShowTooltips'>"
937            "          <attribute name='label' translatable='yes'>Tooltips for Beginners</attribute>"
938            "          <attribute name='action'>AppMenu.ShowTooltips</attribute>"
939            "        </item>"
940            "        <item id='AutoRestoreWinDim'>"
941            "          <attribute name='label' translatable='yes'>Auto restore Window Dimensions</attribute>"
942            "          <attribute name='action'>AppMenu.AutoRestoreWinDim</attribute>"
943            "        </item>"
944            "      </section>"
945            "      <section>"
946            "        <item id='RefreshAll'>"
947            "          <attribute name='label' translatable='yes'>Refresh All</attribute>"
948            "          <attribute name='action'>AppMenu.RefreshAll</attribute>"
949            "        </item>"
950            "      </section>"
951            "    </menu>"
952            "    <menu id='MenuTools'>"
953            "      <attribute name='label' translatable='yes'>Tools</attribute>"
954            "      <section>"
955            "        <item id='CombineInstruments'>"
956            "          <attribute name='label' translatable='yes'>Combine Instruments ...</attribute>"
957            "          <attribute name='action'>AppMenu.CombineInstruments</attribute>"
958            "        </item>"
959            "        <item id='MergeFiles'>"
960            "          <attribute name='label' translatable='yes'>Merge Files ...</attribute>"
961            "          <attribute name='action'>AppMenu.MergeFiles</attribute>"
962            "        </item>"
963            "      </section>"
964            "    </menu>"
965            "    <menu id='MenuSettings'>"
966            "      <attribute name='label' translatable='yes'>Settings</attribute>"
967            "      <section>"
968            "        <item id='WarnUserOnExtensions'>"
969            "          <attribute name='label' translatable='yes'>Warning on Format Extensions</attribute>"
970            "          <attribute name='action'>AppMenu.WarnUserOnExtensions</attribute>"
971            "        </item>"
972            "        <item id='SyncSamplerInstrumentSelection'>"
973            "          <attribute name='label' translatable='yes'>Synchronize Sampler Selection</attribute>"
974            "          <attribute name='action'>AppMenu.SyncSamplerInstrumentSelection</attribute>"
975            "        </item>"
976            "        <item id='MoveRootNoteWithRegionMoved'>"
977            "          <attribute name='label' translatable='yes'>Move Root Note with Region moved</attribute>"
978            "          <attribute name='action'>AppMenu.MoveRootNoteWithRegionMoved</attribute>"
979            "        </item>"
980            "        <item id='SaveWithTemporaryFile'>"
981            "          <attribute name='label' translatable='yes'>Save with temporary file</attribute>"
982            "          <attribute name='action'>AppMenu.SaveWithTemporaryFile</attribute>"
983            "        </item>"
984            "      </section>"
985            "    </menu>"
986            "    <menu id='MenuHelp'>"
987            "      <attribute name='label' translatable='yes'>Help</attribute>"
988            "      <section>"
989            "        <item id='About'>"
990            "          <attribute name='label' translatable='yes'>About ...</attribute>"
991            "          <attribute name='action'>AppMenu.About</attribute>"
992            "        </item>"
993            "      </section>"
994            "    </menu>"
995            "  </menubar>"
996            // popups
997            "  <menu id='PopupMenu'>"
998            "    <section>"
999            "      <item id='InstrProperties'>"
1000            "        <attribute name='label' translatable='yes'>Instrument Properties</attribute>"
1001            "        <attribute name='action'>AppMenu.InstrProperties</attribute>"
1002            "      </item>"
1003            "      <item id='MidiRules'>"
1004            "        <attribute name='label' translatable='yes'>MIDI Rules</attribute>"
1005            "        <attribute name='action'>AppMenu.MidiRules</attribute>"
1006            "      </item>"
1007            "      <item id='ScriptSlots'>"
1008            "        <attribute name='label' translatable='yes'>Script Slots</attribute>"
1009            "        <attribute name='action'>AppMenu.ScriptSlots</attribute>"
1010            "      </item>"
1011            "      <item id='AddInstrument'>"
1012            "        <attribute name='label' translatable='yes'>Add Instrument</attribute>"
1013            "        <attribute name='action'>AppMenu.AddInstrument</attribute>"
1014            "      </item>"
1015            "      <item id='DupInstrument'>"
1016            "        <attribute name='label' translatable='yes'>Duplicate Instrument</attribute>"
1017            "        <attribute name='action'>AppMenu.DupInstrument</attribute>"
1018            "      </item>"
1019            "      <item id='CombInstruments'>"
1020            "        <attribute name='label' translatable='yes'>Combine Instruments</attribute>"
1021            "        <attribute name='action'>AppMenu.CombInstruments</attribute>"
1022            "      </item>"
1023            "    </section>"
1024            "    <section>"
1025            "      <item id='RemoveInstrument'>"
1026            "        <attribute name='label' translatable='yes'>Remove Instruments</attribute>"
1027            "        <attribute name='action'>AppMenu.RemoveInstrument</attribute>"
1028            "      </item>"
1029            "    </section>"
1030            "  </menu>"
1031            "  <menu id='SamplePopupMenu'>"
1032            "    <section>"
1033            "      <item id='SampleProperties'>"
1034            "        <attribute name='label' translatable='yes'>Sample Properties</attribute>"
1035            "        <attribute name='action'>AppMenu.SampleProperties</attribute>"
1036            "      </item>"
1037            "      <item id='AddGroup'>"
1038            "        <attribute name='label' translatable='yes'>Add Sample Group</attribute>"
1039            "        <attribute name='action'>AppMenu.AddGroup</attribute>"
1040            "      </item>"
1041            "      <item id='AddSample'>"
1042            "        <attribute name='label' translatable='yes'>Add Sample</attribute>"
1043            "        <attribute name='action'>AppMenu.AddSample</attribute>"
1044            "      </item>"
1045            "      <item id='ShowSampleRefs'>"
1046            "        <attribute name='label' translatable='yes'>Show Sample References ...</attribute>"
1047            "        <attribute name='action'>AppMenu.ShowSampleRefs</attribute>"
1048            "      </item>"
1049            "      <item id='ReplaceSample'>"
1050            "        <attribute name='label' translatable='yes'>Replace Sample</attribute>"
1051            "        <attribute name='action'>AppMenu.ReplaceSample</attribute>"
1052            "      </item>"
1053            "      <item id='ReplaceAllSamplesInAllGroups'>"
1054            "        <attribute name='label' translatable='yes'>Replace all Samples ...</attribute>"
1055            "        <attribute name='action'>AppMenu.ReplaceAllSamplesInAllGroups</attribute>"
1056            "      </item>"
1057            "    </section>"
1058            "    <section>"
1059            "      <item id='RemoveSample'>"
1060            "        <attribute name='label' translatable='yes'>Remove Sample</attribute>"
1061            "        <attribute name='action'>AppMenu.RemoveSample</attribute>"
1062            "      </item>"
1063            "      <item id='RemoveUnusedSamples'>"
1064            "        <attribute name='label' translatable='yes'>Remove unused Samples</attribute>"
1065            "        <attribute name='action'>AppMenu.RemoveUnusedSamples</attribute>"
1066            "      </item>"
1067            "    </section>"
1068            "  </menu>"
1069            "  <menu id='ScriptPopupMenu'>"
1070            "    <section>"
1071            "      <item id='AddScriptGroup'>"
1072            "        <attribute name='label' translatable='yes'>Add Script Group</attribute>"
1073            "        <attribute name='action'>AppMenu.AddScriptGroup</attribute>"
1074            "      </item>"
1075            "      <item id='AddScript'>"
1076            "        <attribute name='label' translatable='yes'>Add Script</attribute>"
1077            "        <attribute name='action'>AppMenu.AddScript</attribute>"
1078            "      </item>"
1079            "      <item id='EditScript'>"
1080            "        <attribute name='label' translatable='yes'>Edit Script</attribute>"
1081            "        <attribute name='action'>AppMenu.EditScript</attribute>"
1082            "      </item>"
1083            "    </section>"
1084            "    <section>"
1085            "      <item id='RemoveScript'>"
1086            "        <attribute name='label' translatable='yes'>Remove Script</attribute>"
1087            "        <attribute name='action'>AppMenu.RemoveScript</attribute>"
1088            "      </item>"
1089            "    </section>"
1090            "  </menu>"
1091            "</interface>";
1092        m_uiManager->add_from_string(ui_info);
1093    #else
1094      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
1095      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
1096      add_accel_group(uiManager->get_accel_group());      add_accel_group(uiManager->get_accel_group());
# Line 227  MainWindow::MainWindow() : Line 1109  MainWindow::MainWindow() :
1109          "      <separator/>"          "      <separator/>"
1110          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
1111          "    </menu>"          "    </menu>"
1112            "    <menu action='MenuEdit'>"
1113            "      <menuitem action='CopyDimRgn'/>"
1114            "      <menuitem action='AdjustClipboard'/>"
1115            "      <menuitem action='PasteDimRgn'/>"
1116            "      <separator/>"
1117            "      <menuitem action='SelectPrevInstr'/>"
1118            "      <menuitem action='SelectNextInstr'/>"
1119            "      <separator/>"
1120            "      <menuitem action='SelectPrevRegion'/>"
1121            "      <menuitem action='SelectNextRegion'/>"
1122            "      <separator/>"
1123            "      <menuitem action='SelectPrevDimension'/>"
1124            "      <menuitem action='SelectNextDimension'/>"
1125            "      <menuitem action='SelectPrevDimRgnZone'/>"
1126            "      <menuitem action='SelectNextDimRgnZone'/>"
1127            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
1128            "      <menuitem action='SelectAddNextDimRgnZone'/>"
1129            "      <separator/>"
1130            "      <menuitem action='CopySampleUnity'/>"
1131            "      <menuitem action='CopySampleTune'/>"
1132            "      <menuitem action='CopySampleLoop'/>"
1133            "    </menu>"
1134            "    <menu action='MenuMacro'>"
1135            "    </menu>"
1136            "    <menu action='MenuSample'>"
1137            "      <menuitem action='SampleProperties'/>"
1138            "      <menuitem action='AddGroup'/>"
1139            "      <menuitem action='AddSample'/>"
1140            "      <menuitem action='ShowSampleRefs'/>"
1141            "      <menuitem action='ReplaceSample' />"
1142            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
1143            "      <separator/>"
1144            "      <menuitem action='RemoveSample'/>"
1145            "      <menuitem action='RemoveUnusedSamples'/>"
1146            "    </menu>"
1147          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
1148            "      <menu action='AllInstruments'>"
1149            "      </menu>"
1150            "      <separator/>"
1151            "      <menuitem action='InstrProperties'/>"
1152            "      <menuitem action='MidiRules'/>"
1153            "      <menuitem action='ScriptSlots'/>"
1154            "      <menu action='AssignScripts'/>"
1155            "      <menuitem action='AddInstrument'/>"
1156            "      <menuitem action='DupInstrument'/>"
1157            "      <menuitem action='CombInstruments'/>"
1158            "      <separator/>"
1159            "      <menuitem action='RemoveInstrument'/>"
1160            "    </menu>"
1161            "    <menu action='MenuScript'>"
1162            "      <menuitem action='AddScriptGroup'/>"
1163            "      <menuitem action='AddScript'/>"
1164            "      <menuitem action='EditScript'/>"
1165            "      <separator/>"
1166            "      <menuitem action='RemoveScript'/>"
1167          "    </menu>"          "    </menu>"
1168          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
1169          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
1170            "      <menuitem action='ShowTooltips'/>"
1171            "      <menuitem action='AutoRestoreWinDim'/>"
1172            "      <separator/>"
1173            "      <menuitem action='RefreshAll'/>"
1174            "    </menu>"
1175            "    <menu action='MenuTools'>"
1176            "      <menuitem action='CombineInstruments'/>"
1177            "      <menuitem action='MergeFiles'/>"
1178            "    </menu>"
1179            "    <menu action='MenuSettings'>"
1180            "      <menuitem action='WarnUserOnExtensions'/>"
1181            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
1182            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
1183            "      <menuitem action='SaveWithTemporaryFile'/>"
1184          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
1185          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
1186          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
1187          "    </menu>"          "    </menu>"
 #endif  
1188          "  </menubar>"          "  </menubar>"
1189          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
1190          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
1191            "    <menuitem action='MidiRules'/>"
1192            "    <menuitem action='ScriptSlots'/>"
1193          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
1194            "    <menuitem action='DupInstrument'/>"
1195            "    <menuitem action='CombInstruments'/>"
1196          "    <separator/>"          "    <separator/>"
1197          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
1198          "  </popup>"          "  </popup>"
# Line 248  MainWindow::MainWindow() : Line 1200  MainWindow::MainWindow() :
1200          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
1201          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
1202          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
1203            "    <menuitem action='ShowSampleRefs'/>"
1204            "    <menuitem action='ReplaceSample' />"
1205            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
1206          "    <separator/>"          "    <separator/>"
1207          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
1208            "    <menuitem action='RemoveUnusedSamples'/>"
1209            "  </popup>"
1210            "  <popup name='ScriptPopupMenu'>"
1211            "    <menuitem action='AddScriptGroup'/>"
1212            "    <menuitem action='AddScript'/>"
1213            "    <menuitem action='EditScript'/>"
1214            "    <separator/>"
1215            "    <menuitem action='RemoveScript'/>"
1216          "  </popup>"          "  </popup>"
1217          "</ui>";          "</ui>";
1218      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
1219    #endif
1220    
1221    #if USE_GTKMM_BUILDER
1222        popup_menu = new Gtk::Menu(
1223            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1224                m_uiManager->get_object("PopupMenu")
1225            )
1226        );
1227        sample_popup = new Gtk::Menu(
1228            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1229                m_uiManager->get_object("SamplePopupMenu")
1230            )
1231        );
1232        script_popup = new Gtk::Menu(
1233            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1234                m_uiManager->get_object("ScriptPopupMenu")
1235            )
1236        );
1237    #else
1238      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
1239        
1240        // Set tooltips for menu items (for some reason, setting a tooltip on the
1241        // respective Gtk::Action objects above will simply be ignored, no matter
1242        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
1243        // Gtk::Action::create()).
1244        {
1245            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1246                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
1247            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."));
1248        }
1249        {
1250            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1251                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
1252            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."));
1253        }
1254        {
1255            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1256                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
1257            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."));
1258        }
1259        {
1260            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1261                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
1262            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."));
1263        }
1264        {
1265            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1266                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
1267            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)."));
1268        }
1269        {
1270            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1271                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
1272            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."));
1273        }
1274        {
1275            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1276                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
1277            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
1278            // copy tooltip to popup menu
1279            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
1280                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
1281            item2->set_tooltip_text(item->get_tooltip_text());
1282        }
1283        {
1284            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1285                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
1286            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
1287        }
1288        {
1289            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1290                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
1291            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
1292        }
1293        {
1294            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1295                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
1296            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
1297        }
1298        {
1299            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
1300                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
1301            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
1302        }
1303    #endif
1304    
1305    #if USE_GTKMM_BUILDER
1306        assign_scripts_menu = new Gtk::Menu(
1307            Glib::RefPtr<Gio::Menu>::cast_dynamic(
1308                m_uiManager->get_object("AssignScripts")
1309            )
1310        );
1311    #else
1312        instrument_menu = static_cast<Gtk::MenuItem*>(
1313            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
1314    
1315        assign_scripts_menu = static_cast<Gtk::MenuItem*>(
1316            uiManager->get_widget("/MenuBar/MenuInstrument/AssignScripts"))->get_submenu();
1317    #endif
1318    
1319    #if USE_GTKMM_BUILDER
1320        Gtk::Widget* menuBar = NULL;
1321        m_uiManager->get_widget("MenuBar", menuBar);
1322    #else
1323      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
1324    #endif
1325    
1326      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
1327      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
1328      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
# Line 264  MainWindow::MainWindow() : Line 1330  MainWindow::MainWindow() :
1330      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
1331      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
1332    
1333        set_file_is_shared(false);
1334    
1335      // Status Bar:      // Status Bar:
1336    #if USE_GTKMM_BOX
1337    # warning No status bar layout for GTKMM 4 yet
1338    #else
1339      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
1340      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
1341    #endif
1342      m_StatusBar.show();      m_StatusBar.show();
1343    
1344      m_RegionChooser.signal_region_selected().connect(      m_RegionChooser.signal_region_selected().connect(
# Line 277  MainWindow::MainWindow() : Line 1349  MainWindow::MainWindow() :
1349    
1350      // Create the Tree model:      // Create the Tree model:
1351      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
1352      m_TreeView.set_model(m_refTreeModel);      m_refTreeModelFilter = Gtk::TreeModelFilter::create(m_refTreeModel);
1353      m_refTreeModel->signal_row_changed().connect(      m_refTreeModelFilter->set_visible_func(
1354            sigc::mem_fun(*this, &MainWindow::instrument_row_visible)
1355        );
1356        m_TreeView.set_model(m_refTreeModelFilter);
1357    
1358        m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1359        m_TreeView.set_has_tooltip(true);
1360        m_TreeView.signal_query_tooltip().connect(
1361            sigc::mem_fun(*this, &MainWindow::onQueryTreeViewTooltip)
1362        );
1363        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
1364          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
1365      );      );
1366    
1367      // Add the TreeView's view columns:      // Add the TreeView's view columns:
1368      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
1369      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
1370        m_TreeView.append_column(_("Scripts"), m_Columns.m_col_scripts);
1371        m_TreeView.set_headers_visible(true);
1372        
1373        // establish drag&drop within the instrument tree view, allowing to reorder
1374        // the sequence of instruments within the gig file
1375        {
1376            std::vector<Gtk::TargetEntry> drag_target_instrument;
1377            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
1378            m_TreeView.drag_source_set(drag_target_instrument);
1379            m_TreeView.drag_dest_set(drag_target_instrument);
1380            m_TreeView.signal_drag_begin().connect(
1381                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
1382            );
1383            m_TreeView.signal_drag_data_get().connect(
1384                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
1385            );
1386            m_TreeView.signal_drag_data_received().connect(
1387                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
1388            );
1389        }
1390    
1391      // create samples treeview (including its data model)      // create samples treeview (including its data model)
1392      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
1393      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
1394        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
1395        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."));
1396      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
1397      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
1398      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
1399        {
1400            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
1401            Gtk::CellRendererText* cellrenderer =
1402                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1403            column->add_attribute(
1404                cellrenderer->property_foreground(), m_SamplesModel.m_color
1405            );
1406        }
1407        {
1408            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
1409            Gtk::CellRendererText* cellrenderer =
1410                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
1411            column->add_attribute(
1412                cellrenderer->property_foreground(), m_SamplesModel.m_color
1413            );
1414        }
1415        m_TreeViewSamples.set_headers_visible(true);
1416    #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
1417        m_TreeViewSamples.signal_button_press_event().connect(
1418            sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1419        );
1420    #else
1421      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
1422          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
1423      );      );
1424    #endif
1425      m_refSamplesTreeModel->signal_row_changed().connect(      m_refSamplesTreeModel->signal_row_changed().connect(
1426          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
1427      );      );
1428    
1429        // create scripts treeview (including its data model)
1430        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
1431        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
1432        m_TreeViewScripts.set_tooltip_text(_(
1433            "Use CTRL + double click for editing a script."
1434            "\n\n"
1435            "Note: instrument scripts are a LinuxSampler extension of the gig "
1436            "format. This feature will not work with the GigaStudio software!"
1437        ));
1438        // m_TreeViewScripts.set_reorderable();
1439        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
1440        m_TreeViewScripts.set_headers_visible(false);
1441    #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
1442        m_TreeViewScripts.signal_button_press_event().connect(
1443            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1444        );
1445    #else
1446        m_TreeViewScripts.signal_button_press_event().connect_notify(
1447            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
1448        );
1449    #endif
1450        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
1451        m_TreeViewScripts.signal_row_activated().connect(
1452            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
1453        );
1454        m_refScriptsTreeModel->signal_row_changed().connect(
1455            sigc::mem_fun(*this, &MainWindow::script_name_changed)
1456        );
1457    
1458        // establish drag&drop between scripts tree view and ScriptSlots window
1459        std::vector<Gtk::TargetEntry> drag_target_gig_script;
1460        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
1461        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
1462        m_TreeViewScripts.signal_drag_begin().connect(
1463            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
1464        );
1465        m_TreeViewScripts.signal_drag_data_get().connect(
1466            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
1467        );
1468    
1469      // 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
1470      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
1471      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
1472      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
1473      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
1474          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 317  MainWindow::MainWindow() : Line 1484  MainWindow::MainWindow() :
1484          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
1485      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
1486          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1487        m_RegionChooser.signal_instrument_changed().connect(
1488            sigc::mem_fun(*this, &MainWindow::region_changed));
1489      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
1490          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1491      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
1492            sigc::mem_fun(*this, &MainWindow::file_changed));
1493        propDialog.signal_changed().connect(
1494          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1495      propDialog.signal_info_changed().connect(      midiRules.signal_changed().connect(
1496          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
1497    
1498      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 330  MainWindow::MainWindow() : Line 1501  MainWindow::MainWindow() :
1501          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
1502      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
1503          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
1504        sample_ref_changed_signal.connect(
1505            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
1506        );
1507        samples_to_be_removed_signal.connect(
1508            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
1509        );
1510    
1511        dimreg_edit.signal_select_sample().connect(
1512            sigc::mem_fun(*this, &MainWindow::select_sample)
1513        );
1514    
1515      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
1516          sigc::hide(          sigc::hide(
1517              sigc::bind(              sigc::bind(
1518                  file_structure_to_be_changed_signal.make_slot(),                  file_structure_to_be_changed_signal.make_slot(),
1519    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1520                    std::ref(this->file)
1521    #else
1522                  sigc::ref(this->file)                  sigc::ref(this->file)
1523    #endif
1524              )              )
1525          )          )
1526      );      );
# Line 343  MainWindow::MainWindow() : Line 1528  MainWindow::MainWindow() :
1528          sigc::hide(          sigc::hide(
1529              sigc::bind(              sigc::bind(
1530                  file_structure_changed_signal.make_slot(),                  file_structure_changed_signal.make_slot(),
1531    #if SIGCXX_MAJOR_VERSION > 2 || (SIGCXX_MAJOR_VERSION == 2 && SIGCXX_MINOR_VERSION >= 8)
1532                    std::ref(this->file)
1533    #else
1534                  sigc::ref(this->file)                  sigc::ref(this->file)
1535    #endif
1536              )              )
1537          )          )
1538      );      );
# Line 364  MainWindow::MainWindow() : Line 1553  MainWindow::MainWindow() :
1553      dimreg_stereo.signal_toggled().connect(      dimreg_stereo.signal_toggled().connect(
1554          sigc::mem_fun(*this, &MainWindow::update_dimregs));          sigc::mem_fun(*this, &MainWindow::update_dimregs));
1555    
1556        m_searchText.signal_changed().connect(
1557            sigc::mem_fun(*m_refTreeModelFilter.operator->(), &Gtk::TreeModelFilter::refilter)
1558        );
1559    
1560      file = 0;      file = 0;
1561      file_is_changed = false;      file_is_changed = false;
     set_file_is_shared(false);  
1562    
1563    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1564      show_all_children();      show_all_children();
1565    #endif
1566    
1567      // start with a new gig file by default      // start with a new gig file by default
1568      on_action_file_new();      on_action_file_new();
1569    
1570        m_TreeViewNotebook.signal_switch_page().connect(
1571            sigc::mem_fun(*this, &MainWindow::on_notebook_tab_switched)
1572        );
1573    
1574        // select 'Instruments' tab by default
1575        // (gtk allows this only if the tab childs are visible, thats why it's here)
1576        m_TreeViewNotebook.set_current_page(1);
1577    
1578        Gtk::Clipboard::get()->signal_owner_change().connect(
1579            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
1580        );
1581        updateClipboardPasteAvailable();
1582        updateClipboardCopyAvailable();
1583    
1584        // setup macros and their keyboard accelerators
1585        {
1586    #if USE_GTKMM_BUILDER
1587            menuMacro = new Gtk::Menu(
1588                Glib::RefPtr<Gio::Menu>::cast_dynamic(
1589                    m_uiManager->get_object("MenuMacro")
1590                )
1591            );
1592    #else
1593            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1594                uiManager->get_widget("/MenuBar/MenuMacro")
1595            )->get_submenu();
1596    #endif
1597    
1598            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
1599            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
1600            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
1601            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
1602            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
1603            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
1604            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
1605            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
1606            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
1607            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
1608            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
1609            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
1610            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
1611            Gtk::AccelMap::add_entry("<Macros>/macro_12", GDK_KEY_F13, noModifier);
1612            Gtk::AccelMap::add_entry("<Macros>/macro_13", GDK_KEY_F14, noModifier);
1613            Gtk::AccelMap::add_entry("<Macros>/macro_14", GDK_KEY_F15, noModifier);
1614            Gtk::AccelMap::add_entry("<Macros>/macro_15", GDK_KEY_F16, noModifier);
1615            Gtk::AccelMap::add_entry("<Macros>/macro_16", GDK_KEY_F17, noModifier);
1616            Gtk::AccelMap::add_entry("<Macros>/macro_17", GDK_KEY_F18, noModifier);
1617            Gtk::AccelMap::add_entry("<Macros>/macro_18", GDK_KEY_F19, noModifier);
1618            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
1619    
1620            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1621            menuMacro->set_accel_group(accelGroup);
1622    
1623            updateMacroMenu();
1624        }
1625    
1626        // setup "Assign Scripts" keyboard accelerators
1627        {
1628            Gtk::AccelMap::add_entry("<Scripts>/script_0", GDK_KEY_F1, Gdk::SHIFT_MASK);
1629            Gtk::AccelMap::add_entry("<Scripts>/script_1", GDK_KEY_F2, Gdk::SHIFT_MASK);
1630            Gtk::AccelMap::add_entry("<Scripts>/script_2", GDK_KEY_F3, Gdk::SHIFT_MASK);
1631            Gtk::AccelMap::add_entry("<Scripts>/script_3", GDK_KEY_F4, Gdk::SHIFT_MASK);
1632            Gtk::AccelMap::add_entry("<Scripts>/script_4", GDK_KEY_F5, Gdk::SHIFT_MASK);
1633            Gtk::AccelMap::add_entry("<Scripts>/script_5", GDK_KEY_F6, Gdk::SHIFT_MASK);
1634            Gtk::AccelMap::add_entry("<Scripts>/script_6", GDK_KEY_F7, Gdk::SHIFT_MASK);
1635            Gtk::AccelMap::add_entry("<Scripts>/script_7", GDK_KEY_F8, Gdk::SHIFT_MASK);
1636            Gtk::AccelMap::add_entry("<Scripts>/script_8", GDK_KEY_F9, Gdk::SHIFT_MASK);
1637            Gtk::AccelMap::add_entry("<Scripts>/script_9", GDK_KEY_F10, Gdk::SHIFT_MASK);
1638            Gtk::AccelMap::add_entry("<Scripts>/script_10", GDK_KEY_F11, Gdk::SHIFT_MASK);
1639            Gtk::AccelMap::add_entry("<Scripts>/script_11", GDK_KEY_F12, Gdk::SHIFT_MASK);
1640            Gtk::AccelMap::add_entry("<Scripts>/script_12", GDK_KEY_F13, Gdk::SHIFT_MASK);
1641            Gtk::AccelMap::add_entry("<Scripts>/script_13", GDK_KEY_F14, Gdk::SHIFT_MASK);
1642            Gtk::AccelMap::add_entry("<Scripts>/script_14", GDK_KEY_F15, Gdk::SHIFT_MASK);
1643            Gtk::AccelMap::add_entry("<Scripts>/script_15", GDK_KEY_F16, Gdk::SHIFT_MASK);
1644            Gtk::AccelMap::add_entry("<Scripts>/script_16", GDK_KEY_F17, Gdk::SHIFT_MASK);
1645            Gtk::AccelMap::add_entry("<Scripts>/script_17", GDK_KEY_F18, Gdk::SHIFT_MASK);
1646            Gtk::AccelMap::add_entry("<Scripts>/script_18", GDK_KEY_F19, Gdk::SHIFT_MASK);
1647            Gtk::AccelMap::add_entry("<Scripts>/DropAllScriptSlots", GDK_KEY_BackSpace, Gdk::SHIFT_MASK);
1648    
1649            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
1650            assign_scripts_menu->set_accel_group(accelGroup);
1651        }
1652    
1653        on_show_tooltips_changed();
1654    
1655        Glib::signal_idle().connect_once(
1656            sigc::mem_fun(*this, &MainWindow::bringToFront),
1657            200
1658        );
1659  }  }
1660    
1661  MainWindow::~MainWindow()  MainWindow::~MainWindow()
1662  {  {
1663  }  }
1664    
1665    void MainWindow::bringToFront() {
1666        #if defined(__APPLE__)
1667        macRaiseAppWindow();
1668        #endif
1669        raise();
1670        present();
1671    }
1672    
1673    void MainWindow::updateMacroMenu() {
1674    #if !USE_GTKMM_BUILDER
1675        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
1676            uiManager->get_widget("/MenuBar/MenuMacro")
1677        )->get_submenu();
1678    #endif
1679    
1680        // remove all entries from "Macro" menu
1681        {
1682            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
1683            for (int i = 0; i < children.size(); ++i) {
1684                Gtk::Widget* child = children[i];
1685                menuMacro->remove(*child);
1686                delete child;
1687            }
1688        }
1689    
1690        // (re)load all macros from config file
1691        try {
1692            Settings::singleton()->loadMacros(m_macros);
1693        } catch (Serialization::Exception e) {
1694            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
1695        } catch (...) {
1696            std::cerr << "Unknown exception while loading macros!" << std::endl;
1697        }
1698    
1699        // add all configured macros as menu items to the "Macro" menu
1700        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
1701            const Serialization::Archive& macro = m_macros[iMacro];
1702            std::string name =
1703                macro.name().empty() ?
1704                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
1705            Gtk::MenuItem* item = new Gtk::MenuItem(name);
1706            item->signal_activate().connect(
1707                sigc::bind(
1708                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
1709                )
1710            );
1711            menuMacro->append(*item);
1712            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
1713            Glib::ustring comment = macro.comment();
1714            if (!comment.empty())
1715                item->set_tooltip_text(comment);
1716        }
1717        // if there are no macros configured at all, then show a dummy entry instead
1718        if (m_macros.empty()) {
1719            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
1720            item->set_sensitive(false);
1721            menuMacro->append(*item);
1722        }
1723    
1724        // add separator line to menu
1725        menuMacro->append(*new Gtk::SeparatorMenuItem);
1726    
1727        {
1728            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
1729            item->signal_activate().connect(
1730                sigc::mem_fun(*this, &MainWindow::setupMacros)
1731            );
1732            menuMacro->append(*item);
1733            item->set_accel_path("<Macros>/SetupMacros");
1734        }
1735    
1736    #if HAS_GTKMM_SHOW_ALL_CHILDREN
1737        menuMacro->show_all_children();
1738    #endif
1739    }
1740    
1741    void MainWindow::onMacroSelected(int iMacro) {
1742        printf("onMacroSelected(%d)\n", iMacro);
1743        if (iMacro < 0 || iMacro >= m_macros.size()) return;
1744        Glib::ustring errorText;
1745        try {
1746            applyMacro(m_macros[iMacro]);
1747        } catch (Serialization::Exception e) {
1748            errorText = e.Message;
1749        } catch (...) {
1750            errorText = _("Unknown exception while applying macro");
1751        }
1752        if (!errorText.empty()) {
1753            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
1754            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1755            msg.run();
1756        }
1757    }
1758    
1759    void MainWindow::setupMacros() {
1760        MacrosSetup* setup = new MacrosSetup();
1761        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
1762        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
1763        setup->signal_macros_changed().connect(
1764            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
1765        );
1766        setup->show();
1767    }
1768    
1769    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
1770        m_macros = macros;
1771        Settings::singleton()->saveMacros(m_macros);
1772        updateMacroMenu();
1773    }
1774    
1775    //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.
1776    void MainWindow::on_notebook_tab_switched(void* page, guint page_num) {
1777        bool isInstrumentsPage = (page_num == 1);
1778        // so far we only support filtering for the instruments list, so hide the
1779        // filter text entry field if another tab is selected
1780        m_searchField.set_visible(isInstrumentsPage);
1781    }
1782    
1783  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
1784  {  {
1785      return !file_is_shared && file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
# Line 397  void MainWindow::region_changed() Line 1799  void MainWindow::region_changed()
1799  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1800  {  {
1801      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
1802      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1803        if (rows.empty()) return NULL;
1804      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.
1805        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1806      if (it) {      if (it) {
1807          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1808          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 442  void MainWindow::update_dimregs() Line 1845  void MainWindow::update_dimregs()
1845              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1846          }          }
1847      }      }
1848    
1849        m_RegionChooser.setModifyAllRegions(all_regions);
1850        m_DimRegionChooser.setModifyAllRegions(all_regions);
1851        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1852        m_DimRegionChooser.setModifyBothChannels(stereo);
1853    
1854        updateClipboardCopyAvailable();
1855  }  }
1856    
1857  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 453  void MainWindow::dimreg_all_dimregs_togg Line 1863  void MainWindow::dimreg_all_dimregs_togg
1863  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1864  {  {
1865      update_dimregs();      update_dimregs();
1866      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1867  }  }
1868    
1869  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1870  {  {
1871    #if !USE_GTKMM_BUILDER
1872        // select item in instrument menu
1873        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1874        if (!rows.empty()) {
1875            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1876            if (it) {
1877                Gtk::TreePath path(it);
1878                int index = path[0];
1879                const std::vector<Gtk::Widget*> children =
1880                    instrument_menu->get_children();
1881                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1882            }
1883        }
1884    #endif
1885    
1886        updateScriptListOfMenu();
1887    
1888      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1889    
1890        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1891            switch_sampler_instrument_signal.emit(get_instrument());
1892        }
1893    }
1894    
1895    
1896    LoaderSaverBase::LoaderSaverBase(const Glib::ustring filename, gig::File* gig) :
1897        filename(filename), gig(gig), thread(0), progress(0.f)
1898    {
1899  }  }
1900    
1901  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
1902  {  {
1903      Loader* loader = static_cast<Loader*>(progress->custom);      LoaderSaverBase* loader = static_cast<LoaderSaverBase*>(progress->custom);
1904      loader->progress_callback(progress->factor);      loader->progress_callback(progress->factor);
1905  }  }
1906    
1907  void Loader::progress_callback(float fraction)  void LoaderSaverBase::progress_callback(float fraction)
1908  {  {
1909      {      {
1910          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
1911          progress = fraction;          progress = fraction;
1912      }      }
1913      progress_dispatcher();      progress_dispatcher();
1914  }  }
1915    
1916  void Loader::thread_function()  #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1917    // make sure stack is 16-byte aligned for SSE instructions
1918    __attribute__((force_align_arg_pointer))
1919    #endif
1920    void LoaderSaverBase::thread_function()
1921  {  {
1922      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
1923      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1924      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
1925      gig = new gig::File(riff);      try {
1926      gig::progress_t progress;          gig::progress_t progress;
1927      progress.callback = loader_progress_callback;          progress.callback = loader_progress_callback;
1928      progress.custom = this;          progress.custom = this;
1929    
1930            thread_function_sub(progress);
1931            printf("End\n");
1932            finished_dispatcher();
1933        } catch (RIFF::Exception e) {
1934            error_message = e.Message;
1935            error_dispatcher.emit();
1936        } catch (...) {
1937            error_message = _("Unknown exception occurred");
1938            error_dispatcher.emit();
1939        }
1940    }
1941    
1942      gig->GetInstrument(0, &progress);  void LoaderSaverBase::launch()
1943      printf("End\n");  {
1944      finished_dispatcher();  #ifdef OLD_THREADS
1945        thread = Glib::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function), true);
1946    #else
1947        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &LoaderSaverBase::thread_function));
1948    #endif
1949        printf("launch thread=%p\n", static_cast<void*>(thread));
1950  }  }
1951    
1952  Loader::Loader(const char* filename)  float LoaderSaverBase::get_progress()
     : thread(0), filename(filename)  
1953  {  {
1954        Glib::Threads::Mutex::Lock lock(progressMutex);
1955        return progress;
1956  }  }
1957    
1958  void Loader::launch()  Glib::Dispatcher& LoaderSaverBase::signal_progress()
1959  {  {
1960      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      return progress_dispatcher;
     printf("launch thread=%x\n", thread);  
1961  }  }
1962    
1963  float Loader::get_progress()  Glib::Dispatcher& LoaderSaverBase::signal_finished()
1964  {  {
1965      float res;      return finished_dispatcher;
     {  
         Glib::Mutex::Lock lock(progressMutex);  
         res = progress;  
     }  
     return res;  
1966  }  }
1967    
1968  Glib::Dispatcher& Loader::signal_progress()  Glib::Dispatcher& LoaderSaverBase::signal_error()
1969  {  {
1970      return progress_dispatcher;      return error_dispatcher;
1971    }
1972    
1973    void LoaderSaverBase::join() {
1974        thread->join();
1975  }  }
1976    
1977  Glib::Dispatcher& Loader::signal_finished()  
1978    Loader::Loader(const char* filename) :
1979        LoaderSaverBase(filename, 0)
1980  {  {
     return finished_dispatcher;  
1981  }  }
1982    
1983  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  void Loader::thread_function_sub(gig::progress_t& progress)
1984    {
1985        RIFF::File* riff = new RIFF::File(filename);
1986        gig = new gig::File(riff);
1987    
1988        gig->GetInstrument(0, &progress);
1989    }
1990    
1991    
1992    Saver::Saver(gig::File* file, Glib::ustring filename) :
1993        LoaderSaverBase(filename, file)
1994    {
1995    }
1996    
1997    void Saver::thread_function_sub(gig::progress_t& progress)
1998    {
1999        // if no filename was provided, that means "save", if filename was provided means "save as"
2000        if (filename.empty()) {
2001            if (!Settings::singleton()->saveWithTemporaryFile) {
2002                // save directly over the existing .gig file
2003                // (requires less disk space than solution below
2004                // but may be slower)
2005                gig->Save(&progress);
2006            } else {
2007                // save the file as separate temporary file first,
2008                // then move the saved file over the old file
2009                // (may result in performance speedup during save)
2010                gig::String tmpname = filename + ".TMP";
2011                gig->Save(tmpname, &progress);
2012    #if defined(WIN32)
2013                if (!DeleteFile(filename.c_str())) {
2014                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
2015                }
2016    #else // POSIX ...
2017                if (unlink(filename.c_str())) {
2018                    throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
2019                }
2020    #endif
2021                if (rename(tmpname.c_str(), filename.c_str())) {
2022    #if defined(WIN32)
2023                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
2024    #else
2025                    throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
2026    #endif
2027                }
2028            }
2029        } else {
2030            gig->Save(filename, &progress);
2031        }
2032    }
2033    
2034    
2035    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
2036      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
2037  {  {
2038    #if USE_GTKMM_BOX
2039        get_content_area()->pack_start(progressBar);
2040    #else
2041      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
2042    #endif
2043    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2044      show_all_children();      show_all_children();
2045    #endif
2046        resize(600,50);
2047  }  }
2048    
2049  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
2050  // 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.
2051  void MainWindow::__clear() {  void MainWindow::__clear() {
     // remove all entries from "Instrument" menu  
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
     instrument_menu->hide();  
     for (int i = 0; i < instrument_menu->get_submenu()->items().size(); i++) {  
         delete &instrument_menu->get_submenu()->items()[i];  
     }  
     instrument_menu->get_submenu()->items().clear();  
2052      // forget all samples that ought to be imported      // forget all samples that ought to be imported
2053      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
2054      // clear the samples and instruments tree views      // clear the samples and instruments tree views
2055      m_refTreeModel->clear();      m_refTreeModel->clear();
2056      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
2057        m_refScriptsTreeModel->clear();
2058    #if !USE_GTKMM_BUILDER
2059        // remove all entries from "Instrument" menu
2060        while (!instrument_menu->get_children().empty()) {
2061            remove_instrument_from_menu(0);
2062        }
2063    #endif
2064      // free libgig's gig::File instance      // free libgig's gig::File instance
2065      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
2066      file = NULL;      file = NULL;
2067      set_file_is_shared(false);      set_file_is_shared(false);
2068  }  }
2069    
2070    void MainWindow::__refreshEntireGUI() {
2071        // clear the samples and instruments tree views
2072        m_refTreeModel->clear();
2073        m_refSamplesTreeModel->clear();
2074        m_refScriptsTreeModel->clear();
2075    #if !USE_GTKMM_BUILDER
2076        // remove all entries from "Instrument" menu
2077        while (!instrument_menu->get_children().empty()) {
2078            remove_instrument_from_menu(0);
2079        }
2080    #endif
2081    
2082        if (!this->file) return;
2083    
2084        load_gig(
2085            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
2086        );
2087    }
2088    
2089  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
2090  {  {
2091      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 563  void MainWindow::on_action_file_new() Line 2098  void MainWindow::on_action_file_new()
2098      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
2099      // already add one new instrument by default      // already add one new instrument by default
2100      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
2101      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
2102      // update GUI with that new gig::File      // update GUI with that new gig::File
2103      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
2104  }  }
# Line 574  bool MainWindow::close_confirmation_dial Line 2109  bool MainWindow::close_confirmation_dial
2109                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
2110      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
2111      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
2112      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
 #endif  
2113      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
2114    #if HAS_GTKMM_STOCK
2115      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2116      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);
2117    #else
2118        dialog.add_button(_("_OK"), Gtk::RESPONSE_OK);
2119        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2120    #endif
2121      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
2122      int response = dialog.run();      int response = dialog.run();
2123      dialog.hide();      dialog.hide();
2124      if (response == Gtk::RESPONSE_YES) return file_save();  
2125      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
2126        if (response == Gtk::RESPONSE_NO) return true;
2127    
2128        // user cancelled dialog, thus don't close app
2129        if (response == Gtk::RESPONSE_CANCEL) return false;
2130    
2131        // TODO: the following return valid is disabled and hard coded instead for
2132        // now, due to the fact that saving with progress bar is now implemented
2133        // asynchronously, as a result the app does not close automatically anymore
2134        // after saving the file has completed
2135        //
2136        //   if (response == Gtk::RESPONSE_YES) return file_save();
2137        //   return response != Gtk::RESPONSE_CANCEL;
2138        //
2139        if (response == Gtk::RESPONSE_YES) file_save();
2140        return false; // always prevent closing the app for now (see comment above)
2141  }  }
2142    
2143  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
2144      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
2145      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
2146      dialog.set_secondary_text(      dialog.set_secondary_text(
2147          _("If you proceed to work on another instrument file, it won't be "          _("If you proceed to work on another instrument file, it won't be "
2148            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
2149            "load it.")            "load it."));
    );  
 #endif  
2150      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
2151    #if HAS_GTKMM_STOCK
2152      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2153    #else
2154        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2155    #endif
2156      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
2157      int response = dialog.run();      int response = dialog.run();
2158      dialog.hide();      dialog.hide();
# Line 612  void MainWindow::on_action_file_open() Line 2166  void MainWindow::on_action_file_open()
2166      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
2167    
2168      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
2169    #if HAS_GTKMM_STOCK
2170      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2171      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2172    #else
2173        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2174        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2175    #endif
2176      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
2177    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2178      Gtk::FileFilter filter;      Gtk::FileFilter filter;
2179      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
2180    #else
2181        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
2182        filter->add_pattern("*.gig");
2183    #endif
2184      dialog.set_filter(filter);      dialog.set_filter(filter);
2185      if (current_dir != "") {      if (current_gig_dir != "") {
2186          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
2187      }      }
2188      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2189          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
2190          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
2191          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%p\n",
2192                   static_cast<void*>(Glib::Threads::Thread::self()));
2193          load_file(filename.c_str());          load_file(filename.c_str());
2194          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
2195      }      }
2196  }  }
2197    
2198  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
2199  {  {
2200      __clear();      __clear();
2201      load_dialog = new LoadDialog("Loading...", *this);  
2202      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2203      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
2204            Glib::filename_display_basename(name) + "' ...",
2205            *this
2206        );
2207    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2208        progress_dialog->show_all();
2209    #endif
2210        loader = new Loader(name); //FIXME: memory leak!
2211      loader->signal_progress().connect(      loader->signal_progress().connect(
2212          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
2213      loader->signal_finished().connect(      loader->signal_finished().connect(
2214          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
2215        loader->signal_error().connect(
2216            sigc::mem_fun(*this, &MainWindow::on_loader_error));
2217      loader->launch();      loader->launch();
2218  }  }
2219    
# Line 655  void MainWindow::load_instrument(gig::In Line 2229  void MainWindow::load_instrument(gig::In
2229      // load the instrument      // load the instrument
2230      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
2231      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
2232      //TODO: automatically select the given instrument      // automatically select the given instrument
2233        int i = 0;
2234        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
2235             instrument = pFile->GetNextInstrument(), ++i)
2236        {
2237            if (instrument == instr) {
2238                // select item in "instruments" tree view
2239                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
2240                // make sure the selected item in the "instruments" tree view is
2241                // visible (scroll to it)
2242                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
2243    #if !USE_GTKMM_BUILDER
2244                // select item in instrument menu
2245                {
2246                    const std::vector<Gtk::Widget*> children =
2247                        instrument_menu->get_children();
2248                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
2249                }
2250    #endif
2251                // update region chooser and dimension region chooser
2252                m_RegionChooser.set_instrument(instr);
2253                break;
2254            }
2255        }
2256  }  }
2257    
2258  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
2259  {  {
2260      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
2261  }  }
2262    
2263  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
2264  {  {
2265        loader->join();
2266      printf("Loader finished!\n");      printf("Loader finished!\n");
2267      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
2268      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
2269      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
2270        progress_dialog->hide();
2271    }
2272    
2273    void MainWindow::on_loader_error()
2274    {
2275        loader->join();
2276        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
2277        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2278        msg.run();
2279        progress_dialog->hide();
2280  }  }
2281    
2282  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 707  bool MainWindow::file_save() Line 2315  bool MainWindow::file_save()
2315    
2316      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
2317      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
2318      try {  
2319          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
2320          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
2321              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
2322              file_is_changed = false;          *this
2323          }      );
2324      } catch (RIFF::Exception e) {  #if HAS_GTKMM_SHOW_ALL_CHILDREN
2325          file_structure_changed_signal.emit(this->file);      progress_dialog->show_all();
2326          Glib::ustring txt = _("Could not save file: ") + e.Message;  #endif
2327          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);      saver = new Saver(this->file); //FIXME: memory leak!
2328          msg.run();      saver->signal_progress().connect(
2329          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2330      }      saver->signal_finished().connect(
2331      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2332        saver->signal_error().connect(
2333            sigc::mem_fun(*this, &MainWindow::on_saver_error));
2334        saver->launch();
2335    
2336        return true;
2337    }
2338    
2339    void MainWindow::on_saver_progress()
2340    {
2341        progress_dialog->set_fraction(saver->get_progress());
2342    }
2343    
2344    void MainWindow::on_saver_error()
2345    {
2346        saver->join();
2347        file_structure_changed_signal.emit(this->file);
2348        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
2349        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2350        msg.run();
2351    }
2352    
2353    void MainWindow::on_saver_finished()
2354    {
2355        saver->join();
2356        this->file = saver->gig;
2357        this->filename = saver->filename;
2358        current_gig_dir = Glib::path_get_dirname(filename);
2359        set_title(Glib::filename_display_basename(filename));
2360        file_has_name = true;
2361        file_is_changed = false;
2362        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
2363      __import_queued_samples();      __import_queued_samples();
2364        std::cout << "Importing queued samples done.\n" << std::flush;
2365    
2366      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
2367      return true;  
2368        __refreshEntireGUI();
2369        progress_dialog->hide();
2370  }  }
2371    
2372  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 735  void MainWindow::on_action_file_save_as( Line 2378  void MainWindow::on_action_file_save_as(
2378  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
2379  {  {
2380      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);
2381    #if HAS_GTKMM_STOCK
2382      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2383      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);
2384    #else
2385        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2386        dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
2387    #endif
2388      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 2  
2389      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
2390      // TODO: an overwrite dialog for gtkmm < 2.8  
2391  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2392      Gtk::FileFilter filter;      Gtk::FileFilter filter;
2393      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
2394    #else
2395        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
2396        filter->add_pattern("*.gig");
2397    #endif
2398      dialog.set_filter(filter);      dialog.set_filter(filter);
2399    
2400      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
2401          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
2402      } else if (current_dir != "") {      {
2403          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
2404            std::string dir = Glib::path_get_dirname(filename);
2405            basename = std::string(_("copy_of_")) + basename;
2406            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
2407            if (Glib::path_is_absolute(filename)) {
2408                dialog.set_filename(copyFileName);
2409            } else {
2410                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
2411            }
2412            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
2413      }      }
2414      dialog.set_current_name(Glib::filename_display_basename(filename));  
2415        // show warning in the dialog
2416        HBox descriptionArea;
2417        descriptionArea.set_spacing(15);
2418        Gtk::Image warningIcon;
2419        warningIcon.set_from_icon_name("dialog-warning",
2420                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
2421        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
2422    #if GTKMM_MAJOR_VERSION < 3
2423        view::WrapLabel description;
2424    #else
2425        Gtk::Label description;
2426        description.set_line_wrap();
2427    #endif
2428        description.set_markup(
2429            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
2430              "<span style=\"italic\">\"Save\"</span> dialog instead of "
2431              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
2432              "to the same .gig file. Using "
2433              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
2434              "same .gig file will end up in corrupted sample wave data!\n")
2435        );
2436        descriptionArea.pack_start(description);
2437    #if USE_GTKMM_BOX
2438        dialog.get_content_area()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2439    #else
2440        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
2441    #endif
2442    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2443        descriptionArea.show_all();
2444    #endif
2445    
2446      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2447          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
2448          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
2449              std::string filename = dialog.get_filename();              filename += ".gig";
             if (!Glib::str_has_suffix(filename, ".gig")) {  
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_dir = Glib::path_get_dirname(filename);  
             set_title(Glib::filename_display_basename(filename));  
             file_has_name = true;  
             file_is_changed = false;  
         } catch (RIFF::Exception e) {  
             file_structure_changed_signal.emit(this->file);  
             Glib::ustring txt = _("Could not save file: ") + e.Message;  
             Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
             msg.run();  
             return false;  
2450          }          }
2451          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
2452          file_structure_changed_signal.emit(this->file);  
2453            progress_dialog = new ProgressDialog( //FIXME: memory leak!
2454                _("Saving") +  Glib::ustring(" '") +
2455                Glib::filename_display_basename(filename) + "' ...",
2456                *this
2457            );
2458    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2459            progress_dialog->show_all();
2460    #endif
2461    
2462            saver = new Saver(file, filename); //FIXME: memory leak!
2463            saver->signal_progress().connect(
2464                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
2465            saver->signal_finished().connect(
2466                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
2467            saver->signal_error().connect(
2468                sigc::mem_fun(*this, &MainWindow::on_saver_error));
2469            saver->launch();
2470    
2471          return true;          return true;
2472      }      }
2473      return false;      return false;
# Line 786  bool MainWindow::file_save_as() Line 2477  bool MainWindow::file_save_as()
2477  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
2478      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
2479      Glib::ustring error_files;      Glib::ustring error_files;
2480      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
2481      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2482           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
2483          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
2484          SF_INFO info;          SF_INFO info;
2485          info.format = 0;          info.format = 0;
2486          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);
2487            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
2488          try {          try {
2489              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
2490              // determine sample's bit depth              // determine sample's bit depth
2491              int bitdepth;              int bitdepth;
2492              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 811  void MainWindow::__import_queued_samples Line 2503  void MainWindow::__import_queued_samples
2503                      break;                      break;
2504                  default:                  default:
2505                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
2506                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
2507              }              }
2508    
2509                // reset write position for sample
2510                iter->first->SetPos(0);
2511    
2512              const int bufsize = 10000;              const int bufsize = 10000;
2513              switch (bitdepth) {              switch (bitdepth) {
2514                  case 16: {                  case 16: {
# Line 823  void MainWindow::__import_queued_samples Line 2518  void MainWindow::__import_queued_samples
2518                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
2519                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
2520                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2521                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
2522                          cnt -= n;                          cnt -= n;
2523                      }                      }
2524                      delete[] buffer;                      delete[] buffer;
# Line 843  void MainWindow::__import_queued_samples Line 2538  void MainWindow::__import_queued_samples
2538                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
2539                          }                          }
2540                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
2541                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
2542                          cnt -= n;                          cnt -= n;
2543                      }                      }
2544                      delete[] srcbuf;                      delete[] srcbuf;
# Line 853  void MainWindow::__import_queued_samples Line 2548  void MainWindow::__import_queued_samples
2548              }              }
2549              // cleanup              // cleanup
2550              sf_close(hFile);              sf_close(hFile);
2551                // let the sampler re-cache the sample if needed
2552                sample_changed_signal.emit(iter->first);
2553              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
2554              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
2555              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
2556              ++iter;              ++iter;
2557              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
2558          } catch (std::string what) {          } catch (std::string what) {
2559              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
2560              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
2561              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
2562              ++iter;              ++iter;
2563          }          }
2564      }      }
2565      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
2566      if (error_files.size()) {      if (!error_files.empty()) {
2567          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;
2568          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2569          msg.run();          msg.run();
# Line 879  void MainWindow::on_action_file_properti Line 2576  void MainWindow::on_action_file_properti
2576      propDialog.deiconify();      propDialog.deiconify();
2577  }  }
2578    
2579    void MainWindow::on_action_warn_user_on_extensions() {
2580        Settings::singleton()->warnUserOnExtensions =
2581            !Settings::singleton()->warnUserOnExtensions;
2582    }
2583    
2584    void MainWindow::on_action_show_tooltips() {
2585        Settings::singleton()->showTooltips =
2586            !Settings::singleton()->showTooltips;
2587    
2588        on_show_tooltips_changed();
2589    }
2590    
2591    void MainWindow::on_show_tooltips_changed() {
2592        const bool b = Settings::singleton()->showTooltips;
2593    
2594        dimreg_label.set_has_tooltip(b);
2595        dimreg_all_regions.set_has_tooltip(b);
2596        dimreg_all_dimregs.set_has_tooltip(b);
2597        dimreg_stereo.set_has_tooltip(b);
2598    
2599        // Not doing this here, we let onQueryTreeViewTooltip() handle this per cell
2600        //m_TreeView.set_has_tooltip(b);
2601    
2602        m_TreeViewSamples.set_has_tooltip(b);
2603        m_TreeViewScripts.set_has_tooltip(b);
2604    
2605        set_has_tooltip(b);
2606    }
2607    
2608    void MainWindow::on_action_sync_sampler_instrument_selection() {
2609        Settings::singleton()->syncSamplerInstrumentSelection =
2610            !Settings::singleton()->syncSamplerInstrumentSelection;
2611    }
2612    
2613    void MainWindow::on_action_move_root_note_with_region_moved() {
2614        Settings::singleton()->moveRootNoteWithRegionMoved =
2615            !Settings::singleton()->moveRootNoteWithRegionMoved;
2616    }
2617    
2618  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
2619  {  {
 #ifdef ABOUT_DIALOG  
2620      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
2621    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
2622        dialog.set_program_name("Gigedit");
2623    #else
2624        dialog.set_name("Gigedit");
2625    #endif
2626      dialog.set_version(VERSION);      dialog.set_version(VERSION);
2627      dialog.set_copyright("Copyright (C) 2006,2007 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2019 Andreas Persson");
2628      dialog.set_comments(      const std::string sComment =
2629          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
2630          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
2631          "Please notice that this is still a very young instrument editor. "          _(
2632          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
2633          "this application.\n"              "\n"
2634          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
2635          "Please report bugs to: http://bugs.linuxsampler.org"              "backup your Gigasampler/GigaStudio files before editing them with "
2636      );              "this application.\n"
2637                "\n"
2638                "Please report bugs to: http://bugs.linuxsampler.org"
2639            );
2640        dialog.set_comments(sComment.c_str());
2641      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
2642      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
2643        dialog.set_position(Gtk::WIN_POS_CENTER);
2644      dialog.run();      dialog.run();
 #endif  
2645  }  }
2646    
2647  PropDialog::PropDialog()  PropDialog::PropDialog()
2648      : table(2,1),      : eFileFormat(_("File Format")),
2649        eName("Name"),        eName(_("Name")),
2650        eCreationDate("Creation date"),        eCreationDate(_("Creation date")),
2651        eComments("Comments"),        eComments(_("Comments")),
2652        eProduct("Product"),        eProduct(_("Product")),
2653        eCopyright("Copyright"),        eCopyright(_("Copyright")),
2654        eArtists("Artists"),        eArtists(_("Artists")),
2655        eGenre("Genre"),        eGenre(_("Genre")),
2656        eKeywords("Keywords"),        eKeywords(_("Keywords")),
2657        eEngineer("Engineer"),        eEngineer(_("Engineer")),
2658        eTechnician("Technician"),        eTechnician(_("Technician")),
2659        eSoftware("Software"),        eSoftware(_("Software")),
2660        eMedium("Medium"),        eMedium(_("Medium")),
2661        eSource("Source"),        eSource(_("Source")),
2662        eSourceForm("Source form"),        eSourceForm(_("Source form")),
2663        eCommissioned("Commissioned"),        eCommissioned(_("Commissioned")),
2664        eSubject("Subject"),        eSubject(_("Subject")),
2665    #if HAS_GTKMM_STOCK
2666        quitButton(Gtk::Stock::CLOSE),        quitButton(Gtk::Stock::CLOSE),
2667        update_model(0)  #else
2668          quitButton(_("_Close")),
2669    #endif
2670          table(2, 1),
2671          m_file(NULL)
2672  {  {
2673      set_title("File Properties");      if (!Settings::singleton()->autoRestoreWindowDimension) {
2674            set_default_size(470, 390);
2675            set_position(Gtk::WIN_POS_MOUSE);
2676        }
2677    
2678        set_title(_("File Properties"));
2679      eName.set_width_chars(50);      eName.set_width_chars(50);
2680    
2681        connect(eFileFormat, &PropDialog::set_FileFormat);
2682      connect(eName, &DLS::Info::Name);      connect(eName, &DLS::Info::Name);
2683      connect(eCreationDate, &DLS::Info::CreationDate);      connect(eCreationDate, &DLS::Info::CreationDate);
2684      connect(eComments, &DLS::Info::Comments);      connect(eComments, &DLS::Info::Comments);
# Line 941  PropDialog::PropDialog() Line 2696  PropDialog::PropDialog()
2696      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
2697      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
2698    
2699        table.add(eFileFormat);
2700      table.add(eName);      table.add(eName);
2701      table.add(eCreationDate);      table.add(eCreationDate);
2702      table.add(eComments);      table.add(eComments);
# Line 958  PropDialog::PropDialog() Line 2714  PropDialog::PropDialog()
2714      table.add(eCommissioned);      table.add(eCommissioned);
2715      table.add(eSubject);      table.add(eSubject);
2716    
2717    #if USE_GTKMM_GRID
2718        table.set_column_spacing(5);
2719    #else
2720      table.set_col_spacings(5);      table.set_col_spacings(5);
2721    #endif
2722    
2723      add(vbox);      add(vbox);
2724    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2725        table.set_margin(5);
2726    #else
2727      table.set_border_width(5);      table.set_border_width(5);
2728    #endif
2729      vbox.add(table);      vbox.add(table);
2730      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
2731      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
2732    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2733        buttonBox.set_margin(5);
2734    #else
2735      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2736    #endif
2737      buttonBox.show();      buttonBox.show();
2738      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2739      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
2740      quitButton.grab_focus();      quitButton.grab_focus();
2741      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
2742          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &PropDialog::hide));
2743    
2744      quitButton.show();      quitButton.show();
2745      vbox.show();      vbox.show();
2746    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2747      show_all_children();      show_all_children();
2748    #endif
2749  }  }
2750    
2751  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_file(gig::File* file)
2752  {  {
2753      this->info = info;      m_file = file;
2754        update(file->pInfo);
2755    
2756        // update file format version combo box
2757        const std::string sGiga = "Gigasampler/GigaStudio v";
2758        const int major = file->pVersion->major;
2759        std::vector<std::string> txts;
2760        std::vector<int> values;
2761        txts.push_back(sGiga + "2"); values.push_back(2);
2762        txts.push_back(sGiga + "3"); values.push_back(3);
2763        txts.push_back(sGiga + "4"); values.push_back(4);
2764        if (major < 2 || major > 4) {
2765            txts.push_back(sGiga + ToString(major)); values.push_back(major);
2766        }
2767        std::vector<const char*> texts;
2768        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
2769        texts.push_back(NULL); values.push_back(0);
2770    
2771      update_model++;      update_model++;
2772      eName.set_value(info->Name);      eFileFormat.set_choices(&texts[0], &values[0]);
2773      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);  
2774      update_model--;      update_model--;
2775  }  }
2776    
2777  sigc::signal<void>& PropDialog::signal_info_changed()  void PropDialog::set_FileFormat(int value)
2778  {  {
2779      return info_changed;      m_file->pVersion->major = value;
2780  }  }
2781    
2782  void InstrumentProps::set_IsDrum(bool value)  
2783    void InstrumentProps::set_Name(const gig::String& name)
2784  {  {
2785      instrument->IsDrum = value;      m->pInfo->Name = name;
2786  }  }
2787    
2788  void InstrumentProps::set_MIDIBank(uint16_t value)  void InstrumentProps::update_name()
2789  {  {
2790      instrument->MIDIBank = value;      update_model++;
2791        eName.set_value(m->pInfo->Name);
2792        update_model--;
2793  }  }
2794    
2795  void InstrumentProps::set_MIDIProgram(uint32_t value)  void InstrumentProps::set_IsDrum(bool value)
2796  {  {
2797      instrument->MIDIProgram = value;      m->IsDrum = value;
2798  }  }
2799    
2800  void InstrumentProps::set_DimensionKeyRange_low(uint8_t value)  void InstrumentProps::set_MIDIBank(uint16_t value)
2801  {  {
2802      instrument->DimensionKeyRange.low = value;      m->MIDIBank = value;
     if (value > instrument->DimensionKeyRange.high) {  
         eDimensionKeyRangeHigh.set_value(value);  
     }  
2803  }  }
2804    
2805  void InstrumentProps::set_DimensionKeyRange_high(uint8_t value)  void InstrumentProps::set_MIDIProgram(uint32_t value)
2806  {  {
2807      instrument->DimensionKeyRange.high = value;      m->MIDIProgram = value;
     if (value < instrument->DimensionKeyRange.low) {  
         eDimensionKeyRangeLow.set_value(value);  
     }  
2808  }  }
2809    
2810  InstrumentProps::InstrumentProps()  InstrumentProps::InstrumentProps() :
2811      : table(2,1),  #if HAS_GTKMM_STOCK
2812        quitButton(Gtk::Stock::CLOSE),      quitButton(Gtk::Stock::CLOSE),
2813        eName("Name"),  #else
2814        eIsDrum("Is drum"),      quitButton(_("_Close")),
2815        eMIDIBank("MIDI bank", 0, 16383),  #endif
2816        eMIDIProgram("MIDI program"),      table(2,1),
2817        eAttenuation("Attenuation", 0, 96, 0, 1),      eName(_("Name")),
2818        eGainPlus6("Gain +6dB", eAttenuation, -6),      eIsDrum(_("Is drum")),
2819        eEffectSend("Effect send", 0, 65535),      eMIDIBank(_("MIDI bank"), 0, 16383),
2820        eFineTune("Fine tune", -8400, 8400),      eMIDIProgram(_("MIDI program")),
2821        ePitchbendRange("Pitchbend range", 0, 12),      eAttenuation(_("Attenuation"), 0, 96, 0, 1),
2822        ePianoReleaseMode("Piano release mode"),      eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
2823        eDimensionKeyRangeLow("Keyswitching range low"),      eEffectSend(_("Effect send"), 0, 65535),
2824        eDimensionKeyRangeHigh("Keyswitching range high"),      eFineTune(_("Fine tune"), -8400, 8400),
2825        update_model(0)      ePitchbendRange(_("Pitchbend range"), 0, 48),
2826  {      ePianoReleaseMode(_("Piano release mode")),
2827      set_title("Instrument Properties");      eDimensionKeyRangeLow(_("Keyswitching range low")),
2828        eDimensionKeyRangeHigh(_("Keyswitching range high"))
2829    {
2830        if (!Settings::singleton()->autoRestoreWindowDimension) {
2831            //set_default_size(470, 390);
2832            set_position(Gtk::WIN_POS_MOUSE);
2833        }
2834    
2835        set_title(_("Instrument Properties"));
2836    
2837      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
2838          _("start of the keyboard area which should switch the "          _("start of the keyboard area which should switch the "
# Line 1064  InstrumentProps::InstrumentProps() Line 2843  InstrumentProps::InstrumentProps()
2843            "\"keyswitching\" dimension")            "\"keyswitching\" dimension")
2844      );      );
2845    
2846        connect(eName, &InstrumentProps::set_Name);
2847      connect(eIsDrum, &InstrumentProps::set_IsDrum);      connect(eIsDrum, &InstrumentProps::set_IsDrum);
2848      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);      connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
2849      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);      connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
# Line 1073  InstrumentProps::InstrumentProps() Line 2853  InstrumentProps::InstrumentProps()
2853      connect(eFineTune, &gig::Instrument::FineTune);      connect(eFineTune, &gig::Instrument::FineTune);
2854      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);      connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
2855      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);      connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
2856      connect(eDimensionKeyRangeLow,      connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
2857              &InstrumentProps::set_DimensionKeyRange_low);              &gig::Instrument::DimensionKeyRange);
2858      connect(eDimensionKeyRangeHigh,  
2859              &InstrumentProps::set_DimensionKeyRange_high);      eName.signal_value_changed().connect(sig_name_changed.make_slot());
2860    
2861    #if USE_GTKMM_GRID
2862        table.set_column_spacing(5);
2863    #else
2864      table.set_col_spacings(5);      table.set_col_spacings(5);
2865    #endif
2866    
2867      table.add(eName);      table.add(eName);
2868      table.add(eIsDrum);      table.add(eIsDrum);
# Line 1094  InstrumentProps::InstrumentProps() Line 2878  InstrumentProps::InstrumentProps()
2878      table.add(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
2879    
2880      add(vbox);      add(vbox);
2881    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2882        table.set_margin(5);
2883    #else
2884      table.set_border_width(5);      table.set_border_width(5);
2885    #endif
2886      vbox.pack_start(table);      vbox.pack_start(table);
2887      table.show();      table.show();
2888      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
2889      buttonBox.set_layout(Gtk::BUTTONBOX_END);      buttonBox.set_layout(Gtk::BUTTONBOX_END);
2890    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
2891        buttonBox.set_margin(5);
2892    #else
2893      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
2894    #endif
2895      buttonBox.show();      buttonBox.show();
2896      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
2897      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
2898      quitButton.grab_focus();      quitButton.grab_focus();
2899    
2900      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 1110  InstrumentProps::InstrumentProps() Line 2902  InstrumentProps::InstrumentProps()
2902    
2903      quitButton.show();      quitButton.show();
2904      vbox.show();      vbox.show();
2905    #if HAS_GTKMM_SHOW_ALL_CHILDREN
2906      show_all_children();      show_all_children();
2907    #endif
2908  }  }
2909    
2910  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
2911  {  {
2912      this->instrument = instrument;      update(instrument);
2913    
2914      update_model++;      update_model++;
2915      eName.set_value(instrument->pInfo->Name);      eName.set_value(instrument->pInfo->Name);
2916      eIsDrum.set_value(instrument->IsDrum);      eIsDrum.set_value(instrument->IsDrum);
2917      eMIDIBank.set_value(instrument->MIDIBank);      eMIDIBank.set_value(instrument->MIDIBank);
2918      eMIDIProgram.set_value(instrument->MIDIProgram);      eMIDIProgram.set_value(instrument->MIDIProgram);
     eAttenuation.set_value(instrument->Attenuation);  
     eGainPlus6.set_value(instrument->Attenuation);  
     eEffectSend.set_value(instrument->EffectSend);  
     eFineTune.set_value(instrument->FineTune);  
     ePitchbendRange.set_value(instrument->PitchbendRange);  
     ePianoReleaseMode.set_value(instrument->PianoReleaseMode);  
     eDimensionKeyRangeLow.set_value(instrument->DimensionKeyRange.low);  
     eDimensionKeyRangeHigh.set_value(instrument->DimensionKeyRange.high);  
2919      update_model--;      update_model--;
2920  }  }
2921    
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
2922    
2923  void MainWindow::file_changed()  void MainWindow::file_changed()
2924  {  {
# Line 1146  void MainWindow::file_changed() Line 2928  void MainWindow::file_changed()
2928      }      }
2929  }  }
2930    
2931    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
2932        sample_ref_count.clear();
2933        
2934        if (!gig) return;
2935    
2936        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
2937             instrument = gig->GetNextInstrument())
2938        {
2939            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2940                 rgn = instrument->GetNextRegion())
2941            {
2942                for (int i = 0; i < 256; ++i) {
2943                    if (!rgn->pDimensionRegions[i]) continue;
2944                    if (rgn->pDimensionRegions[i]->pSample) {
2945                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
2946                    }
2947                }
2948            }
2949        }
2950    }
2951    
2952    bool MainWindow::onQueryTreeViewTooltip(int x, int y, bool keyboardTip, const Glib::RefPtr<Gtk::Tooltip>& tooltip) {
2953        Gtk::TreeModel::iterator iter;
2954        if (!m_TreeView.get_tooltip_context_iter(x, y, keyboardTip, iter)) {
2955            return false;
2956        }
2957        Gtk::TreeModel::Path path(iter);
2958        Gtk::TreeModel::Row row = *iter;
2959        Gtk::TreeViewColumn* pointedColumn = NULL;
2960        // resolve the precise table column the mouse points to
2961        {
2962            Gtk::TreeModel::Path path; // unused
2963            int cellX, cellY; // unused
2964            m_TreeView.get_path_at_pos(x, y, path, pointedColumn, cellX, cellY);
2965        }
2966        Gtk::TreeViewColumn* scriptsColumn = m_TreeView.get_column(2);
2967        if (pointedColumn == scriptsColumn) { // mouse hovers scripts column ...
2968            // show the script(s) assigned to the hovered instrument as tooltip
2969            tooltip->set_markup( row[m_Columns.m_col_tooltip] );
2970            m_TreeView.set_tooltip_cell(tooltip, &path, scriptsColumn, NULL);
2971        } else {
2972            // if beginners' tooltips is disabled then don't show the following one
2973            if (!Settings::singleton()->showTooltips)
2974                return false;
2975            // yeah, a beginners tooltip
2976            tooltip->set_text(_(
2977                "Right click here for actions on instruments & MIDI Rules. "
2978                "Drag & drop to change the order of instruments."
2979            ));
2980            m_TreeView.set_tooltip_cell(tooltip, &path, pointedColumn, NULL);
2981        }
2982        return true;
2983    }
2984    
2985    static Glib::ustring scriptTooltipFor(gig::Instrument* instrument, int index) {
2986        Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2987        const int iScriptSlots = instrument->ScriptSlotCount();
2988        Glib::ustring tooltip = "<u>(" + ToString(index) + ") “"  + name + "”</u>\n\n";
2989        if (!iScriptSlots)
2990            tooltip += "<span foreground='red'><i>No script assigned</i></span>";
2991        else {
2992            for (int i = 0; i < iScriptSlots; ++i) {
2993                tooltip += "• " + ToString(i+1) + ". Script: “<span foreground='#46DEFF'><b>" +
2994                           instrument->GetScriptOfSlot(i)->Name + "</b></span>”";
2995                if (i + 1 < iScriptSlots) tooltip += "\n\n";
2996            }
2997        }
2998        return tooltip;
2999    }
3000    
3001  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
3002  {  {
3003      file = 0;      file = 0;
3004      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
3005    
3006      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
3007            (filename && strlen(filename) > 0) ?
3008                filename : (!gig->GetFileName().empty()) ?
3009                    gig->GetFileName() : _("Unsaved Gig File");
3010      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
3011      file_has_name = filename;      file_has_name = filename;
3012      file_is_changed = false;      file_is_changed = false;
3013    
3014      propDialog.set_info(gig->pInfo);      propDialog.set_file(gig);
   
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
3015    
3016      int instrument_index = 0;      instrument_name_connection.block();
3017      Gtk::RadioMenuItem::Group instrument_group;      int index = 0;
3018      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
3019           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
3020            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3021            const int iScriptSlots = instrument->ScriptSlotCount();
3022    
3023          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
3024          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
3025          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
3026            row[m_Columns.m_col_name] = name;
3027          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
3028          // create a menu item for this instrument          row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3029          Gtk::RadioMenuItem* item =          row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3030              new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());  
3031          instrument_menu->get_submenu()->append(*item);  #if !USE_GTKMM_BUILDER
3032          item->signal_activate().connect(          add_instrument_to_menu(name);
3033              sigc::bind(  #endif
                 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  
                 instrument_index  
             )  
         );  
         instrument_index++;  
3034      }      }
3035      instrument_menu->show();      instrument_name_connection.unblock();
3036      instrument_menu->get_submenu()->show_all_children();  #if !USE_GTKMM_BUILDER
3037        uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
3038    #endif
3039    
3040        updateSampleRefCountMap(gig);
3041    
3042      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
3043          if (group->Name != "") {          if (group->Name != "") {
3044              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
3045              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
3046              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
3047              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
3048              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
3049              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1196  void MainWindow::load_gig(gig::File* gig Line 3051  void MainWindow::load_gig(gig::File* gig
3051                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
3052                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
3053                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
3054                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
3055                        gig_to_utf8(sample->pInfo->Name);
3056                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
3057                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
3058                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
3059                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3060                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3061              }              }
3062          }          }
3063      }      }
3064        
3065        for (int i = 0; gig->GetScriptGroup(i); ++i) {
3066            gig::ScriptGroup* group = gig->GetScriptGroup(i);
3067    
3068            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
3069            Gtk::TreeModel::Row rowGroup = *iterGroup;
3070            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
3071            rowGroup[m_ScriptsModel.m_col_group]  = group;
3072            rowGroup[m_ScriptsModel.m_col_script] = NULL;
3073            for (int s = 0; group->GetScript(s); ++s) {
3074                gig::Script* script = group->GetScript(s);
3075    
3076                Gtk::TreeModel::iterator iterScript =
3077                    m_refScriptsTreeModel->append(rowGroup.children());
3078                Gtk::TreeModel::Row rowScript = *iterScript;
3079                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
3080                rowScript[m_ScriptsModel.m_col_script] = script;
3081                rowScript[m_ScriptsModel.m_col_group]  = NULL;
3082            }
3083        }
3084        // unfold all sample groups & script groups by default
3085        m_TreeViewSamples.expand_all();
3086        m_TreeViewScripts.expand_all();
3087    
3088      file = gig;      file = gig;
3089    
3090      // select the first instrument      // select the first instrument
3091      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
3092      tree_sel_ref->select(Gtk::TreePath("0"));  
3093        instr_props_set_instrument();
3094        gig::Instrument* instrument = get_instrument();
3095        if (instrument) {
3096            midiRules.set_instrument(instrument);
3097        }
3098  }  }
3099    
3100  void MainWindow::show_instr_props()  bool MainWindow::instr_props_set_instrument()
3101  {  {
3102      gig::Instrument* instrument = get_instrument();      instrumentProps.signal_name_changed().clear();
3103      if (instrument)  
3104      {      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3105        if (rows.empty()) {
3106            instrumentProps.hide();
3107            return false;
3108        }
3109        //NOTE: was const_iterator before, which did not compile with GTKMM4 development branch, probably going to be fixed before final GTKMM4 release though.
3110        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3111        if (it) {
3112            Gtk::TreeModel::Row row = *it;
3113            gig::Instrument* instrument = row[m_Columns.m_col_instr];
3114    
3115          instrumentProps.set_instrument(instrument);          instrumentProps.set_instrument(instrument);
3116    
3117            // make sure instrument tree is updated when user changes the
3118            // instrument name in instrument properties window
3119            instrumentProps.signal_name_changed().connect(
3120                sigc::bind(
3121                    sigc::mem_fun(*this,
3122                                  &MainWindow::instr_name_changed_by_instr_props),
3123                    it));
3124        } else {
3125            instrumentProps.hide();
3126        }
3127        //NOTE: explicit boolean cast required for GTKMM4 development branch here
3128        return it ? true : false;
3129    }
3130    
3131    void MainWindow::show_instr_props()
3132    {
3133        if (instr_props_set_instrument()) {
3134          instrumentProps.show();          instrumentProps.show();
3135          instrumentProps.deiconify();          instrumentProps.deiconify();
3136      }      }
3137  }  }
3138    
3139    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
3140    {
3141        Gtk::TreeModel::Row row = *it;
3142        Glib::ustring name = row[m_Columns.m_col_name];
3143    
3144        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3145        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
3146        if (gigname != name) {
3147            Gtk::TreeModel::Path path(*it);
3148            const int index = path[0];
3149            row[m_Columns.m_col_name] = gigname;
3150            row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3151        }
3152    }
3153    
3154    void MainWindow::show_midi_rules()
3155    {
3156        if (gig::Instrument* instrument = get_instrument())
3157        {
3158            midiRules.set_instrument(instrument);
3159            midiRules.show();
3160            midiRules.deiconify();
3161        }
3162    }
3163    
3164    void MainWindow::show_script_slots() {
3165        if (!file) return;
3166        // get selected instrument
3167        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
3168        if (rows.empty()) return;
3169        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3170        if (!it) return;
3171        Gtk::TreeModel::Row row = *it;
3172        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3173        if (!instrument) return;
3174    
3175        ScriptSlots* window = new ScriptSlots;
3176        window->setInstrument(instrument);
3177        window->signal_script_slots_changed().connect(
3178            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
3179        );
3180        //window->reparent(*this);
3181        window->show();
3182    }
3183    
3184    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
3185        if (!pInstrument) return;
3186        const int iScriptSlots = pInstrument->ScriptSlotCount();
3187    
3188        //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!
3189        //Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3190        Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3191    
3192        for (int i = 0; i < model->children().size(); ++i) {
3193            Gtk::TreeModel::Row row = model->children()[i];
3194            if (row[m_Columns.m_col_instr] != pInstrument) continue;
3195            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
3196            row[m_Columns.m_col_tooltip] = scriptTooltipFor(pInstrument, i);
3197            break;
3198        }
3199    
3200        // causes the sampler to reload the instrument with the new script
3201        on_sel_change();
3202    }
3203    
3204    void MainWindow::assignScript(gig::Script* pScript) {
3205        if (!pScript) {
3206            printf("assignScript() : !script\n");
3207            return;
3208        }
3209        printf("assignScript('%s')\n", pScript->Name.c_str());
3210    
3211        gig::Instrument* pInstrument = get_instrument();
3212        if (!pInstrument) {
3213            printf("!instrument\n");
3214            return;
3215        }
3216    
3217        pInstrument->AddScriptSlot(pScript);
3218    
3219        onScriptSlotsModified(pInstrument);
3220    }
3221    
3222    void MainWindow::dropAllScriptSlots() {
3223        gig::Instrument* pInstrument = get_instrument();
3224        if (!pInstrument) {
3225            printf("!instrument\n");
3226            return;
3227        }
3228    
3229        const int iScriptSlots = pInstrument->ScriptSlotCount();
3230        for (int i = iScriptSlots - 1; i >= 0; --i)
3231            pInstrument->RemoveScriptSlot(i);
3232    
3233        onScriptSlotsModified(pInstrument);
3234    }
3235    
3236    void MainWindow::on_action_refresh_all() {
3237        __refreshEntireGUI();
3238    }
3239    
3240  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
3241    #if USE_GLIB_ACTION
3242        bool active = false;
3243        m_actionToggleStatusBar->get_state(active);
3244        // for some reason toggle state does not change automatically
3245        active = !active;
3246        m_actionToggleStatusBar->change_state(active);
3247        if (active)
3248            m_StatusBar.show();
3249        else
3250            m_StatusBar.hide();
3251    #else
3252      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
3253          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
3254      if (!item) {      if (!item) {
# Line 1230  void MainWindow::on_action_view_status_b Line 3257  void MainWindow::on_action_view_status_b
3257      }      }
3258      if (item->get_active()) m_StatusBar.show();      if (item->get_active()) m_StatusBar.show();
3259      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
3260    #endif
3261  }  }
3262    
3263  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_auto_restore_win_dim() {
3264  {  #if USE_GLIB_ACTION
3265        bool active = false;
3266        m_actionToggleRestoreWinDim->get_state(active);
3267        // for some reason toggle state does not change automatically
3268        active = !active;
3269        m_actionToggleRestoreWinDim->change_state(active);
3270        Settings::singleton()->autoRestoreWindowDimension = active;
3271    #else
3272        Gtk::CheckMenuItem* item =
3273            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
3274        if (!item) {
3275            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
3276            return;
3277        }
3278        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
3279    #endif
3280    }
3281    
3282    void MainWindow::on_save_with_temporary_file() {
3283    #if USE_GLIB_ACTION
3284        bool active = false;
3285        m_actionToggleSaveWithTempFile->get_state(active);
3286        // for some reason toggle state does not change automatically
3287        active = !active;
3288        m_actionToggleSaveWithTempFile->change_state(active);
3289        Settings::singleton()->saveWithTemporaryFile = active;
3290    #else
3291        Gtk::CheckMenuItem* item =
3292            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
3293        if (!item) {
3294            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
3295            return;
3296        }
3297        Settings::singleton()->saveWithTemporaryFile = item->get_active();
3298    #endif
3299    }
3300    
3301    bool MainWindow::is_copy_samples_unity_note_enabled() const {
3302    #if USE_GLIB_ACTION
3303        bool active = false;
3304        m_actionToggleCopySampleUnity->get_state(active);
3305        return active;
3306    #else
3307        Gtk::CheckMenuItem* item =
3308            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
3309        if (!item) {
3310            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
3311            return true;
3312        }
3313        return item->get_active();
3314    #endif
3315    }
3316    
3317    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
3318    #if USE_GLIB_ACTION
3319        bool active = false;
3320        m_actionToggleCopySampleTune->get_state(active);
3321        return active;
3322    #else
3323        Gtk::CheckMenuItem* item =
3324            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
3325        if (!item) {
3326            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
3327            return true;
3328        }
3329        return item->get_active();
3330    #endif
3331    }
3332    
3333    bool MainWindow::is_copy_samples_loop_enabled() const {
3334    #if USE_GLIB_ACTION
3335        bool active = false;
3336        m_actionToggleCopySampleLoop->get_state(active);
3337        return active;
3338    #else
3339        Gtk::CheckMenuItem* item =
3340            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
3341        if (!item) {
3342            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
3343            return true;
3344        }
3345        return item->get_active();
3346    #endif
3347    }
3348    
3349    #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
3350    bool MainWindow::on_button_release(Gdk::EventButton& _button) {
3351        GdkEventButton* button = _button.gobj();
3352    #else
3353    void MainWindow::on_button_release(GdkEventButton* button) {
3354    #endif
3355      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
3356          show_instr_props();          show_instr_props();
3357      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3358            // gig v2 files have no midi rules
3359            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
3360    #if USE_GTKMM_BUILDER
3361            m_actionMIDIRules->property_enabled() = bEnabled;
3362    #else
3363            static_cast<Gtk::MenuItem*>(
3364                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
3365                    bEnabled
3366                );
3367            static_cast<Gtk::MenuItem*>(
3368                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
3369                    bEnabled
3370                );
3371    #endif
3372          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
3373      }      }
3374    #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
3375        return false;
3376    #endif
3377  }  }
3378    
3379  void MainWindow::on_instrument_selection_change(int index) {  #if !USE_GTKMM_BUILDER
3380      m_RegionChooser.set_instrument(file->GetInstrument(index));  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
3381        if (item->get_active()) {
3382            const std::vector<Gtk::Widget*> children =
3383                instrument_menu->get_children();
3384            std::vector<Gtk::Widget*>::const_iterator it =
3385                find(children.begin(), children.end(), item);
3386            if (it != children.end()) {
3387                int index = it - children.begin();
3388                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
3389    
3390                m_RegionChooser.set_instrument(file->GetInstrument(index));
3391            }
3392        }
3393  }  }
3394    #endif
3395    
3396    void MainWindow::select_instrument(gig::Instrument* instrument) {
3397        if (!instrument) return;
3398    
3399        //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!
3400        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3401        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3402    
3403        for (int i = 0; i < model->children().size(); ++i) {
3404            Gtk::TreeModel::Row row = model->children()[i];
3405            if (row[m_Columns.m_col_instr] == instrument) {
3406                // select and show the respective instrument in the list view
3407                show_intruments_tab();
3408                m_TreeView.get_selection()->unselect_all();
3409                
3410    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3411                auto iterSel = model->children()[i].get_iter();
3412                m_TreeView.get_selection()->select(iterSel);
3413    #else
3414                m_TreeView.get_selection()->select(model->children()[i]);
3415    #endif
3416                std::vector<Gtk::TreeModel::Path> rows =
3417                    m_TreeView.get_selection()->get_selected_rows();
3418                if (!rows.empty())
3419                    m_TreeView.scroll_to_row(rows[0]);
3420                on_sel_change(); // the regular instrument selection change callback
3421            }
3422        }
3423    }
3424    
3425    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
3426    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
3427        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
3428        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
3429    
3430        //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!
3431        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
3432        //Glib::RefPtr<Gtk::TreeModel> model = m_refTreeModelFilter->get_model();
3433    
3434        for (int i = 0; i < model->children().size(); ++i) {
3435            Gtk::TreeModel::Row row = model->children()[i];
3436            if (row[m_Columns.m_col_instr] == pInstrument) {
3437                // select and show the respective instrument in the list view
3438                show_intruments_tab();
3439                m_TreeView.get_selection()->unselect_all();
3440    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3441                auto iterSel = model->children()[i].get_iter();
3442                m_TreeView.get_selection()->select(iterSel);
3443    #else
3444                m_TreeView.get_selection()->select(model->children()[i]);
3445    #endif
3446                std::vector<Gtk::TreeModel::Path> rows =
3447                    m_TreeView.get_selection()->get_selected_rows();
3448                if (!rows.empty())
3449                    m_TreeView.scroll_to_row(rows[0]);
3450                on_sel_change(); // the regular instrument selection change callback
3451    
3452                // select respective region in the region selector
3453                m_RegionChooser.set_region(pRegion);
3454    
3455                // select and show the respective dimension region in the editor
3456                //update_dimregs();
3457                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
3458                //dimreg_edit.set_dim_region(dimRgn);
3459    
3460                return true;
3461            }
3462        }
3463    
3464        return false;
3465    }
3466    
3467    void MainWindow::select_sample(gig::Sample* sample) {
3468        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3469        for (int g = 0; g < model->children().size(); ++g) {
3470            Gtk::TreeModel::Row rowGroup = model->children()[g];
3471            for (int s = 0; s < rowGroup.children().size(); ++s) {
3472                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3473                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
3474                    show_samples_tab();
3475                    m_TreeViewSamples.get_selection()->unselect_all();
3476    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
3477                    auto iterSel = rowGroup.children()[s].get_iter();
3478                    m_TreeViewSamples.get_selection()->select(iterSel);
3479    #else
3480                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
3481    #endif
3482                    std::vector<Gtk::TreeModel::Path> rows =
3483                        m_TreeViewSamples.get_selection()->get_selected_rows();
3484                    if (rows.empty()) return;
3485                    m_TreeViewSamples.scroll_to_row(rows[0]);
3486                    return;
3487                }
3488            }
3489        }
3490    }
3491    
3492    #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
3493    bool MainWindow::on_sample_treeview_button_release(Gdk::EventButton& _button) {
3494        GdkEventButton* button = _button.gobj();
3495    #else
3496  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
3497    #endif
3498      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3499            // by default if Ctrl keys is pressed down, then a mouse right-click
3500            // does not select the respective row, so we must assure this
3501            // programmatically ...
3502            /*{
3503                Gtk::TreeModel::Path path;
3504                Gtk::TreeViewColumn* pColumn = NULL;
3505                int cellX, cellY;
3506                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
3507                    (int)button->x, (int)button->y,
3508                    path, pColumn, cellX, cellY
3509                );
3510                if (bSuccess) {
3511                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
3512                        printf("not selected !!!\n");
3513                        m_TreeViewSamples.get_selection()->select(path);
3514                    }
3515                }
3516            }*/
3517    
3518    #if !USE_GTKMM_BUILDER
3519          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
3520              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
3521    #endif
3522    
3523          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
3524          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3525          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3526          bool group_selected  = false;          const int n = rows.size();
3527          bool sample_selected = false;          int nGroups  = 0;
3528          if (it) {          int nSamples = 0;
3529            for (int r = 0; r < n; ++r) {
3530                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3531                if (!it) continue;
3532              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
3533              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
3534              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
3535          }          }
3536    
3537    #if USE_GTKMM_BUILDER
3538            m_actionSampleProperties->property_enabled() = (n == 1);
3539            m_actionAddSample->property_enabled() = (n);
3540            m_actionAddSampleGroup->property_enabled() = (file);
3541            m_actionViewSampleRefs->property_enabled() = (nSamples == 1);
3542            m_actionRemoveSample->property_enabled() = (n);
3543            m_actionReplaceSample->property_enabled() = (nSamples == 1);
3544    #else
3545          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
3546              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
3547          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
3548              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
3549          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
3550              set_sensitive(file);              set_sensitive(file);
3551            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
3552                set_sensitive(nSamples == 1);
3553          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
3554              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
3555    #endif
3556          // show sample popup          // show sample popup
3557          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
3558    
3559    #if !USE_GTKMM_BUILDER
3560            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
3561                set_sensitive(n == 1);
3562            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
3563                set_sensitive(n);
3564            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
3565                set_sensitive(file);
3566            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
3567                set_sensitive(nSamples == 1);
3568            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
3569                set_sensitive(n);
3570    #endif
3571      }      }
3572        
3573    #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
3574        return false;
3575    #endif
3576  }  }
3577    
3578  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
3579      static int __instrument_indexer = 0;  bool MainWindow::on_script_treeview_button_release(Gdk::EventButton& _button) {
3580      if (!file) return;      GdkEventButton* button = _button.gobj();
3581      gig::Instrument* instrument = file->AddInstrument();  #else
3582      __instrument_indexer++;  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
3583      instrument->pInfo->Name =  #endif
3584          "Unnamed Instrument " + ToString(__instrument_indexer);      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
3585    #if !USE_GTKMM_BUILDER
3586            Gtk::Menu* script_popup =
3587                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
3588    #endif
3589            // update enabled/disabled state of sample popup items
3590            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3591            Gtk::TreeModel::iterator it = sel->get_selected();
3592            bool group_selected  = false;
3593            bool script_selected = false;
3594            if (it) {
3595                Gtk::TreeModel::Row row = *it;
3596                group_selected  = row[m_ScriptsModel.m_col_group];
3597                script_selected = row[m_ScriptsModel.m_col_script];
3598            }
3599    #if USE_GTKMM_BUILDER
3600            m_actionAddScript->property_enabled() = (group_selected || script_selected);
3601            m_actionAddScriptGroup->property_enabled() = (file);
3602            m_actionEditScript->property_enabled() = (script_selected);
3603            m_actionRemoveScript->property_enabled() = (group_selected || script_selected);
3604    #else
3605            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
3606                set_sensitive(group_selected || script_selected);
3607            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
3608                set_sensitive(file);
3609            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
3610                set_sensitive(script_selected);    
3611            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
3612                set_sensitive(group_selected || script_selected);
3613    #endif
3614            // show sample popup
3615            script_popup->popup(button->button, button->time);
3616    
3617    #if !USE_GTKMM_BUILDER
3618            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
3619                set_sensitive(group_selected || script_selected);
3620            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
3621                set_sensitive(file);
3622            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
3623                set_sensitive(script_selected);    
3624            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
3625                set_sensitive(group_selected || script_selected);
3626    #endif
3627        }
3628    #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
3629        return false;
3630    #endif
3631    }
3632    
3633    void MainWindow::updateScriptListOfMenu() {
3634        // remove all entries from "Assign Script" menu
3635        {
3636            const std::vector<Gtk::Widget*> children = assign_scripts_menu->get_children();
3637            for (int i = 0; i < children.size(); ++i) {
3638                Gtk::Widget* child = children[i];
3639                assign_scripts_menu->remove(*child);
3640                delete child;
3641            }
3642        }
3643    
3644        int iTotalScripts = 0;
3645    
3646        if (!file) goto noScripts;
3647    
3648        // add all configured macros as menu items to the "Macro" menu
3649        for (int iGroup = 0; file->GetScriptGroup(iGroup); ++iGroup) {
3650            gig::ScriptGroup* pGroup = file->GetScriptGroup(iGroup);
3651            for (int iScript = 0; pGroup->GetScript(iScript); ++iScript, ++iTotalScripts) {
3652                gig::Script* pScript = pGroup->GetScript(iScript);
3653                std::string name = pScript->Name;
3654    
3655                Gtk::MenuItem* item = new Gtk::MenuItem(name);
3656                item->signal_activate().connect(
3657                    sigc::bind(
3658                        sigc::mem_fun(*this, &MainWindow::assignScript), pScript
3659                    )
3660                );
3661                assign_scripts_menu->append(*item);
3662                item->set_accel_path("<Scripts>/script_" + ToString(iTotalScripts));
3663                //item->set_tooltip_text(comment);
3664            }
3665        }
3666    
3667        noScripts:
3668    
3669        // if there are no macros configured at all, then show a dummy entry instead
3670        if (!iTotalScripts) {
3671            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Scripts"));
3672            item->set_sensitive(false);
3673            assign_scripts_menu->append(*item);
3674        }
3675    
3676        // add separator line to menu
3677        assign_scripts_menu->append(*new Gtk::SeparatorMenuItem);
3678    
3679        {
3680            Gtk::MenuItem* item = new Gtk::MenuItem(_("Unassign All Scripts"));
3681            item->signal_activate().connect(
3682                sigc::mem_fun(*this, &MainWindow::dropAllScriptSlots)
3683            );
3684            assign_scripts_menu->append(*item);
3685            item->set_accel_path("<Scripts>/DropAllScriptSlots");
3686        }
3687    
3688    #if HAS_GTKMM_SHOW_ALL_CHILDREN
3689        assign_scripts_menu->show_all_children();
3690    #endif
3691    }
3692    
3693    #if !USE_GTKMM_BUILDER
3694    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
3695        const Glib::ustring& name, int position) {
3696    
3697        Gtk::RadioMenuItem::Group instrument_group;
3698        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3699        if (!children.empty()) {
3700            instrument_group =
3701                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
3702        }
3703        Gtk::RadioMenuItem* item =
3704            new Gtk::RadioMenuItem(instrument_group, name);
3705        if (position < 0) {
3706            instrument_menu->append(*item);
3707        } else {
3708            instrument_menu->insert(*item, position);
3709        }
3710        item->show();
3711        item->signal_activate().connect(
3712            sigc::bind(
3713                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
3714                item));
3715        return item;
3716    }
3717    #endif
3718    
3719    #if !USE_GTKMM_BUILDER
3720    void MainWindow::remove_instrument_from_menu(int index) {
3721        const std::vector<Gtk::Widget*> children =
3722            instrument_menu->get_children();
3723        Gtk::Widget* child = children[index];
3724        instrument_menu->remove(*child);
3725        delete child;
3726    }
3727    #endif
3728    
3729    void MainWindow::add_instrument(gig::Instrument* instrument) {
3730        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
3731    
3732      // update instrument tree view      // update instrument tree view
3733        instrument_name_connection.block();
3734      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
3735      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
3736      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      const int index = m_refTreeModel->children().size() - 1;
3737        rowInstr[m_Columns.m_col_nr] = index;
3738        rowInstr[m_Columns.m_col_name] = name;
3739      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
3740        rowInstr[m_Columns.m_col_scripts] = "";
3741        rowInstr[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3742        instrument_name_connection.unblock();
3743    
3744    #if !USE_GTKMM_BUILDER
3745        add_instrument_to_menu(name);
3746    #endif
3747        select_instrument(instrument);
3748      file_changed();      file_changed();
3749  }  }
3750    
3751    void MainWindow::on_action_add_instrument() {
3752        static int __instrument_indexer = 0;
3753        if (!file) return;
3754        gig::Instrument* instrument = file->AddInstrument();
3755        __instrument_indexer++;
3756        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
3757                                                ToString(__instrument_indexer));
3758    
3759        add_instrument(instrument);
3760    }
3761    
3762    void MainWindow::on_action_duplicate_instrument() {
3763        if (!file) return;
3764    
3765        // retrieve the currently selected instrument
3766        // (being the original instrument to be duplicated)
3767        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3768        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3769        for (int r = 0; r < rows.size(); ++r) {
3770            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
3771            if (it) {
3772                Gtk::TreeModel::Row row = *it;
3773                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
3774                if (instrOrig) {
3775                    // duplicate the orginal instrument
3776                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
3777                    instrNew->pInfo->Name =
3778                        instrOrig->pInfo->Name +
3779                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
3780    
3781                    add_instrument(instrNew);
3782                }
3783            }
3784        }
3785    }
3786    
3787  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
3788      if (!file) return;      if (!file) return;
3789      if (file_is_shared) {      if (file_is_shared) {
# Line 1301  void MainWindow::on_action_remove_instru Line 3798  void MainWindow::on_action_remove_instru
3798      }      }
3799    
3800      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3801      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3802      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3803            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
3804            if (!it) continue;
3805          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3806          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
3807          try {          try {
3808                Gtk::TreePath path(it);
3809                int index = path[0];
3810    
3811              // remove instrument from the gig file              // remove instrument from the gig file
3812              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
3813              file_changed();              file_changed();
3814    
3815    #if !USE_GTKMM_BUILDER
3816                remove_instrument_from_menu(index);
3817    #endif
3818    
3819                // remove row from instruments tree view
3820                m_refTreeModel->erase(it);
3821                // update "Nr" column of all instrument rows
3822                {
3823                    int index = 0;
3824                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
3825                         it != m_refTreeModel->children().end(); ++it, ++index)
3826                    {
3827                        Gtk::TreeModel::Row row = *it;
3828                        gig::Instrument* instrument = row[m_Columns.m_col_instr];
3829                        row[m_Columns.m_col_nr] = index;
3830                        row[m_Columns.m_col_tooltip] = scriptTooltipFor(instrument, index);
3831                    }
3832                }
3833    
3834    #if GTKMM_MAJOR_VERSION < 3
3835                // select another instrument (in gtk3 this is done
3836                // automatically)
3837                if (!m_refTreeModel->children().empty()) {
3838                    if (index == m_refTreeModel->children().size()) {
3839                        index--;
3840                    }
3841                    m_TreeView.get_selection()->select(
3842                        Gtk::TreePath(ToString(index)));
3843                }
3844    #endif
3845                instr_props_set_instrument();
3846                instr = get_instrument();
3847                if (instr) {
3848                    midiRules.set_instrument(instr);
3849                } else {
3850                    midiRules.hide();
3851                }
3852          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
3853              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3854              msg.run();              msg.run();
# Line 1321  void MainWindow::on_action_remove_instru Line 3859  void MainWindow::on_action_remove_instru
3859  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
3860      //TODO: show a dialog where the selected sample's properties can be edited      //TODO: show a dialog where the selected sample's properties can be edited
3861      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
3862          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
3863      );      );
3864      msg.run();      msg.run();
3865  }  }
3866    
3867    void MainWindow::on_action_add_script_group() {
3868        static int __script_indexer = 0;
3869        if (!file) return;
3870        gig::ScriptGroup* group = file->AddScriptGroup();
3871        group->Name = gig_from_utf8(_("Unnamed Group"));
3872        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
3873        __script_indexer++;
3874        // update sample tree view
3875        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
3876        Gtk::TreeModel::Row rowGroup = *iterGroup;
3877        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
3878        rowGroup[m_ScriptsModel.m_col_script] = NULL;
3879        rowGroup[m_ScriptsModel.m_col_group] = group;
3880        file_changed();
3881    }
3882    
3883    void MainWindow::on_action_add_script() {
3884        if (!file) return;
3885        // get selected group
3886        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3887        Gtk::TreeModel::iterator it = sel->get_selected();
3888        if (!it) return;
3889        Gtk::TreeModel::Row row = *it;
3890        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3891        if (!group) { // not a group, but a script is selected (probably)
3892            gig::Script* script = row[m_ScriptsModel.m_col_script];
3893            if (!script) return;
3894            it = row.parent(); // resolve parent (that is the script's group)
3895            if (!it) return;
3896            row = *it;
3897            group = row[m_ScriptsModel.m_col_group];
3898            if (!group) return;
3899        }
3900    
3901        // add a new script to the .gig file
3902        gig::Script* script = group->AddScript();    
3903        Glib::ustring name = _("Unnamed Script");
3904        script->Name = gig_from_utf8(name);
3905    
3906        // add script to the tree view
3907        Gtk::TreeModel::iterator iterScript =
3908            m_refScriptsTreeModel->append(row.children());
3909        Gtk::TreeModel::Row rowScript = *iterScript;
3910        rowScript[m_ScriptsModel.m_col_name] = name;
3911        rowScript[m_ScriptsModel.m_col_script] = script;
3912        rowScript[m_ScriptsModel.m_col_group]  = NULL;
3913    
3914        // unfold group of new script item in treeview
3915        Gtk::TreeModel::Path path(iterScript);
3916        m_TreeViewScripts.expand_to_path(path);
3917    }
3918    
3919    void MainWindow::on_action_edit_script() {
3920        if (!file) return;
3921        // get selected script
3922        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3923        Gtk::TreeModel::iterator it = sel->get_selected();
3924        if (!it) return;
3925        Gtk::TreeModel::Row row = *it;
3926        gig::Script* script = row[m_ScriptsModel.m_col_script];
3927        if (!script) return;
3928    
3929        ScriptEditor* editor = new ScriptEditor;
3930        editor->signal_script_to_be_changed.connect(
3931            signal_script_to_be_changed.make_slot()
3932        );
3933        editor->signal_script_changed.connect(
3934            signal_script_changed.make_slot()
3935        );
3936        editor->setScript(script);
3937        //editor->reparent(*this);
3938        editor->show();
3939    }
3940    
3941    void MainWindow::on_action_remove_script() {
3942        if (!file) return;
3943        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3944        Gtk::TreeModel::iterator it = sel->get_selected();
3945        if (it) {
3946            Gtk::TreeModel::Row row = *it;
3947            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3948            gig::Script* script     = row[m_ScriptsModel.m_col_script];
3949            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3950            try {
3951                // remove script group or script from the gig file
3952                if (group) {
3953                    // notify everybody that we're going to remove these samples
3954    //TODO:         scripts_to_be_removed_signal.emit(members);
3955                    // delete the group in the .gig file including the
3956                    // samples that belong to the group
3957                    file->DeleteScriptGroup(group);
3958                    // notify that we're done with removal
3959    //TODO:         scripts_removed_signal.emit();
3960                    file_changed();
3961                } else if (script) {
3962                    // notify everybody that we're going to remove this sample
3963    //TODO:         std::list<gig::Script*> lscripts;
3964    //TODO:         lscripts.push_back(script);
3965    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
3966                    // remove sample from the .gig file
3967                    script->GetGroup()->DeleteScript(script);
3968                    // notify that we're done with removal
3969    //TODO:         scripts_removed_signal.emit();
3970                    dimreg_changed();
3971                    file_changed();
3972                }
3973                // remove respective row(s) from samples tree view
3974                m_refScriptsTreeModel->erase(it);
3975            } catch (RIFF::Exception e) {
3976                // pretend we're done with removal (i.e. to avoid dead locks)
3977    //TODO:     scripts_removed_signal.emit();
3978                // show error message
3979                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3980                msg.run();
3981            }
3982        }
3983    }
3984    
3985  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
3986      static int __sample_indexer = 0;      static int __sample_indexer = 0;
3987      if (!file) return;      if (!file) return;
3988      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
3989      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
3990      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
3991      __sample_indexer++;      __sample_indexer++;
3992      // update sample tree view      // update sample tree view
3993      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
3994      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
3995      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
3996      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
3997      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
3998      file_changed();      file_changed();
3999  }  }
4000    
4001    void MainWindow::on_action_replace_sample() {
4002        add_or_replace_sample(true);
4003    }
4004    
4005  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
4006        add_or_replace_sample(false);
4007    }
4008    
4009    void MainWindow::add_or_replace_sample(bool replace) {
4010      if (!file) return;      if (!file) return;
4011      // get selected group  
4012        // get selected group (and probably selected sample)
4013      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4014      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4015        if (rows.empty()) return;
4016        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4017      if (!it) return;      if (!it) return;
4018      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
4019        gig::Sample* sample = NULL;
4020      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
4021      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
4022          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
4023          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
4024          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
4025          if (!it) return;          if (!it) return;
4026          row = *it;          if (!replace) row = *it;
4027          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
4028          if (!group) return;          if (!group) return;
4029      }      }
4030        if (replace && !sample) return;
4031    
4032      // show 'browse for file' dialog      // show 'browse for file' dialog
4033      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
4034    #if HAS_GTKMM_STOCK
4035      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4036      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
4037      dialog.set_select_multiple(true);  #else
4038      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4039        dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
4040    #endif
4041        dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
4042    
4043        // matches all file types supported by libsndfile
4044    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
4045        Gtk::FileFilter soundfilter;
4046    #else
4047        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
4048    #endif
4049      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
4050          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
4051          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1372  void MainWindow::on_action_add_sample() Line 4053  void MainWindow::on_action_add_sample()
4053          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
4054          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
4055      };      };
4056        const char* soundfiles = _("Sound Files");
4057        const char* allfiles = _("All Files");
4058    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
4059      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
4060          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
4061      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
4062      Gtk::FileFilter allpassfilter; // matches every file  
4063        // matches every file
4064        Gtk::FileFilter allpassfilter;
4065      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
4066      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
4067    #else
4068        for (int i = 0; supportedFileTypes[i]; i++)
4069            soundfilter->add_pattern(supportedFileTypes[i]);
4070        soundfilter->set_name(soundfiles);
4071    
4072        // matches every file
4073        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
4074        allpassfilter->add_pattern("*.*");
4075        allpassfilter->set_name(allfiles);
4076    #endif
4077      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
4078      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
4079        if (current_sample_dir != "") {
4080            dialog.set_current_folder(current_sample_dir);
4081        }
4082      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
4083            current_sample_dir = dialog.get_current_folder();
4084          Glib::ustring error_files;          Glib::ustring error_files;
4085          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
4086          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
4087               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
4088              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
4089              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file information
4090              SF_INFO info;              SF_INFO info;
4091              info.format = 0;              info.format = 0;
4092              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
4093              try {              try {
4094                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
4095                  int bitdepth;                  int bitdepth;
4096                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
4097                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1407  void MainWindow::on_action_add_sample() Line 4107  void MainWindow::on_action_add_sample()
4107                          break;                          break;
4108                      default:                      default:
4109                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
4110                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
4111                  }                  }
4112                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
4113                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
4114                  // file name without path                  // file name without path
4115                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
4116                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1420  void MainWindow::on_action_add_sample() Line 4120  void MainWindow::on_action_add_sample()
4120                          break;                          break;
4121                      }                      }
4122                  }                  }
4123                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
4124                  sample->Channels = info.channels;                  sample->Channels = info.channels;
4125                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
4126                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1434  void MainWindow::on_action_add_sample() Line 4134  void MainWindow::on_action_add_sample()
4134                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
4135                  {                  {
4136                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
4137                        sample->FineTune      = instrument.detune;
4138    
 #if HAVE_SF_INSTRUMENT_LOOPS  
4139                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
4140                          sample->Loops = 1;                          sample->Loops = 1;
4141    
# Line 1455  void MainWindow::on_action_add_sample() Line 4155  void MainWindow::on_action_add_sample()
4155                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
4156                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
4157                      }                      }
 #endif  
4158                  }                  }
4159    
4160                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
4161                  // physically when File::Save() is called)                  // physically when File::Save() is called)
4162                  sample->Resize(info.frames);                  sample->Resize(info.frames);
4163                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
4164                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
4165                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
4166                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
4167                  SampleImportItem sched_item;                  SampleImportItem sched_item;
4168                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
4169                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
4170                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
4171                  // add sample to the tree view                  // add sample to the tree view
4172                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
4173                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
4174                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
4175                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
4176                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
4177                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
4178                        rowSample[m_SamplesModel.m_col_name] =
4179                            gig_to_utf8(sample->pInfo->Name);
4180                        rowSample[m_SamplesModel.m_col_sample] = sample;
4181                        rowSample[m_SamplesModel.m_col_group]  = NULL;
4182                    }
4183                  // close sound file                  // close sound file
4184                  sf_close(hFile);                  sf_close(hFile);
4185                  file_changed();                  file_changed();
4186              } 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)
4187                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
4188                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
4189              }              }
4190          }          }
4191          // 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
4192          if (error_files.size()) {          if (!error_files.empty()) {
4193              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
4194                    (replace
4195                        ? _("Failed to replace sample with:\n")
4196                        : _("Could not add the following sample(s):\n"))
4197                    + error_files;
4198                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4199                msg.run();
4200            }
4201        }
4202    }
4203    
4204    void MainWindow::on_action_replace_all_samples_in_all_groups()
4205    {
4206        if (!file) return;
4207        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
4208                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
4209        const char* str =
4210            _("This is a very specific function. It tries to replace all samples "
4211              "in the current gig file by samples located in the chosen "
4212              "directory.\n\n"
4213              "It works like this: For each sample in the gig file, it tries to "
4214              "find a sample file in the selected directory with the same name as "
4215              "the sample in the gig file. Optionally, you can add a filename "
4216              "extension below, which will be added to the filename expected to be "
4217              "found. That is, assume you have a gig file with a sample called "
4218              "'Snare', if you enter '.wav' below (like it's done by default), it "
4219              "expects to find a sample file called 'Snare.wav' and will replace "
4220              "the sample in the gig file accordingly. If you don't need an "
4221              "extension, blank the field below. Any gig sample where no "
4222              "appropriate sample file could be found will be reported and left "
4223              "untouched.\n");
4224    #if GTKMM_MAJOR_VERSION < 3
4225        view::WrapLabel description(str);
4226    #else
4227        Gtk::Label description(str);
4228        description.set_line_wrap();
4229    #endif
4230        HBox entryArea;
4231        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
4232        Gtk::Entry postfixEntryBox;
4233        postfixEntryBox.set_text(".wav");
4234        entryArea.pack_start(entryLabel);
4235        entryArea.pack_start(postfixEntryBox);
4236    #if USE_GTKMM_BOX
4237        dialog.get_content_area()->pack_start(description, Gtk::PACK_SHRINK);
4238        dialog.get_content_area()->pack_start(entryArea, Gtk::PACK_SHRINK);
4239    #else
4240        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
4241        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
4242    #endif
4243        description.show();
4244    
4245    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4246        entryArea.show_all();
4247    #else
4248        entryArea.show();
4249    #endif
4250    
4251    #if HAS_GTKMM_STOCK
4252        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4253    #else
4254        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4255    #endif
4256        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
4257        dialog.set_select_multiple(false);
4258        if (current_sample_dir != "") {
4259            dialog.set_current_folder(current_sample_dir);
4260        }
4261        if (dialog.run() == Gtk::RESPONSE_OK)
4262        {
4263            current_sample_dir = dialog.get_current_folder();
4264            Glib::ustring error_files;
4265            std::string folder = dialog.get_filename();
4266            for (gig::Sample* sample = file->GetFirstSample();
4267                 sample; sample = file->GetNextSample())
4268            {
4269                std::string filename =
4270                    folder + G_DIR_SEPARATOR_S +
4271                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
4272                                             postfixEntryBox.get_text());
4273                SF_INFO info;
4274                info.format = 0;
4275                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
4276                try
4277                {
4278                    if (!hFile) throw std::string(_("could not open file"));
4279                    switch (info.format & 0xff) {
4280                        case SF_FORMAT_PCM_S8:
4281                        case SF_FORMAT_PCM_16:
4282                        case SF_FORMAT_PCM_U8:
4283                        case SF_FORMAT_PCM_24:
4284                        case SF_FORMAT_PCM_32:
4285                        case SF_FORMAT_FLOAT:
4286                        case SF_FORMAT_DOUBLE:
4287                            break;
4288                        default:
4289                            sf_close(hFile);
4290                            throw std::string(_("format not supported"));
4291                    }
4292                    SampleImportItem sched_item;
4293                    sched_item.gig_sample  = sample;
4294                    sched_item.sample_path = filename;
4295                    m_SampleImportQueue[sample] = sched_item;
4296                    sf_close(hFile);
4297                    file_changed();
4298                }
4299                catch (std::string what)
4300                {
4301                    if (!error_files.empty()) error_files += "\n";
4302                    error_files += Glib::filename_to_utf8(filename) +
4303                        " (" + what + ")";
4304                }
4305            }
4306            // show error message box when some file(s) could not be opened / added
4307            if (!error_files.empty()) {
4308                Glib::ustring txt =
4309                    _("Could not replace the following sample(s):\n") + error_files;
4310              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4311              msg.run();              msg.run();
4312          }          }
# Line 1496  void MainWindow::on_action_add_sample() Line 4316  void MainWindow::on_action_add_sample()
4316  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
4317      if (!file) return;      if (!file) return;
4318      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4319      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4320      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
4321            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
4322            if (!it) continue;
4323          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
4324          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
4325          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1505  void MainWindow::on_action_remove_sample Line 4327  void MainWindow::on_action_remove_sample
4327          try {          try {
4328              // remove group or sample from the gig file              // remove group or sample from the gig file
4329              if (group) {              if (group) {
4330                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
4331                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
4332                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
4333                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1522  void MainWindow::on_action_remove_sample Line 4344  void MainWindow::on_action_remove_sample
4344                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
4345                  // them from the import queue                  // them from the import queue
4346                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
4347                       member != members.end(); ++member) {                       member != members.end(); ++member)
4348                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
4349                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
4350                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
4351                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
4352                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
4353                      }                      }
4354                  }                  }
4355                  file_changed();                  file_changed();
# Line 1545  void MainWindow::on_action_remove_sample Line 4364  void MainWindow::on_action_remove_sample
4364                  samples_removed_signal.emit();                  samples_removed_signal.emit();
4365                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
4366                  // the import queue                  // the import queue
4367                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
4368                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
4369                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
4370                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
4371                  }                  }
4372                  dimreg_changed();                  dimreg_changed();
4373                  file_changed();                  file_changed();
# Line 1569  void MainWindow::on_action_remove_sample Line 4384  void MainWindow::on_action_remove_sample
4384      }      }
4385  }  }
4386    
4387    void MainWindow::on_action_remove_unused_samples() {
4388        if (!file) return;
4389    
4390        // collect all samples that are not referenced by any instrument
4391        std::list<gig::Sample*> lsamples;
4392        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
4393            gig::Sample* sample = file->GetSample(iSample);
4394            bool isUsed = false;
4395            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
4396                                  instrument = file->GetNextInstrument())
4397            {
4398                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
4399                                  rgn = instrument->GetNextRegion())
4400                {
4401                    for (int i = 0; i < 256; ++i) {
4402                        if (!rgn->pDimensionRegions[i]) continue;
4403                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
4404                        isUsed = true;
4405                        goto endOfRefSearch;
4406                    }
4407                }
4408            }
4409            endOfRefSearch:
4410            if (!isUsed) lsamples.push_back(sample);
4411        }
4412    
4413        if (lsamples.empty()) return;
4414    
4415        // notify everybody that we're going to remove these samples
4416        samples_to_be_removed_signal.emit(lsamples);
4417    
4418        // remove collected samples
4419        try {
4420            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
4421                 itSample != lsamples.end(); ++itSample)
4422            {
4423                gig::Sample* sample = *itSample;
4424                // remove sample from the .gig file
4425                file->DeleteSample(sample);
4426                // if sample was just previously added, remove it from the import queue
4427                if (m_SampleImportQueue.count(sample)) {
4428                    printf("Removing previously added sample '%s'\n",
4429                           m_SampleImportQueue[sample].sample_path.c_str());
4430                    m_SampleImportQueue.erase(sample);
4431                }
4432            }
4433        } catch (RIFF::Exception e) {
4434            // show error message
4435            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
4436            msg.run();
4437        }
4438    
4439        // notify everybody that we're done with removal
4440        samples_removed_signal.emit();
4441    
4442        dimreg_changed();
4443        file_changed();
4444        __refreshEntireGUI();
4445    }
4446    
4447    // see comment on on_sample_treeview_drag_begin()
4448    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4449    {
4450        first_call_to_drag_data_get = true;
4451    }
4452    
4453    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4454                                                       Gtk::SelectionData& selection_data, guint, guint)
4455    {
4456        if (!first_call_to_drag_data_get) return;
4457        first_call_to_drag_data_get = false;
4458    
4459        // get selected script
4460        gig::Script* script = NULL;
4461        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
4462        Gtk::TreeModel::iterator it = sel->get_selected();
4463        if (it) {
4464            Gtk::TreeModel::Row row = *it;
4465            script = row[m_ScriptsModel.m_col_script];
4466        }
4467        // pass the gig::Script as pointer
4468        selection_data.set(selection_data.get_target(), 0/*unused*/,
4469                           (const guchar*)&script,
4470                           sizeof(script)/*length of data in bytes*/);
4471    }
4472    
4473    // see comment on on_sample_treeview_drag_begin()
4474    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
4475    {
4476        first_call_to_drag_data_get = true;
4477    }
4478    
4479    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
4480                                                           Gtk::SelectionData& selection_data, guint, guint)
4481    {
4482        if (!first_call_to_drag_data_get) return;
4483        first_call_to_drag_data_get = false;
4484    
4485        // get selected source instrument
4486        gig::Instrument* src = NULL;
4487        {
4488            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4489            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4490            if (!rows.empty()) {
4491                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
4492                if (it) {
4493                    Gtk::TreeModel::Row row = *it;
4494                    src = row[m_Columns.m_col_instr];
4495                }
4496            }
4497        }
4498        if (!src) return;
4499    
4500        // pass the source gig::Instrument as pointer
4501        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
4502                           sizeof(src)/*length of data in bytes*/);
4503    }
4504    
4505    void MainWindow::on_instruments_treeview_drop_drag_data_received(
4506        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
4507        const Gtk::SelectionData& selection_data, guint, guint time)
4508    {
4509        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
4510        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
4511            return;
4512    
4513        gig::Instrument* dst = NULL;
4514        {
4515            Gtk::TreeModel::Path path;
4516            const bool found = m_TreeView.get_path_at_pos(x, y, path);
4517            if (!found) return;
4518    
4519            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
4520            if (!iter) return;
4521            Gtk::TreeModel::Row row = *iter;
4522            dst = row[m_Columns.m_col_instr];
4523        }
4524        if (!dst) return;
4525    
4526        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
4527        src->MoveTo(dst);
4528        __refreshEntireGUI();
4529        select_instrument(src);
4530    }
4531    
4532  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
4533  // 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
4534  // 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 1587  void MainWindow::on_sample_treeview_drag Line 4547  void MainWindow::on_sample_treeview_drag
4547      // get selected sample      // get selected sample
4548      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
4549      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4550      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4551      if (it) {      if (!rows.empty()) {
4552          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4553          sample = row[m_SamplesModel.m_col_sample];          if (it) {
4554                Gtk::TreeModel::Row row = *it;
4555                sample = row[m_SamplesModel.m_col_sample];
4556            }
4557      }      }
4558      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
4559      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 1627  void MainWindow::on_sample_label_drop_dr Line 4590  void MainWindow::on_sample_label_drop_dr
4590          bool channels_changed = false;          bool channels_changed = false;
4591          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
4592              // remove the samplechannel dimension              // remove the samplechannel dimension
4593    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
4594              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
4595              channels_changed = true;              channels_changed = true;
4596              region_changed();              region_changed();
4597    */
4598          }          }
4599          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
4600                sample,
4601                is_copy_samples_unity_note_enabled(),
4602                is_copy_samples_fine_tune_enabled(),
4603                is_copy_samples_loop_enabled()
4604            );
4605    
4606          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
4607              // add samplechannel dimension              // add samplechannel dimension
# Line 1674  void MainWindow::sample_name_changed(con Line 4644  void MainWindow::sample_name_changed(con
4644      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
4645      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
4646      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
4647        gig::String gigname(gig_from_utf8(name));
4648      if (group) {      if (group) {
4649          if (group->Name != name) {          if (group->Name != gigname) {
4650              group->Name = name;              group->Name = gigname;
4651              printf("group name changed\n");              printf("group name changed\n");
4652              file_changed();              file_changed();
4653          }          }
4654      } else if (sample) {      } else if (sample) {
4655          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
4656              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
4657              printf("sample name changed\n");              printf("sample name changed\n");
4658              file_changed();              file_changed();
4659          }          }
4660      }      }
4661  }  }
4662    
4663    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
4664                                         const Gtk::TreeModel::iterator& iter) {
4665        if (!iter) return;
4666        Gtk::TreeModel::Row row = *iter;
4667        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
4668        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
4669        gig::Script* script     = row[m_ScriptsModel.m_col_script];
4670        gig::String gigname(gig_from_utf8(name));
4671        if (group) {
4672            if (group->Name != gigname) {
4673                group->Name = gigname;
4674                printf("script group name changed\n");
4675                file_changed();
4676            }
4677        } else if (script) {
4678            if (script->Name != gigname) {
4679                script->Name = gigname;
4680                printf("script name changed\n");
4681                file_changed();
4682            }
4683        }
4684    }
4685    
4686    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
4687                                           Gtk::TreeViewColumn* column)
4688    {
4689        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
4690        if (!iter) return;
4691        Gtk::TreeModel::Row row = *iter;
4692        gig::Script* script = row[m_ScriptsModel.m_col_script];
4693        if (!script) return;
4694    
4695        ScriptEditor* editor = new ScriptEditor;
4696        editor->signal_script_to_be_changed.connect(
4697            signal_script_to_be_changed.make_slot()
4698        );
4699        editor->signal_script_changed.connect(
4700            signal_script_changed.make_slot()
4701        );
4702        editor->setScript(script);
4703        //editor->reparent(*this);
4704        editor->show();
4705    }
4706    
4707  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
4708                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
4709      if (!iter) return;      if (!iter) return;
4710      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
4711      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
4712    
4713    #if !USE_GTKMM_BUILDER
4714        // change name in instrument menu
4715        int index = path[0];
4716        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
4717        if (index < children.size()) {
4718    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
4719            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
4720    #else
4721            remove_instrument_from_menu(index);
4722            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
4723            item->set_active();
4724    #endif
4725        }
4726    #endif
4727    
4728        // change name in gig
4729      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
4730      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
4731          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
4732            instrument->pInfo->Name = gigname;
4733    
4734            // change name in the instrument properties window
4735            if (instrumentProps.get_instrument() == instrument) {
4736                instrumentProps.update_name();
4737            }
4738    
4739          file_changed();          file_changed();
4740      }      }
4741  }  }
4742    
4743    bool MainWindow::instrument_row_visible(const Gtk::TreeModel::const_iterator& iter) {
4744        if (!iter)
4745            return true;
4746    
4747        Glib::ustring pattern = m_searchText.get_text().lowercase();
4748        trim(pattern);
4749        if (pattern.empty()) return true;
4750    
4751    #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
4752        //HACK: on GTKMM4 development branch const_iterator cannot be easily converted to iterator, probably going to be fixed before final GTKMM4 release though.
4753        Gtk::TreeModel::Row row = **(Gtk::TreeModel::iterator*)(&iter);
4754    #else
4755        Gtk::TreeModel::Row row = *iter;
4756    #endif
4757        Glib::ustring name = row[m_Columns.m_col_name];
4758        name = name.lowercase();
4759    
4760        std::vector<Glib::ustring> tokens = Glib::Regex::split_simple(" ", pattern);
4761        for (int t = 0; t < tokens.size(); ++t)
4762            if (name.find(tokens[t]) == Glib::ustring::npos)
4763                return false;
4764    
4765        return true;
4766    }
4767    
4768    void MainWindow::on_action_combine_instruments() {
4769        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
4770    
4771        // take over selection from instruments list view for the combine dialog's
4772        // list view as pre-selection
4773        std::set<int> indeces;
4774        {
4775            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
4776            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4777            for (int r = 0; r < rows.size(); ++r) {
4778                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
4779                if (it) {
4780                    Gtk::TreeModel::Row row = *it;
4781                    int index = row[m_Columns.m_col_nr];
4782                    indeces.insert(index);
4783                }
4784            }
4785        }
4786        d->setSelectedInstruments(indeces);
4787    
4788    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4789        d->show_all();
4790    #else
4791        d->show();
4792    #endif
4793        d->run();
4794        if (d->fileWasChanged()) {
4795            // update GUI with new instrument just created
4796            add_instrument(d->newCombinedInstrument());
4797        }
4798        delete d;
4799    }
4800    
4801    void MainWindow::on_action_view_references() {
4802        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
4803        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
4804        if (rows.empty()) return;
4805        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
4806        if (!it) return;
4807        Gtk::TreeModel::Row row = *it;
4808        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
4809        if (!sample) return;
4810    
4811        ReferencesView* d = new ReferencesView(*this);
4812        d->setSample(sample);
4813        d->dimension_region_selected.connect(
4814            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
4815        );
4816    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4817        d->show_all();
4818    #else
4819        d->show();
4820    #endif
4821        d->resize(500, 400);
4822        d->run();
4823        delete d;
4824    }
4825    
4826    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
4827        struct _Source {
4828            std::vector<RIFF::File*> riffs;
4829            std::vector<gig::File*> gigs;
4830            
4831            ~_Source() {
4832                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
4833                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
4834                riffs.clear();
4835                gigs.clear();
4836            }
4837        } sources;
4838    
4839        if (filenames.empty())
4840            throw RIFF::Exception(_("No files selected, so nothing done."));
4841    
4842        // first open all input files (to avoid output file corruption)
4843        int i;
4844        try {
4845            for (i = 0; i < filenames.size(); ++i) {
4846                const std::string& filename = filenames[i];
4847                printf("opening file=%s\n", filename.c_str());
4848    
4849                RIFF::File* riff = new RIFF::File(filename);
4850                sources.riffs.push_back(riff);
4851    
4852                gig::File* gig = new gig::File(riff);
4853                sources.gigs.push_back(gig);
4854            }
4855        } catch (RIFF::Exception e) {
4856            throw RIFF::Exception(
4857                _("Error occurred while opening '") +
4858                filenames[i] +
4859                "': " +
4860                e.Message
4861            );
4862        } catch (...) {
4863            throw RIFF::Exception(
4864                _("Unknown exception occurred while opening '") +
4865                filenames[i] + "'"
4866            );
4867        }
4868    
4869        // now merge the opened .gig files to the main .gig file currently being
4870        // open in gigedit
4871        try {
4872            for (i = 0; i < filenames.size(); ++i) {
4873                const std::string& filename = filenames[i];
4874                printf("merging file=%s\n", filename.c_str());
4875                assert(i < sources.gigs.size());
4876    
4877                this->file->AddContentOf(sources.gigs[i]);
4878            }
4879        } catch (RIFF::Exception e) {
4880            throw RIFF::Exception(
4881                _("Error occurred while merging '") +
4882                filenames[i] +
4883                "': " +
4884                e.Message
4885            );
4886        } catch (...) {
4887            throw RIFF::Exception(
4888                _("Unknown exception occurred while merging '") +
4889                filenames[i] + "'"
4890            );
4891        }
4892    
4893        // Finally save gig file persistently to disk ...
4894        //NOTE: requires that this gig file already has a filename !
4895        {
4896            std::cout << "Saving file\n" << std::flush;
4897            file_structure_to_be_changed_signal.emit(this->file);
4898    
4899            progress_dialog = new ProgressDialog( //FIXME: memory leak!
4900                _("Saving") +  Glib::ustring(" '") +
4901                Glib::filename_display_basename(this->filename) + "' ...",
4902                *this
4903            );
4904    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4905            progress_dialog->show_all();
4906    #else
4907            progress_dialog->show();
4908    #endif
4909            saver = new Saver(this->file); //FIXME: memory leak!
4910            saver->signal_progress().connect(
4911                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
4912            saver->signal_finished().connect(
4913                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
4914            saver->signal_error().connect(
4915                sigc::mem_fun(*this, &MainWindow::on_saver_error));
4916            saver->launch();
4917        }
4918    }
4919    
4920    void MainWindow::on_action_merge_files() {
4921        if (this->file->GetFileName().empty()) {
4922            Glib::ustring txt = _(
4923                "You seem to have a new .gig file open that has not been saved "
4924                "yet. You must save it somewhere before starting to merge it with "
4925                "other .gig files though, because during the merge operation the "
4926                "other files' sample data must be written on file level to the "
4927                "target .gig file."
4928            );
4929            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4930            msg.run();
4931            return;
4932        }
4933    
4934        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
4935    #if HAS_GTKMM_STOCK
4936        dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
4937    #else
4938        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
4939    #endif
4940        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
4941        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
4942    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
4943        Gtk::FileFilter filter;
4944        filter.add_pattern("*.gig");
4945    #else
4946        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
4947        filter->add_pattern("*.gig");
4948    #endif
4949        dialog.set_filter(filter);
4950        if (current_gig_dir != "") {
4951            dialog.set_current_folder(current_gig_dir);
4952        }
4953        dialog.set_select_multiple(true);
4954    
4955        // show warning in the file picker dialog
4956        HBox descriptionArea;
4957        descriptionArea.set_spacing(15);
4958        Gtk::Image warningIcon;
4959        warningIcon.set_from_icon_name("dialog-warning",
4960                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
4961        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
4962    #if GTKMM_MAJOR_VERSION < 3
4963        view::WrapLabel description;
4964    #else
4965        Gtk::Label description;
4966        description.set_line_wrap();
4967    #endif
4968        description.set_markup(_(
4969            "\nSelect at least one .gig file that shall be merged to the .gig file "
4970            "currently being open in gigedit.\n\n"
4971            "<b>Please Note:</b> Merging with other files will modify your "
4972            "currently open .gig file on file level! And be aware that the current "
4973            "merge algorithm does not detect duplicate samples yet. So if you are "
4974            "merging files which are using equivalent sample data, those "
4975            "equivalent samples will currently be treated as separate samples and "
4976            "will accordingly be stored separately in the target .gig file!"
4977        ));
4978        descriptionArea.pack_start(description);
4979    #if USE_GTKMM_BOX
4980    # warning No description area implemented for dialog on GTKMM 3
4981    #else
4982        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
4983    #endif
4984    #if HAS_GTKMM_SHOW_ALL_CHILDREN
4985        descriptionArea.show_all();
4986    #else
4987        descriptionArea.show();
4988    #endif
4989    
4990        if (dialog.run() == Gtk::RESPONSE_OK) {
4991            printf("on_action_merge_files self=%p\n",
4992                   static_cast<void*>(Glib::Threads::Thread::self()));
4993            std::vector<std::string> filenames = dialog.get_filenames();
4994    
4995            // merge the selected files to the currently open .gig file
4996            try {
4997                mergeFiles(filenames);
4998            } catch (RIFF::Exception e) {
4999                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
5000                msg.run();
5001            }
5002    
5003            // update GUI
5004            __refreshEntireGUI();
5005        }
5006    }
5007    
5008  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
5009      this->file_is_shared = b;      this->file_is_shared = b;
5010    
# Line 1715  void MainWindow::set_file_is_shared(bool Line 5019  void MainWindow::set_file_is_shared(bool
5019              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
5020          );          );
5021      }      }
5022    
5023        {
5024    #if USE_GTKMM_BUILDER
5025            m_actionToggleSyncSamplerSelection->property_enabled() = b;
5026    #else
5027            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
5028                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
5029            if (item) item->set_sensitive(b);
5030    #endif
5031        }
5032    }
5033    
5034    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
5035        if (!sample) return;
5036        sample_ref_count[sample] += offset;
5037        const int refcount = sample_ref_count[sample];
5038    
5039        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
5040        for (int g = 0; g < model->children().size(); ++g) {
5041            Gtk::TreeModel::Row rowGroup = model->children()[g];
5042            for (int s = 0; s < rowGroup.children().size(); ++s) {
5043                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
5044                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
5045                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
5046                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
5047            }
5048        }
5049    }
5050    
5051    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
5052        on_sample_ref_count_incremented(oldSample, -1);
5053        on_sample_ref_count_incremented(newSample, +1);
5054    }
5055    
5056    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
5057        // just in case a new sample is added later with exactly the same memory
5058        // address, which would lead to incorrect refcount if not deleted here
5059        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
5060             it != samples.end(); ++it)
5061        {
5062            sample_ref_count.erase(*it);
5063        }
5064    }
5065    
5066    void MainWindow::show_samples_tab() {
5067        m_TreeViewNotebook.set_current_page(0);
5068    }
5069    
5070    void MainWindow::show_intruments_tab() {
5071        m_TreeViewNotebook.set_current_page(1);
5072    }
5073    
5074    void MainWindow::show_scripts_tab() {
5075        m_TreeViewNotebook.set_current_page(2);
5076    }
5077    
5078    void MainWindow::select_instrument_by_dir(int dir) {
5079        if (!file) return;
5080        gig::Instrument* pInstrument = get_instrument();
5081        if (!pInstrument) {
5082            select_instrument( file->GetInstrument(0) );
5083            return;
5084        }
5085        for (int i = 0; file->GetInstrument(i); ++i) {
5086            if (file->GetInstrument(i) == pInstrument) {
5087                select_instrument( file->GetInstrument(i + dir) );
5088                return;
5089            }
5090        }
5091    }
5092    
5093    void MainWindow::select_prev_instrument() {
5094        select_instrument_by_dir(-1);
5095    }
5096    
5097    void MainWindow::select_next_instrument() {
5098        select_instrument_by_dir(1);
5099    }
5100    
5101    void MainWindow::select_prev_region() {
5102        m_RegionChooser.select_prev_region();
5103    }
5104    
5105    void MainWindow::select_next_region() {
5106        m_RegionChooser.select_next_region();
5107    }
5108    
5109    void MainWindow::select_next_dim_rgn_zone() {
5110        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5111        m_DimRegionChooser.select_next_dimzone();
5112    }
5113    
5114    void MainWindow::select_prev_dim_rgn_zone() {
5115        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5116        m_DimRegionChooser.select_prev_dimzone();
5117    }
5118    
5119    void MainWindow::select_add_next_dim_rgn_zone() {
5120        m_DimRegionChooser.select_next_dimzone(true);
5121    }
5122    
5123    void MainWindow::select_add_prev_dim_rgn_zone() {
5124        m_DimRegionChooser.select_prev_dimzone(true);
5125    }
5126    
5127    void MainWindow::select_prev_dimension() {
5128        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5129        m_DimRegionChooser.select_prev_dimension();
5130    }
5131    
5132    void MainWindow::select_next_dimension() {
5133        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
5134        m_DimRegionChooser.select_next_dimension();
5135    }
5136    
5137    #define CLIPBOARD_DIMENSIONREGION_TARGET \
5138        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
5139    
5140    void MainWindow::copy_selected_dimrgn() {
5141        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5142        if (!pDimRgn) {
5143            updateClipboardPasteAvailable();
5144            updateClipboardCopyAvailable();
5145            return;
5146        }
5147    
5148        std::vector<Gtk::TargetEntry> targets;
5149        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
5150    
5151        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5152        clipboard->set(
5153            targets,
5154            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
5155            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
5156        );
5157    
5158        m_serializationArchive.serialize(pDimRgn);
5159    
5160        updateClipboardPasteAvailable();
5161    }
5162    
5163    void MainWindow::paste_copied_dimrgn() {
5164        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5165        clipboard->request_contents(
5166            CLIPBOARD_DIMENSIONREGION_TARGET,
5167            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
5168        );
5169        updateClipboardPasteAvailable();
5170    }
5171    
5172    void MainWindow::adjust_clipboard_content() {
5173        MacroEditor* editor = new MacroEditor();
5174        editor->setMacro(&m_serializationArchive, true);
5175        editor->show();
5176    }
5177    
5178    void MainWindow::updateClipboardPasteAvailable() {
5179        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
5180        clipboard->request_targets(
5181            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
5182        );
5183    }
5184    
5185    void MainWindow::updateClipboardCopyAvailable() {
5186        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
5187    #if USE_GTKMM_BUILDER
5188        m_actionCopyDimRgn->property_enabled() = bDimensionRegionCopyIsPossible;
5189    #else
5190        static_cast<Gtk::MenuItem*>(
5191            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
5192        )->set_sensitive(bDimensionRegionCopyIsPossible);
5193    #endif
5194    }
5195    
5196    #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
5197    void MainWindow::on_clipboard_owner_change(Gdk::EventOwnerChange& event) {
5198    #else
5199    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
5200    #endif
5201        updateClipboardPasteAvailable();
5202    }
5203    
5204    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
5205        const std::string target = selection_data.get_target();
5206        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5207            selection_data.set(
5208                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
5209                &m_serializationArchive.rawData()[0],
5210                m_serializationArchive.rawData().size()
5211            );
5212        } else {
5213            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
5214        }
5215    }
5216    
5217    void MainWindow::on_clipboard_clear() {
5218        m_serializationArchive.clear();
5219        updateClipboardPasteAvailable();
5220        updateClipboardCopyAvailable();
5221    }
5222    
5223    //NOTE: Might throw exception !!!
5224    void MainWindow::applyMacro(Serialization::Archive& macro) {
5225        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
5226        if (!pDimRgn) return;
5227    
5228        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
5229             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
5230        {
5231            gig::DimensionRegion* pDimRgn = *itDimReg;
5232            DimRegionChangeGuard(this, pDimRgn);
5233            macro.deserialize(pDimRgn);
5234        }
5235        //region_changed()
5236        file_changed();
5237        dimreg_changed();
5238    }
5239    
5240    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
5241        const std::string target = selection_data.get_target();
5242        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
5243            Glib::ustring errorText;
5244            try {
5245                m_serializationArchive.decode(
5246                    selection_data.get_data(), selection_data.get_length()
5247                );
5248                applyMacro(m_serializationArchive);
5249            } catch (Serialization::Exception e) {
5250                errorText = e.Message;
5251            } catch (...) {
5252                errorText = _("Unknown exception while pasting DimensionRegion");
5253            }
5254            if (!errorText.empty()) {
5255                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
5256                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
5257                msg.run();
5258            }
5259        }
5260    }
5261    
5262    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
5263        const bool bDimensionRegionPasteIsPossible =
5264            std::find(targets.begin(), targets.end(),
5265                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
5266    
5267    #if USE_GTKMM_BUILDER
5268        m_actionPasteDimRgn->property_enabled() = bDimensionRegionPasteIsPossible;
5269        m_actionAdjustClipboard->property_enabled() = bDimensionRegionPasteIsPossible;
5270    #else
5271        static_cast<Gtk::MenuItem*>(
5272            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
5273        )->set_sensitive(bDimensionRegionPasteIsPossible);
5274    
5275        static_cast<Gtk::MenuItem*>(
5276            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
5277        )->set_sensitive(bDimensionRegionPasteIsPossible);
5278    #endif
5279  }  }
5280    
5281  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 1741  sigc::signal<void, gig::Region*>& MainWi Line 5302  sigc::signal<void, gig::Region*>& MainWi
5302      return region_changed_signal;      return region_changed_signal;
5303  }  }
5304    
5305    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
5306        return sample_changed_signal;
5307    }
5308    
5309  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
5310      return sample_ref_changed_signal;      return sample_ref_changed_signal;
5311  }  }
# Line 1768  sigc::signal<void, int/*key*/, int/*velo Line 5333  sigc::signal<void, int/*key*/, int/*velo
5333  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
5334      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
5335  }  }
5336    
5337    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
5338        return switch_sampler_instrument_signal;
5339    }

Legend:
Removed from v.1661  
changed lines
  Added in v.3471

  ViewVC Help
Powered by ViewVC