/[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 2566 by schoenebeck, Tue May 20 14:35:36 2014 UTC revision 3258 by schoenebeck, Tue May 30 20:17:12 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 31  Line 39 
39  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
40  #include <gtkmm/main.h>  #include <gtkmm/main.h>
41  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
42    #include <gtkmm/accelmap.h>
43  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
44  #include "wrapLabel.hh"  #include "wrapLabel.hh"
45  #endif  #endif
# Line 45  Line 54 
54  #include "mainwindow.h"  #include "mainwindow.h"
55  #include "Settings.h"  #include "Settings.h"
56  #include "CombineInstrumentsDialog.h"  #include "CombineInstrumentsDialog.h"
57    #include "scripteditor.h"
58    #include "scriptslots.h"
59    #include "ReferencesView.h"
60  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
61  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
62    #include "gfx/builtinpix.h"
63    #include "MacroEditor.h"
64    #include "MacrosSetup.h"
65    #if defined(__APPLE__)
66    # include "MacHelper.h"
67    #endif
68    
69  MainWindow::MainWindow() :  MainWindow::MainWindow() :
70        m_DimRegionChooser(*this),
71      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
72      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
73      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
74      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
75        labelLegend(_("Legend:")),
76        labelNoSample(_(" No Sample")),
77        labelMissingSample(_(" Missing some Sample(s)")),
78        labelLooped(_(" Looped")),
79        labelSomeLoops(_(" Some Loop(s)"))
80  {  {
81        loadBuiltInPix();
82    
83  //    set_border_width(5);  //    set_border_width(5);
 //    set_default_size(400, 200);  
84    
85        if (!Settings::singleton()->autoRestoreWindowDimension) {
86            set_default_size(800, 600);
87            set_position(Gtk::WIN_POS_CENTER);
88        }
89    
90      add(m_VBox);      add(m_VBox);
91    
# Line 78  MainWindow::MainWindow() : Line 106  MainWindow::MainWindow() :
106      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
107      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
108    
109        m_ScrolledWindowScripts.add(m_TreeViewScripts);
110        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
111    
112    
113      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
114    
# Line 89  MainWindow::MainWindow() : Line 120  MainWindow::MainWindow() :
120      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
121      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
122      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
123        {
124            legend_hbox.add(labelLegend);
125    
126            imageNoSample.set(redDot);
127            imageNoSample.set_alignment(Gtk::ALIGN_END);
128            labelNoSample.set_alignment(Gtk::ALIGN_START);
129            legend_hbox.add(imageNoSample);
130            legend_hbox.add(labelNoSample);
131    
132            imageMissingSample.set(yellowDot);
133            imageMissingSample.set_alignment(Gtk::ALIGN_END);
134            labelMissingSample.set_alignment(Gtk::ALIGN_START);
135            legend_hbox.add(imageMissingSample);
136            legend_hbox.add(labelMissingSample);
137    
138            imageLooped.set(blackLoop);
139            imageLooped.set_alignment(Gtk::ALIGN_END);
140            labelLooped.set_alignment(Gtk::ALIGN_START);
141            legend_hbox.add(imageLooped);
142            legend_hbox.add(labelLooped);
143    
144            imageSomeLoops.set(grayLoop);
145            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
146            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
147            legend_hbox.add(imageSomeLoops);
148            legend_hbox.add(labelSomeLoops);
149    
150            legend_hbox.show_all_children();
151        }
152        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
153      m_HPaned.add2(dimreg_vbox);      m_HPaned.add2(dimreg_vbox);
154    
155      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 159  MainWindow::MainWindow() :
159    
160      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
161      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
162        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
163    
164      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
165    
# Line 130  MainWindow::MainWindow() : Line 191  MainWindow::MainWindow() :
191                       sigc::mem_fun(                       sigc::mem_fun(
192                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
193      actionGroup->add(Gtk::Action::create("MidiRules",      actionGroup->add(Gtk::Action::create("MidiRules",
194                                           _("_Midi Rules")),                                           _("_Midi Rules...")),
195                       sigc::mem_fun(                       sigc::mem_fun(
196                           *this, &MainWindow::show_midi_rules));                           *this, &MainWindow::show_midi_rules));
197        actionGroup->add(Gtk::Action::create("ScriptSlots",
198                                             _("_Script Slots...")),
199                         sigc::mem_fun(
200                             *this, &MainWindow::show_script_slots));
201      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
202                       sigc::mem_fun(                       sigc::mem_fun(
203                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
204      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
205            Gtk::Action::create("MenuSample", _("_Sample")),
206            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
207        );
208        actionGroup->add(
209            Gtk::Action::create("MenuInstrument", _("_Instrument")),
210            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
211        );
212        actionGroup->add(
213            Gtk::Action::create("MenuScript", _("Scr_ipt")),
214            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
215        );
216        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
217    
218      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
219    
220        const Gdk::ModifierType primaryModifierKey =
221    #if defined(__APPLE__)
222        Gdk::META_MASK; // Cmd key on Mac
223    #else
224        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
225    #endif
226    
227        actionGroup->add(Gtk::Action::create("CopyDimRgn",
228                                             _("Copy selected dimension region")),
229                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
230                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
231    
232        actionGroup->add(Gtk::Action::create("PasteDimRgn",
233                                             _("Paste dimension region")),
234                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
235                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
236    
237        actionGroup->add(Gtk::Action::create("AdjustClipboard",
238                                             _("Adjust Clipboard Content")),
239                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
240                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
241    
242        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
243                                             _("Select Previous Region")),
244                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
245                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
246    
247        actionGroup->add(Gtk::Action::create("SelectNextRegion",
248                                             _("Select Next Region")),
249                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
250                         sigc::mem_fun(*this, &MainWindow::select_next_region));
251    
252        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
253                                             _("Select Previous Dimension Region Zone")),
254                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
255                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
256    
257        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
258                                             _("Select Next Dimension Region Zone")),
259                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
260                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
261    
262        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
263                                             _("Select Previous Dimension")),
264                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
265                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
266    
267        actionGroup->add(Gtk::Action::create("SelectNextDimension",
268                                             _("Select Next Dimension")),
269                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
270                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
271    
272        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
273                                             _("Add Previous Dimension Region Zone to Selection")),
274                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
275                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
276    
277        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
278                                             _("Add Next Dimension Region Zone to Selection")),
279                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
280                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
281    
282      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
283          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
284      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 157  MainWindow::MainWindow() : Line 295  MainWindow::MainWindow() :
295      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
296    
297    
298      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));      actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
299    
300    
301        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
302      toggle_action =      toggle_action =
303          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
304      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 165  MainWindow::MainWindow() : Line 306  MainWindow::MainWindow() :
306                       sigc::mem_fun(                       sigc::mem_fun(
307                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
308    
309        toggle_action =
310            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
311        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
312        actionGroup->add(toggle_action,
313                         sigc::mem_fun(
314                             *this, &MainWindow::on_auto_restore_win_dim));
315    
316        toggle_action =
317            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
318        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
319        actionGroup->add(toggle_action,
320                         sigc::mem_fun(
321                             *this, &MainWindow::on_save_with_temporary_file));
322    
323        actionGroup->add(
324            Gtk::Action::create("RefreshAll", _("_Refresh All")),
325            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
326        );                
327    
328      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
329      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
330                                           action->property_label()));                                           action->property_label()));
# Line 195  MainWindow::MainWindow() : Line 355  MainWindow::MainWindow() :
355          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
356      );      );
357    
358        toggle_action =
359            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
360        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
361        actionGroup->add(
362            toggle_action,
363            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
364        );
365    
366        toggle_action =
367            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
368        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
369        actionGroup->add(
370            toggle_action,
371            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
372        );
373    
374    
375      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
376    
# Line 227  MainWindow::MainWindow() : Line 403  MainWindow::MainWindow() :
403          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
404      );      );
405      actionGroup->add(      actionGroup->add(
406            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
407            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
408        );
409        actionGroup->add(
410            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
411            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
412        );
413        actionGroup->add(
414            Gtk::Action::create("ReplaceSample",
415                                _("Replace Sample...")),
416            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
417        );
418        actionGroup->add(
419          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
420                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
421          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)
422      );      );
423        
424        // script right-click popup actions
425        actionGroup->add(
426            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
427            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
428        );
429        actionGroup->add(
430            Gtk::Action::create("AddScript", _("Add _Script")),
431            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
432        );
433        actionGroup->add(
434            Gtk::Action::create("EditScript", _("_Edit Script...")),
435            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
436        );
437        actionGroup->add(
438            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
439            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
440        );
441    
442      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
443      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 251  MainWindow::MainWindow() : Line 458  MainWindow::MainWindow() :
458          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
459          "    </menu>"          "    </menu>"
460          "    <menu action='MenuEdit'>"          "    <menu action='MenuEdit'>"
461            "      <menuitem action='CopyDimRgn'/>"
462            "      <menuitem action='AdjustClipboard'/>"
463            "      <menuitem action='PasteDimRgn'/>"
464            "      <separator/>"
465            "      <menuitem action='SelectPrevRegion'/>"
466            "      <menuitem action='SelectNextRegion'/>"
467            "      <separator/>"
468            "      <menuitem action='SelectPrevDimension'/>"
469            "      <menuitem action='SelectNextDimension'/>"
470            "      <menuitem action='SelectPrevDimRgnZone'/>"
471            "      <menuitem action='SelectNextDimRgnZone'/>"
472            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
473            "      <menuitem action='SelectAddNextDimRgnZone'/>"
474            "      <separator/>"
475          "      <menuitem action='CopySampleUnity'/>"          "      <menuitem action='CopySampleUnity'/>"
476          "      <menuitem action='CopySampleTune'/>"          "      <menuitem action='CopySampleTune'/>"
477          "      <menuitem action='CopySampleLoop'/>"          "      <menuitem action='CopySampleLoop'/>"
478          "    </menu>"          "    </menu>"
479            "    <menu action='MenuMacro'>"
480            "    </menu>"
481            "    <menu action='MenuSample'>"
482            "      <menuitem action='SampleProperties'/>"
483            "      <menuitem action='AddGroup'/>"
484            "      <menuitem action='AddSample'/>"
485            "      <menuitem action='ShowSampleRefs'/>"
486            "      <menuitem action='ReplaceSample' />"
487            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
488            "      <separator/>"
489            "      <menuitem action='RemoveSample'/>"
490            "      <menuitem action='RemoveUnusedSamples'/>"
491            "    </menu>"
492          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
493            "      <menu action='AllInstruments'>"
494            "      </menu>"
495            "      <separator/>"
496            "      <menuitem action='InstrProperties'/>"
497            "      <menuitem action='MidiRules'/>"
498            "      <menuitem action='ScriptSlots'/>"
499            "      <menuitem action='AddInstrument'/>"
500            "      <menuitem action='DupInstrument'/>"
501            "      <separator/>"
502            "      <menuitem action='RemoveInstrument'/>"
503            "    </menu>"
504            "    <menu action='MenuScript'>"
505            "      <menuitem action='AddScriptGroup'/>"
506            "      <menuitem action='AddScript'/>"
507            "      <menuitem action='EditScript'/>"
508            "      <separator/>"
509            "      <menuitem action='RemoveScript'/>"
510          "    </menu>"          "    </menu>"
511          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
512          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
513            "      <menuitem action='AutoRestoreWinDim'/>"
514            "      <separator/>"
515            "      <menuitem action='RefreshAll'/>"
516          "    </menu>"          "    </menu>"
517          "    <menu action='MenuTools'>"          "    <menu action='MenuTools'>"
518          "      <menuitem action='CombineInstruments'/>"          "      <menuitem action='CombineInstruments'/>"
# Line 266  MainWindow::MainWindow() : Line 520  MainWindow::MainWindow() :
520          "    </menu>"          "    </menu>"
521          "    <menu action='MenuSettings'>"          "    <menu action='MenuSettings'>"
522          "      <menuitem action='WarnUserOnExtensions'/>"          "      <menuitem action='WarnUserOnExtensions'/>"
523            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
524            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
525            "      <menuitem action='SaveWithTemporaryFile'/>"
526          "    </menu>"          "    </menu>"
527          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
528          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 274  MainWindow::MainWindow() : Line 531  MainWindow::MainWindow() :
531          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
532          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
533          "    <menuitem action='MidiRules'/>"          "    <menuitem action='MidiRules'/>"
534            "    <menuitem action='ScriptSlots'/>"
535          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
536          "    <menuitem action='DupInstrument'/>"          "    <menuitem action='DupInstrument'/>"
537          "    <separator/>"          "    <separator/>"
# Line 283  MainWindow::MainWindow() : Line 541  MainWindow::MainWindow() :
541          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
542          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
543          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
544            "    <menuitem action='ShowSampleRefs'/>"
545            "    <menuitem action='ReplaceSample' />"
546          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
547          "    <separator/>"          "    <separator/>"
548          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
549            "    <menuitem action='RemoveUnusedSamples'/>"
550            "  </popup>"
551            "  <popup name='ScriptPopupMenu'>"
552            "    <menuitem action='AddScriptGroup'/>"
553            "    <menuitem action='AddScript'/>"
554            "    <menuitem action='EditScript'/>"
555            "    <separator/>"
556            "    <menuitem action='RemoveScript'/>"
557          "  </popup>"          "  </popup>"
558          "</ui>";          "</ui>";
559      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
# Line 318  MainWindow::MainWindow() : Line 586  MainWindow::MainWindow() :
586      }      }
587      {      {
588          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
589                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
590            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)."));
591        }
592        {
593            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
594                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
595            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."));
596        }
597        {
598            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
599                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
600            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
601            // copy tooltip to popup menu
602            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
603                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
604            item2->set_tooltip_text(item->get_tooltip_text());
605        }
606        {
607            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
608                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
609            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
610        }
611        {
612            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
613                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
614            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
615        }
616        {
617            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
618              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
619          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."));
620      }      }
# Line 329  MainWindow::MainWindow() : Line 626  MainWindow::MainWindow() :
626    
627    
628      instrument_menu = static_cast<Gtk::MenuItem*>(      instrument_menu = static_cast<Gtk::MenuItem*>(
629          uiManager->get_widget("/MenuBar/MenuInstrument"))->get_submenu();          uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
630    
631      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
632      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
# Line 355  MainWindow::MainWindow() : Line 652  MainWindow::MainWindow() :
652      // Create the Tree model:      // Create the Tree model:
653      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
654      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
655      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules."));      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
656        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
657      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
658          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
659      );      );
660    
661      // Add the TreeView's view columns:      // Add the TreeView's view columns:
662      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
663      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
664        m_TreeView.append_column(_("Scripts"), m_Columns.m_col_scripts);
665        m_TreeView.set_headers_visible(true);
666        
667        // establish drag&drop within the instrument tree view, allowing to reorder
668        // the sequence of instruments within the gig file
669        {
670            std::vector<Gtk::TargetEntry> drag_target_instrument;
671            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
672            m_TreeView.drag_source_set(drag_target_instrument);
673            m_TreeView.drag_dest_set(drag_target_instrument);
674            m_TreeView.signal_drag_begin().connect(
675                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
676            );
677            m_TreeView.signal_drag_data_get().connect(
678                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
679            );
680            m_TreeView.signal_drag_data_received().connect(
681                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
682            );
683        }
684    
685      // create samples treeview (including its data model)      // create samples treeview (including its data model)
686      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
687      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
688        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
689      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."));
690      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
691      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
692      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
693        {
694            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
695            Gtk::CellRendererText* cellrenderer =
696                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
697            column->add_attribute(
698                cellrenderer->property_foreground(), m_SamplesModel.m_color
699            );
700        }
701        {
702            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
703            Gtk::CellRendererText* cellrenderer =
704                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
705            column->add_attribute(
706                cellrenderer->property_foreground(), m_SamplesModel.m_color
707            );
708        }
709        m_TreeViewSamples.set_headers_visible(true);
710      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
711          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
712      );      );
# Line 378  MainWindow::MainWindow() : Line 714  MainWindow::MainWindow() :
714          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
715      );      );
716    
717        // create scripts treeview (including its data model)
718        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
719        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
720        m_TreeViewScripts.set_tooltip_text(_(
721            "Use CTRL + double click for editing a script."
722            "\n\n"
723            "Note: instrument scripts are a LinuxSampler extension of the gig "
724            "format. This feature will not work with the GigaStudio software!"
725        ));
726        // m_TreeViewScripts.set_reorderable();
727        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
728        m_TreeViewScripts.set_headers_visible(false);
729        m_TreeViewScripts.signal_button_press_event().connect_notify(
730            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
731        );
732        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
733        m_TreeViewScripts.signal_row_activated().connect(
734            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
735        );
736        m_refScriptsTreeModel->signal_row_changed().connect(
737            sigc::mem_fun(*this, &MainWindow::script_name_changed)
738        );
739    
740        // establish drag&drop between scripts tree view and ScriptSlots window
741        std::vector<Gtk::TargetEntry> drag_target_gig_script;
742        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
743        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
744        m_TreeViewScripts.signal_drag_begin().connect(
745            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
746        );
747        m_TreeViewScripts.signal_drag_data_get().connect(
748            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
749        );
750    
751      // 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
752      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
753      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 766  MainWindow::MainWindow() :
766          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
767      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
768          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
769        m_RegionChooser.signal_instrument_changed().connect(
770            sigc::mem_fun(*this, &MainWindow::region_changed));
771      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
772          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
773      instrumentProps.signal_changed().connect(      instrumentProps.signal_changed().connect(
# Line 411  MainWindow::MainWindow() : Line 783  MainWindow::MainWindow() :
783          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
784      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
785          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
786        sample_ref_changed_signal.connect(
787            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
788        );
789        samples_to_be_removed_signal.connect(
790            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
791        );
792    
793        dimreg_edit.signal_select_sample().connect(
794            sigc::mem_fun(*this, &MainWindow::select_sample)
795        );
796    
797      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
798          sigc::hide(          sigc::hide(
# Line 455  MainWindow::MainWindow() : Line 837  MainWindow::MainWindow() :
837    
838      // select 'Instruments' tab by default      // select 'Instruments' tab by default
839      // (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)
840      m_TreeViewNotebook.set_current_page(1);      m_TreeViewNotebook.set_current_page(1);
841    
842        Gtk::Clipboard::get()->signal_owner_change().connect(
843            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
844        );
845        updateClipboardPasteAvailable();
846        updateClipboardCopyAvailable();
847    
848        // setup macros and their keyboard accelerators
849        {
850            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
851                uiManager->get_widget("/MenuBar/MenuMacro")
852            )->get_submenu();
853    
854            const Gdk::ModifierType primaryModifierKey =
855    #if defined(__APPLE__)
856                Gdk::META_MASK; // Cmd key on Mac
857    #else
858                Gdk::CONTROL_MASK; // Ctrl key on all other OSs
859    #endif
860    
861            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
862            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
863            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
864            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
865            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
866            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
867            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
868            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
869            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
870            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
871            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
872            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
873            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
874            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
875    
876            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
877            menuMacro->set_accel_group(accelGroup);
878    
879            updateMacroMenu();
880        }
881    
882        Glib::signal_idle().connect_once(
883            sigc::mem_fun(*this, &MainWindow::bringToFront),
884            200
885        );
886  }  }
887    
888  MainWindow::~MainWindow()  MainWindow::~MainWindow()
889  {  {
890  }  }
891    
892    void MainWindow::bringToFront() {
893        #if defined(__APPLE__)
894        macRaiseAppWindow();
895        #endif
896        raise();
897        present();
898    }
899    
900    void MainWindow::updateMacroMenu() {
901        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
902            uiManager->get_widget("/MenuBar/MenuMacro")
903        )->get_submenu();
904    
905        // remove all entries from "Macro" menu
906        {
907            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
908            for (int i = 0; i < children.size(); ++i) {
909                Gtk::Widget* child = children[i];
910                menuMacro->remove(*child);
911                delete child;
912            }
913        }
914    
915        // (re)load all macros from config file
916        try {
917            Settings::singleton()->loadMacros(m_macros);
918        } catch (Serialization::Exception e) {
919            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
920        } catch (...) {
921            std::cerr << "Unknown exception while loading macros!" << std::endl;
922        }
923    
924        // add all configured macros as menu items to the "Macro" menu
925        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
926            const Serialization::Archive& macro = m_macros[iMacro];
927            std::string name =
928                macro.name().empty() ?
929                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
930            Gtk::MenuItem* item = new Gtk::MenuItem(name);
931            item->signal_activate().connect(
932                sigc::bind(
933                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
934                )
935            );
936            menuMacro->append(*item);
937            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
938            Glib::ustring comment = macro.comment();
939            if (!comment.empty())
940                item->set_tooltip_text(comment);
941        }
942        // if there are no macros configured at all, then show a dummy entry instead
943        if (m_macros.empty()) {
944            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
945            item->set_sensitive(false);
946            menuMacro->append(*item);
947        }
948    
949        // add separator line to menu
950        menuMacro->append(*new Gtk::SeparatorMenuItem);
951    
952        {
953            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
954            item->signal_activate().connect(
955                sigc::mem_fun(*this, &MainWindow::setupMacros)
956            );
957            menuMacro->append(*item);
958            item->set_accel_path("<Macros>/SetupMacros");
959        }
960    
961        menuMacro->show_all_children();
962    }
963    
964    void MainWindow::onMacroSelected(int iMacro) {
965        printf("onMacroSelected(%d)\n", iMacro);
966        if (iMacro < 0 || iMacro >= m_macros.size()) return;
967        Glib::ustring errorText;
968        try {
969            applyMacro(m_macros[iMacro]);
970        } catch (Serialization::Exception e) {
971            errorText = e.Message;
972        } catch (...) {
973            errorText = _("Unknown exception while applying macro");
974        }
975        if (!errorText.empty()) {
976            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
977            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
978            msg.run();
979        }
980    }
981    
982    void MainWindow::setupMacros() {
983        MacrosSetup* setup = new MacrosSetup();
984        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
985        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
986        setup->signal_macros_changed().connect(
987            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
988        );
989        setup->show();
990    }
991    
992    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
993        m_macros = macros;
994        Settings::singleton()->saveMacros(m_macros);
995        updateMacroMenu();
996    }
997    
998  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
999  {  {
1000      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 1014  void MainWindow::region_changed()
1014  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1015  {  {
1016      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
1017      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1018          m_TreeView.get_selection()->get_selected();      if (rows.empty()) return NULL;
1019        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
1020      if (it) {      if (it) {
1021          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1022          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 525  void MainWindow::update_dimregs() Line 1059  void MainWindow::update_dimregs()
1059              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1060          }          }
1061      }      }
1062    
1063        m_RegionChooser.setModifyAllRegions(all_regions);
1064        m_DimRegionChooser.setModifyAllRegions(all_regions);
1065        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1066        m_DimRegionChooser.setModifyBothChannels(stereo);
1067    
1068        updateClipboardCopyAvailable();
1069  }  }
1070    
1071  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 536  void MainWindow::dimreg_all_dimregs_togg Line 1077  void MainWindow::dimreg_all_dimregs_togg
1077  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1078  {  {
1079      update_dimregs();      update_dimregs();
1080      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1081  }  }
1082    
1083  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1084  {  {
1085      // select item in instrument menu      // select item in instrument menu
1086      Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1087      if (it) {      if (!rows.empty()) {
1088          Gtk::TreePath path(it);          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1089          int index = path[0];          if (it) {
1090          const std::vector<Gtk::Widget*> children =              Gtk::TreePath path(it);
1091              instrument_menu->get_children();              int index = path[0];
1092          static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();              const std::vector<Gtk::Widget*> children =
1093                    instrument_menu->get_children();
1094                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1095            }
1096      }      }
1097    
1098      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1099    
1100        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1101            switch_sampler_instrument_signal.emit(get_instrument());
1102        }
1103  }  }
1104    
1105  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 1117  void Loader::progress_callback(float fra
1117      progress_dispatcher();      progress_dispatcher();
1118  }  }
1119    
1120    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1121    // make sure stack is 16-byte aligned for SSE instructions
1122    __attribute__((force_align_arg_pointer))
1123    #endif
1124  void Loader::thread_function()  void Loader::thread_function()
1125  {  {
1126      printf("thread_function self=%x\n", Glib::Threads::Thread::self());      printf("thread_function self=%p\n",
1127      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1128      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
1129      gig = new gig::File(riff);      try {
1130      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
1131      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
1132      progress.custom = this;          gig::progress_t progress;
1133            progress.callback = loader_progress_callback;
1134      gig->GetInstrument(0, &progress);          progress.custom = this;
1135      printf("End\n");  
1136      finished_dispatcher();          gig->GetInstrument(0, &progress);
1137            printf("End\n");
1138            finished_dispatcher();
1139        } catch (RIFF::Exception e) {
1140            error_message = e.Message;
1141            error_dispatcher.emit();
1142        } catch (...) {
1143            error_message = _("Unknown exception occurred");
1144            error_dispatcher.emit();
1145        }
1146  }  }
1147    
1148  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
1149      : filename(filename), thread(0)      : filename(filename), gig(0), thread(0), progress(0.f)
1150  {  {
1151  }  }
1152    
# Line 596  void Loader::launch() Line 1157  void Loader::launch()
1157  #else  #else
1158      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
1159  #endif  #endif
1160      printf("launch thread=%x\n", thread);      printf("launch thread=%p\n", static_cast<void*>(thread));
1161  }  }
1162    
1163  float Loader::get_progress()  float Loader::get_progress()
# Line 619  Glib::Dispatcher& Loader::signal_finishe Line 1180  Glib::Dispatcher& Loader::signal_finishe
1180      return finished_dispatcher;      return finished_dispatcher;
1181  }  }
1182    
1183  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
1184    {
1185        return error_dispatcher;
1186    }
1187    
1188    void saver_progress_callback(gig::progress_t* progress)
1189    {
1190        Saver* saver = static_cast<Saver*>(progress->custom);
1191        saver->progress_callback(progress->factor);
1192    }
1193    
1194    void Saver::progress_callback(float fraction)
1195    {
1196        {
1197            Glib::Threads::Mutex::Lock lock(progressMutex);
1198            progress = fraction;
1199        }
1200        progress_dispatcher.emit();
1201    }
1202    
1203    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1204    // make sure stack is 16-byte aligned for SSE instructions
1205    __attribute__((force_align_arg_pointer))
1206    #endif
1207    void Saver::thread_function()
1208    {
1209        printf("thread_function self=%p\n",
1210               static_cast<void*>(Glib::Threads::Thread::self()));
1211        printf("Start %s\n", filename.c_str());
1212        try {
1213            gig::progress_t progress;
1214            progress.callback = saver_progress_callback;
1215            progress.custom = this;
1216    
1217            // if no filename was provided, that means "save", if filename was provided means "save as"
1218            if (filename.empty()) {
1219                if (!Settings::singleton()->saveWithTemporaryFile) {
1220                    // save directly over the existing .gig file
1221                    // (requires less disk space than solution below
1222                    // but may be slower)
1223                    gig->Save(&progress);
1224                } else {
1225                    // save the file as separate temporary file first,
1226                    // then move the saved file over the old file
1227                    // (may result in performance speedup during save)
1228                    gig::String tmpname = filename + ".TMP";
1229                    gig->Save(tmpname, &progress);
1230                    #if defined(WIN32)
1231                    if (!DeleteFile(filename.c_str())) {
1232                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1233                    }
1234                    #else // POSIX ...
1235                    if (unlink(filename.c_str())) {
1236                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
1237                    }
1238                    #endif
1239                    if (rename(tmpname.c_str(), filename.c_str())) {
1240                        #if defined(WIN32)
1241                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1242                        #else
1243                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
1244                        #endif
1245                    }
1246                }
1247            } else {
1248                gig->Save(filename, &progress);
1249            }
1250    
1251            printf("End\n");
1252            finished_dispatcher.emit();
1253        } catch (RIFF::Exception e) {
1254            error_message = e.Message;
1255            error_dispatcher.emit();
1256        } catch (...) {
1257            error_message = _("Unknown exception occurred");
1258            error_dispatcher.emit();
1259        }
1260    }
1261    
1262    Saver::Saver(gig::File* file, Glib::ustring filename)
1263        : gig(file), filename(filename), thread(0), progress(0.f)
1264    {
1265    }
1266    
1267    void Saver::launch()
1268    {
1269    #ifdef OLD_THREADS
1270        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1271    #else
1272        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1273    #endif
1274        printf("launch thread=%p\n", static_cast<void*>(thread));
1275    }
1276    
1277    float Saver::get_progress()
1278    {
1279        float res;
1280        {
1281            Glib::Threads::Mutex::Lock lock(progressMutex);
1282            res = progress;
1283        }
1284        return res;
1285    }
1286    
1287    Glib::Dispatcher& Saver::signal_progress()
1288    {
1289        return progress_dispatcher;
1290    }
1291    
1292    Glib::Dispatcher& Saver::signal_finished()
1293    {
1294        return finished_dispatcher;
1295    }
1296    
1297    Glib::Dispatcher& Saver::signal_error()
1298    {
1299        return error_dispatcher;
1300    }
1301    
1302    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1303      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1304  {  {
1305      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1306      show_all_children();      show_all_children();
1307        resize(600,50);
1308  }  }
1309    
1310  // 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 1315  void MainWindow::__clear() {
1315      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1316      m_refTreeModel->clear();      m_refTreeModel->clear();
1317      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1318        m_refScriptsTreeModel->clear();
1319      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1320      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1321          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 648  void MainWindow::__refreshEntireGUI() { Line 1330  void MainWindow::__refreshEntireGUI() {
1330      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1331      m_refTreeModel->clear();      m_refTreeModel->clear();
1332      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1333        m_refScriptsTreeModel->clear();
1334      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1335      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1336          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 690  bool MainWindow::close_confirmation_dial Line 1373  bool MainWindow::close_confirmation_dial
1373      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1374      int response = dialog.run();      int response = dialog.run();
1375      dialog.hide();      dialog.hide();
1376      if (response == Gtk::RESPONSE_YES) return file_save();  
1377      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1378        if (response == Gtk::RESPONSE_NO) return true;
1379    
1380        // user cancelled dialog, thus don't close app
1381        if (response == Gtk::RESPONSE_CANCEL) return false;
1382    
1383        // TODO: the following return valid is disabled and hard coded instead for
1384        // now, due to the fact that saving with progress bar is now implemented
1385        // asynchronously, as a result the app does not close automatically anymore
1386        // after saving the file has completed
1387        //
1388        //   if (response == Gtk::RESPONSE_YES) return file_save();
1389        //   return response != Gtk::RESPONSE_CANCEL;
1390        //
1391        if (response == Gtk::RESPONSE_YES) file_save();
1392        return false; // always prevent closing the app for now (see comment above)
1393  }  }
1394    
1395  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 733  void MainWindow::on_action_file_open() Line 1431  void MainWindow::on_action_file_open()
1431      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1432          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1433          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1434          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());          printf("on_action_file_open self=%p\n",
1435                   static_cast<void*>(Glib::Threads::Thread::self()));
1436          load_file(filename.c_str());          load_file(filename.c_str());
1437          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1438      }      }
# Line 742  void MainWindow::on_action_file_open() Line 1441  void MainWindow::on_action_file_open()
1441  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1442  {  {
1443      __clear();      __clear();
1444      load_dialog = new LoadDialog(_("Loading..."), *this);  
1445      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1446      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1447            Glib::filename_display_basename(name) + "' ...",
1448            *this
1449        );
1450        progress_dialog->show_all();
1451        loader = new Loader(name); //FIXME: memory leak!
1452      loader->signal_progress().connect(      loader->signal_progress().connect(
1453          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1454      loader->signal_finished().connect(      loader->signal_finished().connect(
1455          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1456        loader->signal_error().connect(
1457            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1458      loader->launch();      loader->launch();
1459  }  }
1460    
# Line 764  void MainWindow::load_instrument(gig::In Line 1470  void MainWindow::load_instrument(gig::In
1470      // load the instrument      // load the instrument
1471      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1472      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1473      //TODO: automatically select the given instrument      // automatically select the given instrument
1474        int i = 0;
1475        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1476             instrument = pFile->GetNextInstrument(), ++i)
1477        {
1478            if (instrument == instr) {
1479                // select item in "instruments" tree view
1480                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1481                // make sure the selected item in the "instruments" tree view is
1482                // visible (scroll to it)
1483                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1484                // select item in instrument menu
1485                {
1486                    const std::vector<Gtk::Widget*> children =
1487                        instrument_menu->get_children();
1488                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1489                }
1490                // update region chooser and dimension region chooser
1491                m_RegionChooser.set_instrument(instr);
1492                break;
1493            }
1494        }
1495  }  }
1496    
1497  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1498  {  {
1499      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1500  }  }
1501    
1502  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1503  {  {
1504      printf("Loader finished!\n");      printf("Loader finished!\n");
1505      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());      printf("on_loader_finished self=%p\n",
1506      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1507      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1508        progress_dialog->hide();
1509    }
1510    
1511    void MainWindow::on_loader_error()
1512    {
1513        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1514        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1515        msg.run();
1516        progress_dialog->hide();
1517  }  }
1518    
1519  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 816  bool MainWindow::file_save() Line 1552  bool MainWindow::file_save()
1552    
1553      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1554      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1555      try {  
1556          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1557          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1558              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1559              file_is_changed = false;          *this
1560          }      );
1561      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1562          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1563          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1564          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1565          msg.run();      saver->signal_finished().connect(
1566          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1567      }      saver->signal_error().connect(
1568      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1569        saver->launch();
1570    
1571        return true;
1572    }
1573    
1574    void MainWindow::on_saver_progress()
1575    {
1576        progress_dialog->set_fraction(saver->get_progress());
1577    }
1578    
1579    void MainWindow::on_saver_error()
1580    {
1581        file_structure_changed_signal.emit(this->file);
1582        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1583        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1584        msg.run();
1585    }
1586    
1587    void MainWindow::on_saver_finished()
1588    {
1589        this->file = saver->gig;
1590        this->filename = saver->filename;
1591        current_gig_dir = Glib::path_get_dirname(filename);
1592        set_title(Glib::filename_display_basename(filename));
1593        file_has_name = true;
1594        file_is_changed = false;
1595        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1596      __import_queued_samples();      __import_queued_samples();
1597        std::cout << "Importing queued samples done.\n" << std::flush;
1598    
1599      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1600      return true;  
1601        __refreshEntireGUI();
1602        progress_dialog->hide();
1603  }  }
1604    
1605  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 876  bool MainWindow::file_save_as() Line 1643  bool MainWindow::file_save_as()
1643      // show warning in the dialog      // show warning in the dialog
1644      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
1645      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
1646      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
1647        warningIcon.set_from_icon_name("dialog-warning",
1648                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1649      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1650  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
1651      view::WrapLabel description;      view::WrapLabel description;
# Line 897  bool MainWindow::file_save_as() Line 1666  bool MainWindow::file_save_as()
1666      descriptionArea.show_all();      descriptionArea.show_all();
1667    
1668      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1669          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1670          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1671              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;  
1672          }          }
1673          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1674          file_structure_changed_signal.emit(this->file);  
1675            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1676                _("Saving") +  Glib::ustring(" '") +
1677                Glib::filename_display_basename(filename) + "' ...",
1678                *this
1679            );
1680            progress_dialog->show_all();
1681    
1682            saver = new Saver(file, filename); //FIXME: memory leak!
1683            saver->signal_progress().connect(
1684                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1685            saver->signal_finished().connect(
1686                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1687            saver->signal_error().connect(
1688                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1689            saver->launch();
1690    
1691          return true;          return true;
1692      }      }
1693      return false;      return false;
# Line 928  bool MainWindow::file_save_as() Line 1697  bool MainWindow::file_save_as()
1697  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1698      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1699      Glib::ustring error_files;      Glib::ustring error_files;
1700      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1701      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1702           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1703          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1704          SF_INFO info;          SF_INFO info;
1705          info.format = 0;          info.format = 0;
1706          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);
1707          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1708          try {          try {
1709              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 1726  void MainWindow::__import_queued_samples
1726                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1727              }              }
1728    
1729                // reset write position for sample
1730                iter->first->SetPos(0);
1731    
1732              const int bufsize = 10000;              const int bufsize = 10000;
1733              switch (bitdepth) {              switch (bitdepth) {
1734                  case 16: {                  case 16: {
# Line 966  void MainWindow::__import_queued_samples Line 1738  void MainWindow::__import_queued_samples
1738                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1739                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1740                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1741                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1742                          cnt -= n;                          cnt -= n;
1743                      }                      }
1744                      delete[] buffer;                      delete[] buffer;
# Line 986  void MainWindow::__import_queued_samples Line 1758  void MainWindow::__import_queued_samples
1758                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1759                          }                          }
1760                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1761                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1762                          cnt -= n;                          cnt -= n;
1763                      }                      }
1764                      delete[] srcbuf;                      delete[] srcbuf;
# Line 997  void MainWindow::__import_queued_samples Line 1769  void MainWindow::__import_queued_samples
1769              // cleanup              // cleanup
1770              sf_close(hFile);              sf_close(hFile);
1771              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
1772              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
1773              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1774              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1775              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1776              ++iter;              ++iter;
1777              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1778          } catch (std::string what) {          } catch (std::string what) {
1779              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1780              if (!error_files.empty()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1781              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1782              ++iter;              ++iter;
1783          }          }
1784      }      }
# Line 1029  void MainWindow::on_action_warn_user_on_ Line 1801  void MainWindow::on_action_warn_user_on_
1801          !Settings::singleton()->warnUserOnExtensions;          !Settings::singleton()->warnUserOnExtensions;
1802  }  }
1803    
1804    void MainWindow::on_action_sync_sampler_instrument_selection() {
1805        Settings::singleton()->syncSamplerInstrumentSelection =
1806            !Settings::singleton()->syncSamplerInstrumentSelection;
1807    }
1808    
1809    void MainWindow::on_action_move_root_note_with_region_moved() {
1810        Settings::singleton()->moveRootNoteWithRegionMoved =
1811            !Settings::singleton()->moveRootNoteWithRegionMoved;
1812    }
1813    
1814  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1815  {  {
1816      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
# Line 1038  void MainWindow::on_action_help_about() Line 1820  void MainWindow::on_action_help_about()
1820      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
1821  #endif  #endif
1822      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1823      dialog.set_copyright("Copyright (C) 2006-2014 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1824      const std::string sComment =      const std::string sComment =
1825          _("Built " __DATE__ "\nUsing ") +          _("Built " __DATE__ "\nUsing ") +
1826          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1827          _(          _(
1828              "Gigedit is released under the GNU General Public License.\n"              "Gigedit is released under the GNU General Public License.\n"
1829              "\n"              "\n"
1830              "Please notice that this is still a very young instrument editor. "              "This program is distributed WITHOUT ANY WARRANTY; So better "
1831              "So better backup your Gigasampler files before editing them with "              "backup your Gigasampler/GigaStudio files before editing them with "
1832              "this application.\n"              "this application.\n"
1833              "\n"              "\n"
1834              "Please report bugs to: http://bugs.linuxsampler.org"              "Please report bugs to: http://bugs.linuxsampler.org"
# Line 1054  void MainWindow::on_action_help_about() Line 1836  void MainWindow::on_action_help_about()
1836      dialog.set_comments(sComment.c_str());      dialog.set_comments(sComment.c_str());
1837      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1838      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1839        dialog.set_position(Gtk::WIN_POS_CENTER);
1840      dialog.run();      dialog.run();
1841  }  }
1842    
# Line 1079  PropDialog::PropDialog() Line 1862  PropDialog::PropDialog()
1862        table(2, 1),        table(2, 1),
1863        m_file(NULL)        m_file(NULL)
1864  {  {
1865        if (!Settings::singleton()->autoRestoreWindowDimension) {
1866            set_default_size(470, 390);
1867            set_position(Gtk::WIN_POS_MOUSE);
1868        }
1869    
1870      set_title(_("File Properties"));      set_title(_("File Properties"));
1871      eName.set_width_chars(50);      eName.set_width_chars(50);
1872    
# Line 1154  void PropDialog::set_file(gig::File* fil Line 1942  void PropDialog::set_file(gig::File* fil
1942      }      }
1943      std::vector<const char*> texts;      std::vector<const char*> texts;
1944      for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());      for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1945      texts.push_back(NULL); values.push_back(NULL);      texts.push_back(NULL); values.push_back(0);
1946      eFileFormat.set_choices(&texts[0], &values[0]);      eFileFormat.set_choices(&texts[0], &values[0]);
1947      eFileFormat.set_value(major);      eFileFormat.set_value(major);
1948  }  }
# Line 1213  InstrumentProps::InstrumentProps() : Line 2001  InstrumentProps::InstrumentProps() :
2001      eDimensionKeyRangeLow(_("Keyswitching range low")),      eDimensionKeyRangeLow(_("Keyswitching range low")),
2002      eDimensionKeyRangeHigh(_("Keyswitching range high"))      eDimensionKeyRangeHigh(_("Keyswitching range high"))
2003  {  {
2004        if (!Settings::singleton()->autoRestoreWindowDimension) {
2005            //set_default_size(470, 390);
2006            set_position(Gtk::WIN_POS_MOUSE);
2007        }
2008    
2009      set_title(_("Instrument Properties"));      set_title(_("Instrument Properties"));
2010    
2011      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
# Line 1295  void MainWindow::file_changed() Line 2088  void MainWindow::file_changed()
2088      }      }
2089  }  }
2090    
2091    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
2092        sample_ref_count.clear();
2093        
2094        if (!gig) return;
2095    
2096        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
2097             instrument = gig->GetNextInstrument())
2098        {
2099            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2100                 rgn = instrument->GetNextRegion())
2101            {
2102                for (int i = 0; i < 256; ++i) {
2103                    if (!rgn->pDimensionRegions[i]) continue;
2104                    if (rgn->pDimensionRegions[i]->pSample) {
2105                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
2106                    }
2107                }
2108            }
2109        }
2110    }
2111    
2112  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
2113  {  {
2114      file = 0;      file = 0;
2115      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
2116    
2117      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
2118            (filename && strlen(filename) > 0) ?
2119                filename : (!gig->GetFileName().empty()) ?
2120                    gig->GetFileName() : _("Unsaved Gig File");
2121      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
2122      file_has_name = filename;      file_has_name = filename;
2123      file_is_changed = false;      file_is_changed = false;
# Line 1309  void MainWindow::load_gig(gig::File* gig Line 2126  void MainWindow::load_gig(gig::File* gig
2126      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
2127    
2128      instrument_name_connection.block();      instrument_name_connection.block();
2129        int index = 0;
2130      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
2131           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
2132          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2133            const int iScriptSlots = instrument->ScriptSlotCount();
2134    
2135          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
2136          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
2137            row[m_Columns.m_col_nr] = index;
2138          row[m_Columns.m_col_name] = name;          row[m_Columns.m_col_name] = name;
2139          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
2140            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
2141    
2142          add_instrument_to_menu(name);          add_instrument_to_menu(name);
2143      }      }
2144      instrument_name_connection.unblock();      instrument_name_connection.unblock();
2145      uiManager->get_widget("/MenuBar/MenuInstrument")->show();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
2146    
2147        updateSampleRefCountMap(gig);
2148    
2149      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
2150          if (group->Name != "") {          if (group->Name != "") {
# Line 1339  void MainWindow::load_gig(gig::File* gig Line 2162  void MainWindow::load_gig(gig::File* gig
2162                      gig_to_utf8(sample->pInfo->Name);                      gig_to_utf8(sample->pInfo->Name);
2163                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2164                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2165                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
2166                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
2167                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
2168              }              }
2169          }          }
2170      }      }
2171        
2172        for (int i = 0; gig->GetScriptGroup(i); ++i) {
2173            gig::ScriptGroup* group = gig->GetScriptGroup(i);
2174    
2175            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2176            Gtk::TreeModel::Row rowGroup = *iterGroup;
2177            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
2178            rowGroup[m_ScriptsModel.m_col_group]  = group;
2179            rowGroup[m_ScriptsModel.m_col_script] = NULL;
2180            for (int s = 0; group->GetScript(s); ++s) {
2181                gig::Script* script = group->GetScript(s);
2182    
2183                Gtk::TreeModel::iterator iterScript =
2184                    m_refScriptsTreeModel->append(rowGroup.children());
2185                Gtk::TreeModel::Row rowScript = *iterScript;
2186                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
2187                rowScript[m_ScriptsModel.m_col_script] = script;
2188                rowScript[m_ScriptsModel.m_col_group]  = NULL;
2189            }
2190        }
2191        // unfold all sample groups & script groups by default
2192        m_TreeViewSamples.expand_all();
2193        m_TreeViewScripts.expand_all();
2194    
2195      file = gig;      file = gig;
2196    
# Line 1359  bool MainWindow::instr_props_set_instrum Line 2208  bool MainWindow::instr_props_set_instrum
2208  {  {
2209      instrumentProps.signal_name_changed().clear();      instrumentProps.signal_name_changed().clear();
2210    
2211      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2212          m_TreeView.get_selection()->get_selected();      if (rows.empty()) {
2213            instrumentProps.hide();
2214            return false;
2215        }
2216        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2217      if (it) {      if (it) {
2218          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2219          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 2263  void MainWindow::show_midi_rules()
2263      }      }
2264  }  }
2265    
2266    void MainWindow::show_script_slots() {
2267        if (!file) return;
2268        // get selected instrument
2269        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2270        if (rows.empty()) return;
2271        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2272        if (!it) return;
2273        Gtk::TreeModel::Row row = *it;
2274        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2275        if (!instrument) return;
2276    
2277        ScriptSlots* window = new ScriptSlots;
2278        window->setInstrument(instrument);
2279        window->signal_script_slots_changed().connect(
2280            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
2281        );
2282        //window->reparent(*this);
2283        window->show();
2284    }
2285    
2286    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
2287        if (!pInstrument) return;
2288        const int iScriptSlots = pInstrument->ScriptSlotCount();
2289    
2290        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2291        for (int i = 0; i < model->children().size(); ++i) {
2292            Gtk::TreeModel::Row row = model->children()[i];
2293            if (row[m_Columns.m_col_instr] != pInstrument) continue;
2294            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
2295            break;
2296        }
2297    }
2298    
2299    void MainWindow::on_action_refresh_all() {
2300        __refreshEntireGUI();
2301    }
2302    
2303  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2304      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2305          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 2311  void MainWindow::on_action_view_status_b
2311      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2312  }  }
2313    
2314    void MainWindow::on_auto_restore_win_dim() {
2315        Gtk::CheckMenuItem* item =
2316            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2317        if (!item) {
2318            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2319            return;
2320        }
2321        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2322    }
2323    
2324    void MainWindow::on_save_with_temporary_file() {
2325        Gtk::CheckMenuItem* item =
2326            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2327        if (!item) {
2328            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2329            return;
2330        }
2331        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2332    }
2333    
2334  bool MainWindow::is_copy_samples_unity_note_enabled() const {  bool MainWindow::is_copy_samples_unity_note_enabled() const {
2335      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2336          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 2367  void MainWindow::on_button_release(GdkEv
2367          show_instr_props();          show_instr_props();
2368      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2369          // gig v2 files have no midi rules          // gig v2 files have no midi rules
2370            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2371            static_cast<Gtk::MenuItem*>(
2372                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2373                    bEnabled
2374                );
2375          static_cast<Gtk::MenuItem*>(          static_cast<Gtk::MenuItem*>(
2376              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2377                  !(file->pVersion && file->pVersion->major == 2));                  bEnabled
2378                );
2379          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2380      }      }
2381  }  }
# Line 1479  void MainWindow::on_instrument_selection Line 2395  void MainWindow::on_instrument_selection
2395      }      }
2396  }  }
2397    
2398    void MainWindow::select_instrument(gig::Instrument* instrument) {
2399        if (!instrument) return;
2400    
2401        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2402        for (int i = 0; i < model->children().size(); ++i) {
2403            Gtk::TreeModel::Row row = model->children()[i];
2404            if (row[m_Columns.m_col_instr] == instrument) {
2405                // select and show the respective instrument in the list view
2406                show_intruments_tab();
2407                m_TreeView.get_selection()->unselect_all();
2408                m_TreeView.get_selection()->select(model->children()[i]);
2409                std::vector<Gtk::TreeModel::Path> rows =
2410                    m_TreeView.get_selection()->get_selected_rows();
2411                if (!rows.empty())
2412                    m_TreeView.scroll_to_row(rows[0]);
2413                on_sel_change(); // the regular instrument selection change callback
2414            }
2415        }
2416    }
2417    
2418    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2419    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2420        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2421        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2422    
2423        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2424        for (int i = 0; i < model->children().size(); ++i) {
2425            Gtk::TreeModel::Row row = model->children()[i];
2426            if (row[m_Columns.m_col_instr] == pInstrument) {
2427                // select and show the respective instrument in the list view
2428                show_intruments_tab();
2429                m_TreeView.get_selection()->unselect_all();
2430                m_TreeView.get_selection()->select(model->children()[i]);
2431                std::vector<Gtk::TreeModel::Path> rows =
2432                    m_TreeView.get_selection()->get_selected_rows();
2433                if (!rows.empty())
2434                    m_TreeView.scroll_to_row(rows[0]);
2435                on_sel_change(); // the regular instrument selection change callback
2436    
2437                // select respective region in the region selector
2438                m_RegionChooser.set_region(pRegion);
2439    
2440                // select and show the respective dimension region in the editor
2441                //update_dimregs();
2442                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2443                //dimreg_edit.set_dim_region(dimRgn);
2444    
2445                return true;
2446            }
2447        }
2448    
2449        return false;
2450    }
2451    
2452    void MainWindow::select_sample(gig::Sample* sample) {
2453        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2454        for (int g = 0; g < model->children().size(); ++g) {
2455            Gtk::TreeModel::Row rowGroup = model->children()[g];
2456            for (int s = 0; s < rowGroup.children().size(); ++s) {
2457                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2458                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2459                    show_samples_tab();
2460                    m_TreeViewSamples.get_selection()->unselect_all();
2461                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2462                    std::vector<Gtk::TreeModel::Path> rows =
2463                        m_TreeViewSamples.get_selection()->get_selected_rows();
2464                    if (rows.empty()) return;
2465                    m_TreeViewSamples.scroll_to_row(rows[0]);
2466                    return;
2467                }
2468            }
2469        }
2470    }
2471    
2472  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2473      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2474            // by default if Ctrl keys is pressed down, then a mouse right-click
2475            // does not select the respective row, so we must assure this
2476            // programmatically ...
2477            /*{
2478                Gtk::TreeModel::Path path;
2479                Gtk::TreeViewColumn* pColumn = NULL;
2480                int cellX, cellY;
2481                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2482                    (int)button->x, (int)button->y,
2483                    path, pColumn, cellX, cellY
2484                );
2485                if (bSuccess) {
2486                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2487                        printf("not selected !!!\n");
2488                        m_TreeViewSamples.get_selection()->select(path);
2489                    }
2490                }
2491            }*/
2492    
2493          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2494              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2495          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2496          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2497          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2498          bool group_selected  = false;          const int n = rows.size();
2499          bool sample_selected = false;          int nGroups  = 0;
2500          if (it) {          int nSamples = 0;
2501            for (int r = 0; r < n; ++r) {
2502                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2503                if (!it) continue;
2504              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2505              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2506              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2507          }          }
2508    
2509          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2510              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2511          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2512              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2513          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2514              set_sensitive(file);              set_sensitive(file);
2515            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2516                set_sensitive(nSamples == 1);
2517          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2518              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2519          // show sample popup          // show sample popup
2520          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2521    
2522            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2523                set_sensitive(n == 1);
2524            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2525                set_sensitive(n);
2526            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2527                set_sensitive(file);
2528            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2529                set_sensitive(nSamples == 1);
2530            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2531                set_sensitive(n);
2532      }      }
2533  }  }
2534    
2535    void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2536        if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2537            Gtk::Menu* script_popup =
2538                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2539            // update enabled/disabled state of sample popup items
2540            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2541            Gtk::TreeModel::iterator it = sel->get_selected();
2542            bool group_selected  = false;
2543            bool script_selected = false;
2544            if (it) {
2545                Gtk::TreeModel::Row row = *it;
2546                group_selected  = row[m_ScriptsModel.m_col_group];
2547                script_selected = row[m_ScriptsModel.m_col_script];
2548            }
2549            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2550                set_sensitive(group_selected || script_selected);
2551            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2552                set_sensitive(file);
2553            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2554                set_sensitive(script_selected);    
2555            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2556                set_sensitive(group_selected || script_selected);
2557            // show sample popup
2558            script_popup->popup(button->button, button->time);
2559    
2560            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2561                set_sensitive(group_selected || script_selected);
2562            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2563                set_sensitive(file);
2564            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2565                set_sensitive(script_selected);    
2566            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2567                set_sensitive(group_selected || script_selected);
2568        }
2569    }
2570    
2571  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2572      const Glib::ustring& name, int position) {      const Glib::ustring& name, int position) {
# Line 1546  void MainWindow::add_instrument(gig::Ins Line 2607  void MainWindow::add_instrument(gig::Ins
2607      instrument_name_connection.block();      instrument_name_connection.block();
2608      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2609      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2610        rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2611      rowInstr[m_Columns.m_col_name] = name;      rowInstr[m_Columns.m_col_name] = name;
2612      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2613        rowInstr[m_Columns.m_col_scripts] = "";
2614      instrument_name_connection.unblock();      instrument_name_connection.unblock();
2615    
2616      add_instrument_to_menu(name);      add_instrument_to_menu(name);
# Line 1574  void MainWindow::on_action_duplicate_ins Line 2637  void MainWindow::on_action_duplicate_ins
2637      // retrieve the currently selected instrument      // retrieve the currently selected instrument
2638      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
2639      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2640      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2641      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
2642      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2643      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
2644      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
2645                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2646      // duplicate the orginal instrument              if (instrOrig) {
2647      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
2648      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2649          instrOrig->pInfo->Name +                  instrNew->pInfo->Name =
2650          gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");                      instrOrig->pInfo->Name +
2651                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2652    
2653      add_instrument(instrNew);                  add_instrument(instrNew);
2654                }
2655            }
2656        }
2657  }  }
2658    
2659  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1603  void MainWindow::on_action_remove_instru Line 2670  void MainWindow::on_action_remove_instru
2670      }      }
2671    
2672      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2673      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2674      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2675            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2676            if (!it) continue;
2677          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2678          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2679          try {          try {
# Line 1619  void MainWindow::on_action_remove_instru Line 2688  void MainWindow::on_action_remove_instru
2688    
2689              // remove row from instruments tree view              // remove row from instruments tree view
2690              m_refTreeModel->erase(it);              m_refTreeModel->erase(it);
2691                // update "Nr" column of all instrument rows
2692                {
2693                    int index = 0;
2694                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2695                         it != m_refTreeModel->children().end(); ++it, ++index)
2696                    {
2697                        Gtk::TreeModel::Row row = *it;
2698                        row[m_Columns.m_col_nr] = index;
2699                    }
2700                }
2701    
2702  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2703              // 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 2732  void MainWindow::on_action_sample_proper
2732      msg.run();      msg.run();
2733  }  }
2734    
2735    void MainWindow::on_action_add_script_group() {
2736        static int __script_indexer = 0;
2737        if (!file) return;
2738        gig::ScriptGroup* group = file->AddScriptGroup();
2739        group->Name = gig_from_utf8(_("Unnamed Group"));
2740        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2741        __script_indexer++;
2742        // update sample tree view
2743        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2744        Gtk::TreeModel::Row rowGroup = *iterGroup;
2745        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2746        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2747        rowGroup[m_ScriptsModel.m_col_group] = group;
2748        file_changed();
2749    }
2750    
2751    void MainWindow::on_action_add_script() {
2752        if (!file) return;
2753        // get selected group
2754        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2755        Gtk::TreeModel::iterator it = sel->get_selected();
2756        if (!it) return;
2757        Gtk::TreeModel::Row row = *it;
2758        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2759        if (!group) { // not a group, but a script is selected (probably)
2760            gig::Script* script = row[m_ScriptsModel.m_col_script];
2761            if (!script) return;
2762            it = row.parent(); // resolve parent (that is the script's group)
2763            if (!it) return;
2764            row = *it;
2765            group = row[m_ScriptsModel.m_col_group];
2766            if (!group) return;
2767        }
2768    
2769        // add a new script to the .gig file
2770        gig::Script* script = group->AddScript();    
2771        Glib::ustring name = _("Unnamed Script");
2772        script->Name = gig_from_utf8(name);
2773    
2774        // add script to the tree view
2775        Gtk::TreeModel::iterator iterScript =
2776            m_refScriptsTreeModel->append(row.children());
2777        Gtk::TreeModel::Row rowScript = *iterScript;
2778        rowScript[m_ScriptsModel.m_col_name] = name;
2779        rowScript[m_ScriptsModel.m_col_script] = script;
2780        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2781    
2782        // unfold group of new script item in treeview
2783        Gtk::TreeModel::Path path(iterScript);
2784        m_TreeViewScripts.expand_to_path(path);
2785    }
2786    
2787    void MainWindow::on_action_edit_script() {
2788        if (!file) return;
2789        // get selected script
2790        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2791        Gtk::TreeModel::iterator it = sel->get_selected();
2792        if (!it) return;
2793        Gtk::TreeModel::Row row = *it;
2794        gig::Script* script = row[m_ScriptsModel.m_col_script];
2795        if (!script) return;
2796    
2797        ScriptEditor* editor = new ScriptEditor;
2798        editor->signal_script_to_be_changed.connect(
2799            signal_script_to_be_changed.make_slot()
2800        );
2801        editor->signal_script_changed.connect(
2802            signal_script_changed.make_slot()
2803        );
2804        editor->setScript(script);
2805        //editor->reparent(*this);
2806        editor->show();
2807    }
2808    
2809    void MainWindow::on_action_remove_script() {
2810        if (!file) return;
2811        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2812        Gtk::TreeModel::iterator it = sel->get_selected();
2813        if (it) {
2814            Gtk::TreeModel::Row row = *it;
2815            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2816            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2817            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2818            try {
2819                // remove script group or script from the gig file
2820                if (group) {
2821                    // notify everybody that we're going to remove these samples
2822    //TODO:         scripts_to_be_removed_signal.emit(members);
2823                    // delete the group in the .gig file including the
2824                    // samples that belong to the group
2825                    file->DeleteScriptGroup(group);
2826                    // notify that we're done with removal
2827    //TODO:         scripts_removed_signal.emit();
2828                    file_changed();
2829                } else if (script) {
2830                    // notify everybody that we're going to remove this sample
2831    //TODO:         std::list<gig::Script*> lscripts;
2832    //TODO:         lscripts.push_back(script);
2833    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2834                    // remove sample from the .gig file
2835                    script->GetGroup()->DeleteScript(script);
2836                    // notify that we're done with removal
2837    //TODO:         scripts_removed_signal.emit();
2838                    dimreg_changed();
2839                    file_changed();
2840                }
2841                // remove respective row(s) from samples tree view
2842                m_refScriptsTreeModel->erase(it);
2843            } catch (RIFF::Exception e) {
2844                // pretend we're done with removal (i.e. to avoid dead locks)
2845    //TODO:     scripts_removed_signal.emit();
2846                // show error message
2847                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2848                msg.run();
2849            }
2850        }
2851    }
2852    
2853  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2854      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2855      if (!file) return;      if (!file) return;
# Line 1669  void MainWindow::on_action_add_group() { Line 2866  void MainWindow::on_action_add_group() {
2866      file_changed();      file_changed();
2867  }  }
2868    
2869    void MainWindow::on_action_replace_sample() {
2870        add_or_replace_sample(true);
2871    }
2872    
2873  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2874        add_or_replace_sample(false);
2875    }
2876    
2877    void MainWindow::add_or_replace_sample(bool replace) {
2878      if (!file) return;      if (!file) return;
2879      // get selected group  
2880        // get selected group (and probably selected sample)
2881      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2882      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2883        if (rows.empty()) return;
2884        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2885      if (!it) return;      if (!it) return;
2886      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2887        gig::Sample* sample = NULL;
2888      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2889      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2890          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2891          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2892          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2893          if (!it) return;          if (!it) return;
2894          row = *it;          if (!replace) row = *it;
2895          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2896          if (!group) return;          if (!group) return;
2897      }      }
2898        if (replace && !sample) return;
2899    
2900      // show 'browse for file' dialog      // show 'browse for file' dialog
2901      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2902      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
2903      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
2904      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
2905    
2906      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
2907  #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 2972  void MainWindow::on_action_add_sample()
2972                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2973                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2974                  }                  }
2975                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2976                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2977                  // file name without path                  // file name without path
2978                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2979                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1813  void MainWindow::on_action_add_sample() Line 3024  void MainWindow::on_action_add_sample()
3024                  // physically when File::Save() is called)                  // physically when File::Save() is called)
3025                  sample->Resize(info.frames);                  sample->Resize(info.frames);
3026                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
3027                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
3028                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
3029                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
3030                  SampleImportItem sched_item;                  SampleImportItem sched_item;
3031                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
3032                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
3033                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
3034                  // add sample to the tree view                  // add sample to the tree view
3035                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
3036                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
3037                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
3038                  rowSample[m_SamplesModel.m_col_name] =                      Gtk::TreeModel::iterator iterSample =
3039                      gig_to_utf8(sample->pInfo->Name);                          m_refSamplesTreeModel->append(row.children());
3040                  rowSample[m_SamplesModel.m_col_sample] = sample;                      Gtk::TreeModel::Row rowSample = *iterSample;
3041                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      rowSample[m_SamplesModel.m_col_name] =
3042                            gig_to_utf8(sample->pInfo->Name);
3043                        rowSample[m_SamplesModel.m_col_sample] = sample;
3044                        rowSample[m_SamplesModel.m_col_group]  = NULL;
3045                    }
3046                  // close sound file                  // close sound file
3047                  sf_close(hFile);                  sf_close(hFile);
3048                  file_changed();                  file_changed();
# Line 1838  void MainWindow::on_action_add_sample() Line 3053  void MainWindow::on_action_add_sample()
3053          }          }
3054          // 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
3055          if (!error_files.empty()) {          if (!error_files.empty()) {
3056              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
3057                    (replace
3058                        ? _("Failed to replace sample with:\n")
3059                        : _("Could not add the following sample(s):\n"))
3060                    + error_files;
3061              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3062              msg.run();              msg.run();
3063          }          }
# Line 1905  void MainWindow::on_action_replace_all_s Line 3124  void MainWindow::on_action_replace_all_s
3124              try              try
3125              {              {
3126                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
3127                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
3128                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
3129                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
3130                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
3131                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
3132                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
3133                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
3134                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
3135                          break;                          break;
3136                      default:                      default:
3137                          sf_close(hFile);                          sf_close(hFile);
# Line 1925  void MainWindow::on_action_replace_all_s Line 3140  void MainWindow::on_action_replace_all_s
3140                  SampleImportItem sched_item;                  SampleImportItem sched_item;
3141                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
3142                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
3143                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
3144                  sf_close(hFile);                  sf_close(hFile);
3145                  file_changed();                  file_changed();
3146              }              }
# Line 1949  void MainWindow::on_action_replace_all_s Line 3164  void MainWindow::on_action_replace_all_s
3164  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
3165      if (!file) return;      if (!file) return;
3166      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3167      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3168      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3169            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3170            if (!it) continue;
3171          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3172          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
3173          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 3192  void MainWindow::on_action_remove_sample
3192                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
3193                  // them from the import queue                  // them from the import queue
3194                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
3195                       member != members.end(); ++member) {                       member != members.end(); ++member)
3196                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
3197                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
3198                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
3199                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
3200                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
3201                      }                      }
3202                  }                  }
3203                  file_changed();                  file_changed();
# Line 1998  void MainWindow::on_action_remove_sample Line 3212  void MainWindow::on_action_remove_sample
3212                  samples_removed_signal.emit();                  samples_removed_signal.emit();
3213                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
3214                  // the import queue                  // the import queue
3215                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
3216                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
3217                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
3218                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
3219                  }                  }
3220                  dimreg_changed();                  dimreg_changed();
3221                  file_changed();                  file_changed();
# Line 2022  void MainWindow::on_action_remove_sample Line 3232  void MainWindow::on_action_remove_sample
3232      }      }
3233  }  }
3234    
3235    void MainWindow::on_action_remove_unused_samples() {
3236        if (!file) return;
3237    
3238        // collect all samples that are not referenced by any instrument
3239        std::list<gig::Sample*> lsamples;
3240        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3241            gig::Sample* sample = file->GetSample(iSample);
3242            bool isUsed = false;
3243            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3244                                  instrument = file->GetNextInstrument())
3245            {
3246                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3247                                  rgn = instrument->GetNextRegion())
3248                {
3249                    for (int i = 0; i < 256; ++i) {
3250                        if (!rgn->pDimensionRegions[i]) continue;
3251                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3252                        isUsed = true;
3253                        goto endOfRefSearch;
3254                    }
3255                }
3256            }
3257            endOfRefSearch:
3258            if (!isUsed) lsamples.push_back(sample);
3259        }
3260    
3261        if (lsamples.empty()) return;
3262    
3263        // notify everybody that we're going to remove these samples
3264        samples_to_be_removed_signal.emit(lsamples);
3265    
3266        // remove collected samples
3267        try {
3268            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3269                 itSample != lsamples.end(); ++itSample)
3270            {
3271                gig::Sample* sample = *itSample;
3272                // remove sample from the .gig file
3273                file->DeleteSample(sample);
3274                // if sample was just previously added, remove it from the import queue
3275                if (m_SampleImportQueue.count(sample)) {
3276                    printf("Removing previously added sample '%s'\n",
3277                           m_SampleImportQueue[sample].sample_path.c_str());
3278                    m_SampleImportQueue.erase(sample);
3279                }
3280            }
3281        } catch (RIFF::Exception e) {
3282            // show error message
3283            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3284            msg.run();
3285        }
3286    
3287        // notify everybody that we're done with removal
3288        samples_removed_signal.emit();
3289    
3290        dimreg_changed();
3291        file_changed();
3292        __refreshEntireGUI();
3293    }
3294    
3295    // see comment on on_sample_treeview_drag_begin()
3296    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3297    {
3298        first_call_to_drag_data_get = true;
3299    }
3300    
3301    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3302                                                       Gtk::SelectionData& selection_data, guint, guint)
3303    {
3304        if (!first_call_to_drag_data_get) return;
3305        first_call_to_drag_data_get = false;
3306    
3307        // get selected script
3308        gig::Script* script = NULL;
3309        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3310        Gtk::TreeModel::iterator it = sel->get_selected();
3311        if (it) {
3312            Gtk::TreeModel::Row row = *it;
3313            script = row[m_ScriptsModel.m_col_script];
3314        }
3315        // pass the gig::Script as pointer
3316        selection_data.set(selection_data.get_target(), 0/*unused*/,
3317                           (const guchar*)&script,
3318                           sizeof(script)/*length of data in bytes*/);
3319    }
3320    
3321    // see comment on on_sample_treeview_drag_begin()
3322    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3323    {
3324        first_call_to_drag_data_get = true;
3325    }
3326    
3327    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3328                                                           Gtk::SelectionData& selection_data, guint, guint)
3329    {
3330        if (!first_call_to_drag_data_get) return;
3331        first_call_to_drag_data_get = false;
3332    
3333        // get selected source instrument
3334        gig::Instrument* src = NULL;
3335        {
3336            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3337            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3338            if (!rows.empty()) {
3339                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3340                if (it) {
3341                    Gtk::TreeModel::Row row = *it;
3342                    src = row[m_Columns.m_col_instr];
3343                }
3344            }
3345        }
3346        if (!src) return;
3347    
3348        // pass the source gig::Instrument as pointer
3349        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3350                           sizeof(src)/*length of data in bytes*/);
3351    }
3352    
3353    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3354        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3355        const Gtk::SelectionData& selection_data, guint, guint time)
3356    {
3357        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3358        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3359            return;
3360    
3361        gig::Instrument* dst = NULL;
3362        {
3363            Gtk::TreeModel::Path path;
3364            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3365            if (!found) return;
3366    
3367            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3368            if (!iter) return;
3369            Gtk::TreeModel::Row row = *iter;
3370            dst = row[m_Columns.m_col_instr];
3371        }
3372        if (!dst) return;
3373    
3374        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3375        src->MoveTo(dst);
3376        __refreshEntireGUI();
3377        select_instrument(src);
3378    }
3379    
3380  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3381  // 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
3382  // 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 3395  void MainWindow::on_sample_treeview_drag
3395      // get selected sample      // get selected sample
3396      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3397      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3398      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3399      if (it) {      if (!rows.empty()) {
3400          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3401          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3402                Gtk::TreeModel::Row row = *it;
3403                sample = row[m_SamplesModel.m_col_sample];
3404            }
3405      }      }
3406      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3407      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 3508  void MainWindow::sample_name_changed(con
3508      }      }
3509  }  }
3510    
3511    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3512                                         const Gtk::TreeModel::iterator& iter) {
3513        if (!iter) return;
3514        Gtk::TreeModel::Row row = *iter;
3515        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3516        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3517        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3518        gig::String gigname(gig_from_utf8(name));
3519        if (group) {
3520            if (group->Name != gigname) {
3521                group->Name = gigname;
3522                printf("script group name changed\n");
3523                file_changed();
3524            }
3525        } else if (script) {
3526            if (script->Name != gigname) {
3527                script->Name = gigname;
3528                printf("script name changed\n");
3529                file_changed();
3530            }
3531        }
3532    }
3533    
3534    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3535                                           Gtk::TreeViewColumn* column)
3536    {
3537        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3538        if (!iter) return;
3539        Gtk::TreeModel::Row row = *iter;
3540        gig::Script* script = row[m_ScriptsModel.m_col_script];
3541        if (!script) return;
3542    
3543        ScriptEditor* editor = new ScriptEditor;
3544        editor->signal_script_to_be_changed.connect(
3545            signal_script_to_be_changed.make_slot()
3546        );
3547        editor->signal_script_changed.connect(
3548            signal_script_changed.make_slot()
3549        );
3550        editor->setScript(script);
3551        //editor->reparent(*this);
3552        editor->show();
3553    }
3554    
3555  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3556                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3557      if (!iter) return;      if (!iter) return;
# Line 2187  void MainWindow::instrument_name_changed Line 3589  void MainWindow::instrument_name_changed
3589  void MainWindow::on_action_combine_instruments() {  void MainWindow::on_action_combine_instruments() {
3590      CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);      CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3591      d->show_all();      d->show_all();
     d->resize(500, 400);  
3592      d->run();      d->run();
3593      if (d->fileWasChanged()) {      if (d->fileWasChanged()) {
3594          // update GUI with new instrument just created          // update GUI with new instrument just created
# Line 2196  void MainWindow::on_action_combine_instr Line 3597  void MainWindow::on_action_combine_instr
3597      delete d;      delete d;
3598  }  }
3599    
3600    void MainWindow::on_action_view_references() {
3601        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3602        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3603        if (rows.empty()) return;
3604        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3605        if (!it) return;
3606        Gtk::TreeModel::Row row = *it;
3607        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3608        if (!sample) return;
3609    
3610        ReferencesView* d = new ReferencesView(*this);
3611        d->setSample(sample);
3612        d->dimension_region_selected.connect(
3613            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3614        );
3615        d->show_all();
3616        d->resize(500, 400);
3617        d->run();
3618        delete d;
3619    }
3620    
3621  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3622      struct _Source {      struct _Source {
3623          std::vector<RIFF::File*> riffs;          std::vector<RIFF::File*> riffs;
# Line 2263  void MainWindow::mergeFiles(const std::v Line 3685  void MainWindow::mergeFiles(const std::v
3685          );          );
3686      }      }
3687    
3688      // Note: requires that this file already has a filename !      // Finally save gig file persistently to disk ...
3689      this->file->Save();      //NOTE: requires that this gig file already has a filename !
3690        {
3691            std::cout << "Saving file\n" << std::flush;
3692            file_structure_to_be_changed_signal.emit(this->file);
3693    
3694            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3695                _("Saving") +  Glib::ustring(" '") +
3696                Glib::filename_display_basename(this->filename) + "' ...",
3697                *this
3698            );
3699            progress_dialog->show_all();
3700            saver = new Saver(this->file); //FIXME: memory leak!
3701            saver->signal_progress().connect(
3702                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3703            saver->signal_finished().connect(
3704                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3705            saver->signal_error().connect(
3706                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3707            saver->launch();
3708        }
3709  }  }
3710    
3711  void MainWindow::on_action_merge_files() {  void MainWindow::on_action_merge_files() {
# Line 2301  void MainWindow::on_action_merge_files() Line 3742  void MainWindow::on_action_merge_files()
3742      // show warning in the file picker dialog      // show warning in the file picker dialog
3743      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
3744      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
3745      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
3746        warningIcon.set_from_icon_name("dialog-warning",
3747                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3748      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3749  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
3750      view::WrapLabel description;      view::WrapLabel description;
# Line 2324  void MainWindow::on_action_merge_files() Line 3767  void MainWindow::on_action_merge_files()
3767      descriptionArea.show_all();      descriptionArea.show_all();
3768    
3769      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
3770          printf("on_action_merge_files self=%x\n", Glib::Threads::Thread::self());          printf("on_action_merge_files self=%p\n",
3771                   static_cast<void*>(Glib::Threads::Thread::self()));
3772          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
3773    
3774          // 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 3780  void MainWindow::on_action_merge_files()
3780          }          }
3781    
3782          // update GUI          // update GUI
3783          __refreshEntireGUI();                  __refreshEntireGUI();
3784      }      }
3785  }  }
3786    
# Line 2354  void MainWindow::set_file_is_shared(bool Line 3798  void MainWindow::set_file_is_shared(bool
3798              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3799          );          );
3800      }      }
3801    
3802        {
3803            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3804                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3805            if (item) item->set_sensitive(b);
3806        }
3807    }
3808    
3809    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3810        if (!sample) return;
3811        sample_ref_count[sample] += offset;
3812        const int refcount = sample_ref_count[sample];
3813    
3814        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3815        for (int g = 0; g < model->children().size(); ++g) {
3816            Gtk::TreeModel::Row rowGroup = model->children()[g];
3817            for (int s = 0; s < rowGroup.children().size(); ++s) {
3818                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3819                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3820                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3821                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3822            }
3823        }
3824    }
3825    
3826    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3827        on_sample_ref_count_incremented(oldSample, -1);
3828        on_sample_ref_count_incremented(newSample, +1);
3829    }
3830    
3831    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3832        // just in case a new sample is added later with exactly the same memory
3833        // address, which would lead to incorrect refcount if not deleted here
3834        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3835             it != samples.end(); ++it)
3836        {
3837            sample_ref_count.erase(*it);
3838        }
3839    }
3840    
3841    void MainWindow::show_samples_tab() {
3842        m_TreeViewNotebook.set_current_page(0);
3843    }
3844    
3845    void MainWindow::show_intruments_tab() {
3846        m_TreeViewNotebook.set_current_page(1);
3847    }
3848    
3849    void MainWindow::show_scripts_tab() {
3850        m_TreeViewNotebook.set_current_page(2);
3851    }
3852    
3853    void MainWindow::select_prev_region() {
3854        m_RegionChooser.select_prev_region();
3855    }
3856    
3857    void MainWindow::select_next_region() {
3858        m_RegionChooser.select_next_region();
3859    }
3860    
3861    void MainWindow::select_next_dim_rgn_zone() {
3862        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3863        m_DimRegionChooser.select_next_dimzone();
3864    }
3865    
3866    void MainWindow::select_prev_dim_rgn_zone() {
3867        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3868        m_DimRegionChooser.select_prev_dimzone();
3869    }
3870    
3871    void MainWindow::select_add_next_dim_rgn_zone() {
3872        m_DimRegionChooser.select_next_dimzone(true);
3873    }
3874    
3875    void MainWindow::select_add_prev_dim_rgn_zone() {
3876        m_DimRegionChooser.select_prev_dimzone(true);
3877    }
3878    
3879    void MainWindow::select_prev_dimension() {
3880        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3881        m_DimRegionChooser.select_prev_dimension();
3882    }
3883    
3884    void MainWindow::select_next_dimension() {
3885        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3886        m_DimRegionChooser.select_next_dimension();
3887    }
3888    
3889    #define CLIPBOARD_DIMENSIONREGION_TARGET \
3890        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
3891    
3892    void MainWindow::copy_selected_dimrgn() {
3893        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3894        if (!pDimRgn) {
3895            updateClipboardPasteAvailable();
3896            updateClipboardCopyAvailable();
3897            return;
3898        }
3899    
3900        std::vector<Gtk::TargetEntry> targets;
3901        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
3902    
3903        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3904        clipboard->set(
3905            targets,
3906            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
3907            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
3908        );
3909    
3910        m_serializationArchive.serialize(pDimRgn);
3911    
3912        updateClipboardPasteAvailable();
3913    }
3914    
3915    void MainWindow::paste_copied_dimrgn() {
3916        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3917        clipboard->request_contents(
3918            CLIPBOARD_DIMENSIONREGION_TARGET,
3919            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
3920        );
3921        updateClipboardPasteAvailable();
3922    }
3923    
3924    void MainWindow::adjust_clipboard_content() {
3925        MacroEditor* editor = new MacroEditor();
3926        editor->setMacro(&m_serializationArchive, true);
3927        editor->show();
3928    }
3929    
3930    void MainWindow::updateClipboardPasteAvailable() {
3931        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
3932        clipboard->request_targets(
3933            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
3934        );
3935    }
3936    
3937    void MainWindow::updateClipboardCopyAvailable() {
3938        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
3939        static_cast<Gtk::MenuItem*>(
3940            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
3941        )->set_sensitive(bDimensionRegionCopyIsPossible);
3942    }
3943    
3944    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
3945        updateClipboardPasteAvailable();
3946    }
3947    
3948    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
3949        const std::string target = selection_data.get_target();
3950        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3951            selection_data.set(
3952                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
3953                &m_serializationArchive.rawData()[0],
3954                m_serializationArchive.rawData().size()
3955            );
3956        } else {
3957            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
3958        }
3959    }
3960    
3961    void MainWindow::on_clipboard_clear() {
3962        m_serializationArchive.clear();
3963        updateClipboardPasteAvailable();
3964        updateClipboardCopyAvailable();
3965    }
3966    
3967    //NOTE: Might throw exception !!!
3968    void MainWindow::applyMacro(Serialization::Archive& macro) {
3969        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
3970        if (!pDimRgn) return;
3971    
3972        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
3973             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
3974        {
3975            gig::DimensionRegion* pDimRgn = *itDimReg;
3976            DimRegionChangeGuard(this, pDimRgn);
3977            macro.deserialize(pDimRgn);
3978        }
3979        //region_changed()
3980        file_changed();
3981        dimreg_changed();
3982    }
3983    
3984    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
3985        const std::string target = selection_data.get_target();
3986        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
3987            Glib::ustring errorText;
3988            try {
3989                m_serializationArchive.decode(
3990                    selection_data.get_data(), selection_data.get_length()
3991                );
3992                applyMacro(m_serializationArchive);
3993            } catch (Serialization::Exception e) {
3994                errorText = e.Message;
3995            } catch (...) {
3996                errorText = _("Unknown exception while pasting DimensionRegion");
3997            }
3998            if (!errorText.empty()) {
3999                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
4000                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4001                msg.run();
4002            }
4003        }
4004    }
4005    
4006    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
4007        const bool bDimensionRegionPasteIsPossible =
4008            std::find(targets.begin(), targets.end(),
4009                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
4010    
4011        static_cast<Gtk::MenuItem*>(
4012            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
4013        )->set_sensitive(bDimensionRegionPasteIsPossible);
4014    
4015        static_cast<Gtk::MenuItem*>(
4016            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
4017        )->set_sensitive(bDimensionRegionPasteIsPossible);
4018  }  }
4019    
4020  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 4072  sigc::signal<void, int/*key*/, int/*velo
4072  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
4073      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
4074  }  }
4075    
4076    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
4077        return switch_sampler_instrument_signal;
4078    }

Legend:
Removed from v.2566  
changed lines
  Added in v.3258

  ViewVC Help
Powered by ViewVC