/[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 2579 by persson, Sat May 24 06:44:39 2014 UTC revision 3157 by schoenebeck, Mon May 8 17:30:10 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006-2014 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 20  Line 20 
20  #include <iostream>  #include <iostream>
21  #include <cstring>  #include <cstring>
22    
23    #include <glibmmconfig.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>  #include <glibmm/convert.h>
32  #include <glibmm/dispatcher.h>  #include <glibmm/dispatcher.h>
33  #include <glibmm/miscutils.h>  #include <glibmm/miscutils.h>
# Line 27  Line 35 
35  #include <gtkmm/aboutdialog.h>  #include <gtkmm/aboutdialog.h>
36  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
37  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
 #include <gtkmm/stock.h>  
38  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
39  #include <gtkmm/main.h>  #include <gtkmm/main.h>
40  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
41    #include <gtkmm/accelmap.h>
42  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
43  #include "wrapLabel.hh"  #include "wrapLabel.hh"
44  #endif  #endif
# Line 45  Line 53 
53  #include "mainwindow.h"  #include "mainwindow.h"
54  #include "Settings.h"  #include "Settings.h"
55  #include "CombineInstrumentsDialog.h"  #include "CombineInstrumentsDialog.h"
56    #include "scripteditor.h"
57    #include "scriptslots.h"
58    #include "ReferencesView.h"
59  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
60  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
61    #include "gfx/builtinpix.h"
62    #include "MacroEditor.h"
63    #include "MacrosSetup.h"
64    
65  MainWindow::MainWindow() :  MainWindow::MainWindow() :
66        m_DimRegionChooser(*this),
67      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
68      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
69      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
70      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
71        labelLegend(_("Legend:")),
72        labelNoSample(_(" No Sample")),
73        labelMissingSample(_(" Missing some Sample(s)")),
74        labelLooped(_(" Looped")),
75        labelSomeLoops(_(" Some Loop(s)"))
76  {  {
77        loadBuiltInPix();
78    
79  //    set_border_width(5);  //    set_border_width(5);
80  //    set_default_size(400, 200);  //    set_default_size(400, 200);
81    
   
82      add(m_VBox);      add(m_VBox);
83    
84      // Handle selection      // Handle selection
# Line 78  MainWindow::MainWindow() : Line 98  MainWindow::MainWindow() :
98      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
99      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
100    
101        m_ScrolledWindowScripts.add(m_TreeViewScripts);
102        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
103    
104    
105      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
106    
# Line 89  MainWindow::MainWindow() : Line 112  MainWindow::MainWindow() :
112      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
113      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
114      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
115        {
116            legend_hbox.add(labelLegend);
117    
118            imageNoSample.set(redDot);
119            imageNoSample.set_alignment(Gtk::ALIGN_END);
120            labelNoSample.set_alignment(Gtk::ALIGN_START);
121            legend_hbox.add(imageNoSample);
122            legend_hbox.add(labelNoSample);
123    
124            imageMissingSample.set(yellowDot);
125            imageMissingSample.set_alignment(Gtk::ALIGN_END);
126            labelMissingSample.set_alignment(Gtk::ALIGN_START);
127            legend_hbox.add(imageMissingSample);
128            legend_hbox.add(labelMissingSample);
129    
130            imageLooped.set(blackLoop);
131            imageLooped.set_alignment(Gtk::ALIGN_END);
132            labelLooped.set_alignment(Gtk::ALIGN_START);
133            legend_hbox.add(imageLooped);
134            legend_hbox.add(labelLooped);
135    
136            imageSomeLoops.set(grayLoop);
137            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
138            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
139            legend_hbox.add(imageSomeLoops);
140            legend_hbox.add(labelSomeLoops);
141    
142            legend_hbox.show_all_children();
143        }
144        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
145      m_HPaned.add2(dimreg_vbox);      m_HPaned.add2(dimreg_vbox);
146    
147      dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));      dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
# Line 98  MainWindow::MainWindow() : Line 151  MainWindow::MainWindow() :
151    
152      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
153      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
154        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
155    
156      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
157    
158      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
159      actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),      actionGroup->add(Gtk::Action::create("New", _("_New")),
160                         Gtk::AccelKey("<control>n"),
161                       sigc::mem_fun(                       sigc::mem_fun(
162                           *this, &MainWindow::on_action_file_new));                           *this, &MainWindow::on_action_file_new));
163      Glib::RefPtr<Gtk::Action> action =      actionGroup->add(Gtk::Action::create("Open", _("_Open...")),
164          Gtk::Action::create("Open", Gtk::Stock::OPEN);                       Gtk::AccelKey("<control>o"),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
165                       sigc::mem_fun(                       sigc::mem_fun(
166                           *this, &MainWindow::on_action_file_open));                           *this, &MainWindow::on_action_file_open));
167      actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),      actionGroup->add(Gtk::Action::create("Save", _("_Save")),
168                         Gtk::AccelKey("<control>s"),
169                       sigc::mem_fun(                       sigc::mem_fun(
170                           *this, &MainWindow::on_action_file_save));                           *this, &MainWindow::on_action_file_save));
171      action = Gtk::Action::create("SaveAs", Gtk::Stock::SAVE_AS);      actionGroup->add(Gtk::Action::create("SaveAs", _("Save _As...")),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
172                       Gtk::AccelKey("<shift><control>s"),                       Gtk::AccelKey("<shift><control>s"),
173                       sigc::mem_fun(                       sigc::mem_fun(
174                           *this, &MainWindow::on_action_file_save_as));                           *this, &MainWindow::on_action_file_save_as));
175      actionGroup->add(Gtk::Action::create("Properties",      actionGroup->add(Gtk::Action::create("Properties",
176                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
177                       sigc::mem_fun(                       sigc::mem_fun(
178                           *this, &MainWindow::on_action_file_properties));                           *this, &MainWindow::on_action_file_properties));
179      actionGroup->add(Gtk::Action::create("InstrProperties",      actionGroup->add(Gtk::Action::create("InstrProperties",
180                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
181                       sigc::mem_fun(                       sigc::mem_fun(
182                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
183      actionGroup->add(Gtk::Action::create("MidiRules",      actionGroup->add(Gtk::Action::create("MidiRules",
184                                           _("_Midi Rules")),                                           _("_Midi Rules...")),
185                       sigc::mem_fun(                       sigc::mem_fun(
186                           *this, &MainWindow::show_midi_rules));                           *this, &MainWindow::show_midi_rules));
187      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("ScriptSlots",
188                                             _("_Script Slots...")),
189                         sigc::mem_fun(
190                             *this, &MainWindow::show_script_slots));
191        actionGroup->add(Gtk::Action::create("Quit", _("_Quit")),
192                         Gtk::AccelKey("<control>q"),
193                       sigc::mem_fun(                       sigc::mem_fun(
194                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
195      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
196            Gtk::Action::create("MenuSample", _("_Sample")),
197            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
198        );
199        actionGroup->add(
200            Gtk::Action::create("MenuInstrument", _("_Instrument")),
201            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
202        );
203        actionGroup->add(
204            Gtk::Action::create("MenuScript", _("Scr_ipt")),
205            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
206        );
207        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
208    
209      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
210    
211        const Gdk::ModifierType primaryModifierKey =
212    #if defined(__APPLE__)
213        Gdk::META_MASK; // Cmd key on Mac
214    #else
215        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
216    #endif
217    
218        actionGroup->add(Gtk::Action::create("CopyDimRgn",
219                                             _("Copy selected dimension region")),
220                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
221                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
222    
223        actionGroup->add(Gtk::Action::create("PasteDimRgn",
224                                             _("Paste dimension region")),
225                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
226                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
227    
228        actionGroup->add(Gtk::Action::create("AdjustClipboard",
229                                             _("Adjust Clipboard Content")),
230                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
231                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
232    
233        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
234                                             _("Select Previous Region")),
235                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
236                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
237    
238        actionGroup->add(Gtk::Action::create("SelectNextRegion",
239                                             _("Select Next Region")),
240                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
241                         sigc::mem_fun(*this, &MainWindow::select_next_region));
242    
243        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
244                                             _("Select Previous Dimension Region Zone")),
245                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
246                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
247    
248        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
249                                             _("Select Next Dimension Region Zone")),
250                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
251                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
252    
253        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
254                                             _("Select Previous Dimension")),
255                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
256                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
257    
258        actionGroup->add(Gtk::Action::create("SelectNextDimension",
259                                             _("Select Next Dimension")),
260                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
261                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
262    
263        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
264                                             _("Add Previous Dimension Region Zone to Selection")),
265                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
266                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
267    
268        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
269                                             _("Add Next Dimension Region Zone to Selection")),
270                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
271                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
272    
273      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
274          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
275      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 157  MainWindow::MainWindow() : Line 286  MainWindow::MainWindow() :
286      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
287    
288    
289      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));      actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
290    
291    
292        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
293      toggle_action =      toggle_action =
294          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
295      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 165  MainWindow::MainWindow() : Line 297  MainWindow::MainWindow() :
297                       sigc::mem_fun(                       sigc::mem_fun(
298                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
299    
300      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      toggle_action =
301      actionGroup->add(Gtk::Action::create("MenuHelp",          Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
302                                           action->property_label()));      toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
303      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),      actionGroup->add(toggle_action,
304                         sigc::mem_fun(
305                             *this, &MainWindow::on_auto_restore_win_dim));
306    
307        toggle_action =
308            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
309        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
310        actionGroup->add(toggle_action,
311                         sigc::mem_fun(
312                             *this, &MainWindow::on_save_with_temporary_file));
313    
314        actionGroup->add(
315            Gtk::Action::create("RefreshAll", _("_Refresh All")),
316            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
317        );                
318    
319        actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
320        actionGroup->add(Gtk::Action::create("About", _("_About")),
321                       sigc::mem_fun(                       sigc::mem_fun(
322                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
323      actionGroup->add(      actionGroup->add(
# Line 180  MainWindow::MainWindow() : Line 329  MainWindow::MainWindow() :
329          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
330      );      );
331      actionGroup->add(      actionGroup->add(
332          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", _("_Remove")),
333          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
334      );      );
335    
# Line 195  MainWindow::MainWindow() : Line 344  MainWindow::MainWindow() :
344          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
345      );      );
346    
347        toggle_action =
348            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
349        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
350        actionGroup->add(
351            toggle_action,
352            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
353        );
354    
355        toggle_action =
356            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
357        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
358        actionGroup->add(
359            toggle_action,
360            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
361        );
362    
363    
364      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
365    
# Line 211  MainWindow::MainWindow() : Line 376  MainWindow::MainWindow() :
376    
377      // sample right-click popup actions      // sample right-click popup actions
378      actionGroup->add(      actionGroup->add(
379          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", _("_Properties")),
380          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
381      );      );
382      actionGroup->add(      actionGroup->add(
# Line 223  MainWindow::MainWindow() : Line 388  MainWindow::MainWindow() :
388          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
389      );      );
390      actionGroup->add(      actionGroup->add(
391          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", _("_Remove")),
392          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
393      );      );
394      actionGroup->add(      actionGroup->add(
395            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
396            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
397        );
398        actionGroup->add(
399            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
400            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
401        );
402        actionGroup->add(
403            Gtk::Action::create("ReplaceSample",
404                                _("Replace Sample...")),
405            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
406        );
407        actionGroup->add(
408          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
409                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
410          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)          sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
411      );      );
412        
413        // script right-click popup actions
414        actionGroup->add(
415            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
416            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
417        );
418        actionGroup->add(
419            Gtk::Action::create("AddScript", _("Add _Script")),
420            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
421        );
422        actionGroup->add(
423            Gtk::Action::create("EditScript", _("_Edit Script...")),
424            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
425        );
426        actionGroup->add(
427            Gtk::Action::create("RemoveScript", _("_Remove")),
428            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
429        );
430    
431      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
432      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 251  MainWindow::MainWindow() : Line 447  MainWindow::MainWindow() :
447          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
448          "    </menu>"          "    </menu>"
449          "    <menu action='MenuEdit'>"          "    <menu action='MenuEdit'>"
450            "      <menuitem action='CopyDimRgn'/>"
451            "      <menuitem action='AdjustClipboard'/>"
452            "      <menuitem action='PasteDimRgn'/>"
453            "      <separator/>"
454            "      <menuitem action='SelectPrevRegion'/>"
455            "      <menuitem action='SelectNextRegion'/>"
456            "      <separator/>"
457            "      <menuitem action='SelectPrevDimension'/>"
458            "      <menuitem action='SelectNextDimension'/>"
459            "      <menuitem action='SelectPrevDimRgnZone'/>"
460            "      <menuitem action='SelectNextDimRgnZone'/>"
461            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
462            "      <menuitem action='SelectAddNextDimRgnZone'/>"
463            "      <separator/>"
464          "      <menuitem action='CopySampleUnity'/>"          "      <menuitem action='CopySampleUnity'/>"
465          "      <menuitem action='CopySampleTune'/>"          "      <menuitem action='CopySampleTune'/>"
466          "      <menuitem action='CopySampleLoop'/>"          "      <menuitem action='CopySampleLoop'/>"
467          "    </menu>"          "    </menu>"
468            "    <menu action='MenuMacro'>"
469            "    </menu>"
470            "    <menu action='MenuSample'>"
471            "      <menuitem action='SampleProperties'/>"
472            "      <menuitem action='AddGroup'/>"
473            "      <menuitem action='AddSample'/>"
474            "      <menuitem action='ShowSampleRefs'/>"
475            "      <menuitem action='ReplaceSample' />"
476            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
477            "      <separator/>"
478            "      <menuitem action='RemoveSample'/>"
479            "      <menuitem action='RemoveUnusedSamples'/>"
480            "    </menu>"
481          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
482            "      <menu action='AllInstruments'>"
483            "      </menu>"
484            "      <separator/>"
485            "      <menuitem action='InstrProperties'/>"
486            "      <menuitem action='MidiRules'/>"
487            "      <menuitem action='ScriptSlots'/>"
488            "      <menuitem action='AddInstrument'/>"
489            "      <menuitem action='DupInstrument'/>"
490            "      <separator/>"
491            "      <menuitem action='RemoveInstrument'/>"
492            "    </menu>"
493            "    <menu action='MenuScript'>"
494            "      <menuitem action='AddScriptGroup'/>"
495            "      <menuitem action='AddScript'/>"
496            "      <menuitem action='EditScript'/>"
497            "      <separator/>"
498            "      <menuitem action='RemoveScript'/>"
499          "    </menu>"          "    </menu>"
500          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
501          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
502            "      <menuitem action='AutoRestoreWinDim'/>"
503            "      <separator/>"
504            "      <menuitem action='RefreshAll'/>"
505          "    </menu>"          "    </menu>"
506          "    <menu action='MenuTools'>"          "    <menu action='MenuTools'>"
507          "      <menuitem action='CombineInstruments'/>"          "      <menuitem action='CombineInstruments'/>"
# Line 266  MainWindow::MainWindow() : Line 509  MainWindow::MainWindow() :
509          "    </menu>"          "    </menu>"
510          "    <menu action='MenuSettings'>"          "    <menu action='MenuSettings'>"
511          "      <menuitem action='WarnUserOnExtensions'/>"          "      <menuitem action='WarnUserOnExtensions'/>"
512            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
513            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
514            "      <menuitem action='SaveWithTemporaryFile'/>"
515          "    </menu>"          "    </menu>"
516          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
517          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 274  MainWindow::MainWindow() : Line 520  MainWindow::MainWindow() :
520          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
521          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
522          "    <menuitem action='MidiRules'/>"          "    <menuitem action='MidiRules'/>"
523            "    <menuitem action='ScriptSlots'/>"
524          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
525          "    <menuitem action='DupInstrument'/>"          "    <menuitem action='DupInstrument'/>"
526          "    <separator/>"          "    <separator/>"
# Line 283  MainWindow::MainWindow() : Line 530  MainWindow::MainWindow() :
530          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
531          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
532          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
533            "    <menuitem action='ShowSampleRefs'/>"
534            "    <menuitem action='ReplaceSample' />"
535          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
536          "    <separator/>"          "    <separator/>"
537          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
538            "    <menuitem action='RemoveUnusedSamples'/>"
539            "  </popup>"
540            "  <popup name='ScriptPopupMenu'>"
541            "    <menuitem action='AddScriptGroup'/>"
542            "    <menuitem action='AddScript'/>"
543            "    <menuitem action='EditScript'/>"
544            "    <separator/>"
545            "    <menuitem action='RemoveScript'/>"
546          "  </popup>"          "  </popup>"
547          "</ui>";          "</ui>";
548      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
# Line 318  MainWindow::MainWindow() : Line 575  MainWindow::MainWindow() :
575      }      }
576      {      {
577          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
578                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
579            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)."));
580        }
581        {
582            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
583                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
584            item->set_tooltip_text(_("If checked, and when a region is moved by dragging it around on the virtual keyboard, the keybord position dependent pitch will move exactly with the amount of semi tones the region was moved around."));
585        }
586        {
587            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
588                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
589            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
590            // copy tooltip to popup menu
591            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
592                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
593            item2->set_tooltip_text(item->get_tooltip_text());
594        }
595        {
596            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
597                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
598            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
599        }
600        {
601            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
602                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
603            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
604        }
605        {
606            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
607              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
608          item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));          item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
609      }      }
# Line 329  MainWindow::MainWindow() : Line 615  MainWindow::MainWindow() :
615    
616    
617      instrument_menu = static_cast<Gtk::MenuItem*>(      instrument_menu = static_cast<Gtk::MenuItem*>(
618          uiManager->get_widget("/MenuBar/MenuInstrument"))->get_submenu();          uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
619    
620      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
621      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
# Line 355  MainWindow::MainWindow() : Line 641  MainWindow::MainWindow() :
641      // Create the Tree model:      // Create the Tree model:
642      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
643      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
644      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules."));      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
645        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
646      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
647          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
648      );      );
649    
650      // Add the TreeView's view columns:      // Add the TreeView's view columns:
651      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
652      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
653        m_TreeView.set_headers_visible(true);
654        
655        // establish drag&drop within the instrument tree view, allowing to reorder
656        // the sequence of instruments within the gig file
657        {
658            std::vector<Gtk::TargetEntry> drag_target_instrument;
659            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
660            m_TreeView.drag_source_set(drag_target_instrument);
661            m_TreeView.drag_dest_set(drag_target_instrument);
662            m_TreeView.signal_drag_begin().connect(
663                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
664            );
665            m_TreeView.signal_drag_data_get().connect(
666                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
667            );
668            m_TreeView.signal_drag_data_received().connect(
669                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
670            );
671        }
672    
673      // create samples treeview (including its data model)      // create samples treeview (including its data model)
674      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
675      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
676        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
677      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."));      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."));
678      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
679      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
680      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
681        {
682            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
683            Gtk::CellRendererText* cellrenderer =
684                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
685            column->add_attribute(
686                cellrenderer->property_foreground(), m_SamplesModel.m_color
687            );
688        }
689        {
690            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
691            Gtk::CellRendererText* cellrenderer =
692                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
693            column->add_attribute(
694                cellrenderer->property_foreground(), m_SamplesModel.m_color
695            );
696        }
697        m_TreeViewSamples.set_headers_visible(true);
698      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
699          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
700      );      );
# Line 378  MainWindow::MainWindow() : Line 702  MainWindow::MainWindow() :
702          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
703      );      );
704    
705        // create scripts treeview (including its data model)
706        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
707        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
708        m_TreeViewScripts.set_tooltip_text(_(
709            "Use CTRL + double click for editing a script."
710            "\n\n"
711            "Note: instrument scripts are a LinuxSampler extension of the gig "
712            "format. This feature will not work with the GigaStudio software!"
713        ));
714        // m_TreeViewScripts.set_reorderable();
715        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
716        m_TreeViewScripts.set_headers_visible(false);
717        m_TreeViewScripts.signal_button_press_event().connect_notify(
718            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
719        );
720        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
721        m_TreeViewScripts.signal_row_activated().connect(
722            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
723        );
724        m_refScriptsTreeModel->signal_row_changed().connect(
725            sigc::mem_fun(*this, &MainWindow::script_name_changed)
726        );
727    
728        // establish drag&drop between scripts tree view and ScriptSlots window
729        std::vector<Gtk::TargetEntry> drag_target_gig_script;
730        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
731        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
732        m_TreeViewScripts.signal_drag_begin().connect(
733            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
734        );
735        m_TreeViewScripts.signal_drag_data_get().connect(
736            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
737        );
738    
739      // 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
740      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
741      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
# Line 396  MainWindow::MainWindow() : Line 754  MainWindow::MainWindow() :
754          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
755      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
756          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
757        m_RegionChooser.signal_instrument_changed().connect(
758            sigc::mem_fun(*this, &MainWindow::region_changed));
759      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
760          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
761      instrumentProps.signal_changed().connect(      instrumentProps.signal_changed().connect(
# Line 411  MainWindow::MainWindow() : Line 771  MainWindow::MainWindow() :
771          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
772      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
773          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
774        sample_ref_changed_signal.connect(
775            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
776        );
777        samples_to_be_removed_signal.connect(
778            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
779        );
780    
781        dimreg_edit.signal_select_sample().connect(
782            sigc::mem_fun(*this, &MainWindow::select_sample)
783        );
784    
785      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
786          sigc::hide(          sigc::hide(
# Line 455  MainWindow::MainWindow() : Line 825  MainWindow::MainWindow() :
825    
826      // select 'Instruments' tab by default      // select 'Instruments' tab by default
827      // (gtk allows this only if the tab childs are visible, thats why it's here)      // (gtk allows this only if the tab childs are visible, thats why it's here)
828      m_TreeViewNotebook.set_current_page(1);      m_TreeViewNotebook.set_current_page(1);
829    
830        Gtk::Clipboard::get()->signal_owner_change().connect(
831            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
832        );
833        updateClipboardPasteAvailable();
834        updateClipboardCopyAvailable();
835    
836        // setup macros and their keyboard accelerators
837        {
838            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
839                uiManager->get_widget("/MenuBar/MenuMacro")
840            )->get_submenu();
841    
842            const Gdk::ModifierType primaryModifierKey =
843    #if defined(__APPLE__)
844                Gdk::META_MASK; // Cmd key on Mac
845    #else
846                Gdk::CONTROL_MASK; // Ctrl key on all other OSs
847    #endif
848    
849            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
850            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
851            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
852            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
853            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
854            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
855            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
856            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
857            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
858            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
859            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
860            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
861            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
862            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
863    
864            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
865            menuMacro->set_accel_group(accelGroup);
866    
867            updateMacroMenu();
868        }
869  }  }
870    
871  MainWindow::~MainWindow()  MainWindow::~MainWindow()
872  {  {
873  }  }
874    
875    void MainWindow::updateMacroMenu() {
876        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
877            uiManager->get_widget("/MenuBar/MenuMacro")
878        )->get_submenu();
879    
880        // remove all entries from "Macro" menu
881        {
882            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
883            for (int i = 0; i < children.size(); ++i) {
884                Gtk::Widget* child = children[i];
885                menuMacro->remove(*child);
886                delete child;
887            }
888        }
889    
890        // (re)load all macros from config file
891        try {
892            Settings::singleton()->loadMacros(m_macros);
893        } catch (Serialization::Exception e) {
894            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
895        } catch (...) {
896            std::cerr << "Unknown exception while loading macros!" << std::endl;
897        }
898    
899        // add all configured macros as menu items to the "Macro" menu
900        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
901            const Serialization::Archive& macro = m_macros[iMacro];
902            std::string name =
903                macro.name().empty() ?
904                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
905            Gtk::MenuItem* item = new Gtk::MenuItem(name);
906            item->signal_activate().connect(
907                sigc::bind(
908                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
909                )
910            );
911            menuMacro->append(*item);
912            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
913        }
914        // if there are no macros configured at all, then show a dummy entry instead
915        if (m_macros.empty()) {
916            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
917            item->set_sensitive(false);
918            menuMacro->append(*item);
919        }
920    
921        // add separator line to menu
922        menuMacro->append(*new Gtk::SeparatorMenuItem);
923    
924        {
925            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
926            item->signal_activate().connect(
927                sigc::mem_fun(*this, &MainWindow::setupMacros)
928            );
929            menuMacro->append(*item);
930            item->set_accel_path("<Macros>/SetupMacros");
931        }
932    
933        menuMacro->show_all_children();
934    }
935    
936    void MainWindow::onMacroSelected(int iMacro) {
937        printf("onMacroSelected(%d)\n", iMacro);
938        if (iMacro < 0 || iMacro >= m_macros.size()) return;
939        Glib::ustring errorText;
940        try {
941            applyMacro(m_macros[iMacro]);
942        } catch (Serialization::Exception e) {
943            errorText = e.Message;
944        } catch (...) {
945            errorText = _("Unknown exception while applying macro");
946        }
947        if (!errorText.empty()) {
948            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
949            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
950            msg.run();
951        }
952    }
953    
954    void MainWindow::setupMacros() {
955        MacrosSetup* setup = new MacrosSetup();
956        setup->setMacros(m_macros);
957        setup->signal_macros_changed().connect(
958            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
959        );
960        setup->show();
961    }
962    
963    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
964        m_macros = macros;
965        Settings::singleton()->saveMacros(m_macros);
966        updateMacroMenu();
967    }
968    
969  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
970  {  {
971      return !file_is_shared && file_is_changed && !close_confirmation_dialog();      return !file_is_shared && file_is_changed && !close_confirmation_dialog();
# Line 481  void MainWindow::region_changed() Line 985  void MainWindow::region_changed()
985  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
986  {  {
987      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
988      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
989          m_TreeView.get_selection()->get_selected();      if (rows.empty()) return NULL;
990        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
991      if (it) {      if (it) {
992          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
993          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 525  void MainWindow::update_dimregs() Line 1030  void MainWindow::update_dimregs()
1030              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1031          }          }
1032      }      }
1033    
1034        m_RegionChooser.setModifyAllRegions(all_regions);
1035        m_DimRegionChooser.setModifyAllRegions(all_regions);
1036        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1037        m_DimRegionChooser.setModifyBothChannels(stereo);
1038    
1039        updateClipboardCopyAvailable();
1040  }  }
1041    
1042  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 536  void MainWindow::dimreg_all_dimregs_togg Line 1048  void MainWindow::dimreg_all_dimregs_togg
1048  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1049  {  {
1050      update_dimregs();      update_dimregs();
1051      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1052  }  }
1053    
1054  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1055  {  {
1056      // select item in instrument menu      // select item in instrument menu
1057      Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1058      if (it) {      if (!rows.empty()) {
1059          Gtk::TreePath path(it);          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1060          int index = path[0];          if (it) {
1061          const std::vector<Gtk::Widget*> children =              Gtk::TreePath path(it);
1062              instrument_menu->get_children();              int index = path[0];
1063          static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();              const std::vector<Gtk::Widget*> children =
1064                    instrument_menu->get_children();
1065                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1066            }
1067      }      }
1068    
1069      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1070    
1071        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1072            switch_sampler_instrument_signal.emit(get_instrument());
1073        }
1074  }  }
1075    
1076  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
# Line 569  void Loader::progress_callback(float fra Line 1088  void Loader::progress_callback(float fra
1088      progress_dispatcher();      progress_dispatcher();
1089  }  }
1090    
1091    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1092    // make sure stack is 16-byte aligned for SSE instructions
1093    __attribute__((force_align_arg_pointer))
1094    #endif
1095  void Loader::thread_function()  void Loader::thread_function()
1096  {  {
1097      printf("thread_function self=%x\n", Glib::Threads::Thread::self());      printf("thread_function self=%p\n",
1098      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1099      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
1100      gig = new gig::File(riff);      try {
1101      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
1102      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
1103      progress.custom = this;          gig::progress_t progress;
1104            progress.callback = loader_progress_callback;
1105      gig->GetInstrument(0, &progress);          progress.custom = this;
1106      printf("End\n");  
1107      finished_dispatcher();          gig->GetInstrument(0, &progress);
1108            printf("End\n");
1109            finished_dispatcher();
1110        } catch (RIFF::Exception e) {
1111            error_message = e.Message;
1112            error_dispatcher.emit();
1113        } catch (...) {
1114            error_message = _("Unknown exception occurred");
1115            error_dispatcher.emit();
1116        }
1117  }  }
1118    
1119  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
1120      : filename(filename), thread(0)      : filename(filename), gig(0), thread(0), progress(0.f)
1121  {  {
1122  }  }
1123    
# Line 596  void Loader::launch() Line 1128  void Loader::launch()
1128  #else  #else
1129      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
1130  #endif  #endif
1131      printf("launch thread=%x\n", thread);      printf("launch thread=%p\n", static_cast<void*>(thread));
1132  }  }
1133    
1134  float Loader::get_progress()  float Loader::get_progress()
# Line 619  Glib::Dispatcher& Loader::signal_finishe Line 1151  Glib::Dispatcher& Loader::signal_finishe
1151      return finished_dispatcher;      return finished_dispatcher;
1152  }  }
1153    
1154  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
1155    {
1156        return error_dispatcher;
1157    }
1158    
1159    void saver_progress_callback(gig::progress_t* progress)
1160    {
1161        Saver* saver = static_cast<Saver*>(progress->custom);
1162        saver->progress_callback(progress->factor);
1163    }
1164    
1165    void Saver::progress_callback(float fraction)
1166    {
1167        {
1168            Glib::Threads::Mutex::Lock lock(progressMutex);
1169            progress = fraction;
1170        }
1171        progress_dispatcher.emit();
1172    }
1173    
1174    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1175    // make sure stack is 16-byte aligned for SSE instructions
1176    __attribute__((force_align_arg_pointer))
1177    #endif
1178    void Saver::thread_function()
1179    {
1180        printf("thread_function self=%p\n",
1181               static_cast<void*>(Glib::Threads::Thread::self()));
1182        printf("Start %s\n", filename.c_str());
1183        try {
1184            gig::progress_t progress;
1185            progress.callback = saver_progress_callback;
1186            progress.custom = this;
1187    
1188            // if no filename was provided, that means "save", if filename was provided means "save as"
1189            if (filename.empty()) {
1190                if (!Settings::singleton()->saveWithTemporaryFile) {
1191                    // save directly over the existing .gig file
1192                    // (requires less disk space than solution below
1193                    // but may be slower)
1194                    gig->Save(&progress);
1195                } else {
1196                    // save the file as separate temporary file first,
1197                    // then move the saved file over the old file
1198                    // (may result in performance speedup during save)
1199                    String tmpname = filename + ".TMP";
1200                    gig->Save(tmpname, &progress);
1201                    #if defined(WIN32)
1202                    if (!DeleteFile(filename.c_str())) {
1203                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1204                    }
1205                    #else // POSIX ...
1206                    if (unlink(filename.c_str())) {
1207                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
1208                    }
1209                    #endif
1210                    if (rename(tmpname.c_str(), filename.c_str())) {
1211                        #if defined(WIN32)
1212                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1213                        #else
1214                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
1215                        #endif
1216                    }
1217                }
1218            } else {
1219                gig->Save(filename, &progress);
1220            }
1221    
1222            printf("End\n");
1223            finished_dispatcher.emit();
1224        } catch (RIFF::Exception e) {
1225            error_message = e.Message;
1226            error_dispatcher.emit();
1227        } catch (...) {
1228            error_message = _("Unknown exception occurred");
1229            error_dispatcher.emit();
1230        }
1231    }
1232    
1233    Saver::Saver(gig::File* file, Glib::ustring filename)
1234        : gig(file), filename(filename), thread(0), progress(0.f)
1235    {
1236    }
1237    
1238    void Saver::launch()
1239    {
1240    #ifdef OLD_THREADS
1241        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1242    #else
1243        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1244    #endif
1245        printf("launch thread=%p\n", static_cast<void*>(thread));
1246    }
1247    
1248    float Saver::get_progress()
1249    {
1250        float res;
1251        {
1252            Glib::Threads::Mutex::Lock lock(progressMutex);
1253            res = progress;
1254        }
1255        return res;
1256    }
1257    
1258    Glib::Dispatcher& Saver::signal_progress()
1259    {
1260        return progress_dispatcher;
1261    }
1262    
1263    Glib::Dispatcher& Saver::signal_finished()
1264    {
1265        return finished_dispatcher;
1266    }
1267    
1268    Glib::Dispatcher& Saver::signal_error()
1269    {
1270        return error_dispatcher;
1271    }
1272    
1273    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1274      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1275  {  {
1276      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1277      show_all_children();      show_all_children();
1278        resize(600,50);
1279  }  }
1280    
1281  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
# Line 634  void MainWindow::__clear() { Line 1286  void MainWindow::__clear() {
1286      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1287      m_refTreeModel->clear();      m_refTreeModel->clear();
1288      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1289        m_refScriptsTreeModel->clear();
1290      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1291      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1292          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 648  void MainWindow::__refreshEntireGUI() { Line 1301  void MainWindow::__refreshEntireGUI() {
1301      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1302      m_refTreeModel->clear();      m_refTreeModel->clear();
1303      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1304        m_refScriptsTreeModel->clear();
1305      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1306      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1307          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 685  bool MainWindow::close_confirmation_dial Line 1339  bool MainWindow::close_confirmation_dial
1339      g_free(msg);      g_free(msg);
1340      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."));
1341      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1342      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1343      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);      dialog.add_button(file_has_name ? _("_Save") : _("Save _As"), Gtk::RESPONSE_YES);
1344      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1345      int response = dialog.run();      int response = dialog.run();
1346      dialog.hide();      dialog.hide();
1347      if (response == Gtk::RESPONSE_YES) return file_save();  
1348      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1349        if (response == Gtk::RESPONSE_NO) return true;
1350    
1351        // user cancelled dialog, thus don't close app
1352        if (response == Gtk::RESPONSE_CANCEL) return false;
1353    
1354        // TODO: the following return valid is disabled and hard coded instead for
1355        // now, due to the fact that saving with progress bar is now implemented
1356        // asynchronously, as a result the app does not close automatically anymore
1357        // after saving the file has completed
1358        //
1359        //   if (response == Gtk::RESPONSE_YES) return file_save();
1360        //   return response != Gtk::RESPONSE_CANCEL;
1361        //
1362        if (response == Gtk::RESPONSE_YES) file_save();
1363        return false; // always prevent closing the app for now (see comment above)
1364  }  }
1365    
1366  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 702  bool MainWindow::leaving_shared_mode_dia Line 1371  bool MainWindow::leaving_shared_mode_dia
1371            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1372            "load it."));            "load it."));
1373      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1374      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1375      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1376      int response = dialog.run();      int response = dialog.run();
1377      dialog.hide();      dialog.hide();
# Line 716  void MainWindow::on_action_file_open() Line 1385  void MainWindow::on_action_file_open()
1385      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
1386    
1387      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1388      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1389      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1390      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1391  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1392      Gtk::FileFilter filter;      Gtk::FileFilter filter;
# Line 733  void MainWindow::on_action_file_open() Line 1402  void MainWindow::on_action_file_open()
1402      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1403          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1404          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1405          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());          printf("on_action_file_open self=%p\n",
1406                   static_cast<void*>(Glib::Threads::Thread::self()));
1407          load_file(filename.c_str());          load_file(filename.c_str());
1408          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1409      }      }
# Line 742  void MainWindow::on_action_file_open() Line 1412  void MainWindow::on_action_file_open()
1412  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1413  {  {
1414      __clear();      __clear();
1415      load_dialog = new LoadDialog(_("Loading..."), *this);  
1416      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1417      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1418            Glib::filename_display_basename(name) + "' ...",
1419            *this
1420        );
1421        progress_dialog->show_all();
1422        loader = new Loader(name); //FIXME: memory leak!
1423      loader->signal_progress().connect(      loader->signal_progress().connect(
1424          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1425      loader->signal_finished().connect(      loader->signal_finished().connect(
1426          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1427        loader->signal_error().connect(
1428            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1429      loader->launch();      loader->launch();
1430  }  }
1431    
# Line 764  void MainWindow::load_instrument(gig::In Line 1441  void MainWindow::load_instrument(gig::In
1441      // load the instrument      // load the instrument
1442      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1443      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1444      //TODO: automatically select the given instrument      // automatically select the given instrument
1445        int i = 0;
1446        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1447             instrument = pFile->GetNextInstrument(), ++i)
1448        {
1449            if (instrument == instr) {
1450                // select item in "instruments" tree view
1451                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1452                // make sure the selected item in the "instruments" tree view is
1453                // visible (scroll to it)
1454                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1455                // select item in instrument menu
1456                {
1457                    const std::vector<Gtk::Widget*> children =
1458                        instrument_menu->get_children();
1459                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1460                }
1461                // update region chooser and dimension region chooser
1462                m_RegionChooser.set_instrument(instr);
1463                break;
1464            }
1465        }
1466  }  }
1467    
1468  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1469  {  {
1470      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1471  }  }
1472    
1473  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1474  {  {
1475      printf("Loader finished!\n");      printf("Loader finished!\n");
1476      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());      printf("on_loader_finished self=%p\n",
1477      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1478      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1479        progress_dialog->hide();
1480    }
1481    
1482    void MainWindow::on_loader_error()
1483    {
1484        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1485        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1486        msg.run();
1487        progress_dialog->hide();
1488  }  }
1489    
1490  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 816  bool MainWindow::file_save() Line 1523  bool MainWindow::file_save()
1523    
1524      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1525      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1526      try {  
1527          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1528          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1529              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1530              file_is_changed = false;          *this
1531          }      );
1532      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1533          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1534          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1535          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1536          msg.run();      saver->signal_finished().connect(
1537          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1538      }      saver->signal_error().connect(
1539      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1540        saver->launch();
1541    
1542        return true;
1543    }
1544    
1545    void MainWindow::on_saver_progress()
1546    {
1547        progress_dialog->set_fraction(saver->get_progress());
1548    }
1549    
1550    void MainWindow::on_saver_error()
1551    {
1552        file_structure_changed_signal.emit(this->file);
1553        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1554        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1555        msg.run();
1556    }
1557    
1558    void MainWindow::on_saver_finished()
1559    {
1560        this->file = saver->gig;
1561        this->filename = saver->filename;
1562        current_gig_dir = Glib::path_get_dirname(filename);
1563        set_title(Glib::filename_display_basename(filename));
1564        file_has_name = true;
1565        file_is_changed = false;
1566        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1567      __import_queued_samples();      __import_queued_samples();
1568        std::cout << "Importing queued samples done.\n" << std::flush;
1569    
1570      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1571      return true;  
1572        __refreshEntireGUI();
1573        progress_dialog->hide();
1574  }  }
1575    
1576  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 843  void MainWindow::on_action_file_save_as( Line 1581  void MainWindow::on_action_file_save_as(
1581    
1582  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1583  {  {
1584      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1585      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1586      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
1587      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1588      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1589    
# Line 876  bool MainWindow::file_save_as() Line 1614  bool MainWindow::file_save_as()
1614      // show warning in the dialog      // show warning in the dialog
1615      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
1616      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
1617      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
1618        warningIcon.set_from_icon_name("dialog-warning",
1619                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1620      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1621  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
1622      view::WrapLabel description;      view::WrapLabel description;
# Line 897  bool MainWindow::file_save_as() Line 1637  bool MainWindow::file_save_as()
1637      descriptionArea.show_all();      descriptionArea.show_all();
1638    
1639      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1640          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1641          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1642              std::string filename = dialog.get_filename();              filename += ".gig";
             if (!Glib::str_has_suffix(filename, ".gig")) {  
                 filename += ".gig";  
             }  
             printf("filename=%s\n", filename.c_str());  
             file->Save(filename);  
             this->filename = filename;  
             current_gig_dir = Glib::path_get_dirname(filename);  
             set_title(Glib::filename_display_basename(filename));  
             file_has_name = true;  
             file_is_changed = false;  
         } catch (RIFF::Exception e) {  
             file_structure_changed_signal.emit(this->file);  
             Glib::ustring txt = _("Could not save file: ") + e.Message;  
             Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);  
             msg.run();  
             return false;  
1643          }          }
1644          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1645          file_structure_changed_signal.emit(this->file);  
1646            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1647                _("Saving") +  Glib::ustring(" '") +
1648                Glib::filename_display_basename(filename) + "' ...",
1649                *this
1650            );
1651            progress_dialog->show_all();
1652    
1653            saver = new Saver(file, filename); //FIXME: memory leak!
1654            saver->signal_progress().connect(
1655                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1656            saver->signal_finished().connect(
1657                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1658            saver->signal_error().connect(
1659                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1660            saver->launch();
1661    
1662          return true;          return true;
1663      }      }
1664      return false;      return false;
# Line 928  bool MainWindow::file_save_as() Line 1668  bool MainWindow::file_save_as()
1668  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1669      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1670      Glib::ustring error_files;      Glib::ustring error_files;
1671      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1672      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1673           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1674          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1675          SF_INFO info;          SF_INFO info;
1676          info.format = 0;          info.format = 0;
1677          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);
1678          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1679          try {          try {
1680              if (!hFile) throw std::string(_("could not open file"));              if (!hFile) throw std::string(_("could not open file"));
# Line 957  void MainWindow::__import_queued_samples Line 1697  void MainWindow::__import_queued_samples
1697                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1698              }              }
1699    
1700                // reset write position for sample
1701                iter->first->SetPos(0);
1702    
1703              const int bufsize = 10000;              const int bufsize = 10000;
1704              switch (bitdepth) {              switch (bitdepth) {
1705                  case 16: {                  case 16: {
# Line 966  void MainWindow::__import_queued_samples Line 1709  void MainWindow::__import_queued_samples
1709                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1710                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1711                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1712                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1713                          cnt -= n;                          cnt -= n;
1714                      }                      }
1715                      delete[] buffer;                      delete[] buffer;
# Line 986  void MainWindow::__import_queued_samples Line 1729  void MainWindow::__import_queued_samples
1729                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1730                          }                          }
1731                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1732                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1733                          cnt -= n;                          cnt -= n;
1734                      }                      }
1735                      delete[] srcbuf;                      delete[] srcbuf;
# Line 997  void MainWindow::__import_queued_samples Line 1740  void MainWindow::__import_queued_samples
1740              // cleanup              // cleanup
1741              sf_close(hFile);              sf_close(hFile);
1742              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
1743              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
1744              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1745              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1746              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1747              ++iter;              ++iter;
1748              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1749          } catch (std::string what) {          } catch (std::string what) {
1750              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1751              if (!error_files.empty()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1752              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1753              ++iter;              ++iter;
1754          }          }
1755      }      }
# Line 1029  void MainWindow::on_action_warn_user_on_ Line 1772  void MainWindow::on_action_warn_user_on_
1772          !Settings::singleton()->warnUserOnExtensions;          !Settings::singleton()->warnUserOnExtensions;
1773  }  }
1774    
1775    void MainWindow::on_action_sync_sampler_instrument_selection() {
1776        Settings::singleton()->syncSamplerInstrumentSelection =
1777            !Settings::singleton()->syncSamplerInstrumentSelection;
1778    }
1779    
1780    void MainWindow::on_action_move_root_note_with_region_moved() {
1781        Settings::singleton()->moveRootNoteWithRegionMoved =
1782            !Settings::singleton()->moveRootNoteWithRegionMoved;
1783    }
1784    
1785  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1786  {  {
1787      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
# Line 1038  void MainWindow::on_action_help_about() Line 1791  void MainWindow::on_action_help_about()
1791      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
1792  #endif  #endif
1793      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1794      dialog.set_copyright("Copyright (C) 2006-2014 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1795      const std::string sComment =      const std::string sComment =
1796          _("Built " __DATE__ "\nUsing ") +          _("Built " __DATE__ "\nUsing ") +
1797          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1798          _(          _(
1799              "Gigedit is released under the GNU General Public License.\n"              "Gigedit is released under the GNU General Public License.\n"
1800              "\n"              "\n"
1801              "Please notice that this is still a very young instrument editor. "              "This program is distributed WITHOUT ANY WARRANTY; So better "
1802              "So better backup your Gigasampler files before editing them with "              "backup your Gigasampler/GigaStudio files before editing them with "
1803              "this application.\n"              "this application.\n"
1804              "\n"              "\n"
1805              "Please report bugs to: http://bugs.linuxsampler.org"              "Please report bugs to: http://bugs.linuxsampler.org"
# Line 1075  PropDialog::PropDialog() Line 1828  PropDialog::PropDialog()
1828        eSourceForm(_("Source form")),        eSourceForm(_("Source form")),
1829        eCommissioned(_("Commissioned")),        eCommissioned(_("Commissioned")),
1830        eSubject(_("Subject")),        eSubject(_("Subject")),
1831        quitButton(Gtk::Stock::CLOSE),        quitButton(_("_Close"), true),
1832        table(2, 1),        table(2, 1),
1833        m_file(NULL)        m_file(NULL)
1834  {  {
# Line 1198  void InstrumentProps::set_MIDIProgram(ui Line 1951  void InstrumentProps::set_MIDIProgram(ui
1951  }  }
1952    
1953  InstrumentProps::InstrumentProps() :  InstrumentProps::InstrumentProps() :
1954      quitButton(Gtk::Stock::CLOSE),      quitButton(_("_Close"), true),
1955      table(2,1),      table(2,1),
1956      eName(_("Name")),      eName(_("Name")),
1957      eIsDrum(_("Is drum")),      eIsDrum(_("Is drum")),
# Line 1295  void MainWindow::file_changed() Line 2048  void MainWindow::file_changed()
2048      }      }
2049  }  }
2050    
2051    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
2052        sample_ref_count.clear();
2053        
2054        if (!gig) return;
2055    
2056        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
2057             instrument = gig->GetNextInstrument())
2058        {
2059            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2060                 rgn = instrument->GetNextRegion())
2061            {
2062                for (int i = 0; i < 256; ++i) {
2063                    if (!rgn->pDimensionRegions[i]) continue;
2064                    if (rgn->pDimensionRegions[i]->pSample) {
2065                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
2066                    }
2067                }
2068            }
2069        }
2070    }
2071    
2072  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
2073  {  {
2074      file = 0;      file = 0;
2075      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
2076    
2077      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
2078            (filename && strlen(filename) > 0) ?
2079                filename : (!gig->GetFileName().empty()) ?
2080                    gig->GetFileName() : _("Unsaved Gig File");
2081      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
2082      file_has_name = filename;      file_has_name = filename;
2083      file_is_changed = false;      file_is_changed = false;
# Line 1309  void MainWindow::load_gig(gig::File* gig Line 2086  void MainWindow::load_gig(gig::File* gig
2086      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
2087    
2088      instrument_name_connection.block();      instrument_name_connection.block();
2089        int index = 0;
2090      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
2091           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
2092          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2093    
2094          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
2095          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
2096            row[m_Columns.m_col_nr] = index;
2097          row[m_Columns.m_col_name] = name;          row[m_Columns.m_col_name] = name;
2098          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
2099    
2100          add_instrument_to_menu(name);          add_instrument_to_menu(name);
2101      }      }
2102      instrument_name_connection.unblock();      instrument_name_connection.unblock();
2103      uiManager->get_widget("/MenuBar/MenuInstrument")->show();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
2104    
2105        updateSampleRefCountMap(gig);
2106    
2107      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
2108          if (group->Name != "") {          if (group->Name != "") {
# Line 1339  void MainWindow::load_gig(gig::File* gig Line 2120  void MainWindow::load_gig(gig::File* gig
2120                      gig_to_utf8(sample->pInfo->Name);                      gig_to_utf8(sample->pInfo->Name);
2121                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2122                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2123                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
2124                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
2125                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
2126              }              }
2127          }          }
2128      }      }
2129        
2130        for (int i = 0; gig->GetScriptGroup(i); ++i) {
2131            gig::ScriptGroup* group = gig->GetScriptGroup(i);
2132    
2133            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2134            Gtk::TreeModel::Row rowGroup = *iterGroup;
2135            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
2136            rowGroup[m_ScriptsModel.m_col_group]  = group;
2137            rowGroup[m_ScriptsModel.m_col_script] = NULL;
2138            for (int s = 0; group->GetScript(s); ++s) {
2139                gig::Script* script = group->GetScript(s);
2140    
2141                Gtk::TreeModel::iterator iterScript =
2142                    m_refScriptsTreeModel->append(rowGroup.children());
2143                Gtk::TreeModel::Row rowScript = *iterScript;
2144                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
2145                rowScript[m_ScriptsModel.m_col_script] = script;
2146                rowScript[m_ScriptsModel.m_col_group]  = NULL;
2147            }
2148        }
2149        // unfold all sample groups & script groups by default
2150        m_TreeViewSamples.expand_all();
2151        m_TreeViewScripts.expand_all();
2152    
2153      file = gig;      file = gig;
2154    
# Line 1359  bool MainWindow::instr_props_set_instrum Line 2166  bool MainWindow::instr_props_set_instrum
2166  {  {
2167      instrumentProps.signal_name_changed().clear();      instrumentProps.signal_name_changed().clear();
2168    
2169      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2170          m_TreeView.get_selection()->get_selected();      if (rows.empty()) {
2171            instrumentProps.hide();
2172            return false;
2173        }
2174        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2175      if (it) {      if (it) {
2176          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2177          gig::Instrument* instrument = row[m_Columns.m_col_instr];          gig::Instrument* instrument = row[m_Columns.m_col_instr];
# Line 1410  void MainWindow::show_midi_rules() Line 2221  void MainWindow::show_midi_rules()
2221      }      }
2222  }  }
2223    
2224    void MainWindow::show_script_slots() {
2225        if (!file) return;
2226        // get selected instrument
2227        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2228        if (rows.empty()) return;
2229        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2230        if (!it) return;
2231        Gtk::TreeModel::Row row = *it;
2232        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2233        if (!instrument) return;
2234    
2235        ScriptSlots* window = new ScriptSlots;
2236        window->setInstrument(instrument);
2237        //window->reparent(*this);
2238        window->show();
2239    }
2240    
2241    void MainWindow::on_action_refresh_all() {
2242        __refreshEntireGUI();
2243    }
2244    
2245  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2246      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2247          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1421  void MainWindow::on_action_view_status_b Line 2253  void MainWindow::on_action_view_status_b
2253      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2254  }  }
2255    
2256    void MainWindow::on_auto_restore_win_dim() {
2257        Gtk::CheckMenuItem* item =
2258            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2259        if (!item) {
2260            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2261            return;
2262        }
2263        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2264    }
2265    
2266    void MainWindow::on_save_with_temporary_file() {
2267        Gtk::CheckMenuItem* item =
2268            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2269        if (!item) {
2270            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2271            return;
2272        }
2273        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2274    }
2275    
2276  bool MainWindow::is_copy_samples_unity_note_enabled() const {  bool MainWindow::is_copy_samples_unity_note_enabled() const {
2277      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2278          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
# Line 1457  void MainWindow::on_button_release(GdkEv Line 2309  void MainWindow::on_button_release(GdkEv
2309          show_instr_props();          show_instr_props();
2310      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2311          // gig v2 files have no midi rules          // gig v2 files have no midi rules
2312            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2313            static_cast<Gtk::MenuItem*>(
2314                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2315                    bEnabled
2316                );
2317          static_cast<Gtk::MenuItem*>(          static_cast<Gtk::MenuItem*>(
2318              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2319                  !(file->pVersion && file->pVersion->major == 2));                  bEnabled
2320                );
2321          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2322      }      }
2323  }  }
# Line 1479  void MainWindow::on_instrument_selection Line 2337  void MainWindow::on_instrument_selection
2337      }      }
2338  }  }
2339    
2340    void MainWindow::select_instrument(gig::Instrument* instrument) {
2341        if (!instrument) return;
2342    
2343        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2344        for (int i = 0; i < model->children().size(); ++i) {
2345            Gtk::TreeModel::Row row = model->children()[i];
2346            if (row[m_Columns.m_col_instr] == instrument) {
2347                // select and show the respective instrument in the list view
2348                show_intruments_tab();
2349                m_TreeView.get_selection()->unselect_all();
2350                m_TreeView.get_selection()->select(model->children()[i]);
2351                std::vector<Gtk::TreeModel::Path> rows =
2352                    m_TreeView.get_selection()->get_selected_rows();
2353                if (!rows.empty())
2354                    m_TreeView.scroll_to_row(rows[0]);
2355                on_sel_change(); // the regular instrument selection change callback
2356            }
2357        }
2358    }
2359    
2360    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2361    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2362        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2363        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2364    
2365        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2366        for (int i = 0; i < model->children().size(); ++i) {
2367            Gtk::TreeModel::Row row = model->children()[i];
2368            if (row[m_Columns.m_col_instr] == pInstrument) {
2369                // select and show the respective instrument in the list view
2370                show_intruments_tab();
2371                m_TreeView.get_selection()->unselect_all();
2372                m_TreeView.get_selection()->select(model->children()[i]);
2373                std::vector<Gtk::TreeModel::Path> rows =
2374                    m_TreeView.get_selection()->get_selected_rows();
2375                if (!rows.empty())
2376                    m_TreeView.scroll_to_row(rows[0]);
2377                on_sel_change(); // the regular instrument selection change callback
2378    
2379                // select respective region in the region selector
2380                m_RegionChooser.set_region(pRegion);
2381    
2382                // select and show the respective dimension region in the editor
2383                //update_dimregs();
2384                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2385                //dimreg_edit.set_dim_region(dimRgn);
2386    
2387                return true;
2388            }
2389        }
2390    
2391        return false;
2392    }
2393    
2394    void MainWindow::select_sample(gig::Sample* sample) {
2395        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2396        for (int g = 0; g < model->children().size(); ++g) {
2397            Gtk::TreeModel::Row rowGroup = model->children()[g];
2398            for (int s = 0; s < rowGroup.children().size(); ++s) {
2399                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2400                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2401                    show_samples_tab();
2402                    m_TreeViewSamples.get_selection()->unselect_all();
2403                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2404                    std::vector<Gtk::TreeModel::Path> rows =
2405                        m_TreeViewSamples.get_selection()->get_selected_rows();
2406                    if (rows.empty()) return;
2407                    m_TreeViewSamples.scroll_to_row(rows[0]);
2408                    return;
2409                }
2410            }
2411        }
2412    }
2413    
2414  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2415      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2416            // by default if Ctrl keys is pressed down, then a mouse right-click
2417            // does not select the respective row, so we must assure this
2418            // programmatically ...
2419            /*{
2420                Gtk::TreeModel::Path path;
2421                Gtk::TreeViewColumn* pColumn = NULL;
2422                int cellX, cellY;
2423                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2424                    (int)button->x, (int)button->y,
2425                    path, pColumn, cellX, cellY
2426                );
2427                if (bSuccess) {
2428                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2429                        printf("not selected !!!\n");
2430                        m_TreeViewSamples.get_selection()->select(path);
2431                    }
2432                }
2433            }*/
2434    
2435          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2436              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2437          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2438          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2439          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2440          bool group_selected  = false;          const int n = rows.size();
2441          bool sample_selected = false;          int nGroups  = 0;
2442          if (it) {          int nSamples = 0;
2443            for (int r = 0; r < n; ++r) {
2444                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2445                if (!it) continue;
2446              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2447              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2448              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2449          }          }
2450    
2451          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2452              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2453          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2454              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2455          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2456              set_sensitive(file);              set_sensitive(file);
2457            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2458                set_sensitive(nSamples == 1);
2459          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2460              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2461          // show sample popup          // show sample popup
2462          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2463    
2464            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2465                set_sensitive(n == 1);
2466            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2467                set_sensitive(n);
2468            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2469                set_sensitive(file);
2470            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2471                set_sensitive(nSamples == 1);
2472            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2473                set_sensitive(n);
2474      }      }
2475  }  }
2476    
2477    void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2478        if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2479            Gtk::Menu* script_popup =
2480                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2481            // update enabled/disabled state of sample popup items
2482            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2483            Gtk::TreeModel::iterator it = sel->get_selected();
2484            bool group_selected  = false;
2485            bool script_selected = false;
2486            if (it) {
2487                Gtk::TreeModel::Row row = *it;
2488                group_selected  = row[m_ScriptsModel.m_col_group];
2489                script_selected = row[m_ScriptsModel.m_col_script];
2490            }
2491            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2492                set_sensitive(group_selected || script_selected);
2493            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2494                set_sensitive(file);
2495            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2496                set_sensitive(script_selected);    
2497            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2498                set_sensitive(group_selected || script_selected);
2499            // show sample popup
2500            script_popup->popup(button->button, button->time);
2501    
2502            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2503                set_sensitive(group_selected || script_selected);
2504            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2505                set_sensitive(file);
2506            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2507                set_sensitive(script_selected);    
2508            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2509                set_sensitive(group_selected || script_selected);
2510        }
2511    }
2512    
2513  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2514      const Glib::ustring& name, int position) {      const Glib::ustring& name, int position) {
# Line 1546  void MainWindow::add_instrument(gig::Ins Line 2549  void MainWindow::add_instrument(gig::Ins
2549      instrument_name_connection.block();      instrument_name_connection.block();
2550      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2551      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2552        rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2553      rowInstr[m_Columns.m_col_name] = name;      rowInstr[m_Columns.m_col_name] = name;
2554      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2555      instrument_name_connection.unblock();      instrument_name_connection.unblock();
# Line 1574  void MainWindow::on_action_duplicate_ins Line 2578  void MainWindow::on_action_duplicate_ins
2578      // retrieve the currently selected instrument      // retrieve the currently selected instrument
2579      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
2580      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2581      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2582      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
2583      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2584      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
2585      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
2586                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2587      // duplicate the orginal instrument              if (instrOrig) {
2588      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
2589      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2590          instrOrig->pInfo->Name +                  instrNew->pInfo->Name =
2591          gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");                      instrOrig->pInfo->Name +
2592                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2593    
2594      add_instrument(instrNew);                  add_instrument(instrNew);
2595                }
2596            }
2597        }
2598  }  }
2599    
2600  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1603  void MainWindow::on_action_remove_instru Line 2611  void MainWindow::on_action_remove_instru
2611      }      }
2612    
2613      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2614      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2615      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2616            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2617            if (!it) continue;
2618          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2619          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2620          try {          try {
# Line 1619  void MainWindow::on_action_remove_instru Line 2629  void MainWindow::on_action_remove_instru
2629    
2630              // remove row from instruments tree view              // remove row from instruments tree view
2631              m_refTreeModel->erase(it);              m_refTreeModel->erase(it);
2632                // update "Nr" column of all instrument rows
2633                {
2634                    int index = 0;
2635                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2636                         it != m_refTreeModel->children().end(); ++it, ++index)
2637                    {
2638                        Gtk::TreeModel::Row row = *it;
2639                        row[m_Columns.m_col_nr] = index;
2640                    }
2641                }
2642    
2643  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2644              // select another instrument (in gtk3 this is done              // select another instrument (in gtk3 this is done
# Line 1653  void MainWindow::on_action_sample_proper Line 2673  void MainWindow::on_action_sample_proper
2673      msg.run();      msg.run();
2674  }  }
2675    
2676    void MainWindow::on_action_add_script_group() {
2677        static int __script_indexer = 0;
2678        if (!file) return;
2679        gig::ScriptGroup* group = file->AddScriptGroup();
2680        group->Name = gig_from_utf8(_("Unnamed Group"));
2681        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2682        __script_indexer++;
2683        // update sample tree view
2684        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2685        Gtk::TreeModel::Row rowGroup = *iterGroup;
2686        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2687        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2688        rowGroup[m_ScriptsModel.m_col_group] = group;
2689        file_changed();
2690    }
2691    
2692    void MainWindow::on_action_add_script() {
2693        if (!file) return;
2694        // get selected group
2695        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2696        Gtk::TreeModel::iterator it = sel->get_selected();
2697        if (!it) return;
2698        Gtk::TreeModel::Row row = *it;
2699        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2700        if (!group) { // not a group, but a script is selected (probably)
2701            gig::Script* script = row[m_ScriptsModel.m_col_script];
2702            if (!script) return;
2703            it = row.parent(); // resolve parent (that is the script's group)
2704            if (!it) return;
2705            row = *it;
2706            group = row[m_ScriptsModel.m_col_group];
2707            if (!group) return;
2708        }
2709    
2710        // add a new script to the .gig file
2711        gig::Script* script = group->AddScript();    
2712        Glib::ustring name = _("Unnamed Script");
2713        script->Name = gig_from_utf8(name);
2714    
2715        // add script to the tree view
2716        Gtk::TreeModel::iterator iterScript =
2717            m_refScriptsTreeModel->append(row.children());
2718        Gtk::TreeModel::Row rowScript = *iterScript;
2719        rowScript[m_ScriptsModel.m_col_name] = name;
2720        rowScript[m_ScriptsModel.m_col_script] = script;
2721        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2722    
2723        // unfold group of new script item in treeview
2724        Gtk::TreeModel::Path path(iterScript);
2725        m_TreeViewScripts.expand_to_path(path);
2726    }
2727    
2728    void MainWindow::on_action_edit_script() {
2729        if (!file) return;
2730        // get selected script
2731        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2732        Gtk::TreeModel::iterator it = sel->get_selected();
2733        if (!it) return;
2734        Gtk::TreeModel::Row row = *it;
2735        gig::Script* script = row[m_ScriptsModel.m_col_script];
2736        if (!script) return;
2737    
2738        ScriptEditor* editor = new ScriptEditor;
2739        editor->signal_script_to_be_changed.connect(
2740            signal_script_to_be_changed.make_slot()
2741        );
2742        editor->signal_script_changed.connect(
2743            signal_script_changed.make_slot()
2744        );
2745        editor->setScript(script);
2746        //editor->reparent(*this);
2747        editor->show();
2748    }
2749    
2750    void MainWindow::on_action_remove_script() {
2751        if (!file) return;
2752        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2753        Gtk::TreeModel::iterator it = sel->get_selected();
2754        if (it) {
2755            Gtk::TreeModel::Row row = *it;
2756            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2757            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2758            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2759            try {
2760                // remove script group or script from the gig file
2761                if (group) {
2762                    // notify everybody that we're going to remove these samples
2763    //TODO:         scripts_to_be_removed_signal.emit(members);
2764                    // delete the group in the .gig file including the
2765                    // samples that belong to the group
2766                    file->DeleteScriptGroup(group);
2767                    // notify that we're done with removal
2768    //TODO:         scripts_removed_signal.emit();
2769                    file_changed();
2770                } else if (script) {
2771                    // notify everybody that we're going to remove this sample
2772    //TODO:         std::list<gig::Script*> lscripts;
2773    //TODO:         lscripts.push_back(script);
2774    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2775                    // remove sample from the .gig file
2776                    script->GetGroup()->DeleteScript(script);
2777                    // notify that we're done with removal
2778    //TODO:         scripts_removed_signal.emit();
2779                    dimreg_changed();
2780                    file_changed();
2781                }
2782                // remove respective row(s) from samples tree view
2783                m_refScriptsTreeModel->erase(it);
2784            } catch (RIFF::Exception e) {
2785                // pretend we're done with removal (i.e. to avoid dead locks)
2786    //TODO:     scripts_removed_signal.emit();
2787                // show error message
2788                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2789                msg.run();
2790            }
2791        }
2792    }
2793    
2794  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2795      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2796      if (!file) return;      if (!file) return;
# Line 1669  void MainWindow::on_action_add_group() { Line 2807  void MainWindow::on_action_add_group() {
2807      file_changed();      file_changed();
2808  }  }
2809    
2810    void MainWindow::on_action_replace_sample() {
2811        add_or_replace_sample(true);
2812    }
2813    
2814  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2815        add_or_replace_sample(false);
2816    }
2817    
2818    void MainWindow::add_or_replace_sample(bool replace) {
2819      if (!file) return;      if (!file) return;
2820      // get selected group  
2821        // get selected group (and probably selected sample)
2822      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2823      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2824        if (rows.empty()) return;
2825        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2826      if (!it) return;      if (!it) return;
2827      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2828        gig::Sample* sample = NULL;
2829      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2830      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2831          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2832          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2833          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2834          if (!it) return;          if (!it) return;
2835          row = *it;          if (!replace) row = *it;
2836          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2837          if (!group) return;          if (!group) return;
2838      }      }
2839        if (replace && !sample) return;
2840    
2841      // show 'browse for file' dialog      // show 'browse for file' dialog
2842      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2843      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2844      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2845      dialog.set_select_multiple(true);      dialog.set_select_multiple(!replace); // allow multi audio file selection only when adding new samples, does not make sense when replacing a specific sample
2846    
2847      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
2848  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
# Line 1761  void MainWindow::on_action_add_sample() Line 2913  void MainWindow::on_action_add_sample()
2913                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2914                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2915                  }                  }
2916                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2917                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2918                  // file name without path                  // file name without path
2919                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2920                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1813  void MainWindow::on_action_add_sample() Line 2965  void MainWindow::on_action_add_sample()
2965                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2966                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2967                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2968                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2969                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2970                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2971                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2972                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2973                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2974                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2975                  // add sample to the tree view                  // add sample to the tree view
2976                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2977                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2978                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2979                  rowSample[m_SamplesModel.m_col_name] =                      Gtk::TreeModel::iterator iterSample =
2980                      gig_to_utf8(sample->pInfo->Name);                          m_refSamplesTreeModel->append(row.children());
2981                  rowSample[m_SamplesModel.m_col_sample] = sample;                      Gtk::TreeModel::Row rowSample = *iterSample;
2982                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      rowSample[m_SamplesModel.m_col_name] =
2983                            gig_to_utf8(sample->pInfo->Name);
2984                        rowSample[m_SamplesModel.m_col_sample] = sample;
2985                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2986                    }
2987                  // close sound file                  // close sound file
2988                  sf_close(hFile);                  sf_close(hFile);
2989                  file_changed();                  file_changed();
# Line 1838  void MainWindow::on_action_add_sample() Line 2994  void MainWindow::on_action_add_sample()
2994          }          }
2995          // 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
2996          if (!error_files.empty()) {          if (!error_files.empty()) {
2997              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
2998                    (replace
2999                        ? _("Failed to replace sample with:\n")
3000                        : _("Could not add the following sample(s):\n"))
3001                    + error_files;
3002              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3003              msg.run();              msg.run();
3004          }          }
# Line 1881  void MainWindow::on_action_replace_all_s Line 3041  void MainWindow::on_action_replace_all_s
3041      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
3042      description.show();      description.show();
3043      entryArea.show_all();      entryArea.show_all();
3044      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3045      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
3046      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
3047      if (current_sample_dir != "") {      if (current_sample_dir != "") {
# Line 1905  void MainWindow::on_action_replace_all_s Line 3065  void MainWindow::on_action_replace_all_s
3065              try              try
3066              {              {
3067                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
3068                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
3069                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
3070                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
3071                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
3072                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
3073                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
3074                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
3075                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
3076                          break;                          break;
3077                      default:                      default:
3078                          sf_close(hFile);                          sf_close(hFile);
# Line 1925  void MainWindow::on_action_replace_all_s Line 3081  void MainWindow::on_action_replace_all_s
3081                  SampleImportItem sched_item;                  SampleImportItem sched_item;
3082                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
3083                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
3084                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
3085                  sf_close(hFile);                  sf_close(hFile);
3086                  file_changed();                  file_changed();
3087              }              }
# Line 1949  void MainWindow::on_action_replace_all_s Line 3105  void MainWindow::on_action_replace_all_s
3105  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
3106      if (!file) return;      if (!file) return;
3107      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3108      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3109      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3110            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3111            if (!it) continue;
3112          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3113          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
3114          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1975  void MainWindow::on_action_remove_sample Line 3133  void MainWindow::on_action_remove_sample
3133                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
3134                  // them from the import queue                  // them from the import queue
3135                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
3136                       member != members.end(); ++member) {                       member != members.end(); ++member)
3137                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
3138                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
3139                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
3140                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
3141                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
3142                      }                      }
3143                  }                  }
3144                  file_changed();                  file_changed();
# Line 1998  void MainWindow::on_action_remove_sample Line 3153  void MainWindow::on_action_remove_sample
3153                  samples_removed_signal.emit();                  samples_removed_signal.emit();
3154                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
3155                  // the import queue                  // the import queue
3156                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
3157                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
3158                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
3159                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
3160                  }                  }
3161                  dimreg_changed();                  dimreg_changed();
3162                  file_changed();                  file_changed();
# Line 2022  void MainWindow::on_action_remove_sample Line 3173  void MainWindow::on_action_remove_sample
3173      }      }
3174  }  }
3175    
3176    void MainWindow::on_action_remove_unused_samples() {
3177        if (!file) return;
3178    
3179        // collect all samples that are not referenced by any instrument
3180        std::list<gig::Sample*> lsamples;
3181        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3182            gig::Sample* sample = file->GetSample(iSample);
3183            bool isUsed = false;
3184            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3185                                  instrument = file->GetNextInstrument())
3186            {
3187                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3188                                  rgn = instrument->GetNextRegion())
3189                {
3190                    for (int i = 0; i < 256; ++i) {
3191                        if (!rgn->pDimensionRegions[i]) continue;
3192                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3193                        isUsed = true;
3194                        goto endOfRefSearch;
3195                    }
3196                }
3197            }
3198            endOfRefSearch:
3199            if (!isUsed) lsamples.push_back(sample);
3200        }
3201    
3202        if (lsamples.empty()) return;
3203    
3204        // notify everybody that we're going to remove these samples
3205        samples_to_be_removed_signal.emit(lsamples);
3206    
3207        // remove collected samples
3208        try {
3209            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3210                 itSample != lsamples.end(); ++itSample)
3211            {
3212                gig::Sample* sample = *itSample;
3213                // remove sample from the .gig file
3214                file->DeleteSample(sample);
3215                // if sample was just previously added, remove it from the import queue
3216                if (m_SampleImportQueue.count(sample)) {
3217                    printf("Removing previously added sample '%s'\n",
3218                           m_SampleImportQueue[sample].sample_path.c_str());
3219                    m_SampleImportQueue.erase(sample);
3220                }
3221            }
3222        } catch (RIFF::Exception e) {
3223            // show error message
3224            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3225            msg.run();
3226        }
3227    
3228        // notify everybody that we're done with removal
3229        samples_removed_signal.emit();
3230    
3231        dimreg_changed();
3232        file_changed();
3233        __refreshEntireGUI();
3234    }
3235    
3236    // see comment on on_sample_treeview_drag_begin()
3237    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3238    {
3239        first_call_to_drag_data_get = true;
3240    }
3241    
3242    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3243                                                       Gtk::SelectionData& selection_data, guint, guint)
3244    {
3245        if (!first_call_to_drag_data_get) return;
3246        first_call_to_drag_data_get = false;
3247    
3248        // get selected script
3249        gig::Script* script = NULL;
3250        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3251        Gtk::TreeModel::iterator it = sel->get_selected();
3252        if (it) {
3253            Gtk::TreeModel::Row row = *it;
3254            script = row[m_ScriptsModel.m_col_script];
3255        }
3256        // pass the gig::Script as pointer
3257        selection_data.set(selection_data.get_target(), 0/*unused*/,
3258                           (const guchar*)&script,
3259                           sizeof(script)/*length of data in bytes*/);
3260    }
3261    
3262    // see comment on on_sample_treeview_drag_begin()
3263    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3264    {
3265        first_call_to_drag_data_get = true;
3266    }
3267    
3268    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3269                                                           Gtk::SelectionData& selection_data, guint, guint)
3270    {
3271        if (!first_call_to_drag_data_get) return;
3272        first_call_to_drag_data_get = false;
3273    
3274        // get selected source instrument
3275        gig::Instrument* src = NULL;
3276        {
3277            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3278            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3279            if (!rows.empty()) {
3280                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3281                if (it) {
3282                    Gtk::TreeModel::Row row = *it;
3283                    src = row[m_Columns.m_col_instr];
3284                }
3285            }
3286        }
3287        if (!src) return;
3288    
3289        // pass the source gig::Instrument as pointer
3290        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3291                           sizeof(src)/*length of data in bytes*/);
3292    }
3293    
3294    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3295        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3296        const Gtk::SelectionData& selection_data, guint, guint time)
3297    {
3298        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3299        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3300            return;
3301    
3302        gig::Instrument* dst = NULL;
3303        {
3304            Gtk::TreeModel::Path path;
3305            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3306            if (!found) return;
3307    
3308            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3309            if (!iter) return;
3310            Gtk::TreeModel::Row row = *iter;
3311            dst = row[m_Columns.m_col_instr];
3312        }
3313        if (!dst) return;
3314    
3315        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3316        src->MoveTo(dst);
3317        __refreshEntireGUI();
3318        select_instrument(src);
3319    }
3320    
3321  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3322  // drag'n'drop (at least when target is an Entry). This work-around  // drag'n'drop (at least when target is an Entry). This work-around
3323  // makes sure the code in drag_data_get and drop_drag_data_received is  // makes sure the code in drag_data_get and drop_drag_data_received is
# Line 2040  void MainWindow::on_sample_treeview_drag Line 3336  void MainWindow::on_sample_treeview_drag
3336      // get selected sample      // get selected sample
3337      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3338      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3339      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3340      if (it) {      if (!rows.empty()) {
3341          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3342          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3343                Gtk::TreeModel::Row row = *it;
3344                sample = row[m_SamplesModel.m_col_sample];
3345            }
3346      }      }
3347      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3348      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 2150  void MainWindow::sample_name_changed(con Line 3449  void MainWindow::sample_name_changed(con
3449      }      }
3450  }  }
3451    
3452    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3453                                         const Gtk::TreeModel::iterator& iter) {
3454        if (!iter) return;
3455        Gtk::TreeModel::Row row = *iter;
3456        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3457        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3458        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3459        gig::String gigname(gig_from_utf8(name));
3460        if (group) {
3461            if (group->Name != gigname) {
3462                group->Name = gigname;
3463                printf("script group name changed\n");
3464                file_changed();
3465            }
3466        } else if (script) {
3467            if (script->Name != gigname) {
3468                script->Name = gigname;
3469                printf("script name changed\n");
3470                file_changed();
3471            }
3472        }
3473    }
3474    
3475    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3476                                           Gtk::TreeViewColumn* column)
3477    {
3478        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3479        if (!iter) return;
3480        Gtk::TreeModel::Row row = *iter;
3481        gig::Script* script = row[m_ScriptsModel.m_col_script];
3482        if (!script) return;
3483    
3484        ScriptEditor* editor = new ScriptEditor;
3485        editor->signal_script_to_be_changed.connect(
3486            signal_script_to_be_changed.make_slot()
3487        );
3488        editor->signal_script_changed.connect(
3489            signal_script_changed.make_slot()
3490        );
3491        editor->setScript(script);
3492        //editor->reparent(*this);
3493        editor->show();
3494    }
3495    
3496  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3497                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3498      if (!iter) return;      if (!iter) return;
# Line 2196  void MainWindow::on_action_combine_instr Line 3539  void MainWindow::on_action_combine_instr
3539      delete d;      delete d;
3540  }  }
3541    
3542    void MainWindow::on_action_view_references() {
3543        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3544        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3545        if (rows.empty()) return;
3546        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3547        if (!it) return;
3548        Gtk::TreeModel::Row row = *it;
3549        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3550        if (!sample) return;
3551    
3552        ReferencesView* d = new ReferencesView(*this);
3553        d->setSample(sample);
3554        d->dimension_region_selected.connect(
3555            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3556        );
3557        d->show_all();
3558        d->resize(500, 400);
3559        d->run();
3560        delete d;
3561    }
3562    
3563  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3564      struct _Source {      struct _Source {
3565          std::vector<RIFF::File*> riffs;          std::vector<RIFF::File*> riffs;
# Line 2263  void MainWindow::mergeFiles(const std::v Line 3627  void MainWindow::mergeFiles(const std::v
3627          );          );
3628      }      }
3629    
3630      // Note: requires that this file already has a filename !      // Finally save gig file persistently to disk ...
3631      this->file->Save();      //NOTE: requires that this gig file already has a filename !
3632        {
3633            std::cout << "Saving file\n" << std::flush;
3634            file_structure_to_be_changed_signal.emit(this->file);
3635    
3636            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3637                _("Saving") +  Glib::ustring(" '") +
3638                Glib::filename_display_basename(this->filename) + "' ...",
3639                *this
3640            );
3641            progress_dialog->show_all();
3642            saver = new Saver(this->file); //FIXME: memory leak!
3643            saver->signal_progress().connect(
3644                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3645            saver->signal_finished().connect(
3646                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3647            saver->signal_error().connect(
3648                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3649            saver->launch();
3650        }
3651  }  }
3652    
3653  void MainWindow::on_action_merge_files() {  void MainWindow::on_action_merge_files() {
# Line 2282  void MainWindow::on_action_merge_files() Line 3665  void MainWindow::on_action_merge_files()
3665      }      }
3666    
3667      Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));      Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3668      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3669      dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);      dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3670      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3671  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
# Line 2301  void MainWindow::on_action_merge_files() Line 3684  void MainWindow::on_action_merge_files()
3684      // show warning in the file picker dialog      // show warning in the file picker dialog
3685      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
3686      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
3687      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
3688        warningIcon.set_from_icon_name("dialog-warning",
3689                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3690      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3691  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
3692      view::WrapLabel description;      view::WrapLabel description;
# Line 2324  void MainWindow::on_action_merge_files() Line 3709  void MainWindow::on_action_merge_files()
3709      descriptionArea.show_all();      descriptionArea.show_all();
3710    
3711      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
3712          printf("on_action_merge_files self=%x\n", Glib::Threads::Thread::self());          printf("on_action_merge_files self=%p\n",
3713                   static_cast<void*>(Glib::Threads::Thread::self()));
3714          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
3715    
3716          // merge the selected files to the currently open .gig file          // merge the selected files to the currently open .gig file
# Line 2336  void MainWindow::on_action_merge_files() Line 3722  void MainWindow::on_action_merge_files()
3722          }          }
3723    
3724          // update GUI          // update GUI
3725          __refreshEntireGUI();                  __refreshEntireGUI();
3726      }      }
3727  }  }
3728    
# Line 2354  void MainWindow::set_file_is_shared(bool Line 3740  void MainWindow::set_file_is_shared(bool
3740              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3741          );          );
3742      }      }
3743    
3744        {
3745            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3746                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3747            if (item) item->set_sensitive(b);
3748        }
3749    }
3750    
3751    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3752        if (!sample) return;
3753        sample_ref_count[sample] += offset;
3754        const int refcount = sample_ref_count[sample];
3755    
3756        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3757        for (int g = 0; g < model->children().size(); ++g) {
3758            Gtk::TreeModel::Row rowGroup = model->children()[g];
3759            for (int s = 0; s < rowGroup.children().size(); ++s) {
3760                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3761                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3762                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3763                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3764            }
3765        }
3766    }
3767    
3768    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3769        on_sample_ref_count_incremented(oldSample, -1);
3770        on_sample_ref_count_incremented(newSample, +1);
3771    }
3772    
3773    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3774        // just in case a new sample is added later with exactly the same memory
3775        // address, which would lead to incorrect refcount if not deleted here
3776        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3777             it != samples.end(); ++it)
3778        {
3779            sample_ref_count.erase(*it);
3780        }
3781    }
3782    
3783    void MainWindow::show_samples_tab() {
3784        m_TreeViewNotebook.set_current_page(0);
3785    }
3786    
3787    void MainWindow::show_intruments_tab() {
3788        m_TreeViewNotebook.set_current_page(1);
3789    }
3790    
3791    void MainWindow::show_scripts_tab() {
3792        m_TreeViewNotebook.set_current_page(2);
3793    }
3794    
3795    void MainWindow::select_prev_region() {
3796        m_RegionChooser.select_prev_region();
3797    }
3798    
3799    void MainWindow::select_next_region() {
3800        m_RegionChooser.select_next_region();
3801    }
3802    
3803    void MainWindow::select_next_dim_rgn_zone() {
3804        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3805        m_DimRegionChooser.select_next_dimzone();
3806    }
3807    
3808    void MainWindow::select_prev_dim_rgn_zone() {
3809        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3810        m_DimRegionChooser.select_prev_dimzone();
3811    }
3812    
3813    void MainWindow::select_add_next_dim_rgn_zone() {
3814        m_DimRegionChooser.select_next_dimzone(true);
3815    }
3816    
3817    void MainWindow::select_add_prev_dim_rgn_zone() {
3818        m_DimRegionChooser.select_prev_dimzone(true);
3819    }
3820    
3821    void MainWindow::select_prev_dimension() {
3822        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3823        m_DimRegionChooser.select_prev_dimension();
3824    }
3825    
3826    void MainWindow::select_next_dimension() {
3827        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3828        m_DimRegionChooser.select_next_dimension();
3829    }
3830    
3831    #define CLIPBOARD_DIMENSIONREGION_TARGET \
3832        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
3833    
3834    void MainWindow::copy_selected_dimrgn() {
3835        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3836        if (!pDimRgn) {
3837            updateClipboardPasteAvailable();
3838            updateClipboardCopyAvailable();
3839            return;
3840        }
3841    
3842        std::vector<Gtk::TargetEntry> targets;
3843        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
3844    
3845        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3846        clipboard->set(
3847            targets,
3848            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
3849            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
3850        );
3851    
3852        m_serializationArchive.serialize(pDimRgn);
3853    
3854        updateClipboardPasteAvailable();
3855    }
3856    
3857    void MainWindow::paste_copied_dimrgn() {
3858        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3859        clipboard->request_contents(
3860            CLIPBOARD_DIMENSIONREGION_TARGET,
3861            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
3862        );
3863        updateClipboardPasteAvailable();
3864    }
3865    
3866    void MainWindow::adjust_clipboard_content() {
3867        MacroEditor* editor = new MacroEditor();
3868        editor->setMacro(&m_serializationArchive);
3869        editor->show();
3870    }
3871    
3872    void MainWindow::updateClipboardPasteAvailable() {
3873        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3874        clipboard->request_targets(
3875            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
3876        );
3877    }
3878    
3879    void MainWindow::updateClipboardCopyAvailable() {
3880        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
3881        static_cast<Gtk::MenuItem*>(
3882            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
3883        )->set_sensitive(bDimensionRegionCopyIsPossible);
3884    }
3885    
3886    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
3887        updateClipboardPasteAvailable();
3888    }
3889    
3890    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
3891        const std::string target = selection_data.get_target();
3892        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3893            selection_data.set(
3894                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
3895                &m_serializationArchive.rawData()[0],
3896                m_serializationArchive.rawData().size()
3897            );
3898        } else {
3899            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
3900        }
3901    }
3902    
3903    void MainWindow::on_clipboard_clear() {
3904        m_serializationArchive.clear();
3905        updateClipboardPasteAvailable();
3906        updateClipboardCopyAvailable();
3907    }
3908    
3909    //NOTE: Might throw exception !!!
3910    void MainWindow::applyMacro(Serialization::Archive& macro) {
3911        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3912        if (!pDimRgn) return;
3913    
3914        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
3915             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
3916        {
3917            gig::DimensionRegion* pDimRgn = *itDimReg;
3918            dimreg_to_be_changed_signal.emit(pDimRgn);
3919            m_serializationArchive.deserialize(pDimRgn);
3920            dimreg_changed_signal.emit(pDimRgn);
3921        }
3922        //region_changed()
3923        file_changed();
3924        dimreg_changed();
3925    }
3926    
3927    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
3928        const std::string target = selection_data.get_target();
3929        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3930            Glib::ustring errorText;
3931            try {
3932                m_serializationArchive.decode(
3933                    selection_data.get_data(), selection_data.get_length()
3934                );
3935                applyMacro(m_serializationArchive);
3936            } catch (Serialization::Exception e) {
3937                errorText = e.Message;
3938            } catch (...) {
3939                errorText = _("Unknown exception while pasting DimensionRegion");
3940            }
3941            if (!errorText.empty()) {
3942                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
3943                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3944                msg.run();
3945            }
3946        }
3947    }
3948    
3949    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
3950        const bool bDimensionRegionPasteIsPossible =
3951            std::find(targets.begin(), targets.end(),
3952                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
3953    
3954        static_cast<Gtk::MenuItem*>(
3955            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
3956        )->set_sensitive(bDimensionRegionPasteIsPossible);
3957    
3958        static_cast<Gtk::MenuItem*>(
3959            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
3960        )->set_sensitive(bDimensionRegionPasteIsPossible);
3961  }  }
3962    
3963  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {  sigc::signal<void, gig::File*>& MainWindow::signal_file_structure_to_be_changed() {
# Line 2411  sigc::signal<void, int/*key*/, int/*velo Line 4015  sigc::signal<void, int/*key*/, int/*velo
4015  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
4016      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
4017  }  }
4018    
4019    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
4020        return switch_sampler_instrument_signal;
4021    }

Legend:
Removed from v.2579  
changed lines
  Added in v.3157

  ViewVC Help
Powered by ViewVC