/[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 2464 by schoenebeck, Thu Sep 5 00:49:13 2013 UTC revision 3123 by schoenebeck, Tue Apr 25 20:45:54 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006-2013 Andreas Persson   * Copyright (C) 2006-2017 Andreas Persson
3   *   *
4   * This program is free software; you can redistribute it and/or   * This program is free software; you can redistribute it and/or
5   * modify it under the terms of the GNU General Public License as   * modify it under the terms of the GNU General Public License as
# Line 20  Line 20 
20  #include <iostream>  #include <iostream>
21  #include <cstring>  #include <cstring>
22    
23    #include <glibmmconfig.h>
24    // threads.h must be included first to be able to build with
25    // G_DISABLE_DEPRECATED
26    #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION == 31 && GLIBMM_MICRO_VERSION >= 2) || \
27        (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION > 31) || GLIBMM_MAJOR_VERSION > 2
28    #include <glibmm/threads.h>
29    #endif
30    
31  #include <glibmm/convert.h>  #include <glibmm/convert.h>
32  #include <glibmm/dispatcher.h>  #include <glibmm/dispatcher.h>
33  #include <glibmm/miscutils.h>  #include <glibmm/miscutils.h>
# Line 27  Line 35 
35  #include <gtkmm/aboutdialog.h>  #include <gtkmm/aboutdialog.h>
36  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
37  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
 #include <gtkmm/stock.h>  
38  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
39  #include <gtkmm/main.h>  #include <gtkmm/main.h>
40  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
# Line 40  Line 47 
47    
48  #include <stdio.h>  #include <stdio.h>
49  #include <sndfile.h>  #include <sndfile.h>
50    #include <assert.h>
51    
52  #include "mainwindow.h"  #include "mainwindow.h"
53    #include "Settings.h"
54    #include "CombineInstrumentsDialog.h"
55    #include "scripteditor.h"
56    #include "scriptslots.h"
57    #include "ReferencesView.h"
58  #include "../../gfx/status_attached.xpm"  #include "../../gfx/status_attached.xpm"
59  #include "../../gfx/status_detached.xpm"  #include "../../gfx/status_detached.xpm"
60    #include "gfx/builtinpix.h"
61    
62  MainWindow::MainWindow() :  MainWindow::MainWindow() :
63        m_DimRegionChooser(*this),
64      dimreg_label(_("Changes apply to:")),      dimreg_label(_("Changes apply to:")),
65      dimreg_all_regions(_("all regions")),      dimreg_all_regions(_("all regions")),
66      dimreg_all_dimregs(_("all dimension splits")),      dimreg_all_dimregs(_("all dimension splits")),
67      dimreg_stereo(_("both channels"))      dimreg_stereo(_("both channels")),
68        labelLegend(_("Legend:")),
69        labelNoSample(_(" No Sample")),
70        labelMissingSample(_(" Missing some Sample(s)")),
71        labelLooped(_(" Looped")),
72        labelSomeLoops(_(" Some Loop(s)"))
73  {  {
74        loadBuiltInPix();
75    
76  //    set_border_width(5);  //    set_border_width(5);
77  //    set_default_size(400, 200);  //    set_default_size(400, 200);
78    
   
79      add(m_VBox);      add(m_VBox);
80    
81      // Handle selection      // Handle selection
# Line 76  MainWindow::MainWindow() : Line 95  MainWindow::MainWindow() :
95      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
96      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
97    
98        m_ScrolledWindowScripts.add(m_TreeViewScripts);
99        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
100    
101    
102      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
103    
# Line 87  MainWindow::MainWindow() : Line 109  MainWindow::MainWindow() :
109      dimreg_hbox.add(dimreg_stereo);      dimreg_hbox.add(dimreg_stereo);
110      dimreg_vbox.add(dimreg_edit);      dimreg_vbox.add(dimreg_edit);
111      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);      dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
112        {
113            legend_hbox.add(labelLegend);
114    
115            imageNoSample.set(redDot);
116            imageNoSample.set_alignment(Gtk::ALIGN_END);
117            labelNoSample.set_alignment(Gtk::ALIGN_START);
118            legend_hbox.add(imageNoSample);
119            legend_hbox.add(labelNoSample);
120    
121            imageMissingSample.set(yellowDot);
122            imageMissingSample.set_alignment(Gtk::ALIGN_END);
123            labelMissingSample.set_alignment(Gtk::ALIGN_START);
124            legend_hbox.add(imageMissingSample);
125            legend_hbox.add(labelMissingSample);
126    
127            imageLooped.set(blackLoop);
128            imageLooped.set_alignment(Gtk::ALIGN_END);
129            labelLooped.set_alignment(Gtk::ALIGN_START);
130            legend_hbox.add(imageLooped);
131            legend_hbox.add(labelLooped);
132    
133            imageSomeLoops.set(grayLoop);
134            imageSomeLoops.set_alignment(Gtk::ALIGN_END);
135            labelSomeLoops.set_alignment(Gtk::ALIGN_START);
136            legend_hbox.add(imageSomeLoops);
137            legend_hbox.add(labelSomeLoops);
138    
139            legend_hbox.show_all_children();
140        }
141        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
142      m_HPaned.add2(dimreg_vbox);      m_HPaned.add2(dimreg_vbox);
143    
144        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
145        dimreg_all_regions.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied to all regions of this instrument as well."));
146        dimreg_all_dimregs.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied as well to all dimension splits of the region selected below."));
147        dimreg_stereo.set_tooltip_text(_("If checked: all changes you perform above will automatically be applied to both audio channel splits (only if a \"stereo\" dimension is defined below)."));
148    
149      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
150      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));      m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
151        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
152    
153      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
154    
155      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
156      actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),      actionGroup->add(Gtk::Action::create("New", _("_New")),
157                         Gtk::AccelKey("<control>n"),
158                       sigc::mem_fun(                       sigc::mem_fun(
159                           *this, &MainWindow::on_action_file_new));                           *this, &MainWindow::on_action_file_new));
160      Glib::RefPtr<Gtk::Action> action =      actionGroup->add(Gtk::Action::create("Open", _("_Open...")),
161          Gtk::Action::create("Open", Gtk::Stock::OPEN);                       Gtk::AccelKey("<control>o"),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
162                       sigc::mem_fun(                       sigc::mem_fun(
163                           *this, &MainWindow::on_action_file_open));                           *this, &MainWindow::on_action_file_open));
164      actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),      actionGroup->add(Gtk::Action::create("Save", _("_Save")),
165                         Gtk::AccelKey("<control>s"),
166                       sigc::mem_fun(                       sigc::mem_fun(
167                           *this, &MainWindow::on_action_file_save));                           *this, &MainWindow::on_action_file_save));
168      action = Gtk::Action::create("SaveAs", Gtk::Stock::SAVE_AS);      actionGroup->add(Gtk::Action::create("SaveAs", _("Save _As...")),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
169                       Gtk::AccelKey("<shift><control>s"),                       Gtk::AccelKey("<shift><control>s"),
170                       sigc::mem_fun(                       sigc::mem_fun(
171                           *this, &MainWindow::on_action_file_save_as));                           *this, &MainWindow::on_action_file_save_as));
172      actionGroup->add(Gtk::Action::create("Properties",      actionGroup->add(Gtk::Action::create("Properties",
173                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
174                       sigc::mem_fun(                       sigc::mem_fun(
175                           *this, &MainWindow::on_action_file_properties));                           *this, &MainWindow::on_action_file_properties));
176      actionGroup->add(Gtk::Action::create("InstrProperties",      actionGroup->add(Gtk::Action::create("InstrProperties",
177                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
178                       sigc::mem_fun(                       sigc::mem_fun(
179                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
180      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("MidiRules",
181                                             _("_Midi Rules...")),
182                         sigc::mem_fun(
183                             *this, &MainWindow::show_midi_rules));
184        actionGroup->add(Gtk::Action::create("ScriptSlots",
185                                             _("_Script Slots...")),
186                         sigc::mem_fun(
187                             *this, &MainWindow::show_script_slots));
188        actionGroup->add(Gtk::Action::create("Quit", _("_Quit")),
189                         Gtk::AccelKey("<control>q"),
190                       sigc::mem_fun(                       sigc::mem_fun(
191                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
192      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
193            Gtk::Action::create("MenuSample", _("_Sample")),
194            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
195        );
196        actionGroup->add(
197            Gtk::Action::create("MenuInstrument", _("_Instrument")),
198            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
199        );
200        actionGroup->add(
201            Gtk::Action::create("MenuScript", _("S_cript")),
202            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
203        );
204        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
205    
206      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));      actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
207    
208        const Gdk::ModifierType primaryModifierKey =
209    #if defined(__APPLE__)
210        Gdk::META_MASK; // Cmd key on Mac
211    #else
212        Gdk::CONTROL_MASK; // Ctrl key on all other OSs
213    #endif
214    
215        actionGroup->add(Gtk::Action::create("SelectPrevRegion",
216                                             _("Select Previous Region")),
217                         Gtk::AccelKey(GDK_KEY_Left, primaryModifierKey),
218                         sigc::mem_fun(*this, &MainWindow::select_prev_region));
219    
220        actionGroup->add(Gtk::Action::create("SelectNextRegion",
221                                             _("Select Next Region")),
222                         Gtk::AccelKey(GDK_KEY_Right, primaryModifierKey),
223                         sigc::mem_fun(*this, &MainWindow::select_next_region));
224    
225        actionGroup->add(Gtk::Action::create("SelectPrevDimRgnZone",
226                                             _("Select Previous Dimension Region Zone")),
227                         Gtk::AccelKey(GDK_KEY_Left, Gdk::MOD1_MASK),
228                         sigc::mem_fun(*this, &MainWindow::select_prev_dim_rgn_zone));
229    
230        actionGroup->add(Gtk::Action::create("SelectNextDimRgnZone",
231                                             _("Select Next Dimension Region Zone")),
232                         Gtk::AccelKey(GDK_KEY_Right, Gdk::MOD1_MASK),
233                         sigc::mem_fun(*this, &MainWindow::select_next_dim_rgn_zone));
234    
235        actionGroup->add(Gtk::Action::create("SelectPrevDimension",
236                                             _("Select Previous Dimension")),
237                         Gtk::AccelKey(GDK_KEY_Up, Gdk::MOD1_MASK),
238                         sigc::mem_fun(*this, &MainWindow::select_prev_dimension));
239    
240        actionGroup->add(Gtk::Action::create("SelectNextDimension",
241                                             _("Select Next Dimension")),
242                         Gtk::AccelKey(GDK_KEY_Down, Gdk::MOD1_MASK),
243                         sigc::mem_fun(*this, &MainWindow::select_next_dimension));
244    
245    
246      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
247          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"), "ffaga");          Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
248      toggle_action->set_active(true);      toggle_action->set_active(true);
     //FIXME: doesn't work, why?  
     toggle_action->set_tooltip(_("Used when dragging a sample to a region's sample reference field."));  
249      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
250    
251      toggle_action =      toggle_action =
252          Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));          Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
253      toggle_action->set_active(true);      toggle_action->set_active(true);
     //FIXME: doesn't work, why?  
     toggle_action->set_tooltip(_("Used when dragging a sample to a region's sample reference field."));  
254      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
255    
256      toggle_action =      toggle_action =
257          Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));          Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
258      toggle_action->set_active(true);      toggle_action->set_active(true);
     //FIXME: doesn't work, why?  
     toggle_action->set_tooltip(_("Used when dragging a sample to a region's sample reference field."));  
259      actionGroup->add(toggle_action);      actionGroup->add(toggle_action);
260    
261    
# Line 161  MainWindow::MainWindow() : Line 267  MainWindow::MainWindow() :
267                       sigc::mem_fun(                       sigc::mem_fun(
268                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
269    
270      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      toggle_action =
271      actionGroup->add(Gtk::Action::create("MenuHelp",          Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
272                                           action->property_label()));      toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
273      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),      actionGroup->add(toggle_action,
274                         sigc::mem_fun(
275                             *this, &MainWindow::on_auto_restore_win_dim));
276    
277        toggle_action =
278            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
279        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
280        actionGroup->add(toggle_action,
281                         sigc::mem_fun(
282                             *this, &MainWindow::on_save_with_temporary_file));
283    
284        actionGroup->add(
285            Gtk::Action::create("RefreshAll", _("_Refresh All")),
286            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
287        );                
288    
289        actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
290        actionGroup->add(Gtk::Action::create("About", _("_About")),
291                       sigc::mem_fun(                       sigc::mem_fun(
292                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
293      actionGroup->add(      actionGroup->add(
# Line 176  MainWindow::MainWindow() : Line 299  MainWindow::MainWindow() :
299          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
300      );      );
301      actionGroup->add(      actionGroup->add(
302          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveInstrument", _("_Remove")),
303          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
304      );      );
305    
306    
307        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
308        
309        toggle_action =
310            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
311        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
312        actionGroup->add(
313            toggle_action,
314            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
315        );
316    
317        toggle_action =
318            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
319        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
320        actionGroup->add(
321            toggle_action,
322            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
323        );
324    
325        toggle_action =
326            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
327        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
328        actionGroup->add(
329            toggle_action,
330            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
331        );
332    
333    
334        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
335    
336        actionGroup->add(
337            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
338            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
339        );
340    
341        actionGroup->add(
342            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
343            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
344        );
345    
346    
347      // sample right-click popup actions      // sample right-click popup actions
348      actionGroup->add(      actionGroup->add(
349          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", _("_Properties")),
350          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
351      );      );
352      actionGroup->add(      actionGroup->add(
# Line 194  MainWindow::MainWindow() : Line 358  MainWindow::MainWindow() :
358          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
359      );      );
360      actionGroup->add(      actionGroup->add(
361          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", _("_Remove")),
362          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
363      );      );
364      actionGroup->add(      actionGroup->add(
365            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
366            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
367        );
368        actionGroup->add(
369            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
370            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
371        );
372        actionGroup->add(
373            Gtk::Action::create("ReplaceSample",
374                                _("Replace Sample...")),
375            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
376        );
377        actionGroup->add(
378          Gtk::Action::create("ReplaceAllSamplesInAllGroups",          Gtk::Action::create("ReplaceAllSamplesInAllGroups",
379                              _("Replace All Samples in All Groups...")),                              _("Replace All Samples in All Groups...")),
380          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)
381      );      );
382        
383        // script right-click popup actions
384        actionGroup->add(
385            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
386            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
387        );
388        actionGroup->add(
389            Gtk::Action::create("AddScript", _("Add _Script")),
390            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
391        );
392        actionGroup->add(
393            Gtk::Action::create("EditScript", _("_Edit Script...")),
394            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
395        );
396        actionGroup->add(
397            Gtk::Action::create("RemoveScript", _("_Remove")),
398            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
399        );
400    
401      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
402      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 222  MainWindow::MainWindow() : Line 417  MainWindow::MainWindow() :
417          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
418          "    </menu>"          "    </menu>"
419          "    <menu action='MenuEdit'>"          "    <menu action='MenuEdit'>"
420            "      <menuitem action='SelectPrevRegion'/>"
421            "      <menuitem action='SelectNextRegion'/>"
422            "      <separator/>"
423            "      <menuitem action='SelectPrevDimRgnZone'/>"
424            "      <menuitem action='SelectNextDimRgnZone'/>"
425            "      <menuitem action='SelectPrevDimension'/>"
426            "      <menuitem action='SelectNextDimension'/>"
427            "      <separator/>"
428          "      <menuitem action='CopySampleUnity'/>"          "      <menuitem action='CopySampleUnity'/>"
429          "      <menuitem action='CopySampleTune'/>"          "      <menuitem action='CopySampleTune'/>"
430          "      <menuitem action='CopySampleLoop'/>"          "      <menuitem action='CopySampleLoop'/>"
431          "    </menu>"          "    </menu>"
432            "    <menu action='MenuSample'>"
433            "      <menuitem action='SampleProperties'/>"
434            "      <menuitem action='AddGroup'/>"
435            "      <menuitem action='AddSample'/>"
436            "      <menuitem action='ShowSampleRefs'/>"
437            "      <menuitem action='ReplaceSample' />"
438            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
439            "      <separator/>"
440            "      <menuitem action='RemoveSample'/>"
441            "      <menuitem action='RemoveUnusedSamples'/>"
442            "    </menu>"
443          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
444            "      <menu action='AllInstruments'>"
445            "      </menu>"
446            "      <separator/>"
447            "      <menuitem action='InstrProperties'/>"
448            "      <menuitem action='MidiRules'/>"
449            "      <menuitem action='ScriptSlots'/>"
450            "      <menuitem action='AddInstrument'/>"
451            "      <menuitem action='DupInstrument'/>"
452            "      <separator/>"
453            "      <menuitem action='RemoveInstrument'/>"
454            "    </menu>"
455            "    <menu action='MenuScript'>"
456            "      <menuitem action='AddScriptGroup'/>"
457            "      <menuitem action='AddScript'/>"
458            "      <menuitem action='EditScript'/>"
459            "      <separator/>"
460            "      <menuitem action='RemoveScript'/>"
461          "    </menu>"          "    </menu>"
462          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
463          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
464            "      <menuitem action='AutoRestoreWinDim'/>"
465            "      <separator/>"
466            "      <menuitem action='RefreshAll'/>"
467            "    </menu>"
468            "    <menu action='MenuTools'>"
469            "      <menuitem action='CombineInstruments'/>"
470            "      <menuitem action='MergeFiles'/>"
471            "    </menu>"
472            "    <menu action='MenuSettings'>"
473            "      <menuitem action='WarnUserOnExtensions'/>"
474            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
475            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
476            "      <menuitem action='SaveWithTemporaryFile'/>"
477          "    </menu>"          "    </menu>"
478          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
479          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
# Line 237  MainWindow::MainWindow() : Line 481  MainWindow::MainWindow() :
481          "  </menubar>"          "  </menubar>"
482          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
483          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
484            "    <menuitem action='MidiRules'/>"
485            "    <menuitem action='ScriptSlots'/>"
486          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
487          "    <menuitem action='DupInstrument'/>"          "    <menuitem action='DupInstrument'/>"
488          "    <separator/>"          "    <separator/>"
# Line 246  MainWindow::MainWindow() : Line 492  MainWindow::MainWindow() :
492          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
493          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
494          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
495            "    <menuitem action='ShowSampleRefs'/>"
496            "    <menuitem action='ReplaceSample' />"
497          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"          "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
498          "    <separator/>"          "    <separator/>"
499          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
500            "    <menuitem action='RemoveUnusedSamples'/>"
501            "  </popup>"
502            "  <popup name='ScriptPopupMenu'>"
503            "    <menuitem action='AddScriptGroup'/>"
504            "    <menuitem action='AddScript'/>"
505            "    <menuitem action='EditScript'/>"
506            "    <separator/>"
507            "    <menuitem action='RemoveScript'/>"
508          "  </popup>"          "  </popup>"
509          "</ui>";          "</ui>";
510      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
511    
512      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
513        
514        // Set tooltips for menu items (for some reason, setting a tooltip on the
515        // respective Gtk::Action objects above will simply be ignored, no matter
516        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
517        // Gtk::Action::create()).
518        {
519            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
520                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
521            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current unity note setting will be altered by this action."));
522        }
523        {
524            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
525                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
526            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current sample playback tuning will be altered by this action."));
527        }
528        {
529            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
530                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
531            item->set_tooltip_text(_("Used when dragging a sample to a region's sample reference field. You may disable this for example if you want to replace an existing sample in a region with a new sample, but don't want that the region's current loop informations to be altered by this action."));
532        }
533        {
534            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
535                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
536            item->set_tooltip_text(_("If checked, a warning will be shown whenever you try to use a feature which is based on a LinuxSampler extension ontop of the original gig format, which would not work with the Gigasampler/GigaStudio application."));
537        }
538        {
539            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
540                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
541            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)."));
542        }
543        {
544            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
545                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
546            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."));
547        }
548        {
549            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
550                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
551            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
552            // copy tooltip to popup menu
553            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
554                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
555            item2->set_tooltip_text(item->get_tooltip_text());
556        }
557        {
558            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
559                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
560            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
561        }
562        {
563            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
564                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
565            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
566        }
567        {
568            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
569                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
570            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
571        }
572        {
573            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
574                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
575            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
576        }
577    
578    
579      instrument_menu = static_cast<Gtk::MenuItem*>(      instrument_menu = static_cast<Gtk::MenuItem*>(
580          uiManager->get_widget("/MenuBar/MenuInstrument"))->get_submenu();          uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
581    
582      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
583      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
# Line 282  MainWindow::MainWindow() : Line 603  MainWindow::MainWindow() :
603      // Create the Tree model:      // Create the Tree model:
604      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
605      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
606        m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
607        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
608      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(      instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
609          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
610      );      );
611    
612      // Add the TreeView's view columns:      // Add the TreeView's view columns:
613      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
614      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
615        m_TreeView.set_headers_visible(true);
616        
617        // establish drag&drop within the instrument tree view, allowing to reorder
618        // the sequence of instruments within the gig file
619        {
620            std::vector<Gtk::TargetEntry> drag_target_instrument;
621            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
622            m_TreeView.drag_source_set(drag_target_instrument);
623            m_TreeView.drag_dest_set(drag_target_instrument);
624            m_TreeView.signal_drag_begin().connect(
625                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
626            );
627            m_TreeView.signal_drag_data_get().connect(
628                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
629            );
630            m_TreeView.signal_drag_data_received().connect(
631                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
632            );
633        }
634    
635      // create samples treeview (including its data model)      // create samples treeview (including its data model)
636      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
637      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
638        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
639        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."));
640      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
641      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
642      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
643        {
644            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
645            Gtk::CellRendererText* cellrenderer =
646                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
647            column->add_attribute(
648                cellrenderer->property_foreground(), m_SamplesModel.m_color
649            );
650        }
651        {
652            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
653            Gtk::CellRendererText* cellrenderer =
654                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
655            column->add_attribute(
656                cellrenderer->property_foreground(), m_SamplesModel.m_color
657            );
658        }
659        m_TreeViewSamples.set_headers_visible(true);
660      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
661          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
662      );      );
# Line 303  MainWindow::MainWindow() : Line 664  MainWindow::MainWindow() :
664          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
665      );      );
666    
667        // create scripts treeview (including its data model)
668        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
669        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
670        m_TreeViewScripts.set_tooltip_text(_(
671            "Use CTRL + double click for editing a script."
672            "\n\n"
673            "Note: instrument scripts are a LinuxSampler extension of the gig "
674            "format. This feature will not work with the GigaStudio software!"
675        ));
676        // m_TreeViewScripts.set_reorderable();
677        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
678        m_TreeViewScripts.set_headers_visible(false);
679        m_TreeViewScripts.signal_button_press_event().connect_notify(
680            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
681        );
682        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
683        m_TreeViewScripts.signal_row_activated().connect(
684            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
685        );
686        m_refScriptsTreeModel->signal_row_changed().connect(
687            sigc::mem_fun(*this, &MainWindow::script_name_changed)
688        );
689    
690        // establish drag&drop between scripts tree view and ScriptSlots window
691        std::vector<Gtk::TargetEntry> drag_target_gig_script;
692        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
693        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
694        m_TreeViewScripts.signal_drag_begin().connect(
695            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
696        );
697        m_TreeViewScripts.signal_drag_data_get().connect(
698            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
699        );
700    
701      // 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
702      std::vector<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
703      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
# Line 321  MainWindow::MainWindow() : Line 716  MainWindow::MainWindow() :
716          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
717      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
718          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
719        m_RegionChooser.signal_instrument_changed().connect(
720            sigc::mem_fun(*this, &MainWindow::region_changed));
721      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
722          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
723      instrumentProps.signal_changed().connect(      instrumentProps.signal_changed().connect(
724          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
725      propDialog.signal_changed().connect(      propDialog.signal_changed().connect(
726          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
727        midiRules.signal_changed().connect(
728            sigc::mem_fun(*this, &MainWindow::file_changed));
729    
730      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
731          dimreg_to_be_changed_signal.make_slot());          dimreg_to_be_changed_signal.make_slot());
# Line 334  MainWindow::MainWindow() : Line 733  MainWindow::MainWindow() :
733          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
734      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
735          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
736        sample_ref_changed_signal.connect(
737            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
738        );
739        samples_to_be_removed_signal.connect(
740            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
741        );
742    
743        dimreg_edit.signal_select_sample().connect(
744            sigc::mem_fun(*this, &MainWindow::select_sample)
745        );
746    
747      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
748          sigc::hide(          sigc::hide(
# Line 375  MainWindow::MainWindow() : Line 784  MainWindow::MainWindow() :
784    
785      // start with a new gig file by default      // start with a new gig file by default
786      on_action_file_new();      on_action_file_new();
787    
788        // select 'Instruments' tab by default
789        // (gtk allows this only if the tab childs are visible, thats why it's here)
790        m_TreeViewNotebook.set_current_page(1);
791  }  }
792    
793  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 400  void MainWindow::region_changed() Line 813  void MainWindow::region_changed()
813  gig::Instrument* MainWindow::get_instrument()  gig::Instrument* MainWindow::get_instrument()
814  {  {
815      gig::Instrument* instrument = 0;      gig::Instrument* instrument = 0;
816      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
817          m_TreeView.get_selection()->get_selected();      if (rows.empty()) return NULL;
818        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
819      if (it) {      if (it) {
820          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
821          instrument = row[m_Columns.m_col_instr];          instrument = row[m_Columns.m_col_instr];
# Line 444  void MainWindow::update_dimregs() Line 858  void MainWindow::update_dimregs()
858              add_region_to_dimregs(region, stereo, all_dimregs);              add_region_to_dimregs(region, stereo, all_dimregs);
859          }          }
860      }      }
861    
862        m_DimRegionChooser.setModifyAllRegions(all_regions);
863        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
864        m_DimRegionChooser.setModifyBothChannels(stereo);
865  }  }
866    
867  void MainWindow::dimreg_all_dimregs_toggled()  void MainWindow::dimreg_all_dimregs_toggled()
# Line 455  void MainWindow::dimreg_all_dimregs_togg Line 873  void MainWindow::dimreg_all_dimregs_togg
873  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
874  {  {
875      update_dimregs();      update_dimregs();
876      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
877  }  }
878    
879  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
880  {  {
881      // select item in instrument menu      // select item in instrument menu
882      Gtk::TreeModel::iterator it = m_TreeView.get_selection()->get_selected();      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
883      if (it) {      if (!rows.empty()) {
884          Gtk::TreePath path(it);          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
885          int index = path[0];          if (it) {
886          const std::vector<Gtk::Widget*> children =              Gtk::TreePath path(it);
887              instrument_menu->get_children();              int index = path[0];
888          static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();              const std::vector<Gtk::Widget*> children =
889                    instrument_menu->get_children();
890                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
891            }
892      }      }
893    
894      m_RegionChooser.set_instrument(get_instrument());      m_RegionChooser.set_instrument(get_instrument());
895    
896        if (Settings::singleton()->syncSamplerInstrumentSelection) {
897            switch_sampler_instrument_signal.emit(get_instrument());
898        }
899  }  }
900    
901  void loader_progress_callback(gig::progress_t* progress)  void loader_progress_callback(gig::progress_t* progress)
# Line 488  void Loader::progress_callback(float fra Line 913  void Loader::progress_callback(float fra
913      progress_dispatcher();      progress_dispatcher();
914  }  }
915    
916    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
917    // make sure stack is 16-byte aligned for SSE instructions
918    __attribute__((force_align_arg_pointer))
919    #endif
920  void Loader::thread_function()  void Loader::thread_function()
921  {  {
922      printf("thread_function self=%x\n", Glib::Threads::Thread::self());      printf("thread_function self=%p\n",
923      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
924      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
925      gig = new gig::File(riff);      try {
926      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
927      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
928      progress.custom = this;          gig::progress_t progress;
929            progress.callback = loader_progress_callback;
930      gig->GetInstrument(0, &progress);          progress.custom = this;
931      printf("End\n");  
932      finished_dispatcher();          gig->GetInstrument(0, &progress);
933            printf("End\n");
934            finished_dispatcher();
935        } catch (RIFF::Exception e) {
936            error_message = e.Message;
937            error_dispatcher.emit();
938        } catch (...) {
939            error_message = _("Unknown exception occurred");
940            error_dispatcher.emit();
941        }
942  }  }
943    
944  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
945      : filename(filename), thread(0)      : filename(filename), gig(0), thread(0), progress(0.f)
946  {  {
947  }  }
948    
# Line 515  void Loader::launch() Line 953  void Loader::launch()
953  #else  #else
954      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));      thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
955  #endif  #endif
956      printf("launch thread=%x\n", thread);      printf("launch thread=%p\n", static_cast<void*>(thread));
957  }  }
958    
959  float Loader::get_progress()  float Loader::get_progress()
# Line 538  Glib::Dispatcher& Loader::signal_finishe Line 976  Glib::Dispatcher& Loader::signal_finishe
976      return finished_dispatcher;      return finished_dispatcher;
977  }  }
978    
979  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
980    {
981        return error_dispatcher;
982    }
983    
984    void saver_progress_callback(gig::progress_t* progress)
985    {
986        Saver* saver = static_cast<Saver*>(progress->custom);
987        saver->progress_callback(progress->factor);
988    }
989    
990    void Saver::progress_callback(float fraction)
991    {
992        {
993            Glib::Threads::Mutex::Lock lock(progressMutex);
994            progress = fraction;
995        }
996        progress_dispatcher.emit();
997    }
998    
999    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
1000    // make sure stack is 16-byte aligned for SSE instructions
1001    __attribute__((force_align_arg_pointer))
1002    #endif
1003    void Saver::thread_function()
1004    {
1005        printf("thread_function self=%p\n",
1006               static_cast<void*>(Glib::Threads::Thread::self()));
1007        printf("Start %s\n", filename.c_str());
1008        try {
1009            gig::progress_t progress;
1010            progress.callback = saver_progress_callback;
1011            progress.custom = this;
1012    
1013            // if no filename was provided, that means "save", if filename was provided means "save as"
1014            if (filename.empty()) {
1015                if (!Settings::singleton()->saveWithTemporaryFile) {
1016                    // save directly over the existing .gig file
1017                    // (requires less disk space than solution below
1018                    // but may be slower)
1019                    gig->Save(&progress);
1020                } else {
1021                    // save the file as separate temporary file first,
1022                    // then move the saved file over the old file
1023                    // (may result in performance speedup during save)
1024                    String tmpname = filename + ".TMP";
1025                    gig->Save(tmpname, &progress);
1026                    #if defined(WIN32)
1027                    if (!DeleteFile(filename.c_str())) {
1028                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
1029                    }
1030                    #else // POSIX ...
1031                    if (unlink(filename.c_str())) {
1032                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
1033                    }
1034                    #endif
1035                    if (rename(tmpname.c_str(), filename.c_str())) {
1036                        #if defined(WIN32)
1037                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
1038                        #else
1039                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
1040                        #endif
1041                    }
1042                }
1043            } else {
1044                gig->Save(filename, &progress);
1045            }
1046    
1047            printf("End\n");
1048            finished_dispatcher.emit();
1049        } catch (RIFF::Exception e) {
1050            error_message = e.Message;
1051            error_dispatcher.emit();
1052        } catch (...) {
1053            error_message = _("Unknown exception occurred");
1054            error_dispatcher.emit();
1055        }
1056    }
1057    
1058    Saver::Saver(gig::File* file, Glib::ustring filename)
1059        : gig(file), filename(filename), thread(0), progress(0.f)
1060    {
1061    }
1062    
1063    void Saver::launch()
1064    {
1065    #ifdef OLD_THREADS
1066        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1067    #else
1068        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1069    #endif
1070        printf("launch thread=%p\n", static_cast<void*>(thread));
1071    }
1072    
1073    float Saver::get_progress()
1074    {
1075        float res;
1076        {
1077            Glib::Threads::Mutex::Lock lock(progressMutex);
1078            res = progress;
1079        }
1080        return res;
1081    }
1082    
1083    Glib::Dispatcher& Saver::signal_progress()
1084    {
1085        return progress_dispatcher;
1086    }
1087    
1088    Glib::Dispatcher& Saver::signal_finished()
1089    {
1090        return finished_dispatcher;
1091    }
1092    
1093    Glib::Dispatcher& Saver::signal_error()
1094    {
1095        return error_dispatcher;
1096    }
1097    
1098    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1099      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1100  {  {
1101      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1102      show_all_children();      show_all_children();
1103        resize(600,50);
1104  }  }
1105    
1106  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
# Line 553  void MainWindow::__clear() { Line 1111  void MainWindow::__clear() {
1111      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1112      m_refTreeModel->clear();      m_refTreeModel->clear();
1113      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1114        m_refScriptsTreeModel->clear();
1115      // remove all entries from "Instrument" menu      // remove all entries from "Instrument" menu
1116      while (!instrument_menu->get_children().empty()) {      while (!instrument_menu->get_children().empty()) {
1117          remove_instrument_from_menu(0);          remove_instrument_from_menu(0);
# Line 563  void MainWindow::__clear() { Line 1122  void MainWindow::__clear() {
1122      set_file_is_shared(false);      set_file_is_shared(false);
1123  }  }
1124    
1125    void MainWindow::__refreshEntireGUI() {
1126        // clear the samples and instruments tree views
1127        m_refTreeModel->clear();
1128        m_refSamplesTreeModel->clear();
1129        m_refScriptsTreeModel->clear();
1130        // remove all entries from "Instrument" menu
1131        while (!instrument_menu->get_children().empty()) {
1132            remove_instrument_from_menu(0);
1133        }
1134    
1135        if (!this->file) return;
1136    
1137        load_gig(
1138            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1139        );
1140    }
1141    
1142  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
1143  {  {
1144      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 588  bool MainWindow::close_confirmation_dial Line 1164  bool MainWindow::close_confirmation_dial
1164      g_free(msg);      g_free(msg);
1165      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));      dialog.set_secondary_text(_("If you close without saving, your changes will be lost."));
1166      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1167      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1168      dialog.add_button(file_has_name ? Gtk::Stock::SAVE : Gtk::Stock::SAVE_AS, Gtk::RESPONSE_YES);      dialog.add_button(file_has_name ? _("_Save") : _("Save _As"), Gtk::RESPONSE_YES);
1169      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1170      int response = dialog.run();      int response = dialog.run();
1171      dialog.hide();      dialog.hide();
1172      if (response == Gtk::RESPONSE_YES) return file_save();  
1173      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1174        if (response == Gtk::RESPONSE_NO) return true;
1175    
1176        // user cancelled dialog, thus don't close app
1177        if (response == Gtk::RESPONSE_CANCEL) return false;
1178    
1179        // TODO: the following return valid is disabled and hard coded instead for
1180        // now, due to the fact that saving with progress bar is now implemented
1181        // asynchronously, as a result the app does not close automatically anymore
1182        // after saving the file has completed
1183        //
1184        //   if (response == Gtk::RESPONSE_YES) return file_save();
1185        //   return response != Gtk::RESPONSE_CANCEL;
1186        //
1187        if (response == Gtk::RESPONSE_YES) file_save();
1188        return false; // always prevent closing the app for now (see comment above)
1189  }  }
1190    
1191  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
# Line 605  bool MainWindow::leaving_shared_mode_dia Line 1196  bool MainWindow::leaving_shared_mode_dia
1196            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1197            "load it."));            "load it."));
1198      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1199      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1200      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1201      int response = dialog.run();      int response = dialog.run();
1202      dialog.hide();      dialog.hide();
# Line 619  void MainWindow::on_action_file_open() Line 1210  void MainWindow::on_action_file_open()
1210      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
1211    
1212      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1213      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1214      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1215      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1216  #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
1217      Gtk::FileFilter filter;      Gtk::FileFilter filter;
# Line 636  void MainWindow::on_action_file_open() Line 1227  void MainWindow::on_action_file_open()
1227      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1228          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1229          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1230          printf("on_action_file_open self=%x\n", Glib::Threads::Thread::self());          printf("on_action_file_open self=%p\n",
1231                   static_cast<void*>(Glib::Threads::Thread::self()));
1232          load_file(filename.c_str());          load_file(filename.c_str());
1233          current_gig_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1234      }      }
# Line 645  void MainWindow::on_action_file_open() Line 1237  void MainWindow::on_action_file_open()
1237  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1238  {  {
1239      __clear();      __clear();
1240      load_dialog = new LoadDialog(_("Loading..."), *this);  
1241      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1242      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1243            Glib::filename_display_basename(name) + "' ...",
1244            *this
1245        );
1246        progress_dialog->show_all();
1247        loader = new Loader(name); //FIXME: memory leak!
1248      loader->signal_progress().connect(      loader->signal_progress().connect(
1249          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1250      loader->signal_finished().connect(      loader->signal_finished().connect(
1251          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1252        loader->signal_error().connect(
1253            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1254      loader->launch();      loader->launch();
1255  }  }
1256    
# Line 667  void MainWindow::load_instrument(gig::In Line 1266  void MainWindow::load_instrument(gig::In
1266      // load the instrument      // load the instrument
1267      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1268      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1269      //TODO: automatically select the given instrument      // automatically select the given instrument
1270        int i = 0;
1271        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1272             instrument = pFile->GetNextInstrument(), ++i)
1273        {
1274            if (instrument == instr) {
1275                // select item in "instruments" tree view
1276                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1277                // make sure the selected item in the "instruments" tree view is
1278                // visible (scroll to it)
1279                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1280                // select item in instrument menu
1281                {
1282                    const std::vector<Gtk::Widget*> children =
1283                        instrument_menu->get_children();
1284                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1285                }
1286                // update region chooser and dimension region chooser
1287                m_RegionChooser.set_instrument(instr);
1288                break;
1289            }
1290        }
1291  }  }
1292    
1293  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1294  {  {
1295      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1296  }  }
1297    
1298  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1299  {  {
1300      printf("Loader finished!\n");      printf("Loader finished!\n");
1301      printf("on_loader_finished self=%x\n", Glib::Threads::Thread::self());      printf("on_loader_finished self=%p\n",
1302      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1303      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1304        progress_dialog->hide();
1305    }
1306    
1307    void MainWindow::on_loader_error()
1308    {
1309        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1310        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1311        msg.run();
1312        progress_dialog->hide();
1313  }  }
1314    
1315  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 719  bool MainWindow::file_save() Line 1348  bool MainWindow::file_save()
1348    
1349      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1350      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1351      try {  
1352          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1353          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1354              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1355              file_is_changed = false;          *this
1356          }      );
1357      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1358          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1359          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1360          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1361          msg.run();      saver->signal_finished().connect(
1362          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1363      }      saver->signal_error().connect(
1364      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1365        saver->launch();
1366    
1367        return true;
1368    }
1369    
1370    void MainWindow::on_saver_progress()
1371    {
1372        progress_dialog->set_fraction(saver->get_progress());
1373    }
1374    
1375    void MainWindow::on_saver_error()
1376    {
1377        file_structure_changed_signal.emit(this->file);
1378        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1379        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1380        msg.run();
1381    }
1382    
1383    void MainWindow::on_saver_finished()
1384    {
1385        this->file = saver->gig;
1386        this->filename = saver->filename;
1387        current_gig_dir = Glib::path_get_dirname(filename);
1388        set_title(Glib::filename_display_basename(filename));
1389        file_has_name = true;
1390        file_is_changed = false;
1391        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1392      __import_queued_samples();      __import_queued_samples();
1393        std::cout << "Importing queued samples done.\n" << std::flush;
1394    
1395      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1396      return true;  
1397        __refreshEntireGUI();
1398        progress_dialog->hide();
1399  }  }
1400    
1401  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 746  void MainWindow::on_action_file_save_as( Line 1406  void MainWindow::on_action_file_save_as(
1406    
1407  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1408  {  {
1409      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1410      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1411      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
1412      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1413      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1414    
# Line 779  bool MainWindow::file_save_as() Line 1439  bool MainWindow::file_save_as()
1439      // show warning in the dialog      // show warning in the dialog
1440      Gtk::HBox descriptionArea;      Gtk::HBox descriptionArea;
1441      descriptionArea.set_spacing(15);      descriptionArea.set_spacing(15);
1442      Gtk::Image warningIcon(Gtk::Stock::DIALOG_WARNING, Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));      Gtk::Image warningIcon;
1443        warningIcon.set_from_icon_name("dialog-warning",
1444                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1445      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);      descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1446  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
1447      view::WrapLabel description;      view::WrapLabel description;
# Line 800  bool MainWindow::file_save_as() Line 1462  bool MainWindow::file_save_as()
1462      descriptionArea.show_all();      descriptionArea.show_all();
1463    
1464      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1465          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1466          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1467              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;  
1468          }          }
1469          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1470          file_structure_changed_signal.emit(this->file);  
1471            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1472                _("Saving") +  Glib::ustring(" '") +
1473                Glib::filename_display_basename(filename) + "' ...",
1474                *this
1475            );
1476            progress_dialog->show_all();
1477    
1478            saver = new Saver(file, filename); //FIXME: memory leak!
1479            saver->signal_progress().connect(
1480                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1481            saver->signal_finished().connect(
1482                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1483            saver->signal_error().connect(
1484                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1485            saver->launch();
1486    
1487          return true;          return true;
1488      }      }
1489      return false;      return false;
# Line 831  bool MainWindow::file_save_as() Line 1493  bool MainWindow::file_save_as()
1493  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1494      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1495      Glib::ustring error_files;      Glib::ustring error_files;
1496      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1497      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::map<gig::Sample*, SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1498           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1499          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",iter->second.sample_path.c_str());
1500          SF_INFO info;          SF_INFO info;
1501          info.format = 0;          info.format = 0;
1502          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);
1503          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);          sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1504          try {          try {
1505              if (!hFile) throw std::string(_("could not open file"));              if (!hFile) throw std::string(_("could not open file"));
# Line 860  void MainWindow::__import_queued_samples Line 1522  void MainWindow::__import_queued_samples
1522                      throw std::string(_("format not supported")); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1523              }              }
1524    
1525                // reset write position for sample
1526                iter->first->SetPos(0);
1527    
1528              const int bufsize = 10000;              const int bufsize = 10000;
1529              switch (bitdepth) {              switch (bitdepth) {
1530                  case 16: {                  case 16: {
# Line 869  void MainWindow::__import_queued_samples Line 1534  void MainWindow::__import_queued_samples
1534                          // libsndfile does the conversion for us (if needed)                          // libsndfile does the conversion for us (if needed)
1535                          int n = sf_readf_short(hFile, buffer, bufsize);                          int n = sf_readf_short(hFile, buffer, bufsize);
1536                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1537                          iter->gig_sample->Write(buffer, n);                          iter->first->Write(buffer, n);
1538                          cnt -= n;                          cnt -= n;
1539                      }                      }
1540                      delete[] buffer;                      delete[] buffer;
# Line 889  void MainWindow::__import_queued_samples Line 1554  void MainWindow::__import_queued_samples
1554                              dstbuf[j++] = srcbuf[i] >> 24;                              dstbuf[j++] = srcbuf[i] >> 24;
1555                          }                          }
1556                          // write from buffer directly (physically) into .gig file                          // write from buffer directly (physically) into .gig file
1557                          iter->gig_sample->Write(dstbuf, n);                          iter->first->Write(dstbuf, n);
1558                          cnt -= n;                          cnt -= n;
1559                      }                      }
1560                      delete[] srcbuf;                      delete[] srcbuf;
# Line 900  void MainWindow::__import_queued_samples Line 1565  void MainWindow::__import_queued_samples
1565              // cleanup              // cleanup
1566              sf_close(hFile);              sf_close(hFile);
1567              // let the sampler re-cache the sample if needed              // let the sampler re-cache the sample if needed
1568              sample_changed_signal.emit(iter->gig_sample);              sample_changed_signal.emit(iter->first);
1569              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1570              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1571              std::list<SampleImportItem>::iterator cur = iter;              std::map<gig::Sample*, SampleImportItem>::iterator cur = iter;
1572              ++iter;              ++iter;
1573              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1574          } catch (std::string what) {          } catch (std::string what) {
1575              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1576              if (!error_files.empty()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1577              error_files += (*iter).sample_path += " (" + what + ")";              error_files += iter->second.sample_path += " (" + what + ")";
1578              ++iter;              ++iter;
1579          }          }
1580      }      }
# Line 927  void MainWindow::on_action_file_properti Line 1592  void MainWindow::on_action_file_properti
1592      propDialog.deiconify();      propDialog.deiconify();
1593  }  }
1594    
1595    void MainWindow::on_action_warn_user_on_extensions() {
1596        Settings::singleton()->warnUserOnExtensions =
1597            !Settings::singleton()->warnUserOnExtensions;
1598    }
1599    
1600    void MainWindow::on_action_sync_sampler_instrument_selection() {
1601        Settings::singleton()->syncSamplerInstrumentSelection =
1602            !Settings::singleton()->syncSamplerInstrumentSelection;
1603    }
1604    
1605    void MainWindow::on_action_move_root_note_with_region_moved() {
1606        Settings::singleton()->moveRootNoteWithRegionMoved =
1607            !Settings::singleton()->moveRootNoteWithRegionMoved;
1608    }
1609    
1610  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1611  {  {
1612      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
# Line 936  void MainWindow::on_action_help_about() Line 1616  void MainWindow::on_action_help_about()
1616      dialog.set_name("Gigedit");      dialog.set_name("Gigedit");
1617  #endif  #endif
1618      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1619      dialog.set_copyright("Copyright (C) 2006-2013 Andreas Persson");      dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1620      dialog.set_comments(_(      const std::string sComment =
1621          "Released under the GNU General Public License.\n"          _("Built " __DATE__ "\nUsing ") +
1622          "\n"          ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1623          "Please notice that this is still a very young instrument editor. "          _(
1624          "So better backup your Gigasampler files before editing them with "              "Gigedit is released under the GNU General Public License.\n"
1625          "this application.\n"              "\n"
1626          "\n"              "This program is distributed WITHOUT ANY WARRANTY; So better "
1627          "Please report bugs to: http://bugs.linuxsampler.org")              "backup your Gigasampler/GigaStudio files before editing them with "
1628      );              "this application.\n"
1629                "\n"
1630                "Please report bugs to: http://bugs.linuxsampler.org"
1631            );
1632        dialog.set_comments(sComment.c_str());
1633      dialog.set_website("http://www.linuxsampler.org");      dialog.set_website("http://www.linuxsampler.org");
1634      dialog.set_website_label("http://www.linuxsampler.org");      dialog.set_website_label("http://www.linuxsampler.org");
1635      dialog.run();      dialog.run();
1636  }  }
1637    
1638  PropDialog::PropDialog()  PropDialog::PropDialog()
1639      : eName(_("Name")),      : eFileFormat(_("File Format")),
1640          eName(_("Name")),
1641        eCreationDate(_("Creation date")),        eCreationDate(_("Creation date")),
1642        eComments(_("Comments")),        eComments(_("Comments")),
1643        eProduct(_("Product")),        eProduct(_("Product")),
# Line 968  PropDialog::PropDialog() Line 1653  PropDialog::PropDialog()
1653        eSourceForm(_("Source form")),        eSourceForm(_("Source form")),
1654        eCommissioned(_("Commissioned")),        eCommissioned(_("Commissioned")),
1655        eSubject(_("Subject")),        eSubject(_("Subject")),
1656        quitButton(Gtk::Stock::CLOSE),        quitButton(_("_Close"), true),
1657        table(2, 1)        table(2, 1),
1658          m_file(NULL)
1659  {  {
1660      set_title(_("File Properties"));      set_title(_("File Properties"));
1661      eName.set_width_chars(50);      eName.set_width_chars(50);
# Line 991  PropDialog::PropDialog() Line 1677  PropDialog::PropDialog()
1677      connect(eCommissioned, &DLS::Info::Commissioned);      connect(eCommissioned, &DLS::Info::Commissioned);
1678      connect(eSubject, &DLS::Info::Subject);      connect(eSubject, &DLS::Info::Subject);
1679    
1680        table.add(eFileFormat);
1681      table.add(eName);      table.add(eName);
1682      table.add(eCreationDate);      table.add(eCreationDate);
1683      table.add(eComments);      table.add(eComments);
# Line 1021  PropDialog::PropDialog() Line 1708  PropDialog::PropDialog()
1708      quitButton.grab_focus();      quitButton.grab_focus();
1709      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
1710          sigc::mem_fun(*this, &PropDialog::hide));          sigc::mem_fun(*this, &PropDialog::hide));
1711        eFileFormat.signal_value_changed().connect(
1712            sigc::mem_fun(*this, &PropDialog::onFileFormatChanged));
1713    
1714      quitButton.show();      quitButton.show();
1715      vbox.show();      vbox.show();
1716      show_all_children();      show_all_children();
1717  }  }
1718    
1719    void PropDialog::set_file(gig::File* file)
1720    {
1721        m_file = file;
1722    
1723        // update file format version combo box
1724        const std::string sGiga = "Gigasampler/GigaStudio v";
1725        const int major = file->pVersion->major;
1726        std::vector<std::string> txts;
1727        std::vector<int> values;
1728        txts.push_back(sGiga + "2"); values.push_back(2);
1729        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1730        if (major != 2 && major != 3) {
1731            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1732        }
1733        std::vector<const char*> texts;
1734        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1735        texts.push_back(NULL); values.push_back(0);
1736        eFileFormat.set_choices(&texts[0], &values[0]);
1737        eFileFormat.set_value(major);
1738    }
1739    
1740    void PropDialog::onFileFormatChanged() {
1741        const int major = eFileFormat.get_value();
1742        if (m_file) m_file->pVersion->major = major;
1743    }
1744    
1745  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_info(DLS::Info* info)
1746  {  {
1747      update(info);      update(info);
# Line 1061  void InstrumentProps::set_MIDIProgram(ui Line 1776  void InstrumentProps::set_MIDIProgram(ui
1776  }  }
1777    
1778  InstrumentProps::InstrumentProps() :  InstrumentProps::InstrumentProps() :
1779      quitButton(Gtk::Stock::CLOSE),      quitButton(_("_Close"), true),
1780      table(2,1),      table(2,1),
1781      eName(_("Name")),      eName(_("Name")),
1782      eIsDrum(_("Is drum")),      eIsDrum(_("Is drum")),
# Line 1158  void MainWindow::file_changed() Line 1873  void MainWindow::file_changed()
1873      }      }
1874  }  }
1875    
1876    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1877        sample_ref_count.clear();
1878        
1879        if (!gig) return;
1880    
1881        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1882             instrument = gig->GetNextInstrument())
1883        {
1884            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1885                 rgn = instrument->GetNextRegion())
1886            {
1887                for (int i = 0; i < 256; ++i) {
1888                    if (!rgn->pDimensionRegions[i]) continue;
1889                    if (rgn->pDimensionRegions[i]->pSample) {
1890                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1891                    }
1892                }
1893            }
1894        }
1895    }
1896    
1897  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1898  {  {
1899      file = 0;      file = 0;
1900      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
1901    
1902      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
1903            (filename && strlen(filename) > 0) ?
1904                filename : (!gig->GetFileName().empty()) ?
1905                    gig->GetFileName() : _("Unsaved Gig File");
1906      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1907      file_has_name = filename;      file_has_name = filename;
1908      file_is_changed = false;      file_is_changed = false;
1909    
1910        propDialog.set_file(gig);
1911      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1912    
1913      instrument_name_connection.block();      instrument_name_connection.block();
1914        int index = 0;
1915      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1916           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
1917          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));          Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1918    
1919          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1920          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1921            row[m_Columns.m_col_nr] = index;
1922          row[m_Columns.m_col_name] = name;          row[m_Columns.m_col_name] = name;
1923          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1924    
1925          add_instrument_to_menu(name);          add_instrument_to_menu(name);
1926      }      }
1927      instrument_name_connection.unblock();      instrument_name_connection.unblock();
1928      uiManager->get_widget("/MenuBar/MenuInstrument")->show();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1929    
1930        updateSampleRefCountMap(gig);
1931    
1932      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1933          if (group->Name != "") {          if (group->Name != "") {
# Line 1201  void MainWindow::load_gig(gig::File* gig Line 1945  void MainWindow::load_gig(gig::File* gig
1945                      gig_to_utf8(sample->pInfo->Name);                      gig_to_utf8(sample->pInfo->Name);
1946                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1947                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1948                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1949                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1950                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1951              }              }
1952          }          }
1953      }      }
1954        
1955        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1956            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1957    
1958            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1959            Gtk::TreeModel::Row rowGroup = *iterGroup;
1960            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1961            rowGroup[m_ScriptsModel.m_col_group]  = group;
1962            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1963            for (int s = 0; group->GetScript(s); ++s) {
1964                gig::Script* script = group->GetScript(s);
1965    
1966                Gtk::TreeModel::iterator iterScript =
1967                    m_refScriptsTreeModel->append(rowGroup.children());
1968                Gtk::TreeModel::Row rowScript = *iterScript;
1969                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1970                rowScript[m_ScriptsModel.m_col_script] = script;
1971                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1972            }
1973        }
1974        // unfold all sample groups & script groups by default
1975        m_TreeViewSamples.expand_all();
1976        m_TreeViewScripts.expand_all();
1977    
1978      file = gig;      file = gig;
1979    
# Line 1211  void MainWindow::load_gig(gig::File* gig Line 1981  void MainWindow::load_gig(gig::File* gig
1981      m_TreeView.get_selection()->select(Gtk::TreePath("0"));      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1982    
1983      instr_props_set_instrument();      instr_props_set_instrument();
1984        gig::Instrument* instrument = get_instrument();
1985        if (instrument) {
1986            midiRules.set_instrument(instrument);
1987        }
1988  }  }
1989    
1990  bool MainWindow::instr_props_set_instrument()  bool MainWindow::instr_props_set_instrument()
1991  {  {
1992      instrumentProps.signal_name_changed().clear();      instrumentProps.signal_name_changed().clear();
1993    
1994      Gtk::TreeModel::const_iterator it =      std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1995          m_TreeView.get_selection()->get_selected();      if (rows.empty()) {
1996            instrumentProps.hide();
1997            return false;
1998        }
1999        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
2000      if (it) {      if (it) {
2001          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2002          gig::Instrument* instrument = row[m_Columns.m_col_instr];          gig::Instrument* instrument = row[m_Columns.m_col_instr];
# Line 1258  void MainWindow::instr_name_changed_by_i Line 2036  void MainWindow::instr_name_changed_by_i
2036      }      }
2037  }  }
2038    
2039    void MainWindow::show_midi_rules()
2040    {
2041        if (gig::Instrument* instrument = get_instrument())
2042        {
2043            midiRules.set_instrument(instrument);
2044            midiRules.show();
2045            midiRules.deiconify();
2046        }
2047    }
2048    
2049    void MainWindow::show_script_slots() {
2050        if (!file) return;
2051        // get selected instrument
2052        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2053        if (rows.empty()) return;
2054        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2055        if (!it) return;
2056        Gtk::TreeModel::Row row = *it;
2057        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2058        if (!instrument) return;
2059    
2060        ScriptSlots* window = new ScriptSlots;
2061        window->setInstrument(instrument);
2062        //window->reparent(*this);
2063        window->show();
2064    }
2065    
2066    void MainWindow::on_action_refresh_all() {
2067        __refreshEntireGUI();
2068    }
2069    
2070  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2071      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2072          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1269  void MainWindow::on_action_view_status_b Line 2078  void MainWindow::on_action_view_status_b
2078      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2079  }  }
2080    
2081    void MainWindow::on_auto_restore_win_dim() {
2082        Gtk::CheckMenuItem* item =
2083            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2084        if (!item) {
2085            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2086            return;
2087        }
2088        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2089    }
2090    
2091    void MainWindow::on_save_with_temporary_file() {
2092        Gtk::CheckMenuItem* item =
2093            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2094        if (!item) {
2095            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2096            return;
2097        }
2098        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2099    }
2100    
2101  bool MainWindow::is_copy_samples_unity_note_enabled() const {  bool MainWindow::is_copy_samples_unity_note_enabled() const {
2102      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2103          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
# Line 1304  void MainWindow::on_button_release(GdkEv Line 2133  void MainWindow::on_button_release(GdkEv
2133      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2134          show_instr_props();          show_instr_props();
2135      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2136            // gig v2 files have no midi rules
2137            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2138            static_cast<Gtk::MenuItem*>(
2139                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2140                    bEnabled
2141                );
2142            static_cast<Gtk::MenuItem*>(
2143                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2144                    bEnabled
2145                );
2146          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2147      }      }
2148  }  }
# Line 1323  void MainWindow::on_instrument_selection Line 2162  void MainWindow::on_instrument_selection
2162      }      }
2163  }  }
2164    
2165    void MainWindow::select_instrument(gig::Instrument* instrument) {
2166        if (!instrument) return;
2167    
2168        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2169        for (int i = 0; i < model->children().size(); ++i) {
2170            Gtk::TreeModel::Row row = model->children()[i];
2171            if (row[m_Columns.m_col_instr] == instrument) {
2172                // select and show the respective instrument in the list view
2173                show_intruments_tab();
2174                m_TreeView.get_selection()->unselect_all();
2175                m_TreeView.get_selection()->select(model->children()[i]);
2176                std::vector<Gtk::TreeModel::Path> rows =
2177                    m_TreeView.get_selection()->get_selected_rows();
2178                if (!rows.empty())
2179                    m_TreeView.scroll_to_row(rows[0]);
2180                on_sel_change(); // the regular instrument selection change callback
2181            }
2182        }
2183    }
2184    
2185    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2186    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2187        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2188        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2189    
2190        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2191        for (int i = 0; i < model->children().size(); ++i) {
2192            Gtk::TreeModel::Row row = model->children()[i];
2193            if (row[m_Columns.m_col_instr] == pInstrument) {
2194                // select and show the respective instrument in the list view
2195                show_intruments_tab();
2196                m_TreeView.get_selection()->unselect_all();
2197                m_TreeView.get_selection()->select(model->children()[i]);
2198                std::vector<Gtk::TreeModel::Path> rows =
2199                    m_TreeView.get_selection()->get_selected_rows();
2200                if (!rows.empty())
2201                    m_TreeView.scroll_to_row(rows[0]);
2202                on_sel_change(); // the regular instrument selection change callback
2203    
2204                // select respective region in the region selector
2205                m_RegionChooser.set_region(pRegion);
2206    
2207                // select and show the respective dimension region in the editor
2208                //update_dimregs();
2209                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2210                //dimreg_edit.set_dim_region(dimRgn);
2211    
2212                return true;
2213            }
2214        }
2215    
2216        return false;
2217    }
2218    
2219    void MainWindow::select_sample(gig::Sample* sample) {
2220        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2221        for (int g = 0; g < model->children().size(); ++g) {
2222            Gtk::TreeModel::Row rowGroup = model->children()[g];
2223            for (int s = 0; s < rowGroup.children().size(); ++s) {
2224                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2225                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2226                    show_samples_tab();
2227                    m_TreeViewSamples.get_selection()->unselect_all();
2228                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2229                    std::vector<Gtk::TreeModel::Path> rows =
2230                        m_TreeViewSamples.get_selection()->get_selected_rows();
2231                    if (rows.empty()) return;
2232                    m_TreeViewSamples.scroll_to_row(rows[0]);
2233                    return;
2234                }
2235            }
2236        }
2237    }
2238    
2239  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2240      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2241            // by default if Ctrl keys is pressed down, then a mouse right-click
2242            // does not select the respective row, so we must assure this
2243            // programmatically ...
2244            /*{
2245                Gtk::TreeModel::Path path;
2246                Gtk::TreeViewColumn* pColumn = NULL;
2247                int cellX, cellY;
2248                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2249                    (int)button->x, (int)button->y,
2250                    path, pColumn, cellX, cellY
2251                );
2252                if (bSuccess) {
2253                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2254                        printf("not selected !!!\n");
2255                        m_TreeViewSamples.get_selection()->select(path);
2256                    }
2257                }
2258            }*/
2259    
2260          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2261              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2262          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2263          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2264          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2265          bool group_selected  = false;          const int n = rows.size();
2266          bool sample_selected = false;          int nGroups  = 0;
2267          if (it) {          int nSamples = 0;
2268            for (int r = 0; r < n; ++r) {
2269                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2270                if (!it) continue;
2271              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2272              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2273              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2274          }          }
2275    
2276          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2277              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2278          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2279              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2280          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2281              set_sensitive(file);              set_sensitive(file);
2282            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2283                set_sensitive(nSamples == 1);
2284          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2285              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2286          // show sample popup          // show sample popup
2287          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2288    
2289            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2290                set_sensitive(n == 1);
2291            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2292                set_sensitive(n);
2293            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2294                set_sensitive(file);
2295            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2296                set_sensitive(nSamples == 1);
2297            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2298                set_sensitive(n);
2299      }      }
2300  }  }
2301    
2302    void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2303        if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2304            Gtk::Menu* script_popup =
2305                dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2306            // update enabled/disabled state of sample popup items
2307            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2308            Gtk::TreeModel::iterator it = sel->get_selected();
2309            bool group_selected  = false;
2310            bool script_selected = false;
2311            if (it) {
2312                Gtk::TreeModel::Row row = *it;
2313                group_selected  = row[m_ScriptsModel.m_col_group];
2314                script_selected = row[m_ScriptsModel.m_col_script];
2315            }
2316            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2317                set_sensitive(group_selected || script_selected);
2318            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2319                set_sensitive(file);
2320            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2321                set_sensitive(script_selected);    
2322            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2323                set_sensitive(group_selected || script_selected);
2324            // show sample popup
2325            script_popup->popup(button->button, button->time);
2326    
2327            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2328                set_sensitive(group_selected || script_selected);
2329            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2330                set_sensitive(file);
2331            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2332                set_sensitive(script_selected);    
2333            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2334                set_sensitive(group_selected || script_selected);
2335        }
2336    }
2337    
2338  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(  Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2339      const Glib::ustring& name, int position) {      const Glib::ustring& name, int position) {
# Line 1390  void MainWindow::add_instrument(gig::Ins Line 2374  void MainWindow::add_instrument(gig::Ins
2374      instrument_name_connection.block();      instrument_name_connection.block();
2375      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2376      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2377        rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2378      rowInstr[m_Columns.m_col_name] = name;      rowInstr[m_Columns.m_col_name] = name;
2379      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2380      instrument_name_connection.unblock();      instrument_name_connection.unblock();
# Line 1418  void MainWindow::on_action_duplicate_ins Line 2403  void MainWindow::on_action_duplicate_ins
2403      // retrieve the currently selected instrument      // retrieve the currently selected instrument
2404      // (being the original instrument to be duplicated)      // (being the original instrument to be duplicated)
2405      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2406      Gtk::TreeModel::iterator itSelection = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2407      if (!itSelection) return;      for (int r = 0; r < rows.size(); ++r) {
2408      Gtk::TreeModel::Row row = *itSelection;          Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2409      gig::Instrument* instrOrig = row[m_Columns.m_col_instr];          if (it) {
2410      if (!instrOrig) return;              Gtk::TreeModel::Row row = *it;
2411                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2412      // duplicate the orginal instrument              if (instrOrig) {
2413      gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);                  // duplicate the orginal instrument
2414      instrNew->pInfo->Name =                  gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2415          instrOrig->pInfo->Name +                  instrNew->pInfo->Name =
2416          gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");                      instrOrig->pInfo->Name +
2417                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2418    
2419      add_instrument(instrNew);                  add_instrument(instrNew);
2420                }
2421            }
2422        }
2423  }  }
2424    
2425  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
# Line 1447  void MainWindow::on_action_remove_instru Line 2436  void MainWindow::on_action_remove_instru
2436      }      }
2437    
2438      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2439      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2440      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2441            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2442            if (!it) continue;
2443          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2444          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2445          try {          try {
# Line 1463  void MainWindow::on_action_remove_instru Line 2454  void MainWindow::on_action_remove_instru
2454    
2455              // remove row from instruments tree view              // remove row from instruments tree view
2456              m_refTreeModel->erase(it);              m_refTreeModel->erase(it);
2457                // update "Nr" column of all instrument rows
2458                {
2459                    int index = 0;
2460                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2461                         it != m_refTreeModel->children().end(); ++it, ++index)
2462                    {
2463                        Gtk::TreeModel::Row row = *it;
2464                        row[m_Columns.m_col_nr] = index;
2465                    }
2466                }
2467    
2468  #if GTKMM_MAJOR_VERSION < 3  #if GTKMM_MAJOR_VERSION < 3
2469              // select another instrument (in gtk3 this is done              // select another instrument (in gtk3 this is done
# Line 1476  void MainWindow::on_action_remove_instru Line 2477  void MainWindow::on_action_remove_instru
2477              }              }
2478  #endif  #endif
2479              instr_props_set_instrument();              instr_props_set_instrument();
2480                instr = get_instrument();
2481                if (instr) {
2482                    midiRules.set_instrument(instr);
2483                } else {
2484                    midiRules.hide();
2485                }
2486          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2487              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2488              msg.run();              msg.run();
# Line 1491  void MainWindow::on_action_sample_proper Line 2498  void MainWindow::on_action_sample_proper
2498      msg.run();      msg.run();
2499  }  }
2500    
2501    void MainWindow::on_action_add_script_group() {
2502        static int __script_indexer = 0;
2503        if (!file) return;
2504        gig::ScriptGroup* group = file->AddScriptGroup();
2505        group->Name = gig_from_utf8(_("Unnamed Group"));
2506        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2507        __script_indexer++;
2508        // update sample tree view
2509        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2510        Gtk::TreeModel::Row rowGroup = *iterGroup;
2511        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2512        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2513        rowGroup[m_ScriptsModel.m_col_group] = group;
2514        file_changed();
2515    }
2516    
2517    void MainWindow::on_action_add_script() {
2518        if (!file) return;
2519        // get selected group
2520        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2521        Gtk::TreeModel::iterator it = sel->get_selected();
2522        if (!it) return;
2523        Gtk::TreeModel::Row row = *it;
2524        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2525        if (!group) { // not a group, but a script is selected (probably)
2526            gig::Script* script = row[m_ScriptsModel.m_col_script];
2527            if (!script) return;
2528            it = row.parent(); // resolve parent (that is the script's group)
2529            if (!it) return;
2530            row = *it;
2531            group = row[m_ScriptsModel.m_col_group];
2532            if (!group) return;
2533        }
2534    
2535        // add a new script to the .gig file
2536        gig::Script* script = group->AddScript();    
2537        Glib::ustring name = _("Unnamed Script");
2538        script->Name = gig_from_utf8(name);
2539    
2540        // add script to the tree view
2541        Gtk::TreeModel::iterator iterScript =
2542            m_refScriptsTreeModel->append(row.children());
2543        Gtk::TreeModel::Row rowScript = *iterScript;
2544        rowScript[m_ScriptsModel.m_col_name] = name;
2545        rowScript[m_ScriptsModel.m_col_script] = script;
2546        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2547    
2548        // unfold group of new script item in treeview
2549        Gtk::TreeModel::Path path(iterScript);
2550        m_TreeViewScripts.expand_to_path(path);
2551    }
2552    
2553    void MainWindow::on_action_edit_script() {
2554        if (!file) return;
2555        // get selected script
2556        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2557        Gtk::TreeModel::iterator it = sel->get_selected();
2558        if (!it) return;
2559        Gtk::TreeModel::Row row = *it;
2560        gig::Script* script = row[m_ScriptsModel.m_col_script];
2561        if (!script) return;
2562    
2563        ScriptEditor* editor = new ScriptEditor;
2564        editor->signal_script_to_be_changed.connect(
2565            signal_script_to_be_changed.make_slot()
2566        );
2567        editor->signal_script_changed.connect(
2568            signal_script_changed.make_slot()
2569        );
2570        editor->setScript(script);
2571        //editor->reparent(*this);
2572        editor->show();
2573    }
2574    
2575    void MainWindow::on_action_remove_script() {
2576        if (!file) return;
2577        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2578        Gtk::TreeModel::iterator it = sel->get_selected();
2579        if (it) {
2580            Gtk::TreeModel::Row row = *it;
2581            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2582            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2583            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2584            try {
2585                // remove script group or script from the gig file
2586                if (group) {
2587                    // notify everybody that we're going to remove these samples
2588    //TODO:         scripts_to_be_removed_signal.emit(members);
2589                    // delete the group in the .gig file including the
2590                    // samples that belong to the group
2591                    file->DeleteScriptGroup(group);
2592                    // notify that we're done with removal
2593    //TODO:         scripts_removed_signal.emit();
2594                    file_changed();
2595                } else if (script) {
2596                    // notify everybody that we're going to remove this sample
2597    //TODO:         std::list<gig::Script*> lscripts;
2598    //TODO:         lscripts.push_back(script);
2599    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2600                    // remove sample from the .gig file
2601                    script->GetGroup()->DeleteScript(script);
2602                    // notify that we're done with removal
2603    //TODO:         scripts_removed_signal.emit();
2604                    dimreg_changed();
2605                    file_changed();
2606                }
2607                // remove respective row(s) from samples tree view
2608                m_refScriptsTreeModel->erase(it);
2609            } catch (RIFF::Exception e) {
2610                // pretend we're done with removal (i.e. to avoid dead locks)
2611    //TODO:     scripts_removed_signal.emit();
2612                // show error message
2613                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2614                msg.run();
2615            }
2616        }
2617    }
2618    
2619  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2620      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2621      if (!file) return;      if (!file) return;
# Line 1507  void MainWindow::on_action_add_group() { Line 2632  void MainWindow::on_action_add_group() {
2632      file_changed();      file_changed();
2633  }  }
2634    
2635    void MainWindow::on_action_replace_sample() {
2636        add_or_replace_sample(true);
2637    }
2638    
2639  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2640        add_or_replace_sample(false);
2641    }
2642    
2643    void MainWindow::add_or_replace_sample(bool replace) {
2644      if (!file) return;      if (!file) return;
2645      // get selected group  
2646        // get selected group (and probably selected sample)
2647      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2648      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2649        if (rows.empty()) return;
2650        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2651      if (!it) return;      if (!it) return;
2652      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2653        gig::Sample* sample = NULL;
2654      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2655      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2656          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2657          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2658          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2659          if (!it) return;          if (!it) return;
2660          row = *it;          if (!replace) row = *it;
2661          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2662          if (!group) return;          if (!group) return;
2663      }      }
2664        if (replace && !sample) return;
2665    
2666      // show 'browse for file' dialog      // show 'browse for file' dialog
2667      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2668      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2669      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2670      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
2671    
2672      // matches all file types supported by libsndfile      // matches all file types supported by libsndfile
2673  #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 1599  void MainWindow::on_action_add_sample() Line 2738  void MainWindow::on_action_add_sample()
2738                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2739                          throw std::string(_("format not supported")); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2740                  }                  }
2741                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2742                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2743                  // file name without path                  // file name without path
2744                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2745                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1624  void MainWindow::on_action_add_sample() Line 2763  void MainWindow::on_action_add_sample()
2763                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2764                  {                  {
2765                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2766                        sample->FineTune      = instrument.detune;
2767    
2768                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2769                          sample->Loops = 1;                          sample->Loops = 1;
# Line 1650  void MainWindow::on_action_add_sample() Line 2790  void MainWindow::on_action_add_sample()
2790                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2791                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2792                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2793                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2794                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2795                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2796                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2797                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2798                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2799                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2800                  // add sample to the tree view                  // add sample to the tree view
2801                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2802                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2803                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2804                  rowSample[m_SamplesModel.m_col_name] =                      Gtk::TreeModel::iterator iterSample =
2805                      gig_to_utf8(sample->pInfo->Name);                          m_refSamplesTreeModel->append(row.children());
2806                  rowSample[m_SamplesModel.m_col_sample] = sample;                      Gtk::TreeModel::Row rowSample = *iterSample;
2807                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      rowSample[m_SamplesModel.m_col_name] =
2808                            gig_to_utf8(sample->pInfo->Name);
2809                        rowSample[m_SamplesModel.m_col_sample] = sample;
2810                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2811                    }
2812                  // close sound file                  // close sound file
2813                  sf_close(hFile);                  sf_close(hFile);
2814                  file_changed();                  file_changed();
# Line 1675  void MainWindow::on_action_add_sample() Line 2819  void MainWindow::on_action_add_sample()
2819          }          }
2820          // 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
2821          if (!error_files.empty()) {          if (!error_files.empty()) {
2822              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
2823                    (replace
2824                        ? _("Failed to replace sample with:\n")
2825                        : _("Could not add the following sample(s):\n"))
2826                    + error_files;
2827              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2828              msg.run();              msg.run();
2829          }          }
# Line 1718  void MainWindow::on_action_replace_all_s Line 2866  void MainWindow::on_action_replace_all_s
2866      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);      dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2867      description.show();      description.show();
2868      entryArea.show_all();      entryArea.show_all();
2869      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2870      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);      dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2871      dialog.set_select_multiple(false);      dialog.set_select_multiple(false);
2872      if (current_sample_dir != "") {      if (current_sample_dir != "") {
# Line 1742  void MainWindow::on_action_replace_all_s Line 2890  void MainWindow::on_action_replace_all_s
2890              try              try
2891              {              {
2892                  if (!hFile) throw std::string(_("could not open file"));                  if (!hFile) throw std::string(_("could not open file"));
                 int bitdepth;  
2893                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2894                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
2895                      case SF_FORMAT_PCM_16:                      case SF_FORMAT_PCM_16:
2896                      case SF_FORMAT_PCM_U8:                      case SF_FORMAT_PCM_U8:
                         bitdepth = 16;  
                         break;  
2897                      case SF_FORMAT_PCM_24:                      case SF_FORMAT_PCM_24:
2898                      case SF_FORMAT_PCM_32:                      case SF_FORMAT_PCM_32:
2899                      case SF_FORMAT_FLOAT:                      case SF_FORMAT_FLOAT:
2900                      case SF_FORMAT_DOUBLE:                      case SF_FORMAT_DOUBLE:
                         bitdepth = 24;  
2901                          break;                          break;
2902                      default:                      default:
2903                          sf_close(hFile);                          sf_close(hFile);
# Line 1762  void MainWindow::on_action_replace_all_s Line 2906  void MainWindow::on_action_replace_all_s
2906                  SampleImportItem sched_item;                  SampleImportItem sched_item;
2907                  sched_item.gig_sample  = sample;                  sched_item.gig_sample  = sample;
2908                  sched_item.sample_path = filename;                  sched_item.sample_path = filename;
2909                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue[sample] = sched_item;
2910                  sf_close(hFile);                  sf_close(hFile);
2911                  file_changed();                  file_changed();
2912              }              }
# Line 1786  void MainWindow::on_action_replace_all_s Line 2930  void MainWindow::on_action_replace_all_s
2930  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
2931      if (!file) return;      if (!file) return;
2932      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2933      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2934      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2935            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2936            if (!it) continue;
2937          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2938          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
2939          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1812  void MainWindow::on_action_remove_sample Line 2958  void MainWindow::on_action_remove_sample
2958                  // if sample(s) were just previously added, remove                  // if sample(s) were just previously added, remove
2959                  // them from the import queue                  // them from the import queue
2960                  for (std::list<gig::Sample*>::iterator member = members.begin();                  for (std::list<gig::Sample*>::iterator member = members.begin();
2961                       member != members.end(); ++member) {                       member != members.end(); ++member)
2962                      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  {
2963                           iter != m_SampleImportQueue.end(); ++iter) {                      if (m_SampleImportQueue.count(*member)) {
2964                          if ((*iter).gig_sample == *member) {                          printf("Removing previously added sample '%s' from group '%s'\n",
2965                              printf("Removing previously added sample '%s' from group '%s'\n",                                 m_SampleImportQueue[sample].sample_path.c_str(), name.c_str());
2966                                     (*iter).sample_path.c_str(), name.c_str());                          m_SampleImportQueue.erase(*member);
                             m_SampleImportQueue.erase(iter);  
                             break;  
                         }  
2967                      }                      }
2968                  }                  }
2969                  file_changed();                  file_changed();
# Line 1835  void MainWindow::on_action_remove_sample Line 2978  void MainWindow::on_action_remove_sample
2978                  samples_removed_signal.emit();                  samples_removed_signal.emit();
2979                  // if sample was just previously added, remove it from                  // if sample was just previously added, remove it from
2980                  // the import queue                  // the import queue
2981                  for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();                  if (m_SampleImportQueue.count(sample)) {
2982                       iter != m_SampleImportQueue.end(); ++iter) {                      printf("Removing previously added sample '%s'\n",
2983                      if ((*iter).gig_sample == sample) {                             m_SampleImportQueue[sample].sample_path.c_str());
2984                          printf("Removing previously added sample '%s'\n",                      m_SampleImportQueue.erase(sample);
                                (*iter).sample_path.c_str());  
                         m_SampleImportQueue.erase(iter);  
                         break;  
                     }  
2985                  }                  }
2986                  dimreg_changed();                  dimreg_changed();
2987                  file_changed();                  file_changed();
# Line 1859  void MainWindow::on_action_remove_sample Line 2998  void MainWindow::on_action_remove_sample
2998      }      }
2999  }  }
3000    
3001    void MainWindow::on_action_remove_unused_samples() {
3002        if (!file) return;
3003    
3004        // collect all samples that are not referenced by any instrument
3005        std::list<gig::Sample*> lsamples;
3006        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
3007            gig::Sample* sample = file->GetSample(iSample);
3008            bool isUsed = false;
3009            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
3010                                  instrument = file->GetNextInstrument())
3011            {
3012                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
3013                                  rgn = instrument->GetNextRegion())
3014                {
3015                    for (int i = 0; i < 256; ++i) {
3016                        if (!rgn->pDimensionRegions[i]) continue;
3017                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
3018                        isUsed = true;
3019                        goto endOfRefSearch;
3020                    }
3021                }
3022            }
3023            endOfRefSearch:
3024            if (!isUsed) lsamples.push_back(sample);
3025        }
3026    
3027        if (lsamples.empty()) return;
3028    
3029        // notify everybody that we're going to remove these samples
3030        samples_to_be_removed_signal.emit(lsamples);
3031    
3032        // remove collected samples
3033        try {
3034            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
3035                 itSample != lsamples.end(); ++itSample)
3036            {
3037                gig::Sample* sample = *itSample;
3038                // remove sample from the .gig file
3039                file->DeleteSample(sample);
3040                // if sample was just previously added, remove it from the import queue
3041                if (m_SampleImportQueue.count(sample)) {
3042                    printf("Removing previously added sample '%s'\n",
3043                           m_SampleImportQueue[sample].sample_path.c_str());
3044                    m_SampleImportQueue.erase(sample);
3045                }
3046            }
3047        } catch (RIFF::Exception e) {
3048            // show error message
3049            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3050            msg.run();
3051        }
3052    
3053        // notify everybody that we're done with removal
3054        samples_removed_signal.emit();
3055    
3056        dimreg_changed();
3057        file_changed();
3058        __refreshEntireGUI();
3059    }
3060    
3061    // see comment on on_sample_treeview_drag_begin()
3062    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3063    {
3064        first_call_to_drag_data_get = true;
3065    }
3066    
3067    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3068                                                       Gtk::SelectionData& selection_data, guint, guint)
3069    {
3070        if (!first_call_to_drag_data_get) return;
3071        first_call_to_drag_data_get = false;
3072    
3073        // get selected script
3074        gig::Script* script = NULL;
3075        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3076        Gtk::TreeModel::iterator it = sel->get_selected();
3077        if (it) {
3078            Gtk::TreeModel::Row row = *it;
3079            script = row[m_ScriptsModel.m_col_script];
3080        }
3081        // pass the gig::Script as pointer
3082        selection_data.set(selection_data.get_target(), 0/*unused*/,
3083                           (const guchar*)&script,
3084                           sizeof(script)/*length of data in bytes*/);
3085    }
3086    
3087    // see comment on on_sample_treeview_drag_begin()
3088    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3089    {
3090        first_call_to_drag_data_get = true;
3091    }
3092    
3093    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3094                                                           Gtk::SelectionData& selection_data, guint, guint)
3095    {
3096        if (!first_call_to_drag_data_get) return;
3097        first_call_to_drag_data_get = false;
3098    
3099        // get selected source instrument
3100        gig::Instrument* src = NULL;
3101        {
3102            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3103            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3104            if (!rows.empty()) {
3105                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3106                if (it) {
3107                    Gtk::TreeModel::Row row = *it;
3108                    src = row[m_Columns.m_col_instr];
3109                }
3110            }
3111        }
3112        if (!src) return;
3113    
3114        // pass the source gig::Instrument as pointer
3115        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3116                           sizeof(src)/*length of data in bytes*/);
3117    }
3118    
3119    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3120        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3121        const Gtk::SelectionData& selection_data, guint, guint time)
3122    {
3123        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3124        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3125            return;
3126    
3127        gig::Instrument* dst = NULL;
3128        {
3129            Gtk::TreeModel::Path path;
3130            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3131            if (!found) return;
3132    
3133            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3134            if (!iter) return;
3135            Gtk::TreeModel::Row row = *iter;
3136            dst = row[m_Columns.m_col_instr];
3137        }
3138        if (!dst) return;
3139    
3140        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3141        src->MoveTo(dst);
3142        __refreshEntireGUI();
3143        select_instrument(src);
3144    }
3145    
3146  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3147  // 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
3148  // 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 1877  void MainWindow::on_sample_treeview_drag Line 3161  void MainWindow::on_sample_treeview_drag
3161      // get selected sample      // get selected sample
3162      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3163      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3164      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3165      if (it) {      if (!rows.empty()) {
3166          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3167          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3168                Gtk::TreeModel::Row row = *it;
3169                sample = row[m_SamplesModel.m_col_sample];
3170            }
3171      }      }
3172      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3173      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 1917  void MainWindow::on_sample_label_drop_dr Line 3204  void MainWindow::on_sample_label_drop_dr
3204          bool channels_changed = false;          bool channels_changed = false;
3205          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
3206              // remove the samplechannel dimension              // remove the samplechannel dimension
3207    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3208              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
3209              channels_changed = true;              channels_changed = true;
3210              region_changed();              region_changed();
3211    */
3212          }          }
3213          dimreg_edit.set_sample(          dimreg_edit.set_sample(
3214              sample,              sample,
# Line 1985  void MainWindow::sample_name_changed(con Line 3274  void MainWindow::sample_name_changed(con
3274      }      }
3275  }  }
3276    
3277    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3278                                         const Gtk::TreeModel::iterator& iter) {
3279        if (!iter) return;
3280        Gtk::TreeModel::Row row = *iter;
3281        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3282        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3283        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3284        gig::String gigname(gig_from_utf8(name));
3285        if (group) {
3286            if (group->Name != gigname) {
3287                group->Name = gigname;
3288                printf("script group name changed\n");
3289                file_changed();
3290            }
3291        } else if (script) {
3292            if (script->Name != gigname) {
3293                script->Name = gigname;
3294                printf("script name changed\n");
3295                file_changed();
3296            }
3297        }
3298    }
3299    
3300    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3301                                           Gtk::TreeViewColumn* column)
3302    {
3303        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3304        if (!iter) return;
3305        Gtk::TreeModel::Row row = *iter;
3306        gig::Script* script = row[m_ScriptsModel.m_col_script];
3307        if (!script) return;
3308    
3309        ScriptEditor* editor = new ScriptEditor;
3310        editor->signal_script_to_be_changed.connect(
3311            signal_script_to_be_changed.make_slot()
3312        );
3313        editor->signal_script_changed.connect(
3314            signal_script_changed.make_slot()
3315        );
3316        editor->setScript(script);
3317        //editor->reparent(*this);
3318        editor->show();
3319    }
3320    
3321  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3322                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3323      if (!iter) return;      if (!iter) return;
# Line 2019  void MainWindow::instrument_name_changed Line 3352  void MainWindow::instrument_name_changed
3352      }      }
3353  }  }
3354    
3355    void MainWindow::on_action_combine_instruments() {
3356        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3357        d->show_all();
3358        d->resize(500, 400);
3359        d->run();
3360        if (d->fileWasChanged()) {
3361            // update GUI with new instrument just created
3362            add_instrument(d->newCombinedInstrument());
3363        }
3364        delete d;
3365    }
3366    
3367    void MainWindow::on_action_view_references() {
3368        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3369        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3370        if (rows.empty()) return;
3371        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3372        if (!it) return;
3373        Gtk::TreeModel::Row row = *it;
3374        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3375        if (!sample) return;
3376    
3377        ReferencesView* d = new ReferencesView(*this);
3378        d->setSample(sample);
3379        d->dimension_region_selected.connect(
3380            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3381        );
3382        d->show_all();
3383        d->resize(500, 400);
3384        d->run();
3385        delete d;
3386    }
3387    
3388    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3389        struct _Source {
3390            std::vector<RIFF::File*> riffs;
3391            std::vector<gig::File*> gigs;
3392            
3393            ~_Source() {
3394                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3395                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3396                riffs.clear();
3397                gigs.clear();
3398            }
3399        } sources;
3400    
3401        if (filenames.empty())
3402            throw RIFF::Exception(_("No files selected, so nothing done."));
3403    
3404        // first open all input files (to avoid output file corruption)
3405        int i;
3406        try {
3407            for (i = 0; i < filenames.size(); ++i) {
3408                const std::string& filename = filenames[i];
3409                printf("opening file=%s\n", filename.c_str());
3410    
3411                RIFF::File* riff = new RIFF::File(filename);
3412                sources.riffs.push_back(riff);
3413    
3414                gig::File* gig = new gig::File(riff);
3415                sources.gigs.push_back(gig);
3416            }
3417        } catch (RIFF::Exception e) {
3418            throw RIFF::Exception(
3419                _("Error occurred while opening '") +
3420                filenames[i] +
3421                "': " +
3422                e.Message
3423            );
3424        } catch (...) {
3425            throw RIFF::Exception(
3426                _("Unknown exception occurred while opening '") +
3427                filenames[i] + "'"
3428            );
3429        }
3430    
3431        // now merge the opened .gig files to the main .gig file currently being
3432        // open in gigedit
3433        try {
3434            for (i = 0; i < filenames.size(); ++i) {
3435                const std::string& filename = filenames[i];
3436                printf("merging file=%s\n", filename.c_str());
3437                assert(i < sources.gigs.size());
3438    
3439                this->file->AddContentOf(sources.gigs[i]);
3440            }
3441        } catch (RIFF::Exception e) {
3442            throw RIFF::Exception(
3443                _("Error occurred while merging '") +
3444                filenames[i] +
3445                "': " +
3446                e.Message
3447            );
3448        } catch (...) {
3449            throw RIFF::Exception(
3450                _("Unknown exception occurred while merging '") +
3451                filenames[i] + "'"
3452            );
3453        }
3454    
3455        // Finally save gig file persistently to disk ...
3456        //NOTE: requires that this gig file already has a filename !
3457        {
3458            std::cout << "Saving file\n" << std::flush;
3459            file_structure_to_be_changed_signal.emit(this->file);
3460    
3461            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3462                _("Saving") +  Glib::ustring(" '") +
3463                Glib::filename_display_basename(this->filename) + "' ...",
3464                *this
3465            );
3466            progress_dialog->show_all();
3467            saver = new Saver(this->file); //FIXME: memory leak!
3468            saver->signal_progress().connect(
3469                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3470            saver->signal_finished().connect(
3471                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3472            saver->signal_error().connect(
3473                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3474            saver->launch();
3475        }
3476    }
3477    
3478    void MainWindow::on_action_merge_files() {
3479        if (this->file->GetFileName().empty()) {
3480            Glib::ustring txt = _(
3481                "You seem to have a new .gig file open that has not been saved "
3482                "yet. You must save it somewhere before starting to merge it with "
3483                "other .gig files though, because during the merge operation the "
3484                "other files' sample data must be written on file level to the "
3485                "target .gig file."
3486            );
3487            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3488            msg.run();
3489            return;
3490        }
3491    
3492        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3493        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3494        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3495        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3496    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3497        Gtk::FileFilter filter;
3498        filter.add_pattern("*.gig");
3499    #else
3500        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3501        filter->add_pattern("*.gig");
3502    #endif
3503        dialog.set_filter(filter);
3504        if (current_gig_dir != "") {
3505            dialog.set_current_folder(current_gig_dir);
3506        }
3507        dialog.set_select_multiple(true);
3508    
3509        // show warning in the file picker dialog
3510        Gtk::HBox descriptionArea;
3511        descriptionArea.set_spacing(15);
3512        Gtk::Image warningIcon;
3513        warningIcon.set_from_icon_name("dialog-warning",
3514                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3515        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3516    #if GTKMM_MAJOR_VERSION < 3
3517        view::WrapLabel description;
3518    #else
3519        Gtk::Label description;
3520        description.set_line_wrap();
3521    #endif
3522        description.set_markup(_(
3523            "\nSelect at least one .gig file that shall be merged to the .gig file "
3524            "currently being open in gigedit.\n\n"
3525            "<b>Please Note:</b> Merging with other files will modify your "
3526            "currently open .gig file on file level! And be aware that the current "
3527            "merge algorithm does not detect duplicate samples yet. So if you are "
3528            "merging files which are using equivalent sample data, those "
3529            "equivalent samples will currently be treated as separate samples and "
3530            "will accordingly be stored separately in the target .gig file!"
3531        ));
3532        descriptionArea.pack_start(description);
3533        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3534        descriptionArea.show_all();
3535    
3536        if (dialog.run() == Gtk::RESPONSE_OK) {
3537            printf("on_action_merge_files self=%p\n",
3538                   static_cast<void*>(Glib::Threads::Thread::self()));
3539            std::vector<std::string> filenames = dialog.get_filenames();
3540    
3541            // merge the selected files to the currently open .gig file
3542            try {
3543                mergeFiles(filenames);
3544            } catch (RIFF::Exception e) {
3545                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3546                msg.run();
3547            }
3548    
3549            // update GUI
3550            __refreshEntireGUI();
3551        }
3552    }
3553    
3554  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
3555      this->file_is_shared = b;      this->file_is_shared = b;
3556    
# Line 2033  void MainWindow::set_file_is_shared(bool Line 3565  void MainWindow::set_file_is_shared(bool
3565              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3566          );          );
3567      }      }
3568    
3569        {
3570            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3571                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3572            if (item) item->set_sensitive(b);
3573        }
3574    }
3575    
3576    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3577        if (!sample) return;
3578        sample_ref_count[sample] += offset;
3579        const int refcount = sample_ref_count[sample];
3580    
3581        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3582        for (int g = 0; g < model->children().size(); ++g) {
3583            Gtk::TreeModel::Row rowGroup = model->children()[g];
3584            for (int s = 0; s < rowGroup.children().size(); ++s) {
3585                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3586                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3587                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3588                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3589            }
3590        }
3591    }
3592    
3593    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3594        on_sample_ref_count_incremented(oldSample, -1);
3595        on_sample_ref_count_incremented(newSample, +1);
3596    }
3597    
3598    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3599        // just in case a new sample is added later with exactly the same memory
3600        // address, which would lead to incorrect refcount if not deleted here
3601        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3602             it != samples.end(); ++it)
3603        {
3604            sample_ref_count.erase(*it);
3605        }
3606    }
3607    
3608    void MainWindow::show_samples_tab() {
3609        m_TreeViewNotebook.set_current_page(0);
3610    }
3611    
3612    void MainWindow::show_intruments_tab() {
3613        m_TreeViewNotebook.set_current_page(1);
3614    }
3615    
3616    void MainWindow::show_scripts_tab() {
3617        m_TreeViewNotebook.set_current_page(2);
3618    }
3619    
3620    void MainWindow::select_prev_region() {
3621        m_RegionChooser.select_prev_region();
3622    }
3623    
3624    void MainWindow::select_next_region() {
3625        m_RegionChooser.select_next_region();
3626    }
3627    
3628    void MainWindow::select_next_dim_rgn_zone() {
3629        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3630        m_DimRegionChooser.select_next_dimzone();
3631    }
3632    
3633    void MainWindow::select_prev_dim_rgn_zone() {
3634        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3635        m_DimRegionChooser.select_prev_dimzone();
3636    }
3637    
3638    void MainWindow::select_prev_dimension() {
3639        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3640        m_DimRegionChooser.select_prev_dimension();
3641    }
3642    
3643    void MainWindow::select_next_dimension() {
3644        if (m_DimRegionChooser.has_focus()) return; // avoid conflict with key stroke handler of DimenionRegionChooser
3645        m_DimRegionChooser.select_next_dimension();
3646  }  }
3647    
3648  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 2090  sigc::signal<void, int/*key*/, int/*velo Line 3700  sigc::signal<void, int/*key*/, int/*velo
3700  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {  sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3701      return m_RegionChooser.signal_keyboard_key_released();      return m_RegionChooser.signal_keyboard_key_released();
3702  }  }
3703    
3704    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3705        return switch_sampler_instrument_signal;
3706    }

Legend:
Removed from v.2464  
changed lines
  Added in v.3123

  ViewVC Help
Powered by ViewVC