/[svn]/gigedit/trunk/src/gigedit/mainwindow.cpp
ViewVC logotype

Diff of /gigedit/trunk/src/gigedit/mainwindow.cpp

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 2579 by persson, Sat May 24 06:44:39 2014 UTC revision 3339 by schoenebeck, Sun Jul 30 18:57:35 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    static const Gdk::ModifierType primaryModifierKey =
70        #if defined(__APPLE__)
71        Gdk::META_MASK; // Cmd key on Mac
72        #else
73        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
74        #endif
75    
76  MainWindow::MainWindow() :  MainWindow::MainWindow() :
77        m_DimRegionChooser(*this),
78      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
79      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
80      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
81      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
82        labelLegend(_("Legend:")),
83        labelNoSample(_(" No Sample")),
84        labelMissingSample(_(" Missing some Sample(s)")),
85        labelLooped(_(" Looped")),
86        labelSomeLoops(_(" Some Loop(s)"))
87  {  {
88        loadBuiltInPix();
89    
90        this->file = NULL;
91    
92  //    set_border_width(5);  //    set_border_width(5);
 //    set_default_size(400, 200);  
93    
94        if (!Settings::singleton()->autoRestoreWindowDimension) {
95            set_default_size(800, 600);
96            set_position(Gtk::WIN_POS_CENTER);
97        }
98    
99      add(m_VBox);      add(m_VBox);
100    
# Line 78  MainWindow::MainWindow() : Line 115  MainWindow::MainWindow() :
115      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
116      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
117    
118        m_ScrolledWindowScripts.add(m_TreeViewScripts);
119        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
120    
121    
122      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
123    
# Line 89  MainWindow::MainWindow() : Line 129  MainWindow::MainWindow() :
129      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
130      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
131      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
132        {
133            legend_hbox.add(labelLegend);
134    
135            imageNoSample.set(redDot);
136            imageNoSample.set_alignment(Gtk::ALIGN_END);
137            labelNoSample.set_alignment(Gtk::ALIGN_START);
138            legend_hbox.add(imageNoSample);
139            legend_hbox.add(labelNoSample);
140    
141            imageMissingSample.set(yellowDot);
142            imageMissingSample.set_alignment(Gtk::ALIGN_END);
143            labelMissingSample.set_alignment(Gtk::ALIGN_START);
144            legend_hbox.add(imageMissingSample);
145            legend_hbox.add(labelMissingSample);
146    
147            imageLooped.set(blackLoop);
148            imageLooped.set_alignment(Gtk::ALIGN_END);
149            labelLooped.set_alignment(Gtk::ALIGN_START);
150            legend_hbox.add(imageLooped);
151            legend_hbox.add(labelLooped);
152    
153            imageSomeLoops.set(grayLoop);
154            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
155            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
156            legend_hbox.add(imageSomeLoops);
157            legend_hbox.add(labelSomeLoops);
158    
159            legend_hbox.show_all_children();
160        }
161        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
162      m_HPaned.add2(dimreg_vbox);      m_HPaned.add2(dimreg_vbox);
163    
164      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 168  MainWindow::MainWindow() :
168    
169      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
170      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
171        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
172    
173      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
174    
# Line 130  MainWindow::MainWindow() : Line 200  MainWindow::MainWindow() :
200                       sigc::mem_fun(                       sigc::mem_fun(
201                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
202      actionGroup->add(Gtk::Action::create("MidiRules",      actionGroup->add(Gtk::Action::create("MidiRules",
203                                           _("_Midi Rules")),                                           _("_Midi Rules...")),
204                       sigc::mem_fun(                       sigc::mem_fun(
205                           *this, &MainWindow::show_midi_rules));                           *this, &MainWindow::show_midi_rules));
206        actionGroup->add(Gtk::Action::create("ScriptSlots",
207                                             _("_Script Slots...")),
208                         sigc::mem_fun(
209                             *this, &MainWindow::show_script_slots));
210      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),
211                       sigc::mem_fun(                       sigc::mem_fun(
212                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
213      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
214            Gtk::Action::create("MenuSample", _("_Sample")),
215            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
216        );
217        actionGroup->add(
218            Gtk::Action::create("MenuInstrument", _("_Instrument")),
219            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
220        );
221        actionGroup->add(
222            Gtk::Action::create("MenuScript", _("Scr_ipt")),
223            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
224        );
225        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
226        actionGroup->add(Gtk::Action::create("AssignScripts", _("Assign Script")));
227    
228      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
229    
230        const Gdk::ModifierType primaryModifierKey =
231    #if defined(__APPLE__)
232        Gdk::META_MASK; // Cmd key on Mac
233    #else
234        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
235    #endif
236    
237        actionGroup->add(Gtk::Action::create("CopyDimRgn",
238                                             _("Copy selected dimension region")),
239                         Gtk::AccelKey(GDK_KEY_c, Gdk::MOD1_MASK),
240                         sigc::mem_fun(*this, &MainWindow::copy_selected_dimrgn));
241    
242        actionGroup->add(Gtk::Action::create("PasteDimRgn",
243                                             _("Paste dimension region")),
244                         Gtk::AccelKey(GDK_KEY_v, Gdk::MOD1_MASK),
245                         sigc::mem_fun(*this, &MainWindow::paste_copied_dimrgn));
246    
247        actionGroup->add(Gtk::Action::create("AdjustClipboard",
248                                             _("Adjust Clipboard Content")),
249                         Gtk::AccelKey(GDK_KEY_x, Gdk::MOD1_MASK),
250                         sigc::mem_fun(*this, &MainWindow::adjust_clipboard_content));
251    
252        actionGroup->add(Gtk::Action::create("SelectPrevInstr",
253                                             _("Select Previous Instrument")),
254                         Gtk::AccelKey(GDK_KEY_Up, primaryModifierKey),
255                         sigc::mem_fun(*this, &MainWindow::select_prev_instrument));
256    
257        actionGroup->add(Gtk::Action::create("SelectNextInstr",
258                                             _("Select Next Instrument")),
259                         Gtk::AccelKey(GDK_KEY_Down, primaryModifierKey),
260                         sigc::mem_fun(*this, &MainWindow::select_next_instrument));
261    
262        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
263                                             _("Select Previous Region")),
264                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
265                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
266    
267        actionGroup->add(Gtk::Action::create("SelectNextRegion",
268                                             _("Select Next Region")),
269                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
270                         sigc::mem_fun(*this, &MainWindow::select_next_region));
271    
272        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
273                                             _("Select Previous Dimension Region Zone")),
274                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
275                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
276    
277        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
278                                             _("Select Next Dimension Region Zone")),
279                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
280                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
281    
282        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
283                                             _("Select Previous Dimension")),
284                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
285                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
286    
287        actionGroup->add(Gtk::Action::create("SelectNextDimension",
288                                             _("Select Next Dimension")),
289                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
290                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
291    
292        actionGroup->add(Gtk::Action::create("SelectAddPrevDimRgnZone",
293                                             _("Add Previous Dimension Region Zone to Selection")),
294                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
295                         sigc::mem_fun(*this, &MainWindow::select_add_prev_dim_rgn_zone));
296    
297        actionGroup->add(Gtk::Action::create("SelectAddNextDimRgnZone",
298                                             _("Add Next Dimension Region Zone to Selection")),
299                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK | Gdk::SHIFT_MASK),
300                         sigc::mem_fun(*this, &MainWindow::select_add_next_dim_rgn_zone));
301    
302      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
303          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
304      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 157  MainWindow::MainWindow() : Line 315  MainWindow::MainWindow() :
315      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
316    
317    
318      actionGroup->add(Gtk::Action::create("MenuView", _("_View")));      actionGroup->add(Gtk::Action::create("MenuMacro", _("_Macro")));
319    
320    
321        actionGroup->add(Gtk::Action::create("MenuView", _("Vie_w")));
322      toggle_action =      toggle_action =
323          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
324      toggle_action->set_active(true);      toggle_action->set_active(true);
# Line 165  MainWindow::MainWindow() : Line 326  MainWindow::MainWindow() :
326                       sigc::mem_fun(                       sigc::mem_fun(
327                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
328    
329        toggle_action =
330            Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
331        toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
332        actionGroup->add(toggle_action,
333                         sigc::mem_fun(
334                             *this, &MainWindow::on_auto_restore_win_dim));
335    
336        toggle_action =
337            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
338        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
339        actionGroup->add(toggle_action,
340                         sigc::mem_fun(
341                             *this, &MainWindow::on_save_with_temporary_file));
342    
343        actionGroup->add(
344            Gtk::Action::create("RefreshAll", _("_Refresh All")),
345            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
346        );                
347    
348      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);
349      actionGroup->add(Gtk::Action::create("MenuHelp",      actionGroup->add(Gtk::Action::create("MenuHelp",
350                                           action->property_label()));                                           action->property_label()));
# Line 180  MainWindow::MainWindow() : Line 360  MainWindow::MainWindow() :
360          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
361      );      );
362      actionGroup->add(      actionGroup->add(
363            Gtk::Action::create("CombInstruments", _("_Combine Instruments ...")),
364            Gtk::AccelKey(GDK_KEY_j, primaryModifierKey),
365            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
366        );
367        actionGroup->add(
368          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),
369          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
370      );      );
# Line 195  MainWindow::MainWindow() : Line 380  MainWindow::MainWindow() :
380          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)          sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
381      );      );
382    
383        toggle_action =
384            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
385        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
386        actionGroup->add(
387            toggle_action,
388            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
389        );
390    
391        toggle_action =
392            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
393        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
394        actionGroup->add(
395            toggle_action,
396            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
397        );
398    
399    
400      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));      actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
401    
# Line 227  MainWindow::MainWindow() : Line 428  MainWindow::MainWindow() :
428          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
429      );      );
430      actionGroup->add(      actionGroup->add(
431            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
432            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
433        );
434        actionGroup->add(
435            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
436            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
437        );
438        actionGroup->add(
439            Gtk::Action::create("ReplaceSample",
440                                _("Replace Sample...")),
441            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
442        );
443        actionGroup->add(
444          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
445                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
446          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)
447      );      );
448        
449        // script right-click popup actions
450        actionGroup->add(
451            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
452            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
453        );
454        actionGroup->add(
455            Gtk::Action::create("AddScript", _("Add _Script")),
456            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
457        );
458        actionGroup->add(
459            Gtk::Action::create("EditScript", _("_Edit Script...")),
460            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
461        );
462        actionGroup->add(
463            Gtk::Action::create("RemoveScript", Gtk::Stock::REMOVE),
464            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
465        );
466    
467      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
468      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 251  MainWindow::MainWindow() : Line 483  MainWindow::MainWindow() :
483          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
484          "    </menu>"          "    </menu>"
485          "    <menu action='MenuEdit'>"          "    <menu action='MenuEdit'>"
486            "      <menuitem action='CopyDimRgn'/>"
487            "      <menuitem action='AdjustClipboard'/>"
488            "      <menuitem action='PasteDimRgn'/>"
489            "      <separator/>"
490            "      <menuitem action='SelectPrevInstr'/>"
491            "      <menuitem action='SelectNextInstr'/>"
492            "      <separator/>"
493            "      <menuitem action='SelectPrevRegion'/>"
494            "      <menuitem action='SelectNextRegion'/>"
495            "      <separator/>"
496            "      <menuitem action='SelectPrevDimension'/>"
497            "      <menuitem action='SelectNextDimension'/>"
498            "      <menuitem action='SelectPrevDimRgnZone'/>"
499            "      <menuitem action='SelectNextDimRgnZone'/>"
500            "      <menuitem action='SelectAddPrevDimRgnZone'/>"
501            "      <menuitem action='SelectAddNextDimRgnZone'/>"
502            "      <separator/>"
503          "      <menuitem action='CopySampleUnity'/>"          "      <menuitem action='CopySampleUnity'/>"
504          "      <menuitem action='CopySampleTune'/>"          "      <menuitem action='CopySampleTune'/>"
505          "      <menuitem action='CopySampleLoop'/>"          "      <menuitem action='CopySampleLoop'/>"
506          "    </menu>"          "    </menu>"
507            "    <menu action='MenuMacro'>"
508            "    </menu>"
509            "    <menu action='MenuSample'>"
510            "      <menuitem action='SampleProperties'/>"
511            "      <menuitem action='AddGroup'/>"
512            "      <menuitem action='AddSample'/>"
513            "      <menuitem action='ShowSampleRefs'/>"
514            "      <menuitem action='ReplaceSample' />"
515            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
516            "      <separator/>"
517            "      <menuitem action='RemoveSample'/>"
518            "      <menuitem action='RemoveUnusedSamples'/>"
519            "    </menu>"
520          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
521            "      <menu action='AllInstruments'>"
522            "      </menu>"
523            "      <separator/>"
524            "      <menuitem action='InstrProperties'/>"
525            "      <menuitem action='MidiRules'/>"
526            "      <menuitem action='ScriptSlots'/>"
527            "      <menu action='AssignScripts'/>"
528            "      <menuitem action='AddInstrument'/>"
529            "      <menuitem action='DupInstrument'/>"
530            "      <menuitem action='CombInstruments'/>"
531            "      <separator/>"
532            "      <menuitem action='RemoveInstrument'/>"
533            "    </menu>"
534            "    <menu action='MenuScript'>"
535            "      <menuitem action='AddScriptGroup'/>"
536            "      <menuitem action='AddScript'/>"
537            "      <menuitem action='EditScript'/>"
538            "      <separator/>"
539            "      <menuitem action='RemoveScript'/>"
540          "    </menu>"          "    </menu>"
541          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
542          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
543            "      <menuitem action='AutoRestoreWinDim'/>"
544            "      <separator/>"
545            "      <menuitem action='RefreshAll'/>"
546          "    </menu>"          "    </menu>"
547          "    <menu action='MenuTools'>"          "    <menu action='MenuTools'>"
548          "      <menuitem action='CombineInstruments'/>"          "      <menuitem action='CombineInstruments'/>"
# Line 266  MainWindow::MainWindow() : Line 550  MainWindow::MainWindow() :
550          "    </menu>"          "    </menu>"
551          "    <menu action='MenuSettings'>"          "    <menu action='MenuSettings'>"
552          "      <menuitem action='WarnUserOnExtensions'/>"          "      <menuitem action='WarnUserOnExtensions'/>"
553            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
554            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
555            "      <menuitem action='SaveWithTemporaryFile'/>"
556          "    </menu>"          "    </menu>"
557          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
558          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 274  MainWindow::MainWindow() : Line 561  MainWindow::MainWindow() :
561          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
562          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
563          "    <menuitem action='MidiRules'/>"          "    <menuitem action='MidiRules'/>"
564            "    <menuitem action='ScriptSlots'/>"
565          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
566          "    <menuitem action='DupInstrument'/>"          "    <menuitem action='DupInstrument'/>"
567            "    <menuitem action='CombInstruments'/>"
568          "    <separator/>"          "    <separator/>"
569          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
570          "  </popup>"          "  </popup>"
# Line 283  MainWindow::MainWindow() : Line 572  MainWindow::MainWindow() :
572          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
573          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
574          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
575            "    <menuitem action='ShowSampleRefs'/>"
576            "    <menuitem action='ReplaceSample' />"
577          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
578          "    <separator/>"          "    <separator/>"
579          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
580            "    <menuitem action='RemoveUnusedSamples'/>"
581            "  </popup>"
582            "  <popup name='ScriptPopupMenu'>"
583            "    <menuitem action='AddScriptGroup'/>"
584            "    <menuitem action='AddScript'/>"
585            "    <menuitem action='EditScript'/>"
586            "    <separator/>"
587            "    <menuitem action='RemoveScript'/>"
588          "  </popup>"          "  </popup>"
589          "</ui>";          "</ui>";
590      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
# Line 318  MainWindow::MainWindow() : Line 617  MainWindow::MainWindow() :
617      }      }
618      {      {
619          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(          Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
620                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
621            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)."));
622        }
623        {
624            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
625                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
626            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."));
627        }
628        {
629            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
630                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
631            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
632            // copy tooltip to popup menu
633            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
634                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
635            item2->set_tooltip_text(item->get_tooltip_text());
636        }
637        {
638            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
639                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
640            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
641        }
642        {
643            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
644                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
645            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
646        }
647        {
648            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
649              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));              uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
650          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."));
651      }      }
# Line 329  MainWindow::MainWindow() : Line 657  MainWindow::MainWindow() :
657    
658    
659      instrument_menu = static_cast<Gtk::MenuItem*>(      instrument_menu = static_cast<Gtk::MenuItem*>(
660          uiManager->get_widget("/MenuBar/MenuInstrument"))->get_submenu();          uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
661    
662        assign_scripts_menu = static_cast<Gtk::MenuItem*>(
663            uiManager->get_widget("/MenuBar/MenuInstrument/AssignScripts"))->get_submenu();
664    
665      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
666      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
# Line 355  MainWindow::MainWindow() : Line 686  MainWindow::MainWindow() :
686      // Create the Tree model:      // Create the Tree model:
687      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
688      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
689      m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules."));      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
690        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
691      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
692          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
693      );      );
694    
695      // Add the TreeView's view columns:      // Add the TreeView's view columns:
696      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
697      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
698        m_TreeView.append_column(_("Scripts"), m_Columns.m_col_scripts);
699        m_TreeView.set_headers_visible(true);
700        
701        // establish drag&drop within the instrument tree view, allowing to reorder
702        // the sequence of instruments within the gig file
703        {
704            std::vector<Gtk::TargetEntry> drag_target_instrument;
705            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
706            m_TreeView.drag_source_set(drag_target_instrument);
707            m_TreeView.drag_dest_set(drag_target_instrument);
708            m_TreeView.signal_drag_begin().connect(
709                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
710            );
711            m_TreeView.signal_drag_data_get().connect(
712                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
713            );
714            m_TreeView.signal_drag_data_received().connect(
715                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
716            );
717        }
718    
719      // create samples treeview (including its data model)      // create samples treeview (including its data model)
720      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
721      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
722        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
723      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."));
724      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
725      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
726      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
727        {
728            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
729            Gtk::CellRendererText* cellrenderer =
730                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
731            column->add_attribute(
732                cellrenderer->property_foreground(), m_SamplesModel.m_color
733            );
734        }
735        {
736            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
737            Gtk::CellRendererText* cellrenderer =
738                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
739            column->add_attribute(
740                cellrenderer->property_foreground(), m_SamplesModel.m_color
741            );
742        }
743        m_TreeViewSamples.set_headers_visible(true);
744      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
745          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
746      );      );
# Line 378  MainWindow::MainWindow() : Line 748  MainWindow::MainWindow() :
748          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
749      );      );
750    
751        // create scripts treeview (including its data model)
752        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
753        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
754        m_TreeViewScripts.set_tooltip_text(_(
755            "Use CTRL + double click for editing a script."
756            "\n\n"
757            "Note: instrument scripts are a LinuxSampler extension of the gig "
758            "format. This feature will not work with the GigaStudio software!"
759        ));
760        // m_TreeViewScripts.set_reorderable();
761        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
762        m_TreeViewScripts.set_headers_visible(false);
763        m_TreeViewScripts.signal_button_press_event().connect_notify(
764            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
765        );
766        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
767        m_TreeViewScripts.signal_row_activated().connect(
768            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
769        );
770        m_refScriptsTreeModel->signal_row_changed().connect(
771            sigc::mem_fun(*this, &MainWindow::script_name_changed)
772        );
773    
774        // establish drag&drop between scripts tree view and ScriptSlots window
775        std::vector<Gtk::TargetEntry> drag_target_gig_script;
776        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
777        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
778        m_TreeViewScripts.signal_drag_begin().connect(
779            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
780        );
781        m_TreeViewScripts.signal_drag_data_get().connect(
782            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
783        );
784    
785      // 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
786      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
787      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 800  MainWindow::MainWindow() :
800          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
801      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
802          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
803        m_RegionChooser.signal_instrument_changed().connect(
804            sigc::mem_fun(*this, &MainWindow::region_changed));
805      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
806          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
807      instrumentProps.signal_changed().connect(      instrumentProps.signal_changed().connect(
# Line 411  MainWindow::MainWindow() : Line 817  MainWindow::MainWindow() :
817          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
818      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
819          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
820        sample_ref_changed_signal.connect(
821            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
822        );
823        samples_to_be_removed_signal.connect(
824            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
825        );
826    
827        dimreg_edit.signal_select_sample().connect(
828            sigc::mem_fun(*this, &MainWindow::select_sample)
829        );
830    
831      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
832          sigc::hide(          sigc::hide(
# Line 455  MainWindow::MainWindow() : Line 871  MainWindow::MainWindow() :
871    
872      // select 'Instruments' tab by default      // select 'Instruments' tab by default
873      // (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)
874      m_TreeViewNotebook.set_current_page(1);      m_TreeViewNotebook.set_current_page(1);
875    
876        Gtk::Clipboard::get()->signal_owner_change().connect(
877            sigc::mem_fun(*this, &MainWindow::on_clipboard_owner_change)
878        );
879        updateClipboardPasteAvailable();
880        updateClipboardCopyAvailable();
881    
882        // setup macros and their keyboard accelerators
883        {
884            Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
885                uiManager->get_widget("/MenuBar/MenuMacro")
886            )->get_submenu();
887    
888            const Gdk::ModifierType noModifier = (Gdk::ModifierType)0;
889            Gtk::AccelMap::add_entry("<Macros>/macro_0", GDK_KEY_F1, noModifier);
890            Gtk::AccelMap::add_entry("<Macros>/macro_1", GDK_KEY_F2, noModifier);
891            Gtk::AccelMap::add_entry("<Macros>/macro_2", GDK_KEY_F3, noModifier);
892            Gtk::AccelMap::add_entry("<Macros>/macro_3", GDK_KEY_F4, noModifier);
893            Gtk::AccelMap::add_entry("<Macros>/macro_4", GDK_KEY_F5, noModifier);
894            Gtk::AccelMap::add_entry("<Macros>/macro_5", GDK_KEY_F6, noModifier);
895            Gtk::AccelMap::add_entry("<Macros>/macro_6", GDK_KEY_F7, noModifier);
896            Gtk::AccelMap::add_entry("<Macros>/macro_7", GDK_KEY_F8, noModifier);
897            Gtk::AccelMap::add_entry("<Macros>/macro_8", GDK_KEY_F9, noModifier);
898            Gtk::AccelMap::add_entry("<Macros>/macro_9", GDK_KEY_F10, noModifier);
899            Gtk::AccelMap::add_entry("<Macros>/macro_10", GDK_KEY_F11, noModifier);
900            Gtk::AccelMap::add_entry("<Macros>/macro_11", GDK_KEY_F12, noModifier);
901            Gtk::AccelMap::add_entry("<Macros>/SetupMacros", 'm', primaryModifierKey);
902    
903            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
904            menuMacro->set_accel_group(accelGroup);
905    
906            updateMacroMenu();
907        }
908    
909        // setup "Assign Scripts" keyboard accelerators
910        {
911            Gtk::AccelMap::add_entry("<Scripts>/script_0", GDK_KEY_F1, Gdk::SHIFT_MASK);
912            Gtk::AccelMap::add_entry("<Scripts>/script_1", GDK_KEY_F2, Gdk::SHIFT_MASK);
913            Gtk::AccelMap::add_entry("<Scripts>/script_2", GDK_KEY_F3, Gdk::SHIFT_MASK);
914            Gtk::AccelMap::add_entry("<Scripts>/script_3", GDK_KEY_F4, Gdk::SHIFT_MASK);
915            Gtk::AccelMap::add_entry("<Scripts>/script_4", GDK_KEY_F5, Gdk::SHIFT_MASK);
916            Gtk::AccelMap::add_entry("<Scripts>/script_5", GDK_KEY_F6, Gdk::SHIFT_MASK);
917            Gtk::AccelMap::add_entry("<Scripts>/script_6", GDK_KEY_F7, Gdk::SHIFT_MASK);
918            Gtk::AccelMap::add_entry("<Scripts>/script_7", GDK_KEY_F8, Gdk::SHIFT_MASK);
919            Gtk::AccelMap::add_entry("<Scripts>/script_8", GDK_KEY_F9, Gdk::SHIFT_MASK);
920            Gtk::AccelMap::add_entry("<Scripts>/script_9", GDK_KEY_F10, Gdk::SHIFT_MASK);
921            Gtk::AccelMap::add_entry("<Scripts>/script_10", GDK_KEY_F11, Gdk::SHIFT_MASK);
922            Gtk::AccelMap::add_entry("<Scripts>/script_11", GDK_KEY_F12, Gdk::SHIFT_MASK);
923    
924            Glib::RefPtr<Gtk::AccelGroup> accelGroup = this->get_accel_group();
925            assign_scripts_menu->set_accel_group(accelGroup);
926        }
927    
928        Glib::signal_idle().connect_once(
929            sigc::mem_fun(*this, &MainWindow::bringToFront),
930            200
931        );
932  }  }
933    
934  MainWindow::~MainWindow()  MainWindow::~MainWindow()
935  {  {
936  }  }
937    
938    void MainWindow::bringToFront() {
939        #if defined(__APPLE__)
940        macRaiseAppWindow();
941        #endif
942        raise();
943        present();
944    }
945    
946    void MainWindow::updateMacroMenu() {
947        Gtk::Menu* menuMacro = dynamic_cast<Gtk::MenuItem*>(
948            uiManager->get_widget("/MenuBar/MenuMacro")
949        )->get_submenu();
950    
951        // remove all entries from "Macro" menu
952        {
953            const std::vector<Gtk::Widget*> children = menuMacro->get_children();
954            for (int i = 0; i < children.size(); ++i) {
955                Gtk::Widget* child = children[i];
956                menuMacro->remove(*child);
957                delete child;
958            }
959        }
960    
961        // (re)load all macros from config file
962        try {
963            Settings::singleton()->loadMacros(m_macros);
964        } catch (Serialization::Exception e) {
965            std::cerr << "Exception while loading macros: " << e.Message << std::endl;
966        } catch (...) {
967            std::cerr << "Unknown exception while loading macros!" << std::endl;
968        }
969    
970        // add all configured macros as menu items to the "Macro" menu
971        for (int iMacro = 0; iMacro < m_macros.size(); ++iMacro) {
972            const Serialization::Archive& macro = m_macros[iMacro];
973            std::string name =
974                macro.name().empty() ?
975                    (std::string(_("Unnamed Macro")) + " " + ToString(iMacro+1)) : macro.name();
976            Gtk::MenuItem* item = new Gtk::MenuItem(name);
977            item->signal_activate().connect(
978                sigc::bind(
979                    sigc::mem_fun(*this, &MainWindow::onMacroSelected), iMacro
980                )
981            );
982            menuMacro->append(*item);
983            item->set_accel_path("<Macros>/macro_" + ToString(iMacro));
984            Glib::ustring comment = macro.comment();
985            if (!comment.empty())
986                item->set_tooltip_text(comment);
987        }
988        // if there are no macros configured at all, then show a dummy entry instead
989        if (m_macros.empty()) {
990            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Macros"));
991            item->set_sensitive(false);
992            menuMacro->append(*item);
993        }
994    
995        // add separator line to menu
996        menuMacro->append(*new Gtk::SeparatorMenuItem);
997    
998        {
999            Gtk::MenuItem* item = new Gtk::MenuItem(_("Setup Macros ..."));
1000            item->signal_activate().connect(
1001                sigc::mem_fun(*this, &MainWindow::setupMacros)
1002            );
1003            menuMacro->append(*item);
1004            item->set_accel_path("<Macros>/SetupMacros");
1005        }
1006    
1007        menuMacro->show_all_children();
1008    }
1009    
1010    void MainWindow::onMacroSelected(int iMacro) {
1011        printf("onMacroSelected(%d)\n", iMacro);
1012        if (iMacro < 0 || iMacro >= m_macros.size()) return;
1013        Glib::ustring errorText;
1014        try {
1015            applyMacro(m_macros[iMacro]);
1016        } catch (Serialization::Exception e) {
1017            errorText = e.Message;
1018        } catch (...) {
1019            errorText = _("Unknown exception while applying macro");
1020        }
1021        if (!errorText.empty()) {
1022            Glib::ustring txt = _("Applying macro failed:\n") + errorText;
1023            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1024            msg.run();
1025        }
1026    }
1027    
1028    void MainWindow::setupMacros() {
1029        MacrosSetup* setup = new MacrosSetup();
1030        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
1031        setup->setMacros(m_macros, &m_serializationArchive, pDimRgn);
1032        setup->signal_macros_changed().connect(
1033            sigc::mem_fun(*this, &MainWindow::onMacrosSetupChanged)
1034        );
1035        setup->show();
1036    }
1037    
1038    void MainWindow::onMacrosSetupChanged(const std::vector<Serialization::Archive>& macros) {
1039        m_macros = macros;
1040        Settings::singleton()->saveMacros(m_macros);
1041        updateMacroMenu();
1042    }
1043    
1044  bool MainWindow::on_delete_event(GdkEventAny* event)  bool MainWindow::on_delete_event(GdkEventAny* event)
1045  {  {
1046      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 1060  void MainWindow::region_changed()
1060  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
1061  {  {
1062      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
1063      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1064          m_TreeView.get_selection()->get_selected();      if (rows.empty()) return NULL;
1065        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
1066      if (it) {      if (it) {
1067          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
1068          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 525  void MainWindow::update_dimregs() Line 1105  void MainWindow::update_dimregs()
1105              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
1106          }          }
1107      }      }
1108    
1109        m_RegionChooser.setModifyAllRegions(all_regions);
1110        m_DimRegionChooser.setModifyAllRegions(all_regions);
1111        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
1112        m_DimRegionChooser.setModifyBothChannels(stereo);
1113    
1114        updateClipboardCopyAvailable();
1115  }  }
1116    
1117  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 536  void MainWindow::dimreg_all_dimregs_togg Line 1123  void MainWindow::dimreg_all_dimregs_togg
1123  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
1124  {  {
1125      update_dimregs();      update_dimregs();
1126      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
1127  }  }
1128    
1129  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
1130  {  {
1131      // select item in instrument menu      // select item in instrument menu
1132      Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1133      if (it) {      if (!rows.empty()) {
1134          Gtk::TreePath path(it);          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
1135          int index = path[0];          if (it) {
1136          const std::vector<Gtk::Widget*> children =              Gtk::TreePath path(it);
1137              instrument_menu->get_children();              int index = path[0];
1138          static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();              const std::vector<Gtk::Widget*> children =
1139                    instrument_menu->get_children();
1140                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
1141            }
1142      }      }
1143    
1144        updateScriptListOfMenu();
1145    
1146      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
1147    
1148        if (Settings::singleton()->syncSamplerInstrumentSelection) {
1149            switch_sampler_instrument_signal.emit(get_instrument());
1150        }
1151  }  }
1152    
1153  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 1165  void Loader::progress_callback(float fra
1165      progress_dispatcher();      progress_dispatcher();
1166  }  }
1167    
1168    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1169    // make sure stack is 16-byte aligned for SSE instructions
1170    __attribute__((force_align_arg_pointer))
1171    #endif
1172  void Loader::thread_function()  void Loader::thread_function()
1173  {  {
1174      printf("thread_function self=%x\n", Glib::Threads::Thread::self());      printf("thread_function self=%p\n",
1175      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1176      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
1177      gig = new gig::File(riff);      try {
1178      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
1179      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
1180      progress.custom = this;          gig::progress_t progress;
1181            progress.callback = loader_progress_callback;
1182      gig->GetInstrument(0, &progress);          progress.custom = this;
1183      printf("End\n");  
1184      finished_dispatcher();          gig->GetInstrument(0, &progress);
1185            printf("End\n");
1186            finished_dispatcher();
1187        } catch (RIFF::Exception e) {
1188            error_message = e.Message;
1189            error_dispatcher.emit();
1190        } catch (...) {
1191            error_message = _("Unknown exception occurred");
1192            error_dispatcher.emit();
1193        }
1194  }  }
1195    
1196  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
1197      : filename(filename), thread(0)      : filename(filename), gig(0), thread(0), progress(0.f)
1198  {  {
1199  }  }
1200    
# Line 596  void Loader::launch() Line 1205  void Loader::launch()
1205  #else  #else
1206      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
1207  #endif  #endif
1208      printf("launch thread=%x\n", thread);      printf("launch thread=%p\n", static_cast<void*>(thread));
1209  }  }
1210    
1211  float Loader::get_progress()  float Loader::get_progress()
# Line 619  Glib::Dispatcher& Loader::signal_finishe Line 1228  Glib::Dispatcher& Loader::signal_finishe
1228      return finished_dispatcher;      return finished_dispatcher;
1229  }  }
1230    
1231  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
1232    {
1233        return error_dispatcher;
1234    }
1235    
1236    void saver_progress_callback(gig::progress_t* progress)
1237    {
1238        Saver* saver = static_cast<Saver*>(progress->custom);
1239        saver->progress_callback(progress->factor);
1240    }
1241    
1242    void Saver::progress_callback(float fraction)
1243    {
1244        {
1245            Glib::Threads::Mutex::Lock lock(progressMutex);
1246            progress = fraction;
1247        }
1248        progress_dispatcher.emit();
1249    }
1250    
1251    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1252    // make sure stack is 16-byte aligned for SSE instructions
1253    __attribute__((force_align_arg_pointer))
1254    #endif
1255    void Saver::thread_function()
1256    {
1257        printf("thread_function self=%p\n",
1258               static_cast<void*>(Glib::Threads::Thread::self()));
1259        printf("Start %s\n", filename.c_str());
1260        try {
1261            gig::progress_t progress;
1262            progress.callback = saver_progress_callback;
1263            progress.custom = this;
1264    
1265            // if no filename was provided, that means "save", if filename was provided means "save as"
1266            if (filename.empty()) {
1267                if (!Settings::singleton()->saveWithTemporaryFile) {
1268                    // save directly over the existing .gig file
1269                    // (requires less disk space than solution below
1270                    // but may be slower)
1271                    gig->Save(&progress);
1272                } else {
1273                    // save the file as separate temporary file first,
1274                    // then move the saved file over the old file
1275                    // (may result in performance speedup during save)
1276                    gig::String tmpname = filename + ".TMP";
1277                    gig->Save(tmpname, &progress);
1278                    #if defined(WIN32)
1279                    if (!DeleteFile(filename.c_str())) {
1280                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1281                    }
1282                    #else // POSIX ...
1283                    if (unlink(filename.c_str())) {
1284                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + gig::String(strerror(errno)));
1285                    }
1286                    #endif
1287                    if (rename(tmpname.c_str(), filename.c_str())) {
1288                        #if defined(WIN32)
1289                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1290                        #else
1291                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + gig::String(strerror(errno)));
1292                        #endif
1293                    }
1294                }
1295            } else {
1296                gig->Save(filename, &progress);
1297            }
1298    
1299            printf("End\n");
1300            finished_dispatcher.emit();
1301        } catch (RIFF::Exception e) {
1302            error_message = e.Message;
1303            error_dispatcher.emit();
1304        } catch (...) {
1305            error_message = _("Unknown exception occurred");
1306            error_dispatcher.emit();
1307        }
1308    }
1309    
1310    Saver::Saver(gig::File* file, Glib::ustring filename)
1311        : gig(file), filename(filename), thread(0), progress(0.f)
1312    {
1313    }
1314    
1315    void Saver::launch()
1316    {
1317    #ifdef OLD_THREADS
1318        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1319    #else
1320        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1321    #endif
1322        printf("launch thread=%p\n", static_cast<void*>(thread));
1323    }
1324    
1325    float Saver::get_progress()
1326    {
1327        float res;
1328        {
1329            Glib::Threads::Mutex::Lock lock(progressMutex);
1330            res = progress;
1331        }
1332        return res;
1333    }
1334    
1335    Glib::Dispatcher& Saver::signal_progress()
1336    {
1337        return progress_dispatcher;
1338    }
1339    
1340    Glib::Dispatcher& Saver::signal_finished()
1341    {
1342        return finished_dispatcher;
1343    }
1344    
1345    Glib::Dispatcher& Saver::signal_error()
1346    {
1347        return error_dispatcher;
1348    }
1349    
1350    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1351      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1352  {  {
1353      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1354      show_all_children();      show_all_children();
1355        resize(600,50);
1356  }  }
1357    
1358  // 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 1363  void MainWindow::__clear() {
1363      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1364      m_refTreeModel->clear();      m_refTreeModel->clear();
1365      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1366        m_refScriptsTreeModel->clear();
1367      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1368      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1369          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 648  void MainWindow::__refreshEntireGUI() { Line 1378  void MainWindow::__refreshEntireGUI() {
1378      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1379      m_refTreeModel->clear();      m_refTreeModel->clear();
1380      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1381        m_refScriptsTreeModel->clear();
1382      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1383      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1384          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 690  bool MainWindow::close_confirmation_dial Line 1421  bool MainWindow::close_confirmation_dial
1421      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1422      int response = dialog.run();      int response = dialog.run();
1423      dialog.hide();      dialog.hide();
1424      if (response == Gtk::RESPONSE_YES) return file_save();  
1425      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1426        if (response == Gtk::RESPONSE_NO) return true;
1427    
1428        // user cancelled dialog, thus don't close app
1429        if (response == Gtk::RESPONSE_CANCEL) return false;
1430    
1431        // TODO: the following return valid is disabled and hard coded instead for
1432        // now, due to the fact that saving with progress bar is now implemented
1433        // asynchronously, as a result the app does not close automatically anymore
1434        // after saving the file has completed
1435        //
1436        //   if (response == Gtk::RESPONSE_YES) return file_save();
1437        //   return response != Gtk::RESPONSE_CANCEL;
1438        //
1439        if (response == Gtk::RESPONSE_YES) file_save();
1440        return false; // always prevent closing the app for now (see comment above)
1441  }  }
1442    
1443  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 733  void MainWindow::on_action_file_open() Line 1479  void MainWindow::on_action_file_open()
1479      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1480          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1481          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1482          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());          printf("on_action_file_open self=%p\n",
1483                   static_cast<void*>(Glib::Threads::Thread::self()));
1484          load_file(filename.c_str());          load_file(filename.c_str());
1485          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1486      }      }
# Line 742  void MainWindow::on_action_file_open() Line 1489  void MainWindow::on_action_file_open()
1489  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1490  {  {
1491      __clear();      __clear();
1492      load_dialog = new LoadDialog(_("Loading..."), *this);  
1493      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1494      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1495            Glib::filename_display_basename(name) + "' ...",
1496            *this
1497        );
1498        progress_dialog->show_all();
1499        loader = new Loader(name); //FIXME: memory leak!
1500      loader->signal_progress().connect(      loader->signal_progress().connect(
1501          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1502      loader->signal_finished().connect(      loader->signal_finished().connect(
1503          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1504        loader->signal_error().connect(
1505            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1506      loader->launch();      loader->launch();
1507  }  }
1508    
# Line 764  void MainWindow::load_instrument(gig::In Line 1518  void MainWindow::load_instrument(gig::In
1518      // load the instrument      // load the instrument
1519      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1520      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1521      //TODO: automatically select the given instrument      // automatically select the given instrument
1522        int i = 0;
1523        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1524             instrument = pFile->GetNextInstrument(), ++i)
1525        {
1526            if (instrument == instr) {
1527                // select item in "instruments" tree view
1528                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1529                // make sure the selected item in the "instruments" tree view is
1530                // visible (scroll to it)
1531                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1532                // select item in instrument menu
1533                {
1534                    const std::vector<Gtk::Widget*> children =
1535                        instrument_menu->get_children();
1536                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1537                }
1538                // update region chooser and dimension region chooser
1539                m_RegionChooser.set_instrument(instr);
1540                break;
1541            }
1542        }
1543  }  }
1544    
1545  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1546  {  {
1547      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1548  }  }
1549    
1550  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1551  {  {
1552      printf("Loader finished!\n");      printf("Loader finished!\n");
1553      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());      printf("on_loader_finished self=%p\n",
1554      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1555      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1556        progress_dialog->hide();
1557    }
1558    
1559    void MainWindow::on_loader_error()
1560    {
1561        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1562        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1563        msg.run();
1564        progress_dialog->hide();
1565  }  }
1566    
1567  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 816  bool MainWindow::file_save() Line 1600  bool MainWindow::file_save()
1600    
1601      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1602      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1603      try {  
1604          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1605          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1606              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1607              file_is_changed = false;          *this
1608          }      );
1609      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1610          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1611          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1612          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1613          msg.run();      saver->signal_finished().connect(
1614          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1615      }      saver->signal_error().connect(
1616      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1617        saver->launch();
1618    
1619        return true;
1620    }
1621    
1622    void MainWindow::on_saver_progress()
1623    {
1624        progress_dialog->set_fraction(saver->get_progress());
1625    }
1626    
1627    void MainWindow::on_saver_error()
1628    {
1629        file_structure_changed_signal.emit(this->file);
1630        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1631        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1632        msg.run();
1633    }
1634    
1635    void MainWindow::on_saver_finished()
1636    {
1637        this->file = saver->gig;
1638        this->filename = saver->filename;
1639        current_gig_dir = Glib::path_get_dirname(filename);
1640        set_title(Glib::filename_display_basename(filename));
1641        file_has_name = true;
1642        file_is_changed = false;
1643        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1644      __import_queued_samples();      __import_queued_samples();
1645        std::cout << "Importing queued samples done.\n" << std::flush;
1646    
1647      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1648      return true;  
1649        __refreshEntireGUI();
1650        progress_dialog->hide();
1651  }  }
1652    
1653  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 876  bool MainWindow::file_save_as() Line 1691  bool MainWindow::file_save_as()
1691      // show warning in the dialog      // show warning in the dialog
1692      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
1693      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
1694      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
1695        warningIcon.set_from_icon_name("dialog-warning",
1696                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1697      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1698  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
1699      view::WrapLabel description;      view::WrapLabel description;
# Line 897  bool MainWindow::file_save_as() Line 1714  bool MainWindow::file_save_as()
1714      descriptionArea.show_all();      descriptionArea.show_all();
1715    
1716      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1717          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1718          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1719              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;  
1720          }          }
1721          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1722          file_structure_changed_signal.emit(this->file);  
1723            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1724                _("Saving") +  Glib::ustring(" '") +
1725                Glib::filename_display_basename(filename) + "' ...",
1726                *this
1727            );
1728            progress_dialog->show_all();
1729    
1730            saver = new Saver(file, filename); //FIXME: memory leak!
1731            saver->signal_progress().connect(
1732                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1733            saver->signal_finished().connect(
1734                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1735            saver->signal_error().connect(
1736                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1737            saver->launch();
1738    
1739          return true;          return true;
1740      }      }
1741      return false;      return false;
# Line 928  bool MainWindow::file_save_as() Line 1745  bool MainWindow::file_save_as()
1745  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1746      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1747      Glib::ustring error_files;      Glib::ustring error_files;
1748      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1749      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1750           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1751          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1752          SF_INFO info;          SF_INFO info;
1753          info.format = 0;          info.format = 0;
1754          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);
1755          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1756          try {          try {
1757              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 1774  void MainWindow::__import_queued_samples
1774                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1775              }              }
1776    
1777                // reset write position for sample
1778                iter->first->SetPos(0);
1779    
1780              const int bufsize = 10000;              const int bufsize = 10000;
1781              switch (bitdepth) {              switch (bitdepth) {
1782                  case 16: {                  case 16: {
# Line 966  void MainWindow::__import_queued_samples Line 1786  void MainWindow::__import_queued_samples
1786                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1787                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1788                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1789                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1790                          cnt -= n;                          cnt -= n;
1791                      }                      }
1792                      delete[] buffer;                      delete[] buffer;
# Line 986  void MainWindow::__import_queued_samples Line 1806  void MainWindow::__import_queued_samples
1806                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1807                          }                          }
1808                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1809                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1810                          cnt -= n;                          cnt -= n;
1811                      }                      }
1812                      delete[] srcbuf;                      delete[] srcbuf;
# Line 997  void MainWindow::__import_queued_samples Line 1817  void MainWindow::__import_queued_samples
1817              // cleanup              // cleanup
1818              sf_close(hFile);              sf_close(hFile);
1819              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
1820              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
1821              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1822              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1823              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1824              ++iter;              ++iter;
1825              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1826          } catch (std::string what) {          } catch (std::string what) {
1827              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1828              if (!error_files.empty()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1829              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1830              ++iter;              ++iter;
1831          }          }
1832      }      }
# Line 1029  void MainWindow::on_action_warn_user_on_ Line 1849  void MainWindow::on_action_warn_user_on_
1849          !Settings::singleton()->warnUserOnExtensions;          !Settings::singleton()->warnUserOnExtensions;
1850  }  }
1851    
1852    void MainWindow::on_action_sync_sampler_instrument_selection() {
1853        Settings::singleton()->syncSamplerInstrumentSelection =
1854            !Settings::singleton()->syncSamplerInstrumentSelection;
1855    }
1856    
1857    void MainWindow::on_action_move_root_note_with_region_moved() {
1858        Settings::singleton()->moveRootNoteWithRegionMoved =
1859            !Settings::singleton()->moveRootNoteWithRegionMoved;
1860    }
1861    
1862  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1863  {  {
1864      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
# Line 1038  void MainWindow::on_action_help_about() Line 1868  void MainWindow::on_action_help_about()
1868      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
1869  #endif  #endif
1870      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1871      dialog.set_copyright("Copyright (C) 2006-2014 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1872      const std::string sComment =      const std::string sComment =
1873          _("Built " __DATE__ "\nUsing ") +          _("Built " __DATE__ "\nUsing ") +
1874          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1875          _(          _(
1876              "Gigedit is released under the GNU General Public License.\n"              "Gigedit is released under the GNU General Public License.\n"
1877              "\n"              "\n"
1878              "Please notice that this is still a very young instrument editor. "              "This program is distributed WITHOUT ANY WARRANTY; So better "
1879              "So better backup your Gigasampler files before editing them with "              "backup your Gigasampler/GigaStudio files before editing them with "
1880              "this application.\n"              "this application.\n"
1881              "\n"              "\n"
1882              "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 1884  void MainWindow::on_action_help_about()
1884      dialog.set_comments(sComment.c_str());      dialog.set_comments(sComment.c_str());
1885      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1886      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1887        dialog.set_position(Gtk::WIN_POS_CENTER);
1888      dialog.run();      dialog.run();
1889  }  }
1890    
# Line 1079  PropDialog::PropDialog() Line 1910  PropDialog::PropDialog()
1910        table(2, 1),        table(2, 1),
1911        m_file(NULL)        m_file(NULL)
1912  {  {
1913        if (!Settings::singleton()->autoRestoreWindowDimension) {
1914            set_default_size(470, 390);
1915            set_position(Gtk::WIN_POS_MOUSE);
1916        }
1917    
1918      set_title(_("File Properties"));      set_title(_("File Properties"));
1919      eName.set_width_chars(50);      eName.set_width_chars(50);
1920    
# Line 1213  InstrumentProps::InstrumentProps() : Line 2049  InstrumentProps::InstrumentProps() :
2049      eDimensionKeyRangeLow(_("Keyswitching range low")),      eDimensionKeyRangeLow(_("Keyswitching range low")),
2050      eDimensionKeyRangeHigh(_("Keyswitching range high"))      eDimensionKeyRangeHigh(_("Keyswitching range high"))
2051  {  {
2052        if (!Settings::singleton()->autoRestoreWindowDimension) {
2053            //set_default_size(470, 390);
2054            set_position(Gtk::WIN_POS_MOUSE);
2055        }
2056    
2057      set_title(_("Instrument Properties"));      set_title(_("Instrument Properties"));
2058    
2059      eDimensionKeyRangeLow.set_tip(      eDimensionKeyRangeLow.set_tip(
# Line 1295  void MainWindow::file_changed() Line 2136  void MainWindow::file_changed()
2136      }      }
2137  }  }
2138    
2139    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
2140        sample_ref_count.clear();
2141        
2142        if (!gig) return;
2143    
2144        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
2145             instrument = gig->GetNextInstrument())
2146        {
2147            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2148                 rgn = instrument->GetNextRegion())
2149            {
2150                for (int i = 0; i < 256; ++i) {
2151                    if (!rgn->pDimensionRegions[i]) continue;
2152                    if (rgn->pDimensionRegions[i]->pSample) {
2153                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
2154                    }
2155                }
2156            }
2157        }
2158    }
2159    
2160  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
2161  {  {
2162      file = 0;      file = 0;
2163      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
2164    
2165      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
2166            (filename && strlen(filename) > 0) ?
2167                filename : (!gig->GetFileName().empty()) ?
2168                    gig->GetFileName() : _("Unsaved Gig File");
2169      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
2170      file_has_name = filename;      file_has_name = filename;
2171      file_is_changed = false;      file_is_changed = false;
# Line 1309  void MainWindow::load_gig(gig::File* gig Line 2174  void MainWindow::load_gig(gig::File* gig
2174      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
2175    
2176      instrument_name_connection.block();      instrument_name_connection.block();
2177        int index = 0;
2178      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
2179           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
2180          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2181            const int iScriptSlots = instrument->ScriptSlotCount();
2182    
2183          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
2184          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
2185            row[m_Columns.m_col_nr] = index;
2186          row[m_Columns.m_col_name] = name;          row[m_Columns.m_col_name] = name;
2187          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
2188            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
2189    
2190          add_instrument_to_menu(name);          add_instrument_to_menu(name);
2191      }      }
2192      instrument_name_connection.unblock();      instrument_name_connection.unblock();
2193      uiManager->get_widget("/MenuBar/MenuInstrument")->show();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
2194    
2195        updateSampleRefCountMap(gig);
2196    
2197      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
2198          if (group->Name != "") {          if (group->Name != "") {
# Line 1339  void MainWindow::load_gig(gig::File* gig Line 2210  void MainWindow::load_gig(gig::File* gig
2210                      gig_to_utf8(sample->pInfo->Name);                      gig_to_utf8(sample->pInfo->Name);
2211                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
2212                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
2213                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
2214                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
2215                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
2216              }              }
2217          }          }
2218      }      }
2219        
2220        for (int i = 0; gig->GetScriptGroup(i); ++i) {
2221            gig::ScriptGroup* group = gig->GetScriptGroup(i);
2222    
2223            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2224            Gtk::TreeModel::Row rowGroup = *iterGroup;
2225            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
2226            rowGroup[m_ScriptsModel.m_col_group]  = group;
2227            rowGroup[m_ScriptsModel.m_col_script] = NULL;
2228            for (int s = 0; group->GetScript(s); ++s) {
2229                gig::Script* script = group->GetScript(s);
2230    
2231                Gtk::TreeModel::iterator iterScript =
2232                    m_refScriptsTreeModel->append(rowGroup.children());
2233                Gtk::TreeModel::Row rowScript = *iterScript;
2234                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
2235                rowScript[m_ScriptsModel.m_col_script] = script;
2236                rowScript[m_ScriptsModel.m_col_group]  = NULL;
2237            }
2238        }
2239        // unfold all sample groups & script groups by default
2240        m_TreeViewSamples.expand_all();
2241        m_TreeViewScripts.expand_all();
2242    
2243      file = gig;      file = gig;
2244    
# Line 1359  bool MainWindow::instr_props_set_instrum Line 2256  bool MainWindow::instr_props_set_instrum
2256  {  {
2257      instrumentProps.signal_name_changed().clear();      instrumentProps.signal_name_changed().clear();
2258    
2259      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2260          m_TreeView.get_selection()->get_selected();      if (rows.empty()) {
2261            instrumentProps.hide();
2262            return false;
2263        }
2264        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2265      if (it) {      if (it) {
2266          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2267          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 2311  void MainWindow::show_midi_rules()
2311      }      }
2312  }  }
2313    
2314    void MainWindow::show_script_slots() {
2315        if (!file) return;
2316        // get selected instrument
2317        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2318        if (rows.empty()) return;
2319        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2320        if (!it) return;
2321        Gtk::TreeModel::Row row = *it;
2322        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2323        if (!instrument) return;
2324    
2325        ScriptSlots* window = new ScriptSlots;
2326        window->setInstrument(instrument);
2327        window->signal_script_slots_changed().connect(
2328            sigc::mem_fun(*this, &MainWindow::onScriptSlotsModified)
2329        );
2330        //window->reparent(*this);
2331        window->show();
2332    }
2333    
2334    void MainWindow::onScriptSlotsModified(gig::Instrument* pInstrument) {
2335        if (!pInstrument) return;
2336        const int iScriptSlots = pInstrument->ScriptSlotCount();
2337    
2338        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2339        for (int i = 0; i < model->children().size(); ++i) {
2340            Gtk::TreeModel::Row row = model->children()[i];
2341            if (row[m_Columns.m_col_instr] != pInstrument) continue;
2342            row[m_Columns.m_col_scripts] = iScriptSlots ? ToString(iScriptSlots) : "";
2343            break;
2344        }
2345    
2346        // causes the sampler to reload the instrument with the new script
2347        on_sel_change();
2348    }
2349    
2350    void MainWindow::assignScript(gig::Script* pScript) {
2351        if (!pScript) {
2352            printf("assignScript() : !script\n");
2353            return;
2354        }
2355        printf("assignScript('%s')\n", pScript->Name.c_str());
2356    
2357        gig::Instrument* pInstrument = get_instrument();
2358        if (!pInstrument) {
2359            printf("!instrument\n");
2360            return;
2361        }
2362    
2363        pInstrument->AddScriptSlot(pScript);
2364    
2365        onScriptSlotsModified(pInstrument);
2366    }
2367    
2368    void MainWindow::on_action_refresh_all() {
2369        __refreshEntireGUI();
2370    }
2371    
2372  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2373      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2374          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 2380  void MainWindow::on_action_view_status_b
2380      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2381  }  }
2382    
2383    void MainWindow::on_auto_restore_win_dim() {
2384        Gtk::CheckMenuItem* item =
2385            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2386        if (!item) {
2387            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2388            return;
2389        }
2390        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2391    }
2392    
2393    void MainWindow::on_save_with_temporary_file() {
2394        Gtk::CheckMenuItem* item =
2395            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2396        if (!item) {
2397            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2398            return;
2399        }
2400        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2401    }
2402    
2403  bool MainWindow::is_copy_samples_unity_note_enabled() const {  bool MainWindow::is_copy_samples_unity_note_enabled() const {
2404      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2405          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 2436  void MainWindow::on_button_release(GdkEv
2436          show_instr_props();          show_instr_props();
2437      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2438          // gig v2 files have no midi rules          // gig v2 files have no midi rules
2439            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2440            static_cast<Gtk::MenuItem*>(
2441                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2442                    bEnabled
2443                );
2444          static_cast<Gtk::MenuItem*>(          static_cast<Gtk::MenuItem*>(
2445              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(              uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2446                  !(file->pVersion && file->pVersion->major == 2));                  bEnabled
2447                );
2448          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2449      }      }
2450  }  }
# Line 1479  void MainWindow::on_instrument_selection Line 2464  void MainWindow::on_instrument_selection
2464      }      }
2465  }  }
2466    
2467    void MainWindow::select_instrument(gig::Instrument* instrument) {
2468        if (!instrument) return;
2469    
2470        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2471        for (int i = 0; i < model->children().size(); ++i) {
2472            Gtk::TreeModel::Row row = model->children()[i];
2473            if (row[m_Columns.m_col_instr] == instrument) {
2474                // select and show the respective instrument in the list view
2475                show_intruments_tab();
2476                m_TreeView.get_selection()->unselect_all();
2477                m_TreeView.get_selection()->select(model->children()[i]);
2478                std::vector<Gtk::TreeModel::Path> rows =
2479                    m_TreeView.get_selection()->get_selected_rows();
2480                if (!rows.empty())
2481                    m_TreeView.scroll_to_row(rows[0]);
2482                on_sel_change(); // the regular instrument selection change callback
2483            }
2484        }
2485    }
2486    
2487    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2488    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2489        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2490        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2491    
2492        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2493        for (int i = 0; i < model->children().size(); ++i) {
2494            Gtk::TreeModel::Row row = model->children()[i];
2495            if (row[m_Columns.m_col_instr] == pInstrument) {
2496                // select and show the respective instrument in the list view
2497                show_intruments_tab();
2498                m_TreeView.get_selection()->unselect_all();
2499                m_TreeView.get_selection()->select(model->children()[i]);
2500                std::vector<Gtk::TreeModel::Path> rows =
2501                    m_TreeView.get_selection()->get_selected_rows();
2502                if (!rows.empty())
2503                    m_TreeView.scroll_to_row(rows[0]);
2504                on_sel_change(); // the regular instrument selection change callback
2505    
2506                // select respective region in the region selector
2507                m_RegionChooser.set_region(pRegion);
2508    
2509                // select and show the respective dimension region in the editor
2510                //update_dimregs();
2511                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2512                //dimreg_edit.set_dim_region(dimRgn);
2513    
2514                return true;
2515            }
2516        }
2517    
2518        return false;
2519    }
2520    
2521    void MainWindow::select_sample(gig::Sample* sample) {
2522        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2523        for (int g = 0; g < model->children().size(); ++g) {
2524            Gtk::TreeModel::Row rowGroup = model->children()[g];
2525            for (int s = 0; s < rowGroup.children().size(); ++s) {
2526                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2527                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2528                    show_samples_tab();
2529                    m_TreeViewSamples.get_selection()->unselect_all();
2530                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2531                    std::vector<Gtk::TreeModel::Path> rows =
2532                        m_TreeViewSamples.get_selection()->get_selected_rows();
2533                    if (rows.empty()) return;
2534                    m_TreeViewSamples.scroll_to_row(rows[0]);
2535                    return;
2536                }
2537            }
2538        }
2539    }
2540    
2541  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2542      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2543            // by default if Ctrl keys is pressed down, then a mouse right-click
2544            // does not select the respective row, so we must assure this
2545            // programmatically ...
2546            /*{
2547                Gtk::TreeModel::Path path;
2548                Gtk::TreeViewColumn* pColumn = NULL;
2549                int cellX, cellY;
2550                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2551                    (int)button->x, (int)button->y,
2552                    path, pColumn, cellX, cellY
2553                );
2554                if (bSuccess) {
2555                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2556                        printf("not selected !!!\n");
2557                        m_TreeViewSamples.get_selection()->select(path);
2558                    }
2559                }
2560            }*/
2561    
2562          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2563              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2564          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2565          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2566          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2567          bool group_selected  = false;          const int n = rows.size();
2568          bool sample_selected = false;          int nGroups  = 0;
2569          if (it) {          int nSamples = 0;
2570            for (int r = 0; r < n; ++r) {
2571                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2572                if (!it) continue;
2573              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2574              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2575              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2576          }          }
2577    
2578          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2579              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2580          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2581              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2582          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2583              set_sensitive(file);              set_sensitive(file);
2584            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2585                set_sensitive(nSamples == 1);
2586          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2587              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2588          // show sample popup          // show sample popup
2589          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2590    
2591            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2592                set_sensitive(n == 1);
2593            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2594                set_sensitive(n);
2595            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2596                set_sensitive(file);
2597            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2598                set_sensitive(nSamples == 1);
2599            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2600                set_sensitive(n);
2601        }
2602    }
2603    
2604    void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2605        if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2606            Gtk::Menu* script_popup =
2607                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2608            // update enabled/disabled state of sample popup items
2609            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2610            Gtk::TreeModel::iterator it = sel->get_selected();
2611            bool group_selected  = false;
2612            bool script_selected = false;
2613            if (it) {
2614                Gtk::TreeModel::Row row = *it;
2615                group_selected  = row[m_ScriptsModel.m_col_group];
2616                script_selected = row[m_ScriptsModel.m_col_script];
2617            }
2618            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2619                set_sensitive(group_selected || script_selected);
2620            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2621                set_sensitive(file);
2622            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2623                set_sensitive(script_selected);    
2624            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2625                set_sensitive(group_selected || script_selected);
2626            // show sample popup
2627            script_popup->popup(button->button, button->time);
2628    
2629            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2630                set_sensitive(group_selected || script_selected);
2631            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2632                set_sensitive(file);
2633            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2634                set_sensitive(script_selected);    
2635            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2636                set_sensitive(group_selected || script_selected);
2637      }      }
2638  }  }
2639    
2640    void MainWindow::updateScriptListOfMenu() {
2641        // remove all entries from "Assign Script" menu
2642        {
2643            const std::vector<Gtk::Widget*> children = assign_scripts_menu->get_children();
2644            for (int i = 0; i < children.size(); ++i) {
2645                Gtk::Widget* child = children[i];
2646                assign_scripts_menu->remove(*child);
2647                delete child;
2648            }
2649        }
2650    
2651        int iTotalScripts = 0;
2652    
2653        if (!file) goto noScripts;
2654    
2655        // add all configured macros as menu items to the "Macro" menu
2656        for (int iGroup = 0; file->GetScriptGroup(iGroup); ++iGroup) {
2657            gig::ScriptGroup* pGroup = file->GetScriptGroup(iGroup);
2658            for (int iScript = 0; pGroup->GetScript(iScript); ++iScript, ++iTotalScripts) {
2659                gig::Script* pScript = pGroup->GetScript(iScript);
2660                std::string name = pScript->Name;
2661    
2662                Gtk::MenuItem* item = new Gtk::MenuItem(name);
2663                item->signal_activate().connect(
2664                    sigc::bind(
2665                        sigc::mem_fun(*this, &MainWindow::assignScript), pScript
2666                    )
2667                );
2668                assign_scripts_menu->append(*item);
2669                item->set_accel_path("<Scripts>/script_" + ToString(iTotalScripts));
2670                //item->set_tooltip_text(comment);
2671            }
2672        }
2673    
2674        noScripts:
2675    
2676        // if there are no macros configured at all, then show a dummy entry instead
2677        if (!iTotalScripts) {
2678            Gtk::MenuItem* item = new Gtk::MenuItem(_("No Scripts"));
2679            item->set_sensitive(false);
2680            assign_scripts_menu->append(*item);
2681        }
2682    
2683        assign_scripts_menu->show_all_children();
2684    }
2685    
2686  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2687      const Glib::ustring& name, int position) {      const Glib::ustring& name, int position) {
# Line 1546  void MainWindow::add_instrument(gig::Ins Line 2722  void MainWindow::add_instrument(gig::Ins
2722      instrument_name_connection.block();      instrument_name_connection.block();
2723      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2724      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2725        rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2726      rowInstr[m_Columns.m_col_name] = name;      rowInstr[m_Columns.m_col_name] = name;
2727      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2728        rowInstr[m_Columns.m_col_scripts] = "";
2729      instrument_name_connection.unblock();      instrument_name_connection.unblock();
2730    
2731      add_instrument_to_menu(name);      add_instrument_to_menu(name);
2732        select_instrument(instrument);
     m_TreeView.get_selection()->select(iterInstr);  
   
2733      file_changed();      file_changed();
2734  }  }
2735    
# Line 1574  void MainWindow::on_action_duplicate_ins Line 2750  void MainWindow::on_action_duplicate_ins
2750      // retrieve the currently selected instrument      // retrieve the currently selected instrument
2751      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
2752      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2753      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2754      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
2755      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2756      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
2757      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
2758                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2759      // duplicate the orginal instrument              if (instrOrig) {
2760      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
2761      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2762          instrOrig->pInfo->Name +                  instrNew->pInfo->Name =
2763          gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");                      instrOrig->pInfo->Name +
2764                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2765    
2766      add_instrument(instrNew);                  add_instrument(instrNew);
2767                }
2768            }
2769        }
2770  }  }
2771    
2772  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1603  void MainWindow::on_action_remove_instru Line 2783  void MainWindow::on_action_remove_instru
2783      }      }
2784    
2785      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2786      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2787      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2788            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2789            if (!it) continue;
2790          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2791          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2792          try {          try {
# Line 1619  void MainWindow::on_action_remove_instru Line 2801  void MainWindow::on_action_remove_instru
2801    
2802              // remove row from instruments tree view              // remove row from instruments tree view
2803              m_refTreeModel->erase(it);              m_refTreeModel->erase(it);
2804                // update "Nr" column of all instrument rows
2805                {
2806                    int index = 0;
2807                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2808                         it != m_refTreeModel->children().end(); ++it, ++index)
2809                    {
2810                        Gtk::TreeModel::Row row = *it;
2811                        row[m_Columns.m_col_nr] = index;
2812                    }
2813                }
2814    
2815  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2816              // 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 2845  void MainWindow::on_action_sample_proper
2845      msg.run();      msg.run();
2846  }  }
2847    
2848    void MainWindow::on_action_add_script_group() {
2849        static int __script_indexer = 0;
2850        if (!file) return;
2851        gig::ScriptGroup* group = file->AddScriptGroup();
2852        group->Name = gig_from_utf8(_("Unnamed Group"));
2853        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2854        __script_indexer++;
2855        // update sample tree view
2856        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2857        Gtk::TreeModel::Row rowGroup = *iterGroup;
2858        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2859        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2860        rowGroup[m_ScriptsModel.m_col_group] = group;
2861        file_changed();
2862    }
2863    
2864    void MainWindow::on_action_add_script() {
2865        if (!file) return;
2866        // get selected group
2867        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2868        Gtk::TreeModel::iterator it = sel->get_selected();
2869        if (!it) return;
2870        Gtk::TreeModel::Row row = *it;
2871        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2872        if (!group) { // not a group, but a script is selected (probably)
2873            gig::Script* script = row[m_ScriptsModel.m_col_script];
2874            if (!script) return;
2875            it = row.parent(); // resolve parent (that is the script's group)
2876            if (!it) return;
2877            row = *it;
2878            group = row[m_ScriptsModel.m_col_group];
2879            if (!group) return;
2880        }
2881    
2882        // add a new script to the .gig file
2883        gig::Script* script = group->AddScript();    
2884        Glib::ustring name = _("Unnamed Script");
2885        script->Name = gig_from_utf8(name);
2886    
2887        // add script to the tree view
2888        Gtk::TreeModel::iterator iterScript =
2889            m_refScriptsTreeModel->append(row.children());
2890        Gtk::TreeModel::Row rowScript = *iterScript;
2891        rowScript[m_ScriptsModel.m_col_name] = name;
2892        rowScript[m_ScriptsModel.m_col_script] = script;
2893        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2894    
2895        // unfold group of new script item in treeview
2896        Gtk::TreeModel::Path path(iterScript);
2897        m_TreeViewScripts.expand_to_path(path);
2898    }
2899    
2900    void MainWindow::on_action_edit_script() {
2901        if (!file) return;
2902        // get selected script
2903        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2904        Gtk::TreeModel::iterator it = sel->get_selected();
2905        if (!it) return;
2906        Gtk::TreeModel::Row row = *it;
2907        gig::Script* script = row[m_ScriptsModel.m_col_script];
2908        if (!script) return;
2909    
2910        ScriptEditor* editor = new ScriptEditor;
2911        editor->signal_script_to_be_changed.connect(
2912            signal_script_to_be_changed.make_slot()
2913        );
2914        editor->signal_script_changed.connect(
2915            signal_script_changed.make_slot()
2916        );
2917        editor->setScript(script);
2918        //editor->reparent(*this);
2919        editor->show();
2920    }
2921    
2922    void MainWindow::on_action_remove_script() {
2923        if (!file) return;
2924        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2925        Gtk::TreeModel::iterator it = sel->get_selected();
2926        if (it) {
2927            Gtk::TreeModel::Row row = *it;
2928            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2929            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2930            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2931            try {
2932                // remove script group or script from the gig file
2933                if (group) {
2934                    // notify everybody that we're going to remove these samples
2935    //TODO:         scripts_to_be_removed_signal.emit(members);
2936                    // delete the group in the .gig file including the
2937                    // samples that belong to the group
2938                    file->DeleteScriptGroup(group);
2939                    // notify that we're done with removal
2940    //TODO:         scripts_removed_signal.emit();
2941                    file_changed();
2942                } else if (script) {
2943                    // notify everybody that we're going to remove this sample
2944    //TODO:         std::list<gig::Script*> lscripts;
2945    //TODO:         lscripts.push_back(script);
2946    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2947                    // remove sample from the .gig file
2948                    script->GetGroup()->DeleteScript(script);
2949                    // notify that we're done with removal
2950    //TODO:         scripts_removed_signal.emit();
2951                    dimreg_changed();
2952                    file_changed();
2953                }
2954                // remove respective row(s) from samples tree view
2955                m_refScriptsTreeModel->erase(it);
2956            } catch (RIFF::Exception e) {
2957                // pretend we're done with removal (i.e. to avoid dead locks)
2958    //TODO:     scripts_removed_signal.emit();
2959                // show error message
2960                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2961                msg.run();
2962            }
2963        }
2964    }
2965    
2966  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2967      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2968      if (!file) return;      if (!file) return;
# Line 1669  void MainWindow::on_action_add_group() { Line 2979  void MainWindow::on_action_add_group() {
2979      file_changed();      file_changed();
2980  }  }
2981    
2982    void MainWindow::on_action_replace_sample() {
2983        add_or_replace_sample(true);
2984    }
2985    
2986  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2987        add_or_replace_sample(false);
2988    }
2989    
2990    void MainWindow::add_or_replace_sample(bool replace) {
2991      if (!file) return;      if (!file) return;
2992      // get selected group  
2993        // get selected group (and probably selected sample)
2994      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2995      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2996        if (rows.empty()) return;
2997        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2998      if (!it) return;      if (!it) return;
2999      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
3000        gig::Sample* sample = NULL;
3001      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
3002      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
3003          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
3004          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
3005          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
3006          if (!it) return;          if (!it) return;
3007          row = *it;          if (!replace) row = *it;
3008          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
3009          if (!group) return;          if (!group) return;
3010      }      }
3011        if (replace && !sample) return;
3012    
3013      // show 'browse for file' dialog      // show 'browse for file' dialog
3014      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
3015      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
3016      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);
3017      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
3018    
3019      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
3020  #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 3085  void MainWindow::on_action_add_sample()
3085                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
3086                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
3087                  }                  }
3088                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
3089                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
3090                  // file name without path                  // file name without path
3091                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
3092                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1813  void MainWindow::on_action_add_sample() Line 3137  void MainWindow::on_action_add_sample()
3137                  // physically when File::Save() is called)                  // physically when File::Save() is called)
3138                  sample->Resize(info.frames);                  sample->Resize(info.frames);
3139                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
3140                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
3141                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
3142                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
3143                  SampleImportItem sched_item;                  SampleImportItem sched_item;
3144                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
3145                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
3146                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
3147                  // add sample to the tree view                  // add sample to the tree view
3148                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
3149                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
3150                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
3151                  rowSample[m_SamplesModel.m_col_name] =                      Gtk::TreeModel::iterator iterSample =
3152                      gig_to_utf8(sample->pInfo->Name);                          m_refSamplesTreeModel->append(row.children());
3153                  rowSample[m_SamplesModel.m_col_sample] = sample;                      Gtk::TreeModel::Row rowSample = *iterSample;
3154                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      rowSample[m_SamplesModel.m_col_name] =
3155                            gig_to_utf8(sample->pInfo->Name);
3156                        rowSample[m_SamplesModel.m_col_sample] = sample;
3157                        rowSample[m_SamplesModel.m_col_group]  = NULL;
3158                    }
3159                  // close sound file                  // close sound file
3160                  sf_close(hFile);                  sf_close(hFile);
3161                  file_changed();                  file_changed();
# Line 1838  void MainWindow::on_action_add_sample() Line 3166  void MainWindow::on_action_add_sample()
3166          }          }
3167          // 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
3168          if (!error_files.empty()) {          if (!error_files.empty()) {
3169              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
3170                    (replace
3171                        ? _("Failed to replace sample with:\n")
3172                        : _("Could not add the following sample(s):\n"))
3173                    + error_files;
3174              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3175              msg.run();              msg.run();
3176          }          }
# Line 1905  void MainWindow::on_action_replace_all_s Line 3237  void MainWindow::on_action_replace_all_s
3237              try              try
3238              {              {
3239                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
3240                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
3241                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
3242                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
3243                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
3244                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
3245                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
3246                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
3247                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
3248                          break;                          break;
3249                      default:                      default:
3250                          sf_close(hFile);                          sf_close(hFile);
# Line 1925  void MainWindow::on_action_replace_all_s Line 3253  void MainWindow::on_action_replace_all_s
3253                  SampleImportItem sched_item;                  SampleImportItem sched_item;
3254                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
3255                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
3256                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
3257                  sf_close(hFile);                  sf_close(hFile);
3258                  file_changed();                  file_changed();
3259              }              }
# Line 1949  void MainWindow::on_action_replace_all_s Line 3277  void MainWindow::on_action_replace_all_s
3277  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
3278      if (!file) return;      if (!file) return;
3279      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3280      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3281      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
3282            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
3283            if (!it) continue;
3284          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
3285          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
3286          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 3305  void MainWindow::on_action_remove_sample
3305                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
3306                  // them from the import queue                  // them from the import queue
3307                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
3308                       member != members.end(); ++member) {                       member != members.end(); ++member)
3309                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
3310                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
3311                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
3312                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
3313                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
3314                      }                      }
3315                  }                  }
3316                  file_changed();                  file_changed();
# Line 1998  void MainWindow::on_action_remove_sample Line 3325  void MainWindow::on_action_remove_sample
3325                  samples_removed_signal.emit();                  samples_removed_signal.emit();
3326                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
3327                  // the import queue                  // the import queue
3328                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
3329                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
3330                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
3331                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
3332                  }                  }
3333                  dimreg_changed();                  dimreg_changed();
3334                  file_changed();                  file_changed();
# Line 2022  void MainWindow::on_action_remove_sample Line 3345  void MainWindow::on_action_remove_sample
3345      }      }
3346  }  }
3347    
3348    void MainWindow::on_action_remove_unused_samples() {
3349        if (!file) return;
3350    
3351        // collect all samples that are not referenced by any instrument
3352        std::list<gig::Sample*> lsamples;
3353        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3354            gig::Sample* sample = file->GetSample(iSample);
3355            bool isUsed = false;
3356            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3357                                  instrument = file->GetNextInstrument())
3358            {
3359                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3360                                  rgn = instrument->GetNextRegion())
3361                {
3362                    for (int i = 0; i < 256; ++i) {
3363                        if (!rgn->pDimensionRegions[i]) continue;
3364                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3365                        isUsed = true;
3366                        goto endOfRefSearch;
3367                    }
3368                }
3369            }
3370            endOfRefSearch:
3371            if (!isUsed) lsamples.push_back(sample);
3372        }
3373    
3374        if (lsamples.empty()) return;
3375    
3376        // notify everybody that we're going to remove these samples
3377        samples_to_be_removed_signal.emit(lsamples);
3378    
3379        // remove collected samples
3380        try {
3381            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3382                 itSample != lsamples.end(); ++itSample)
3383            {
3384                gig::Sample* sample = *itSample;
3385                // remove sample from the .gig file
3386                file->DeleteSample(sample);
3387                // if sample was just previously added, remove it from the import queue
3388                if (m_SampleImportQueue.count(sample)) {
3389                    printf("Removing previously added sample '%s'\n",
3390                           m_SampleImportQueue[sample].sample_path.c_str());
3391                    m_SampleImportQueue.erase(sample);
3392                }
3393            }
3394        } catch (RIFF::Exception e) {
3395            // show error message
3396            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3397            msg.run();
3398        }
3399    
3400        // notify everybody that we're done with removal
3401        samples_removed_signal.emit();
3402    
3403        dimreg_changed();
3404        file_changed();
3405        __refreshEntireGUI();
3406    }
3407    
3408    // see comment on on_sample_treeview_drag_begin()
3409    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3410    {
3411        first_call_to_drag_data_get = true;
3412    }
3413    
3414    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3415                                                       Gtk::SelectionData& selection_data, guint, guint)
3416    {
3417        if (!first_call_to_drag_data_get) return;
3418        first_call_to_drag_data_get = false;
3419    
3420        // get selected script
3421        gig::Script* script = NULL;
3422        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3423        Gtk::TreeModel::iterator it = sel->get_selected();
3424        if (it) {
3425            Gtk::TreeModel::Row row = *it;
3426            script = row[m_ScriptsModel.m_col_script];
3427        }
3428        // pass the gig::Script as pointer
3429        selection_data.set(selection_data.get_target(), 0/*unused*/,
3430                           (const guchar*)&script,
3431                           sizeof(script)/*length of data in bytes*/);
3432    }
3433    
3434    // see comment on on_sample_treeview_drag_begin()
3435    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3436    {
3437        first_call_to_drag_data_get = true;
3438    }
3439    
3440    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3441                                                           Gtk::SelectionData& selection_data, guint, guint)
3442    {
3443        if (!first_call_to_drag_data_get) return;
3444        first_call_to_drag_data_get = false;
3445    
3446        // get selected source instrument
3447        gig::Instrument* src = NULL;
3448        {
3449            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3450            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3451            if (!rows.empty()) {
3452                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3453                if (it) {
3454                    Gtk::TreeModel::Row row = *it;
3455                    src = row[m_Columns.m_col_instr];
3456                }
3457            }
3458        }
3459        if (!src) return;
3460    
3461        // pass the source gig::Instrument as pointer
3462        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3463                           sizeof(src)/*length of data in bytes*/);
3464    }
3465    
3466    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3467        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3468        const Gtk::SelectionData& selection_data, guint, guint time)
3469    {
3470        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3471        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3472            return;
3473    
3474        gig::Instrument* dst = NULL;
3475        {
3476            Gtk::TreeModel::Path path;
3477            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3478            if (!found) return;
3479    
3480            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3481            if (!iter) return;
3482            Gtk::TreeModel::Row row = *iter;
3483            dst = row[m_Columns.m_col_instr];
3484        }
3485        if (!dst) return;
3486    
3487        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3488        src->MoveTo(dst);
3489        __refreshEntireGUI();
3490        select_instrument(src);
3491    }
3492    
3493  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3494  // 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
3495  // 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 3508  void MainWindow::on_sample_treeview_drag
3508      // get selected sample      // get selected sample
3509      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3510      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3511      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3512      if (it) {      if (!rows.empty()) {
3513          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3514          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3515                Gtk::TreeModel::Row row = *it;
3516                sample = row[m_SamplesModel.m_col_sample];
3517            }
3518      }      }
3519      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3520      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 3621  void MainWindow::sample_name_changed(con
3621      }      }
3622  }  }
3623    
3624    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3625                                         const Gtk::TreeModel::iterator& iter) {
3626        if (!iter) return;
3627        Gtk::TreeModel::Row row = *iter;
3628        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3629        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3630        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3631        gig::String gigname(gig_from_utf8(name));
3632        if (group) {
3633            if (group->Name != gigname) {
3634                group->Name = gigname;
3635                printf("script group name changed\n");
3636                file_changed();
3637            }
3638        } else if (script) {
3639            if (script->Name != gigname) {
3640                script->Name = gigname;
3641                printf("script name changed\n");
3642                file_changed();
3643            }
3644        }
3645    }
3646    
3647    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3648                                           Gtk::TreeViewColumn* column)
3649    {
3650        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3651        if (!iter) return;
3652        Gtk::TreeModel::Row row = *iter;
3653        gig::Script* script = row[m_ScriptsModel.m_col_script];
3654        if (!script) return;
3655    
3656        ScriptEditor* editor = new ScriptEditor;
3657        editor->signal_script_to_be_changed.connect(
3658            signal_script_to_be_changed.make_slot()
3659        );
3660        editor->signal_script_changed.connect(
3661            signal_script_changed.make_slot()
3662        );
3663        editor->setScript(script);
3664        //editor->reparent(*this);
3665        editor->show();
3666    }
3667    
3668  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3669                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3670      if (!iter) return;      if (!iter) return;
# Line 2186  void MainWindow::instrument_name_changed Line 3701  void MainWindow::instrument_name_changed
3701    
3702  void MainWindow::on_action_combine_instruments() {  void MainWindow::on_action_combine_instruments() {
3703      CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);      CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3704    
3705        // take over selection from instruments list view for the combine dialog's
3706        // list view as pre-selection
3707        std::set<int> indeces;
3708        {
3709            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3710            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3711            for (int r = 0; r < rows.size(); ++r) {
3712                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
3713                if (it) {
3714                    Gtk::TreeModel::Row row = *it;
3715                    int index = row[m_Columns.m_col_nr];
3716                    indeces.insert(index);
3717                }
3718            }
3719        }
3720        d->setSelectedInstruments(indeces);
3721    
3722      d->show_all();      d->show_all();
     d->resize(500, 400);  
3723      d->run();      d->run();
3724      if (d->fileWasChanged()) {      if (d->fileWasChanged()) {
3725          // update GUI with new instrument just created          // update GUI with new instrument just created
# Line 2196  void MainWindow::on_action_combine_instr Line 3728  void MainWindow::on_action_combine_instr
3728      delete d;      delete d;
3729  }  }
3730    
3731    void MainWindow::on_action_view_references() {
3732        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3733        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3734        if (rows.empty()) return;
3735        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3736        if (!it) return;
3737        Gtk::TreeModel::Row row = *it;
3738        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3739        if (!sample) return;
3740    
3741        ReferencesView* d = new ReferencesView(*this);
3742        d->setSample(sample);
3743        d->dimension_region_selected.connect(
3744            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3745        );
3746        d->show_all();
3747        d->resize(500, 400);
3748        d->run();
3749        delete d;
3750    }
3751    
3752  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {  void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3753      struct _Source {      struct _Source {
3754          std::vector<RIFF::File*> riffs;          std::vector<RIFF::File*> riffs;
# Line 2263  void MainWindow::mergeFiles(const std::v Line 3816  void MainWindow::mergeFiles(const std::v
3816          );          );
3817      }      }
3818    
3819      // Note: requires that this file already has a filename !      // Finally save gig file persistently to disk ...
3820      this->file->Save();      //NOTE: requires that this gig file already has a filename !
3821        {
3822            std::cout << "Saving file\n" << std::flush;
3823            file_structure_to_be_changed_signal.emit(this->file);
3824    
3825            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3826                _("Saving") +  Glib::ustring(" '") +
3827                Glib::filename_display_basename(this->filename) + "' ...",
3828                *this
3829            );
3830            progress_dialog->show_all();
3831            saver = new Saver(this->file); //FIXME: memory leak!
3832            saver->signal_progress().connect(
3833                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3834            saver->signal_finished().connect(
3835                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3836            saver->signal_error().connect(
3837                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3838            saver->launch();
3839        }
3840  }  }
3841    
3842  void MainWindow::on_action_merge_files() {  void MainWindow::on_action_merge_files() {
# Line 2301  void MainWindow::on_action_merge_files() Line 3873  void MainWindow::on_action_merge_files()
3873      // show warning in the file picker dialog      // show warning in the file picker dialog
3874      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
3875      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
3876      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
3877        warningIcon.set_from_icon_name("dialog-warning",
3878                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3879      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3880  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
3881      view::WrapLabel description;      view::WrapLabel description;
# Line 2324  void MainWindow::on_action_merge_files() Line 3898  void MainWindow::on_action_merge_files()
3898      descriptionArea.show_all();      descriptionArea.show_all();
3899    
3900      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
3901          printf("on_action_merge_files self=%x\n", Glib::Threads::Thread::self());          printf("on_action_merge_files self=%p\n",
3902                   static_cast<void*>(Glib::Threads::Thread::self()));
3903          std::vector<std::string> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
3904    
3905          // 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 3911  void MainWindow::on_action_merge_files()
3911          }          }
3912    
3913          // update GUI          // update GUI
3914          __refreshEntireGUI();                  __refreshEntireGUI();
3915      }      }
3916  }  }
3917    
# Line 2354  void MainWindow::set_file_is_shared(bool Line 3929  void MainWindow::set_file_is_shared(bool
3929              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3930          );          );
3931      }      }
3932    
3933        {
3934            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3935                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3936            if (item) item->set_sensitive(b);
3937        }
3938    }
3939    
3940    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3941        if (!sample) return;
3942        sample_ref_count[sample] += offset;
3943        const int refcount = sample_ref_count[sample];
3944    
3945        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3946        for (int g = 0; g < model->children().size(); ++g) {
3947            Gtk::TreeModel::Row rowGroup = model->children()[g];
3948            for (int s = 0; s < rowGroup.children().size(); ++s) {
3949                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3950                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3951                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3952                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3953            }
3954        }
3955    }
3956    
3957    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3958        on_sample_ref_count_incremented(oldSample, -1);
3959        on_sample_ref_count_incremented(newSample, +1);
3960    }
3961    
3962    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3963        // just in case a new sample is added later with exactly the same memory
3964        // address, which would lead to incorrect refcount if not deleted here
3965        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3966             it != samples.end(); ++it)
3967        {
3968            sample_ref_count.erase(*it);
3969        }
3970    }
3971    
3972    void MainWindow::show_samples_tab() {
3973        m_TreeViewNotebook.set_current_page(0);
3974    }
3975    
3976    void MainWindow::show_intruments_tab() {
3977        m_TreeViewNotebook.set_current_page(1);
3978    }
3979    
3980    void MainWindow::show_scripts_tab() {
3981        m_TreeViewNotebook.set_current_page(2);
3982    }
3983    
3984    void MainWindow::select_instrument_by_dir(int dir) {
3985        if (!file) return;
3986        gig::Instrument* pInstrument = get_instrument();
3987        if (!pInstrument) {
3988            select_instrument( file->GetInstrument(0) );
3989            return;
3990        }
3991        for (int i = 0; file->GetInstrument(i); ++i) {
3992            if (file->GetInstrument(i) == pInstrument) {
3993                select_instrument( file->GetInstrument(i + dir) );
3994                return;
3995            }
3996        }
3997    }
3998    
3999    void MainWindow::select_prev_instrument() {
4000        select_instrument_by_dir(-1);
4001    }
4002    
4003    void MainWindow::select_next_instrument() {
4004        select_instrument_by_dir(1);
4005    }
4006    
4007    void MainWindow::select_prev_region() {
4008        m_RegionChooser.select_prev_region();
4009    }
4010    
4011    void MainWindow::select_next_region() {
4012        m_RegionChooser.select_next_region();
4013    }
4014    
4015    void MainWindow::select_next_dim_rgn_zone() {
4016        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
4017        m_DimRegionChooser.select_next_dimzone();
4018    }
4019    
4020    void MainWindow::select_prev_dim_rgn_zone() {
4021        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
4022        m_DimRegionChooser.select_prev_dimzone();
4023    }
4024    
4025    void MainWindow::select_add_next_dim_rgn_zone() {
4026        m_DimRegionChooser.select_next_dimzone(true);
4027    }
4028    
4029    void MainWindow::select_add_prev_dim_rgn_zone() {
4030        m_DimRegionChooser.select_prev_dimzone(true);
4031    }
4032    
4033    void MainWindow::select_prev_dimension() {
4034        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
4035        m_DimRegionChooser.select_prev_dimension();
4036    }
4037    
4038    void MainWindow::select_next_dimension() {
4039        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
4040        m_DimRegionChooser.select_next_dimension();
4041    }
4042    
4043    #define CLIPBOARD_DIMENSIONREGION_TARGET \
4044        ("libgig.DimensionRegion." + m_serializationArchive.rawDataFormat())
4045    
4046    void MainWindow::copy_selected_dimrgn() {
4047        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
4048        if (!pDimRgn) {
4049            updateClipboardPasteAvailable();
4050            updateClipboardCopyAvailable();
4051            return;
4052        }
4053    
4054        std::vector<Gtk::TargetEntry> targets;
4055        targets.push_back( Gtk::TargetEntry(CLIPBOARD_DIMENSIONREGION_TARGET) );
4056    
4057        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
4058        clipboard->set(
4059            targets,
4060            sigc::mem_fun(*this, &MainWindow::on_clipboard_get),
4061            sigc::mem_fun(*this, &MainWindow::on_clipboard_clear)
4062        );
4063    
4064        m_serializationArchive.serialize(pDimRgn);
4065    
4066        updateClipboardPasteAvailable();
4067    }
4068    
4069    void MainWindow::paste_copied_dimrgn() {
4070        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
4071        clipboard->request_contents(
4072            CLIPBOARD_DIMENSIONREGION_TARGET,
4073            sigc::mem_fun(*this, &MainWindow::on_clipboard_received)
4074        );
4075        updateClipboardPasteAvailable();
4076    }
4077    
4078    void MainWindow::adjust_clipboard_content() {
4079        MacroEditor* editor = new MacroEditor();
4080        editor->setMacro(&m_serializationArchive, true);
4081        editor->show();
4082    }
4083    
4084    void MainWindow::updateClipboardPasteAvailable() {
4085        Glib::RefPtr<Gtk::Clipboard> clipboard = Gtk::Clipboard::get();
4086        clipboard->request_targets(
4087            sigc::mem_fun(*this, &MainWindow::on_clipboard_received_targets)
4088        );
4089    }
4090    
4091    void MainWindow::updateClipboardCopyAvailable() {
4092        bool bDimensionRegionCopyIsPossible = m_DimRegionChooser.get_main_dimregion();
4093        static_cast<Gtk::MenuItem*>(
4094            uiManager->get_widget("/MenuBar/MenuEdit/CopyDimRgn")
4095        )->set_sensitive(bDimensionRegionCopyIsPossible);
4096    }
4097    
4098    void MainWindow::on_clipboard_owner_change(GdkEventOwnerChange* event) {
4099        updateClipboardPasteAvailable();
4100    }
4101    
4102    void MainWindow::on_clipboard_get(Gtk::SelectionData& selection_data, guint /*info*/) {
4103        const std::string target = selection_data.get_target();
4104        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
4105            selection_data.set(
4106                CLIPBOARD_DIMENSIONREGION_TARGET, 8 /* "format": probably unused*/,
4107                &m_serializationArchive.rawData()[0],
4108                m_serializationArchive.rawData().size()
4109            );
4110        } else {
4111            std::cerr << "Clipboard: content for unknown target '" << target << "' requested\n";
4112        }
4113    }
4114    
4115    void MainWindow::on_clipboard_clear() {
4116        m_serializationArchive.clear();
4117        updateClipboardPasteAvailable();
4118        updateClipboardCopyAvailable();
4119    }
4120    
4121    //NOTE: Might throw exception !!!
4122    void MainWindow::applyMacro(Serialization::Archive& macro) {
4123        gig::DimensionRegion* pDimRgn = m_DimRegionChooser.get_main_dimregion();
4124        if (!pDimRgn) return;
4125    
4126        for (std::set<gig::DimensionRegion*>::iterator itDimReg = dimreg_edit.dimregs.begin();
4127             itDimReg != dimreg_edit.dimregs.end(); ++itDimReg)
4128        {
4129            gig::DimensionRegion* pDimRgn = *itDimReg;
4130            DimRegionChangeGuard(this, pDimRgn);
4131            macro.deserialize(pDimRgn);
4132        }
4133        //region_changed()
4134        file_changed();
4135        dimreg_changed();
4136    }
4137    
4138    void MainWindow::on_clipboard_received(const Gtk::SelectionData& selection_data) {
4139        const std::string target = selection_data.get_target();
4140        if (target == CLIPBOARD_DIMENSIONREGION_TARGET) {
4141            Glib::ustring errorText;
4142            try {
4143                m_serializationArchive.decode(
4144                    selection_data.get_data(), selection_data.get_length()
4145                );
4146                applyMacro(m_serializationArchive);
4147            } catch (Serialization::Exception e) {
4148                errorText = e.Message;
4149            } catch (...) {
4150                errorText = _("Unknown exception while pasting DimensionRegion");
4151            }
4152            if (!errorText.empty()) {
4153                Glib::ustring txt = _("Pasting DimensionRegion failed:\n") + errorText;
4154                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
4155                msg.run();
4156            }
4157        }
4158    }
4159    
4160    void MainWindow::on_clipboard_received_targets(const std::vector<Glib::ustring>& targets) {
4161        const bool bDimensionRegionPasteIsPossible =
4162            std::find(targets.begin(), targets.end(),
4163                      CLIPBOARD_DIMENSIONREGION_TARGET) != targets.end();
4164    
4165        static_cast<Gtk::MenuItem*>(
4166            uiManager->get_widget("/MenuBar/MenuEdit/PasteDimRgn")
4167        )->set_sensitive(bDimensionRegionPasteIsPossible);
4168    
4169        static_cast<Gtk::MenuItem*>(
4170            uiManager->get_widget("/MenuBar/MenuEdit/AdjustClipboard")
4171        )->set_sensitive(bDimensionRegionPasteIsPossible);
4172  }  }
4173    
4174  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 4226  sigc::signal<void, int/*key*/, int/*velo
4226  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
4227      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
4228  }  }
4229    
4230    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
4231        return switch_sampler_instrument_signal;
4232    }

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

  ViewVC Help
Powered by ViewVC