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

Legend:
Removed from v.1300  
changed lines
  Added in v.3409

  ViewVC Help
Powered by ViewVC