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

Legend:
Removed from v.1396  
changed lines
  Added in v.3472

  ViewVC Help
Powered by ViewVC