/[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 1415 by schoenebeck, Sat Oct 13 13:14:10 2007 UTC revision 3106 by schoenebeck, Sat Feb 11 17:04:48 2017 UTC
# Line 1  Line 1 
1  /*  /*
2   * Copyright (C) 2006, 2007 Andreas Persson   * Copyright (C) 2006-2017 Andreas Persson
3   *   *
4   * This program is free software; you can redistribute it and/or   * This program is free software; you can redistribute it and/or
5   * modify it under the terms of the GNU General Public License as   * modify it under the terms of the GNU General Public License as
# Line 18  Line 18 
18   */   */
19    
20  #include <iostream>  #include <iostream>
21    #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>
32    #include <glibmm/dispatcher.h>
33    #include <glibmm/miscutils.h>
34    #include <glibmm/stringutils.h>
35    #include <gtkmm/aboutdialog.h>
36  #include <gtkmm/filechooserdialog.h>  #include <gtkmm/filechooserdialog.h>
37  #include <gtkmm/messagedialog.h>  #include <gtkmm/messagedialog.h>
 #include <gtkmm/stock.h>  
38  #include <gtkmm/targetentry.h>  #include <gtkmm/targetentry.h>
39  #include <gtkmm/main.h>  #include <gtkmm/main.h>
40  #include <gtkmm/toggleaction.h>  #include <gtkmm/toggleaction.h>
41    #if GTKMM_MAJOR_VERSION < 3
42  #include "global.h"  #include "wrapLabel.hh"
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
 #define ABOUT_DIALOG  
 #include <gtkmm/aboutdialog.h>  
43  #endif  #endif
44    
45  #if (GLIBMM_MAJOR_VERSION == 2 && GLIBMM_MINOR_VERSION < 6) || GLIBMM_MAJOR_VERSION < 2  #include "global.h"
46  namespace Glib {  #include "compat.h"
 Glib::ustring filename_display_basename(const std::string& filename)  
 {  
     gchar* gstr = g_path_get_basename(filename.c_str());  
     Glib::ustring str(gstr);  
     g_free(gstr);  
     return Glib::filename_to_utf8(str);  
 }  
 }  
 #endif  
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  template<class T> inline std::string ToString(T o) {  MainWindow::MainWindow() :
63      std::stringstream ss;      m_DimRegionChooser(*this),
64      ss << o;      dimreg_label(_("Changes apply to:")),
65      return ss.str();      dimreg_all_regions(_("all regions")),
66  }      dimreg_all_dimregs(_("all dimension splits")),
67        dimreg_stereo(_("both channels")),
68  MainWindow::MainWindow()      labelNoSample(_(" No Sample")),
69        labelMissingSample(_(" Missing some Sample(s)")),
70        labelLooped(_(" Looped")),
71        labelSomeLoops(_(" Some Loop(s)"))
72  {  {
73        loadBuiltInPix();
74    
75  //    set_border_width(5);  //    set_border_width(5);
76  //    set_default_size(400, 200);  //    set_default_size(400, 200);
77    
   
78      add(m_VBox);      add(m_VBox);
79    
80      // Handle selection      // Handle selection
81      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->signal_changed().connect(
     tree_sel_ref->signal_changed().connect(  
82          sigc::mem_fun(*this, &MainWindow::on_sel_change));          sigc::mem_fun(*this, &MainWindow::on_sel_change));
83    
84      // m_TreeView.set_reorderable();      // m_TreeView.set_reorderable();
# Line 85  MainWindow::MainWindow() Line 94  MainWindow::MainWindow()
94      m_ScrolledWindowSamples.add(m_TreeViewSamples);      m_ScrolledWindowSamples.add(m_TreeViewSamples);
95      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);      m_ScrolledWindowSamples.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
96    
97        m_ScrolledWindowScripts.add(m_TreeViewScripts);
98        m_ScrolledWindowScripts.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
99    
100    
101      m_TreeViewNotebook.set_size_request(300);      m_TreeViewNotebook.set_size_request(300);
102    
103      m_HPaned.add1(m_TreeViewNotebook);      m_HPaned.add1(m_TreeViewNotebook);
104      m_HPaned.add2(dimreg_edit);      dimreg_hbox.add(dimreg_label);
105        dimreg_hbox.add(dimreg_all_regions);
106        dimreg_hbox.add(dimreg_all_dimregs);
107      m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, "Samples");      dimreg_stereo.set_active();
108      m_TreeViewNotebook.append_page(m_ScrolledWindow, "Instruments");      dimreg_hbox.add(dimreg_stereo);
109        dimreg_vbox.add(dimreg_edit);
110        dimreg_vbox.pack_start(dimreg_hbox, Gtk::PACK_SHRINK);
111        {
112            imageNoSample.set(redDot);
113            imageNoSample.set_alignment(Gtk::ALIGN_RIGHT);
114            labelNoSample.set_alignment(Gtk::ALIGN_LEFT);
115            legend_hbox.add(imageNoSample);
116            legend_hbox.add(labelNoSample);
117    
118            imageMissingSample.set(yellowDot);
119            imageMissingSample.set_alignment(Gtk::ALIGN_RIGHT);
120            labelMissingSample.set_alignment(Gtk::ALIGN_LEFT);
121            legend_hbox.add(imageMissingSample);
122            legend_hbox.add(labelMissingSample);
123    
124            imageLooped.set(blackLoop);
125            imageLooped.set_alignment(Gtk::ALIGN_RIGHT);
126            labelLooped.set_alignment(Gtk::ALIGN_LEFT);
127            legend_hbox.add(imageLooped);
128            legend_hbox.add(labelLooped);
129    
130            imageSomeLoops.set(grayLoop);
131            imageSomeLoops.set_alignment(Gtk::ALIGN_RIGHT);
132            labelSomeLoops.set_alignment(Gtk::ALIGN_LEFT);
133            legend_hbox.add(imageSomeLoops);
134            legend_hbox.add(labelSomeLoops);
135    
136            legend_hbox.show_all_children();
137        }
138        dimreg_vbox.pack_start(legend_hbox, Gtk::PACK_SHRINK);
139        m_HPaned.add2(dimreg_vbox);
140    
141        dimreg_label.set_tooltip_text(_("To automatically apply your changes above globally to the entire instrument, check all 3 check boxes on the right."));
142        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."));
143        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."));
144        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)."));
145    
146        m_TreeViewNotebook.append_page(m_ScrolledWindowSamples, _("Samples"));
147        m_TreeViewNotebook.append_page(m_ScrolledWindow, _("Instruments"));
148        m_TreeViewNotebook.append_page(m_ScrolledWindowScripts, _("Scripts"));
149    
150      actionGroup = Gtk::ActionGroup::create();      actionGroup = Gtk::ActionGroup::create();
151    
152      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));      actionGroup->add(Gtk::Action::create("MenuFile", _("_File")));
153      actionGroup->add(Gtk::Action::create("New", Gtk::Stock::NEW),      actionGroup->add(Gtk::Action::create("New", _("_New")),
154                         Gtk::AccelKey("<control>n"),
155                       sigc::mem_fun(                       sigc::mem_fun(
156                           *this, &MainWindow::on_action_file_new));                           *this, &MainWindow::on_action_file_new));
157      Glib::RefPtr<Gtk::Action> action =      actionGroup->add(Gtk::Action::create("Open", _("_Open...")),
158          Gtk::Action::create("Open", Gtk::Stock::OPEN);                       Gtk::AccelKey("<control>o"),
     action->property_label() = action->property_label() + "...";  
     actionGroup->add(action,  
159                       sigc::mem_fun(                       sigc::mem_fun(
160                           *this, &MainWindow::on_action_file_open));                           *this, &MainWindow::on_action_file_open));
161      actionGroup->add(Gtk::Action::create("Save", Gtk::Stock::SAVE),      actionGroup->add(Gtk::Action::create("Save", _("_Save")),
162                         Gtk::AccelKey("<control>s"),
163                       sigc::mem_fun(                       sigc::mem_fun(
164                           *this, &MainWindow::on_action_file_save));                           *this, &MainWindow::on_action_file_save));
165      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,  
166                       Gtk::AccelKey("<shift><control>s"),                       Gtk::AccelKey("<shift><control>s"),
167                       sigc::mem_fun(                       sigc::mem_fun(
168                           *this, &MainWindow::on_action_file_save_as));                           *this, &MainWindow::on_action_file_save_as));
169      actionGroup->add(Gtk::Action::create("Properties",      actionGroup->add(Gtk::Action::create("Properties",
170                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
171                       sigc::mem_fun(                       sigc::mem_fun(
172                           *this, &MainWindow::on_action_file_properties));                           *this, &MainWindow::on_action_file_properties));
173      actionGroup->add(Gtk::Action::create("InstrProperties",      actionGroup->add(Gtk::Action::create("InstrProperties",
174                                           Gtk::Stock::PROPERTIES),                                           _("_Properties")),
175                       sigc::mem_fun(                       sigc::mem_fun(
176                           *this, &MainWindow::show_instr_props));                           *this, &MainWindow::show_instr_props));
177      actionGroup->add(Gtk::Action::create("Quit", Gtk::Stock::QUIT),      actionGroup->add(Gtk::Action::create("MidiRules",
178                                             _("_Midi Rules...")),
179                         sigc::mem_fun(
180                             *this, &MainWindow::show_midi_rules));
181        actionGroup->add(Gtk::Action::create("ScriptSlots",
182                                             _("_Script Slots...")),
183                         sigc::mem_fun(
184                             *this, &MainWindow::show_script_slots));
185        actionGroup->add(Gtk::Action::create("Quit", _("_Quit")),
186                         Gtk::AccelKey("<control>q"),
187                       sigc::mem_fun(                       sigc::mem_fun(
188                           *this, &MainWindow::on_action_quit));                           *this, &MainWindow::on_action_quit));
189      actionGroup->add(Gtk::Action::create("MenuInstrument", _("_Instrument")));      actionGroup->add(
190            Gtk::Action::create("MenuSample", _("_Sample")),
191            sigc::mem_fun(*this, &MainWindow::show_samples_tab)
192        );
193        actionGroup->add(
194            Gtk::Action::create("MenuInstrument", _("_Instrument")),
195            sigc::mem_fun(*this, &MainWindow::show_intruments_tab)
196        );
197        actionGroup->add(
198            Gtk::Action::create("MenuScript", _("S_cript")),
199            sigc::mem_fun(*this, &MainWindow::show_scripts_tab)
200        );
201        actionGroup->add(Gtk::Action::create("AllInstruments", _("_Select")));
202    
203        actionGroup->add(Gtk::Action::create("MenuEdit", _("_Edit")));
204    
     actionGroup->add(Gtk::Action::create("MenuView", _("_View")));  
205      Glib::RefPtr<Gtk::ToggleAction> toggle_action =      Glib::RefPtr<Gtk::ToggleAction> toggle_action =
206            Gtk::ToggleAction::create("CopySampleUnity", _("Copy Sample's _Unity Note"));
207        toggle_action->set_active(true);
208        actionGroup->add(toggle_action);
209    
210        toggle_action =
211            Gtk::ToggleAction::create("CopySampleTune", _("Copy Sample's _Fine Tune"));
212        toggle_action->set_active(true);
213        actionGroup->add(toggle_action);
214    
215        toggle_action =
216            Gtk::ToggleAction::create("CopySampleLoop", _("Copy Sample's _Loop Points"));
217        toggle_action->set_active(true);
218        actionGroup->add(toggle_action);
219    
220    
221        actionGroup->add(Gtk::Action::create("MenuView", _("_View")));
222        toggle_action =
223          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));          Gtk::ToggleAction::create("Statusbar", _("_Statusbar"));
224      toggle_action->set_active(true);      toggle_action->set_active(true);
225      actionGroup->add(toggle_action,      actionGroup->add(toggle_action,
226                       sigc::mem_fun(                       sigc::mem_fun(
227                           *this, &MainWindow::on_action_view_status_bar));                           *this, &MainWindow::on_action_view_status_bar));
228    
229      action = Gtk::Action::create("MenuHelp", Gtk::Stock::HELP);      toggle_action =
230      actionGroup->add(Gtk::Action::create("MenuHelp",          Gtk::ToggleAction::create("AutoRestoreWinDim", _("_Auto Restore Window Dimension"));
231                                           action->property_label()));      toggle_action->set_active(Settings::singleton()->autoRestoreWindowDimension);
232  #ifdef ABOUT_DIALOG      actionGroup->add(toggle_action,
233      actionGroup->add(Gtk::Action::create("About", Gtk::Stock::ABOUT),                       sigc::mem_fun(
234                             *this, &MainWindow::on_auto_restore_win_dim));
235    
236        toggle_action =
237            Gtk::ToggleAction::create("SaveWithTemporaryFile", _("Save with _temporary file"));
238        toggle_action->set_active(Settings::singleton()->saveWithTemporaryFile);
239        actionGroup->add(toggle_action,
240                         sigc::mem_fun(
241                             *this, &MainWindow::on_save_with_temporary_file));
242    
243        actionGroup->add(
244            Gtk::Action::create("RefreshAll", _("_Refresh All")),
245            sigc::mem_fun(*this, &MainWindow::on_action_refresh_all)
246        );                
247    
248        actionGroup->add(Gtk::Action::create("MenuHelp", _("_Help")));
249        actionGroup->add(Gtk::Action::create("About", _("_About")),
250                       sigc::mem_fun(                       sigc::mem_fun(
251                           *this, &MainWindow::on_action_help_about));                           *this, &MainWindow::on_action_help_about));
 #endif  
252      actionGroup->add(      actionGroup->add(
253          Gtk::Action::create("AddInstrument", _("Add _Instrument")),          Gtk::Action::create("AddInstrument", _("Add _Instrument")),
254          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_add_instrument)
255      );      );
256      actionGroup->add(      actionGroup->add(
257          Gtk::Action::create("RemoveInstrument", Gtk::Stock::REMOVE),          Gtk::Action::create("DupInstrument", _("_Duplicate Instrument")),
258            sigc::mem_fun(*this, &MainWindow::on_action_duplicate_instrument)
259        );
260        actionGroup->add(
261            Gtk::Action::create("RemoveInstrument", _("_Remove")),
262          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)          sigc::mem_fun(*this, &MainWindow::on_action_remove_instrument)
263      );      );
264    
265    
266        actionGroup->add(Gtk::Action::create("MenuSettings", _("_Settings")));
267        
268        toggle_action =
269            Gtk::ToggleAction::create("WarnUserOnExtensions", _("Show warning on format _extensions"));
270        toggle_action->set_active(Settings::singleton()->warnUserOnExtensions);
271        actionGroup->add(
272            toggle_action,
273            sigc::mem_fun(*this, &MainWindow::on_action_warn_user_on_extensions)
274        );
275    
276        toggle_action =
277            Gtk::ToggleAction::create("SyncSamplerInstrumentSelection", _("Synchronize sampler's instrument selection"));
278        toggle_action->set_active(Settings::singleton()->syncSamplerInstrumentSelection);
279        actionGroup->add(
280            toggle_action,
281            sigc::mem_fun(*this, &MainWindow::on_action_sync_sampler_instrument_selection)
282        );
283    
284        toggle_action =
285            Gtk::ToggleAction::create("MoveRootNoteWithRegionMoved", _("Move root note with region moved"));
286        toggle_action->set_active(Settings::singleton()->moveRootNoteWithRegionMoved);
287        actionGroup->add(
288            toggle_action,
289            sigc::mem_fun(*this, &MainWindow::on_action_move_root_note_with_region_moved)
290        );
291    
292    
293        actionGroup->add(Gtk::Action::create("MenuTools", _("_Tools")));
294    
295        actionGroup->add(
296            Gtk::Action::create("CombineInstruments", _("_Combine Instruments...")),
297            sigc::mem_fun(*this, &MainWindow::on_action_combine_instruments)
298        );
299    
300        actionGroup->add(
301            Gtk::Action::create("MergeFiles", _("_Merge Files...")),
302            sigc::mem_fun(*this, &MainWindow::on_action_merge_files)
303        );
304    
305    
306      // sample right-click popup actions      // sample right-click popup actions
307      actionGroup->add(      actionGroup->add(
308          Gtk::Action::create("SampleProperties", Gtk::Stock::PROPERTIES),          Gtk::Action::create("SampleProperties", _("_Properties")),
309          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)          sigc::mem_fun(*this, &MainWindow::on_action_sample_properties)
310      );      );
311      actionGroup->add(      actionGroup->add(
# Line 165  MainWindow::MainWindow() Line 313  MainWindow::MainWindow()
313          sigc::mem_fun(*this, &MainWindow::on_action_add_group)          sigc::mem_fun(*this, &MainWindow::on_action_add_group)
314      );      );
315      actionGroup->add(      actionGroup->add(
316          Gtk::Action::create("AddSample", _("Add _Sample(s)")),          Gtk::Action::create("AddSample", _("Add _Sample(s)...")),
317          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)          sigc::mem_fun(*this, &MainWindow::on_action_add_sample)
318      );      );
319      actionGroup->add(      actionGroup->add(
320          Gtk::Action::create("RemoveSample", Gtk::Stock::REMOVE),          Gtk::Action::create("RemoveSample", _("_Remove")),
321          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)          sigc::mem_fun(*this, &MainWindow::on_action_remove_sample)
322      );      );
323        actionGroup->add(
324            Gtk::Action::create("RemoveUnusedSamples", _("Remove _Unused Samples")),
325            sigc::mem_fun(*this, &MainWindow::on_action_remove_unused_samples)
326        );
327        actionGroup->add(
328            Gtk::Action::create("ShowSampleRefs", _("Show References...")),
329            sigc::mem_fun(*this, &MainWindow::on_action_view_references)
330        );
331        actionGroup->add(
332            Gtk::Action::create("ReplaceSample",
333                                _("Replace Sample...")),
334            sigc::mem_fun(*this, &MainWindow::on_action_replace_sample)
335        );
336        actionGroup->add(
337            Gtk::Action::create("ReplaceAllSamplesInAllGroups",
338                                _("Replace All Samples in All Groups...")),
339            sigc::mem_fun(*this, &MainWindow::on_action_replace_all_samples_in_all_groups)
340        );
341        
342        // script right-click popup actions
343        actionGroup->add(
344            Gtk::Action::create("AddScriptGroup", _("Add _Group")),
345            sigc::mem_fun(*this, &MainWindow::on_action_add_script_group)
346        );
347        actionGroup->add(
348            Gtk::Action::create("AddScript", _("Add _Script")),
349            sigc::mem_fun(*this, &MainWindow::on_action_add_script)
350        );
351        actionGroup->add(
352            Gtk::Action::create("EditScript", _("_Edit Script...")),
353            sigc::mem_fun(*this, &MainWindow::on_action_edit_script)
354        );
355        actionGroup->add(
356            Gtk::Action::create("RemoveScript", _("_Remove")),
357            sigc::mem_fun(*this, &MainWindow::on_action_remove_script)
358        );
359    
360      uiManager = Gtk::UIManager::create();      uiManager = Gtk::UIManager::create();
361      uiManager->insert_action_group(actionGroup);      uiManager->insert_action_group(actionGroup);
# Line 191  MainWindow::MainWindow() Line 375  MainWindow::MainWindow()
375          "      <separator/>"          "      <separator/>"
376          "      <menuitem action='Quit'/>"          "      <menuitem action='Quit'/>"
377          "    </menu>"          "    </menu>"
378            "    <menu action='MenuEdit'>"
379            "      <menuitem action='CopySampleUnity'/>"
380            "      <menuitem action='CopySampleTune'/>"
381            "      <menuitem action='CopySampleLoop'/>"
382            "    </menu>"
383            "    <menu action='MenuSample'>"
384            "      <menuitem action='SampleProperties'/>"
385            "      <menuitem action='AddGroup'/>"
386            "      <menuitem action='AddSample'/>"
387            "      <menuitem action='ShowSampleRefs'/>"
388            "      <menuitem action='ReplaceSample' />"
389            "      <menuitem action='ReplaceAllSamplesInAllGroups' />"
390            "      <separator/>"
391            "      <menuitem action='RemoveSample'/>"
392            "      <menuitem action='RemoveUnusedSamples'/>"
393            "    </menu>"
394          "    <menu action='MenuInstrument'>"          "    <menu action='MenuInstrument'>"
395            "      <menu action='AllInstruments'>"
396            "      </menu>"
397            "      <separator/>"
398            "      <menuitem action='InstrProperties'/>"
399            "      <menuitem action='MidiRules'/>"
400            "      <menuitem action='ScriptSlots'/>"
401            "      <menuitem action='AddInstrument'/>"
402            "      <menuitem action='DupInstrument'/>"
403            "      <separator/>"
404            "      <menuitem action='RemoveInstrument'/>"
405            "    </menu>"
406            "    <menu action='MenuScript'>"
407            "      <menuitem action='AddScriptGroup'/>"
408            "      <menuitem action='AddScript'/>"
409            "      <menuitem action='EditScript'/>"
410            "      <separator/>"
411            "      <menuitem action='RemoveScript'/>"
412          "    </menu>"          "    </menu>"
413          "    <menu action='MenuView'>"          "    <menu action='MenuView'>"
414          "      <menuitem action='Statusbar'/>"          "      <menuitem action='Statusbar'/>"
415            "      <menuitem action='AutoRestoreWinDim'/>"
416            "      <separator/>"
417            "      <menuitem action='RefreshAll'/>"
418            "    </menu>"
419            "    <menu action='MenuTools'>"
420            "      <menuitem action='CombineInstruments'/>"
421            "      <menuitem action='MergeFiles'/>"
422            "    </menu>"
423            "    <menu action='MenuSettings'>"
424            "      <menuitem action='WarnUserOnExtensions'/>"
425            "      <menuitem action='SyncSamplerInstrumentSelection'/>"
426            "      <menuitem action='MoveRootNoteWithRegionMoved'/>"
427            "      <menuitem action='SaveWithTemporaryFile'/>"
428          "    </menu>"          "    </menu>"
 #ifdef ABOUT_DIALOG  
429          "    <menu action='MenuHelp'>"          "    <menu action='MenuHelp'>"
430          "      <menuitem action='About'/>"          "      <menuitem action='About'/>"
431          "    </menu>"          "    </menu>"
 #endif  
432          "  </menubar>"          "  </menubar>"
433          "  <popup name='PopupMenu'>"          "  <popup name='PopupMenu'>"
434          "    <menuitem action='InstrProperties'/>"          "    <menuitem action='InstrProperties'/>"
435            "    <menuitem action='MidiRules'/>"
436            "    <menuitem action='ScriptSlots'/>"
437          "    <menuitem action='AddInstrument'/>"          "    <menuitem action='AddInstrument'/>"
438            "    <menuitem action='DupInstrument'/>"
439          "    <separator/>"          "    <separator/>"
440          "    <menuitem action='RemoveInstrument'/>"          "    <menuitem action='RemoveInstrument'/>"
441          "  </popup>"          "  </popup>"
# Line 212  MainWindow::MainWindow() Line 443  MainWindow::MainWindow()
443          "    <menuitem action='SampleProperties'/>"          "    <menuitem action='SampleProperties'/>"
444          "    <menuitem action='AddGroup'/>"          "    <menuitem action='AddGroup'/>"
445          "    <menuitem action='AddSample'/>"          "    <menuitem action='AddSample'/>"
446            "    <menuitem action='ShowSampleRefs'/>"
447            "    <menuitem action='ReplaceSample' />"
448            "    <menuitem action='ReplaceAllSamplesInAllGroups' />"
449          "    <separator/>"          "    <separator/>"
450          "    <menuitem action='RemoveSample'/>"          "    <menuitem action='RemoveSample'/>"
451            "    <menuitem action='RemoveUnusedSamples'/>"
452            "  </popup>"
453            "  <popup name='ScriptPopupMenu'>"
454            "    <menuitem action='AddScriptGroup'/>"
455            "    <menuitem action='AddScript'/>"
456            "    <menuitem action='EditScript'/>"
457            "    <separator/>"
458            "    <menuitem action='RemoveScript'/>"
459          "  </popup>"          "  </popup>"
460          "</ui>";          "</ui>";
461      uiManager->add_ui_from_string(ui_info);      uiManager->add_ui_from_string(ui_info);
462    
463      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));      popup_menu = dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/PopupMenu"));
464        
465        // Set tooltips for menu items (for some reason, setting a tooltip on the
466        // respective Gtk::Action objects above will simply be ignored, no matter
467        // if using Gtk::Action::set_tooltip() or passing the tooltip string on
468        // Gtk::Action::create()).
469        {
470            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
471                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
472            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."));
473        }
474        {
475            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
476                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
477            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."));
478        }
479        {
480            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
481                uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
482            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."));
483        }
484        {
485            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
486                uiManager->get_widget("/MenuBar/MenuSettings/WarnUserOnExtensions"));
487            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."));
488        }
489        {
490            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
491                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
492            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)."));
493        }
494        {
495            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
496                uiManager->get_widget("/MenuBar/MenuSettings/MoveRootNoteWithRegionMoved"));
497            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."));
498        }
499        {
500            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
501                uiManager->get_widget("/MenuBar/MenuSample/RemoveUnusedSamples"));
502            item->set_tooltip_text(_("Removes all samples that are not referenced by any instrument (i.e. red ones)."));
503            // copy tooltip to popup menu
504            Gtk::MenuItem* item2 = dynamic_cast<Gtk::MenuItem*>(
505                uiManager->get_widget("/SamplePopupMenu/RemoveUnusedSamples"));
506            item2->set_tooltip_text(item->get_tooltip_text());
507        }
508        {
509            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
510                uiManager->get_widget("/MenuBar/MenuView/RefreshAll"));
511            item->set_tooltip_text(_("Reloads the currently open gig file and updates the entire graphical user interface."));
512        }
513        {
514            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
515                uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
516            item->set_tooltip_text(_("If checked, size and position of all windows will be saved and automatically restored next time."));
517        }
518        {
519            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
520                uiManager->get_widget("/MenuBar/MenuTools/CombineInstruments"));
521            item->set_tooltip_text(_("Create combi sounds out of individual sounds of this .gig file."));
522        }
523        {
524            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
525                uiManager->get_widget("/MenuBar/MenuTools/MergeFiles"));
526            item->set_tooltip_text(_("Add instruments and samples of other .gig files to this .gig file."));
527        }
528    
529    
530        instrument_menu = static_cast<Gtk::MenuItem*>(
531            uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments"))->get_submenu();
532    
533      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");      Gtk::Widget* menuBar = uiManager->get_widget("/MenuBar");
534      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(*menuBar, Gtk::PACK_SHRINK);
535      m_VBox.pack_start(m_HPaned);      m_VBox.pack_start(m_HPaned);
536      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_RegionChooser, Gtk::PACK_SHRINK);
537        m_VBox.pack_start(m_RegionChooser.m_VirtKeybPropsBox, Gtk::PACK_SHRINK);
538      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_DimRegionChooser, Gtk::PACK_SHRINK);
539      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);      m_VBox.pack_start(m_StatusBar, Gtk::PACK_SHRINK);
540    
541        set_file_is_shared(false);
542    
543      // Status Bar:      // Status Bar:
544      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateLabel, Gtk::PACK_SHRINK);
545      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);      m_StatusBar.pack_start(m_AttachedStateImage, Gtk::PACK_SHRINK);
# Line 241  MainWindow::MainWindow() Line 554  MainWindow::MainWindow()
554      // Create the Tree model:      // Create the Tree model:
555      m_refTreeModel = Gtk::ListStore::create(m_Columns);      m_refTreeModel = Gtk::ListStore::create(m_Columns);
556      m_TreeView.set_model(m_refTreeModel);      m_TreeView.set_model(m_refTreeModel);
557      m_refTreeModel->signal_row_changed().connect(      m_TreeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
558        m_TreeView.set_tooltip_text(_("Right click here for actions on instruments & MIDI Rules. Drag & drop to change the order of instruments."));
559        instrument_name_connection = m_refTreeModel->signal_row_changed().connect(
560          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)          sigc::mem_fun(*this, &MainWindow::instrument_name_changed)
561      );      );
562    
563      // Add the TreeView's view columns:      // Add the TreeView's view columns:
564      m_TreeView.append_column_editable("Instrument", m_Columns.m_col_name);      m_TreeView.append_column(_("Nr"), m_Columns.m_col_nr);
565      m_TreeView.set_headers_visible(false);      m_TreeView.append_column_editable(_("Instrument"), m_Columns.m_col_name);
566        m_TreeView.set_headers_visible(true);
567        
568        // establish drag&drop within the instrument tree view, allowing to reorder
569        // the sequence of instruments within the gig file
570        {
571            std::vector<Gtk::TargetEntry> drag_target_instrument;
572            drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
573            m_TreeView.drag_source_set(drag_target_instrument);
574            m_TreeView.drag_dest_set(drag_target_instrument);
575            m_TreeView.signal_drag_begin().connect(
576                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_begin)
577            );
578            m_TreeView.signal_drag_data_get().connect(
579                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drag_data_get)
580            );
581            m_TreeView.signal_drag_data_received().connect(
582                sigc::mem_fun(*this, &MainWindow::on_instruments_treeview_drop_drag_data_received)
583            );
584        }
585    
586      // create samples treeview (including its data model)      // create samples treeview (including its data model)
587      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);      m_refSamplesTreeModel = SamplesTreeStore::create(m_SamplesModel);
588      m_TreeViewSamples.set_model(m_refSamplesTreeModel);      m_TreeViewSamples.set_model(m_refSamplesTreeModel);
589        m_TreeViewSamples.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
590        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."));
591      // m_TreeViewSamples.set_reorderable();      // m_TreeViewSamples.set_reorderable();
592      m_TreeViewSamples.append_column_editable("Samples", m_SamplesModel.m_col_name);      m_TreeViewSamples.append_column_editable(_("Name"), m_SamplesModel.m_col_name);
593      m_TreeViewSamples.set_headers_visible(false);      m_TreeViewSamples.append_column(_("Referenced"), m_SamplesModel.m_col_refcount);
594        {
595            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(0);
596            Gtk::CellRendererText* cellrenderer =
597                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
598            column->add_attribute(
599                cellrenderer->property_foreground(), m_SamplesModel.m_color
600            );
601        }
602        {
603            Gtk::TreeViewColumn* column = m_TreeViewSamples.get_column(1);
604            Gtk::CellRendererText* cellrenderer =
605                dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell());
606            column->add_attribute(
607                cellrenderer->property_foreground(), m_SamplesModel.m_color
608            );
609        }
610        m_TreeViewSamples.set_headers_visible(true);
611      m_TreeViewSamples.signal_button_press_event().connect_notify(      m_TreeViewSamples.signal_button_press_event().connect_notify(
612          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_button_release)
613      );      );
# Line 262  MainWindow::MainWindow() Line 615  MainWindow::MainWindow()
615          sigc::mem_fun(*this, &MainWindow::sample_name_changed)          sigc::mem_fun(*this, &MainWindow::sample_name_changed)
616      );      );
617    
618        // create scripts treeview (including its data model)
619        m_refScriptsTreeModel = ScriptsTreeStore::create(m_ScriptsModel);
620        m_TreeViewScripts.set_model(m_refScriptsTreeModel);
621        m_TreeViewScripts.set_tooltip_text(_(
622            "Use CTRL + double click for editing a script."
623            "\n\n"
624            "Note: instrument scripts are a LinuxSampler extension of the gig "
625            "format. This feature will not work with the GigaStudio software!"
626        ));
627        // m_TreeViewScripts.set_reorderable();
628        m_TreeViewScripts.append_column_editable("Samples", m_ScriptsModel.m_col_name);
629        m_TreeViewScripts.set_headers_visible(false);
630        m_TreeViewScripts.signal_button_press_event().connect_notify(
631            sigc::mem_fun(*this, &MainWindow::on_script_treeview_button_release)
632        );
633        //FIXME: why the heck does this double click signal_row_activated() only fire while CTRL key is pressed ?
634        m_TreeViewScripts.signal_row_activated().connect(
635            sigc::mem_fun(*this, &MainWindow::script_double_clicked)
636        );
637        m_refScriptsTreeModel->signal_row_changed().connect(
638            sigc::mem_fun(*this, &MainWindow::script_name_changed)
639        );
640    
641        // establish drag&drop between scripts tree view and ScriptSlots window
642        std::vector<Gtk::TargetEntry> drag_target_gig_script;
643        drag_target_gig_script.push_back(Gtk::TargetEntry("gig::Script"));
644        m_TreeViewScripts.drag_source_set(drag_target_gig_script);
645        m_TreeViewScripts.signal_drag_begin().connect(
646            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_begin)
647        );
648        m_TreeViewScripts.signal_drag_data_get().connect(
649            sigc::mem_fun(*this, &MainWindow::on_scripts_treeview_drag_data_get)
650        );
651    
652      // 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
653      std::list<Gtk::TargetEntry> drag_target_gig_sample;      std::vector<Gtk::TargetEntry> drag_target_gig_sample;
654      drag_target_gig_sample.push_back( Gtk::TargetEntry("gig::Sample") );      drag_target_gig_sample.push_back(Gtk::TargetEntry("gig::Sample"));
655      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);      m_TreeViewSamples.drag_source_set(drag_target_gig_sample);
656      m_TreeViewSamples.signal_drag_begin().connect(      m_TreeViewSamples.signal_drag_begin().connect(
657          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)          sigc::mem_fun(*this, &MainWindow::on_sample_treeview_drag_begin)
# Line 280  MainWindow::MainWindow() Line 667  MainWindow::MainWindow()
667          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));          sigc::hide(sigc::mem_fun(*this, &MainWindow::file_changed)));
668      m_RegionChooser.signal_instrument_changed().connect(      m_RegionChooser.signal_instrument_changed().connect(
669          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
670        m_RegionChooser.signal_instrument_changed().connect(
671            sigc::mem_fun(*this, &MainWindow::region_changed));
672      m_DimRegionChooser.signal_region_changed().connect(      m_DimRegionChooser.signal_region_changed().connect(
673          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
674      instrumentProps.signal_instrument_changed().connect(      instrumentProps.signal_changed().connect(
675            sigc::mem_fun(*this, &MainWindow::file_changed));
676        propDialog.signal_changed().connect(
677            sigc::mem_fun(*this, &MainWindow::file_changed));
678        midiRules.signal_changed().connect(
679          sigc::mem_fun(*this, &MainWindow::file_changed));          sigc::mem_fun(*this, &MainWindow::file_changed));
680    
681      dimreg_edit.signal_dimreg_to_be_changed().connect(      dimreg_edit.signal_dimreg_to_be_changed().connect(
# Line 291  MainWindow::MainWindow() Line 684  MainWindow::MainWindow()
684          dimreg_changed_signal.make_slot());          dimreg_changed_signal.make_slot());
685      dimreg_edit.signal_sample_ref_changed().connect(      dimreg_edit.signal_sample_ref_changed().connect(
686          sample_ref_changed_signal.make_slot());          sample_ref_changed_signal.make_slot());
687        sample_ref_changed_signal.connect(
688            sigc::mem_fun(*this, &MainWindow::on_sample_ref_changed)
689        );
690        samples_to_be_removed_signal.connect(
691            sigc::mem_fun(*this, &MainWindow::on_samples_to_be_removed)
692        );
693    
694        dimreg_edit.signal_select_sample().connect(
695            sigc::mem_fun(*this, &MainWindow::select_sample)
696        );
697    
698      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(      m_RegionChooser.signal_instrument_struct_to_be_changed().connect(
699          sigc::hide(          sigc::hide(
# Line 313  MainWindow::MainWindow() Line 716  MainWindow::MainWindow()
716      m_RegionChooser.signal_region_changed_signal().connect(      m_RegionChooser.signal_region_changed_signal().connect(
717          region_changed_signal.make_slot());          region_changed_signal.make_slot());
718    
719        note_on_signal.connect(
720            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_on_event));
721        note_off_signal.connect(
722            sigc::mem_fun(m_RegionChooser, &RegionChooser::on_note_off_event));
723    
724        dimreg_all_regions.signal_toggled().connect(
725            sigc::mem_fun(*this, &MainWindow::update_dimregs));
726        dimreg_all_dimregs.signal_toggled().connect(
727            sigc::mem_fun(*this, &MainWindow::dimreg_all_dimregs_toggled));
728        dimreg_stereo.signal_toggled().connect(
729            sigc::mem_fun(*this, &MainWindow::update_dimregs));
730    
731      file = 0;      file = 0;
732      file_is_changed = false;      file_is_changed = false;
     set_file_is_shared(false);  
733    
734      show_all_children();      show_all_children();
735    
736      // start with a new gig file by default      // start with a new gig file by default
737      on_action_file_new();      on_action_file_new();
738    
739        // select 'Instruments' tab by default
740        // (gtk allows this only if the tab childs are visible, thats why it's here)
741        m_TreeViewNotebook.set_current_page(1);
742  }  }
743    
744  MainWindow::~MainWindow()  MainWindow::~MainWindow()
# Line 343  void MainWindow::region_changed() Line 761  void MainWindow::region_changed()
761      m_DimRegionChooser.set_region(m_RegionChooser.get_region());      m_DimRegionChooser.set_region(m_RegionChooser.get_region());
762  }  }
763    
764    gig::Instrument* MainWindow::get_instrument()
765    {
766        gig::Instrument* instrument = 0;
767        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
768        if (rows.empty()) return NULL;
769        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
770        if (it) {
771            Gtk::TreeModel::Row row = *it;
772            instrument = row[m_Columns.m_col_instr];
773        }
774        return instrument;
775    }
776    
777    void MainWindow::add_region_to_dimregs(gig::Region* region, bool stereo, bool all_dimregs)
778    {
779        if (all_dimregs) {
780            for (int i = 0 ; i < region->DimensionRegions ; i++) {
781                if (region->pDimensionRegions[i]) {
782                    dimreg_edit.dimregs.insert(region->pDimensionRegions[i]);
783                }
784            }
785        } else {
786            m_DimRegionChooser.get_dimregions(region, stereo, dimreg_edit.dimregs);
787        }
788    }
789    
790    void MainWindow::update_dimregs()
791    {
792        dimreg_edit.dimregs.clear();
793        bool all_regions = dimreg_all_regions.get_active();
794        bool stereo = dimreg_stereo.get_active();
795        bool all_dimregs = dimreg_all_dimregs.get_active();
796    
797        if (all_regions) {
798            gig::Instrument* instrument = get_instrument();
799            if (instrument) {
800                for (gig::Region* region = instrument->GetFirstRegion() ;
801                     region ;
802                     region = instrument->GetNextRegion()) {
803                    add_region_to_dimregs(region, stereo, all_dimregs);
804                }
805            }
806        } else {
807            gig::Region* region = m_RegionChooser.get_region();
808            if (region) {
809                add_region_to_dimregs(region, stereo, all_dimregs);
810            }
811        }
812    
813        m_DimRegionChooser.setModifyAllRegions(all_regions);
814        m_DimRegionChooser.setModifyAllDimensionRegions(all_dimregs);
815        m_DimRegionChooser.setModifyBothChannels(stereo);
816    }
817    
818    void MainWindow::dimreg_all_dimregs_toggled()
819    {
820        dimreg_stereo.set_sensitive(!dimreg_all_dimregs.get_active());
821        update_dimregs();
822    }
823    
824  void MainWindow::dimreg_changed()  void MainWindow::dimreg_changed()
825  {  {
826      dimreg_edit.set_dim_region(m_DimRegionChooser.get_dimregion());      update_dimregs();
827        dimreg_edit.set_dim_region(m_DimRegionChooser.get_main_dimregion());
828  }  }
829    
830  void MainWindow::on_sel_change()  void MainWindow::on_sel_change()
831  {  {
832      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      // select item in instrument menu
833        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
834        if (!rows.empty()) {
835            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
836            if (it) {
837                Gtk::TreePath path(it);
838                int index = path[0];
839                const std::vector<Gtk::Widget*> children =
840                    instrument_menu->get_children();
841                static_cast<Gtk::RadioMenuItem*>(children[index])->set_active();
842            }
843        }
844    
845      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();      m_RegionChooser.set_instrument(get_instrument());
     if (it) {  
         Gtk::TreeModel::Row row = *it;  
         std::cout << row[m_Columns.m_col_name] << std::endl;  
846    
847          m_RegionChooser.set_instrument(row[m_Columns.m_col_instr]);      if (Settings::singleton()->syncSamplerInstrumentSelection) {
848      } else {          switch_sampler_instrument_signal.emit(get_instrument());
         m_RegionChooser.set_instrument(0);  
849      }      }
850  }  }
851    
# Line 372  void loader_progress_callback(gig::progr Line 858  void loader_progress_callback(gig::progr
858  void Loader::progress_callback(float fraction)  void Loader::progress_callback(float fraction)
859  {  {
860      {      {
861          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
862          progress = fraction;          progress = fraction;
863      }      }
864      progress_dispatcher();      progress_dispatcher();
865  }  }
866    
867    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
868    // make sure stack is 16-byte aligned for SSE instructions
869    __attribute__((force_align_arg_pointer))
870    #endif
871  void Loader::thread_function()  void Loader::thread_function()
872  {  {
873      printf("thread_function self=%x\n", Glib::Thread::self());      printf("thread_function self=%p\n",
874      printf("Start %s\n", filename);             static_cast<void*>(Glib::Threads::Thread::self()));
875      RIFF::File* riff = new RIFF::File(filename);      printf("Start %s\n", filename.c_str());
876      gig = new gig::File(riff);      try {
877      gig::progress_t progress;          RIFF::File* riff = new RIFF::File(filename);
878      progress.callback = loader_progress_callback;          gig = new gig::File(riff);
879      progress.custom = this;          gig::progress_t progress;
880            progress.callback = loader_progress_callback;
881      gig->GetInstrument(0, &progress);          progress.custom = this;
882      printf("End\n");  
883      finished_dispatcher();          gig->GetInstrument(0, &progress);
884            printf("End\n");
885            finished_dispatcher();
886        } catch (RIFF::Exception e) {
887            error_message = e.Message;
888            error_dispatcher.emit();
889        } catch (...) {
890            error_message = _("Unknown exception occurred");
891            error_dispatcher.emit();
892        }
893  }  }
894    
895  Loader::Loader(const char* filename)  Loader::Loader(const char* filename)
896      : thread(0), filename(filename)      : filename(filename), gig(0), thread(0), progress(0.f)
897  {  {
898  }  }
899    
900  void Loader::launch()  void Loader::launch()
901  {  {
902    #ifdef OLD_THREADS
903      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);      thread = Glib::Thread::create(sigc::mem_fun(*this, &Loader::thread_function), true);
904      printf("launch thread=%x\n", thread);  #else
905        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Loader::thread_function));
906    #endif
907        printf("launch thread=%p\n", static_cast<void*>(thread));
908  }  }
909    
910  float Loader::get_progress()  float Loader::get_progress()
911  {  {
912      float res;      float res;
913      {      {
914          Glib::Mutex::Lock lock(progressMutex);          Glib::Threads::Mutex::Lock lock(progressMutex);
915          res = progress;          res = progress;
916      }      }
917      return res;      return res;
# Line 424  Glib::Dispatcher& Loader::signal_finishe Line 927  Glib::Dispatcher& Loader::signal_finishe
927      return finished_dispatcher;      return finished_dispatcher;
928  }  }
929    
930  LoadDialog::LoadDialog(const Glib::ustring& title, Gtk::Window& parent)  Glib::Dispatcher& Loader::signal_error()
931    {
932        return error_dispatcher;
933    }
934    
935    void saver_progress_callback(gig::progress_t* progress)
936    {
937        Saver* saver = static_cast<Saver*>(progress->custom);
938        saver->progress_callback(progress->factor);
939    }
940    
941    void Saver::progress_callback(float fraction)
942    {
943        {
944            Glib::Threads::Mutex::Lock lock(progressMutex);
945            progress = fraction;
946        }
947        progress_dispatcher.emit();
948    }
949    
950    #if defined(WIN32) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
951    // make sure stack is 16-byte aligned for SSE instructions
952    __attribute__((force_align_arg_pointer))
953    #endif
954    void Saver::thread_function()
955    {
956        printf("thread_function self=%p\n",
957               static_cast<void*>(Glib::Threads::Thread::self()));
958        printf("Start %s\n", filename.c_str());
959        try {
960            gig::progress_t progress;
961            progress.callback = saver_progress_callback;
962            progress.custom = this;
963    
964            // if no filename was provided, that means "save", if filename was provided means "save as"
965            if (filename.empty()) {
966                if (!Settings::singleton()->saveWithTemporaryFile) {
967                    // save directly over the existing .gig file
968                    // (requires less disk space than solution below
969                    // but may be slower)
970                    gig->Save(&progress);
971                } else {
972                    // save the file as separate temporary file first,
973                    // then move the saved file over the old file
974                    // (may result in performance speedup during save)
975                    String tmpname = filename + ".TMP";
976                    gig->Save(tmpname, &progress);
977                    #if defined(WIN32)
978                    if (!DeleteFile(filename.c_str())) {
979                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file).");
980                    }
981                    #else // POSIX ...
982                    if (unlink(filename.c_str())) {
983                        throw RIFF::Exception("Could not replace original file with temporary file (unable to remove original file): " + String(strerror(errno)));
984                    }
985                    #endif
986                    if (rename(tmpname.c_str(), filename.c_str())) {
987                        #if defined(WIN32)
988                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file).");
989                        #else
990                        throw RIFF::Exception("Could not replace original file with temporary file (unable to rename temp file): " + String(strerror(errno)));
991                        #endif
992                    }
993                }
994            } else {
995                gig->Save(filename, &progress);
996            }
997    
998            printf("End\n");
999            finished_dispatcher.emit();
1000        } catch (RIFF::Exception e) {
1001            error_message = e.Message;
1002            error_dispatcher.emit();
1003        } catch (...) {
1004            error_message = _("Unknown exception occurred");
1005            error_dispatcher.emit();
1006        }
1007    }
1008    
1009    Saver::Saver(gig::File* file, Glib::ustring filename)
1010        : gig(file), filename(filename), thread(0), progress(0.f)
1011    {
1012    }
1013    
1014    void Saver::launch()
1015    {
1016    #ifdef OLD_THREADS
1017        thread = Glib::Thread::create(sigc::mem_fun(*this, &Saver::thread_function), true);
1018    #else
1019        thread = Glib::Threads::Thread::create(sigc::mem_fun(*this, &Saver::thread_function));
1020    #endif
1021        printf("launch thread=%p\n", static_cast<void*>(thread));
1022    }
1023    
1024    float Saver::get_progress()
1025    {
1026        float res;
1027        {
1028            Glib::Threads::Mutex::Lock lock(progressMutex);
1029            res = progress;
1030        }
1031        return res;
1032    }
1033    
1034    Glib::Dispatcher& Saver::signal_progress()
1035    {
1036        return progress_dispatcher;
1037    }
1038    
1039    Glib::Dispatcher& Saver::signal_finished()
1040    {
1041        return finished_dispatcher;
1042    }
1043    
1044    Glib::Dispatcher& Saver::signal_error()
1045    {
1046        return error_dispatcher;
1047    }
1048    
1049    ProgressDialog::ProgressDialog(const Glib::ustring& title, Gtk::Window& parent)
1050      : Gtk::Dialog(title, parent, true)      : Gtk::Dialog(title, parent, true)
1051  {  {
1052      get_vbox()->pack_start(progressBar);      get_vbox()->pack_start(progressBar);
1053      show_all_children();      show_all_children();
1054        resize(600,50);
1055  }  }
1056    
1057  // Clear all GUI elements / controls. This method is typically called  // Clear all GUI elements / controls. This method is typically called
1058  // before a new .gig file is to be created or to be loaded.  // before a new .gig file is to be created or to be loaded.
1059  void MainWindow::__clear() {  void MainWindow::__clear() {
     // remove all entries from "Instrument" menu  
     Gtk::MenuItem* instrument_menu =  
         dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));  
     instrument_menu->hide();  
     for (int i = 0; i < instrument_menu->get_submenu()->items().size(); i++) {  
         delete &instrument_menu->get_submenu()->items()[i];  
     }  
     instrument_menu->get_submenu()->items().clear();  
1060      // forget all samples that ought to be imported      // forget all samples that ought to be imported
1061      m_SampleImportQueue.clear();      m_SampleImportQueue.clear();
1062      // clear the samples and instruments tree views      // clear the samples and instruments tree views
1063      m_refTreeModel->clear();      m_refTreeModel->clear();
1064      m_refSamplesTreeModel->clear();      m_refSamplesTreeModel->clear();
1065        m_refScriptsTreeModel->clear();
1066        // remove all entries from "Instrument" menu
1067        while (!instrument_menu->get_children().empty()) {
1068            remove_instrument_from_menu(0);
1069        }
1070      // free libgig's gig::File instance      // free libgig's gig::File instance
1071      if (file && !file_is_shared) delete file;      if (file && !file_is_shared) delete file;
1072      file = NULL;      file = NULL;
1073      set_file_is_shared(false);      set_file_is_shared(false);
1074  }  }
1075    
1076    void MainWindow::__refreshEntireGUI() {
1077        // clear the samples and instruments tree views
1078        m_refTreeModel->clear();
1079        m_refSamplesTreeModel->clear();
1080        m_refScriptsTreeModel->clear();
1081        // remove all entries from "Instrument" menu
1082        while (!instrument_menu->get_children().empty()) {
1083            remove_instrument_from_menu(0);
1084        }
1085    
1086        if (!this->file) return;
1087    
1088        load_gig(
1089            this->file, this->file->pInfo->Name.c_str(), this->file_is_shared
1090        );
1091    }
1092    
1093  void MainWindow::on_action_file_new()  void MainWindow::on_action_file_new()
1094  {  {
1095      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;      if (!file_is_shared && file_is_changed && !close_confirmation_dialog()) return;
# Line 465  void MainWindow::on_action_file_new() Line 1102  void MainWindow::on_action_file_new()
1102      gig::File* pFile = new gig::File;      gig::File* pFile = new gig::File;
1103      // already add one new instrument by default      // already add one new instrument by default
1104      gig::Instrument* pInstrument = pFile->AddInstrument();      gig::Instrument* pInstrument = pFile->AddInstrument();
1105      pInstrument->pInfo->Name = "Unnamed Instrument";      pInstrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument"));
1106      // update GUI with that new gig::File      // update GUI with that new gig::File
1107      load_gig(pFile, 0 /*no file name yet*/);      load_gig(pFile, 0 /*no file name yet*/);
1108  }  }
# Line 476  bool MainWindow::close_confirmation_dial Line 1113  bool MainWindow::close_confirmation_dial
1113                                   Glib::filename_display_basename(filename).c_str());                                   Glib::filename_display_basename(filename).c_str());
1114      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
1115      g_free(msg);      g_free(msg);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1116      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."));
 #endif  
1117      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);      dialog.add_button(_("Close _Without Saving"), Gtk::RESPONSE_NO);
1118      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1119      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);
1120      dialog.set_default_response(Gtk::RESPONSE_YES);      dialog.set_default_response(Gtk::RESPONSE_YES);
1121      int response = dialog.run();      int response = dialog.run();
1122      dialog.hide();      dialog.hide();
1123      if (response == Gtk::RESPONSE_YES) return file_save();  
1124      return response != Gtk::RESPONSE_CANCEL;      // user decided to exit app without saving
1125        if (response == Gtk::RESPONSE_NO) return true;
1126    
1127        // user cancelled dialog, thus don't close app
1128        if (response == Gtk::RESPONSE_CANCEL) return false;
1129    
1130        // TODO: the following return valid is disabled and hard coded instead for
1131        // now, due to the fact that saving with progress bar is now implemented
1132        // asynchronously, as a result the app does not close automatically anymore
1133        // after saving the file has completed
1134        //
1135        //   if (response == Gtk::RESPONSE_YES) return file_save();
1136        //   return response != Gtk::RESPONSE_CANCEL;
1137        //
1138        if (response == Gtk::RESPONSE_YES) file_save();
1139        return false; // always prevent closing the app for now (see comment above)
1140  }  }
1141    
1142  bool MainWindow::leaving_shared_mode_dialog() {  bool MainWindow::leaving_shared_mode_dialog() {
1143      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");      Glib::ustring msg = _("Detach from sampler and proceed working stand-alone?");
1144      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);      Gtk::MessageDialog dialog(*this, msg, false, Gtk::MESSAGE_WARNING, Gtk::BUTTONS_NONE);
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 6) || GTKMM_MAJOR_VERSION > 2  
1145      dialog.set_secondary_text(      dialog.set_secondary_text(
1146          _("If you proceed to work on another instrument file, it won't be "          _("If you proceed to work on another instrument file, it won't be "
1147            "used by the sampler until you tell the sampler explicitly to "            "used by the sampler until you tell the sampler explicitly to "
1148            "load it.")            "load it."));
    );  
 #endif  
1149      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);      dialog.add_button(_("_Yes, Detach"), Gtk::RESPONSE_YES);
1150      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1151      dialog.set_default_response(Gtk::RESPONSE_CANCEL);      dialog.set_default_response(Gtk::RESPONSE_CANCEL);
1152      int response = dialog.run();      int response = dialog.run();
1153      dialog.hide();      dialog.hide();
# Line 514  void MainWindow::on_action_file_open() Line 1161  void MainWindow::on_action_file_open()
1161      if (file_is_shared && !leaving_shared_mode_dialog()) return;      if (file_is_shared && !leaving_shared_mode_dialog()) return;
1162    
1163      Gtk::FileChooserDialog dialog(*this, _("Open file"));      Gtk::FileChooserDialog dialog(*this, _("Open file"));
1164      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1165      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
1166      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
1167    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1168      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1169      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1170    #else
1171        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1172        filter->add_pattern("*.gig");
1173    #endif
1174      dialog.set_filter(filter);      dialog.set_filter(filter);
1175      if (current_dir != "") {      if (current_gig_dir != "") {
1176          dialog.set_current_folder(current_dir);          dialog.set_current_folder(current_gig_dir);
1177      }      }
1178      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1179          std::string filename = dialog.get_filename();          std::string filename = dialog.get_filename();
1180          printf("filename=%s\n", filename.c_str());          printf("filename=%s\n", filename.c_str());
1181          printf("on_action_file_open self=%x\n", Glib::Thread::self());          printf("on_action_file_open self=%p\n",
1182                   static_cast<void*>(Glib::Threads::Thread::self()));
1183          load_file(filename.c_str());          load_file(filename.c_str());
1184          current_dir = Glib::path_get_dirname(filename);          current_gig_dir = Glib::path_get_dirname(filename);
1185      }      }
1186  }  }
1187    
1188  void MainWindow::load_file(const char* name)  void MainWindow::load_file(const char* name)
1189  {  {
1190      __clear();      __clear();
1191      load_dialog = new LoadDialog("Loading...", *this);  
1192      load_dialog->show_all();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1193      loader = new Loader(strdup(name));          _("Loading") +  Glib::ustring(" '") +
1194            Glib::filename_display_basename(name) + "' ...",
1195            *this
1196        );
1197        progress_dialog->show_all();
1198        loader = new Loader(name); //FIXME: memory leak!
1199      loader->signal_progress().connect(      loader->signal_progress().connect(
1200          sigc::mem_fun(*this, &MainWindow::on_loader_progress));          sigc::mem_fun(*this, &MainWindow::on_loader_progress));
1201      loader->signal_finished().connect(      loader->signal_finished().connect(
1202          sigc::mem_fun(*this, &MainWindow::on_loader_finished));          sigc::mem_fun(*this, &MainWindow::on_loader_finished));
1203        loader->signal_error().connect(
1204            sigc::mem_fun(*this, &MainWindow::on_loader_error));
1205      loader->launch();      loader->launch();
1206  }  }
1207    
# Line 557  void MainWindow::load_instrument(gig::In Line 1217  void MainWindow::load_instrument(gig::In
1217      // load the instrument      // load the instrument
1218      gig::File* pFile = (gig::File*) instr->GetParent();      gig::File* pFile = (gig::File*) instr->GetParent();
1219      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);      load_gig(pFile, 0 /*file name*/, true /*shared instrument*/);
1220      //TODO: automatically select the given instrument      // automatically select the given instrument
1221        int i = 0;
1222        for (gig::Instrument* instrument = pFile->GetFirstInstrument(); instrument;
1223             instrument = pFile->GetNextInstrument(), ++i)
1224        {
1225            if (instrument == instr) {
1226                // select item in "instruments" tree view
1227                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(i)));
1228                // make sure the selected item in the "instruments" tree view is
1229                // visible (scroll to it)
1230                m_TreeView.scroll_to_row(Gtk::TreePath(ToString(i)));
1231                // select item in instrument menu
1232                {
1233                    const std::vector<Gtk::Widget*> children =
1234                        instrument_menu->get_children();
1235                    static_cast<Gtk::RadioMenuItem*>(children[i])->set_active();
1236                }
1237                // update region chooser and dimension region chooser
1238                m_RegionChooser.set_instrument(instr);
1239                break;
1240            }
1241        }
1242  }  }
1243    
1244  void MainWindow::on_loader_progress()  void MainWindow::on_loader_progress()
1245  {  {
1246      load_dialog->set_fraction(loader->get_progress());      progress_dialog->set_fraction(loader->get_progress());
1247  }  }
1248    
1249  void MainWindow::on_loader_finished()  void MainWindow::on_loader_finished()
1250  {  {
1251      printf("Loader finished!\n");      printf("Loader finished!\n");
1252      printf("on_loader_finished self=%x\n", Glib::Thread::self());      printf("on_loader_finished self=%p\n",
1253      load_gig(loader->gig, loader->filename);             static_cast<void*>(Glib::Threads::Thread::self()));
1254      load_dialog->hide();      load_gig(loader->gig, loader->filename.c_str());
1255        progress_dialog->hide();
1256    }
1257    
1258    void MainWindow::on_loader_error()
1259    {
1260        Glib::ustring txt = _("Could not load file: ") + loader->error_message;
1261        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1262        msg.run();
1263        progress_dialog->hide();
1264  }  }
1265    
1266  void MainWindow::on_action_file_save()  void MainWindow::on_action_file_save()
# Line 609  bool MainWindow::file_save() Line 1299  bool MainWindow::file_save()
1299    
1300      std::cout << "Saving file\n" << std::flush;      std::cout << "Saving file\n" << std::flush;
1301      file_structure_to_be_changed_signal.emit(this->file);      file_structure_to_be_changed_signal.emit(this->file);
1302      try {  
1303          file->Save();      progress_dialog = new ProgressDialog( //FIXME: memory leak!
1304          if (file_is_changed) {          _("Saving") +  Glib::ustring(" '") +
1305              set_title(get_title().substr(1));          Glib::filename_display_basename(this->filename) + "' ...",
1306              file_is_changed = false;          *this
1307          }      );
1308      } catch (RIFF::Exception e) {      progress_dialog->show_all();
1309          file_structure_changed_signal.emit(this->file);      saver = new Saver(this->file); //FIXME: memory leak!
1310          Glib::ustring txt = _("Could not save file: ") + e.Message;      saver->signal_progress().connect(
1311          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1312          msg.run();      saver->signal_finished().connect(
1313          return false;          sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1314      }      saver->signal_error().connect(
1315      std::cout << "Saving file done\n" << std::flush;          sigc::mem_fun(*this, &MainWindow::on_saver_error));
1316        saver->launch();
1317    
1318        return true;
1319    }
1320    
1321    void MainWindow::on_saver_progress()
1322    {
1323        progress_dialog->set_fraction(saver->get_progress());
1324    }
1325    
1326    void MainWindow::on_saver_error()
1327    {
1328        file_structure_changed_signal.emit(this->file);
1329        Glib::ustring txt = _("Could not save file: ") + saver->error_message;
1330        Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1331        msg.run();
1332    }
1333    
1334    void MainWindow::on_saver_finished()
1335    {
1336        this->file = saver->gig;
1337        this->filename = saver->filename;
1338        current_gig_dir = Glib::path_get_dirname(filename);
1339        set_title(Glib::filename_display_basename(filename));
1340        file_has_name = true;
1341        file_is_changed = false;
1342        std::cout << "Saving file done. Importing queued samples now ...\n" << std::flush;
1343      __import_queued_samples();      __import_queued_samples();
1344        std::cout << "Importing queued samples done.\n" << std::flush;
1345    
1346      file_structure_changed_signal.emit(this->file);      file_structure_changed_signal.emit(this->file);
1347      return true;  
1348        __refreshEntireGUI();
1349        progress_dialog->hide();
1350  }  }
1351    
1352  void MainWindow::on_action_file_save_as()  void MainWindow::on_action_file_save_as()
# Line 636  void MainWindow::on_action_file_save_as( Line 1357  void MainWindow::on_action_file_save_as(
1357    
1358  bool MainWindow::file_save_as()  bool MainWindow::file_save_as()
1359  {  {
1360      Gtk::FileChooserDialog dialog(*this, _("Save as"), Gtk::FILE_CHOOSER_ACTION_SAVE);      Gtk::FileChooserDialog dialog(*this, _("Save As"), Gtk::FILE_CHOOSER_ACTION_SAVE);
1361      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
1362      dialog.add_button(Gtk::Stock::SAVE, Gtk::RESPONSE_OK);      dialog.add_button(_("_Save"), Gtk::RESPONSE_OK);
1363      dialog.set_default_response(Gtk::RESPONSE_OK);      dialog.set_default_response(Gtk::RESPONSE_OK);
   
 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 8) || GTKMM_MAJOR_VERSION > 2  
1364      dialog.set_do_overwrite_confirmation();      dialog.set_do_overwrite_confirmation();
1365      // TODO: an overwrite dialog for gtkmm < 2.8  
1366  #endif  #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
1367      Gtk::FileFilter filter;      Gtk::FileFilter filter;
1368      filter.add_pattern("*.gig");      filter.add_pattern("*.gig");
1369    #else
1370        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
1371        filter->add_pattern("*.gig");
1372    #endif
1373      dialog.set_filter(filter);      dialog.set_filter(filter);
1374    
1375      if (Glib::path_is_absolute(filename)) {      // set initial dir and filename of the Save As dialog
1376          dialog.set_filename(filename);      // and prepare that initial filename as a copy of the gig
1377      } else if (current_dir != "") {      {
1378          dialog.set_current_folder(current_dir);          std::string basename = Glib::path_get_basename(filename);
1379            std::string dir = Glib::path_get_dirname(filename);
1380            basename = std::string(_("copy_of_")) + basename;
1381            Glib::ustring copyFileName = Glib::build_filename(dir, basename);
1382            if (Glib::path_is_absolute(filename)) {
1383                dialog.set_filename(copyFileName);
1384            } else {
1385                if (current_gig_dir != "") dialog.set_current_folder(current_gig_dir);
1386            }
1387            dialog.set_current_name(Glib::filename_display_basename(copyFileName));
1388      }      }
1389      dialog.set_current_name(Glib::filename_display_basename(filename));  
1390        // show warning in the dialog
1391        Gtk::HBox descriptionArea;
1392        descriptionArea.set_spacing(15);
1393        Gtk::Image warningIcon;
1394        warningIcon.set_from_icon_name("dialog-warning",
1395                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
1396        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
1397    #if GTKMM_MAJOR_VERSION < 3
1398        view::WrapLabel description;
1399    #else
1400        Gtk::Label description;
1401        description.set_line_wrap();
1402    #endif
1403        description.set_markup(
1404            _("\n<b>CAUTION:</b> You <b>MUST</b> use the "
1405              "<span style=\"italic\">\"Save\"</span> dialog instead of "
1406              "<span style=\"italic\">\"Save As...\"</span> if you want to save "
1407              "to the same .gig file. Using "
1408              "<span style=\"italic\">\"Save As...\"</span> for writing to the "
1409              "same .gig file will end up in corrupted sample wave data!\n")
1410        );
1411        descriptionArea.pack_start(description);
1412        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
1413        descriptionArea.show_all();
1414    
1415      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
1416          file_structure_to_be_changed_signal.emit(this->file);          std::string filename = dialog.get_filename();
1417          try {          if (!Glib::str_has_suffix(filename, ".gig")) {
1418              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_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;  
1419          }          }
1420          __import_queued_samples();          printf("filename=%s\n", filename.c_str());
1421          file_structure_changed_signal.emit(this->file);  
1422            progress_dialog = new ProgressDialog( //FIXME: memory leak!
1423                _("Saving") +  Glib::ustring(" '") +
1424                Glib::filename_display_basename(filename) + "' ...",
1425                *this
1426            );
1427            progress_dialog->show_all();
1428    
1429            saver = new Saver(file, filename); //FIXME: memory leak!
1430            saver->signal_progress().connect(
1431                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
1432            saver->signal_finished().connect(
1433                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
1434            saver->signal_error().connect(
1435                sigc::mem_fun(*this, &MainWindow::on_saver_error));
1436            saver->launch();
1437    
1438          return true;          return true;
1439      }      }
1440      return false;      return false;
# Line 688  bool MainWindow::file_save_as() Line 1444  bool MainWindow::file_save_as()
1444  void MainWindow::__import_queued_samples() {  void MainWindow::__import_queued_samples() {
1445      std::cout << "Starting sample import\n" << std::flush;      std::cout << "Starting sample import\n" << std::flush;
1446      Glib::ustring error_files;      Glib::ustring error_files;
1447      printf("Samples to import: %d\n", m_SampleImportQueue.size());      printf("Samples to import: %d\n", int(m_SampleImportQueue.size()));
1448      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();      for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
1449           iter != m_SampleImportQueue.end(); ) {           iter != m_SampleImportQueue.end(); ) {
1450          printf("Importing sample %s\n",(*iter).sample_path.c_str());          printf("Importing sample %s\n",(*iter).sample_path.c_str());
1451          SF_INFO info;          SF_INFO info;
1452          info.format = 0;          info.format = 0;
1453          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);          SNDFILE* hFile = sf_open((*iter).sample_path.c_str(), SFM_READ, &info);
1454            sf_command(hFile, SFC_SET_SCALE_FLOAT_INT_READ, 0, SF_TRUE);
1455          try {          try {
1456              if (!hFile) throw std::string("could not open file");              if (!hFile) throw std::string(_("could not open file"));
1457              // determine sample's bit depth              // determine sample's bit depth
1458              int bitdepth;              int bitdepth;
1459              switch (info.format & 0xff) {              switch (info.format & 0xff) {
# Line 713  void MainWindow::__import_queued_samples Line 1470  void MainWindow::__import_queued_samples
1470                      break;                      break;
1471                  default:                  default:
1472                      sf_close(hFile); // close sound file                      sf_close(hFile); // close sound file
1473                      throw std::string("format not supported"); // unsupported subformat (yet?)                      throw std::string(_("format not supported")); // unsupported subformat (yet?)
1474              }              }
1475    
1476              const int bufsize = 10000;              const int bufsize = 10000;
# Line 755  void MainWindow::__import_queued_samples Line 1512  void MainWindow::__import_queued_samples
1512              }              }
1513              // cleanup              // cleanup
1514              sf_close(hFile);              sf_close(hFile);
1515                // let the sampler re-cache the sample if needed
1516                sample_changed_signal.emit(iter->gig_sample);
1517              // on success we remove the sample from the import queue,              // on success we remove the sample from the import queue,
1518              // otherwise keep it, maybe it works the next time ?              // otherwise keep it, maybe it works the next time ?
1519              std::list<SampleImportItem>::iterator cur = iter;              std::list<SampleImportItem>::iterator cur = iter;
# Line 762  void MainWindow::__import_queued_samples Line 1521  void MainWindow::__import_queued_samples
1521              m_SampleImportQueue.erase(cur);              m_SampleImportQueue.erase(cur);
1522          } catch (std::string what) {          } catch (std::string what) {
1523              // remember the files that made trouble (and their cause)              // remember the files that made trouble (and their cause)
1524              if (error_files.size()) error_files += "\n";              if (!error_files.empty()) error_files += "\n";
1525              error_files += (*iter).sample_path += " (" + what + ")";              error_files += (*iter).sample_path += " (" + what + ")";
1526              ++iter;              ++iter;
1527          }          }
1528      }      }
1529      // show error message box when some sample(s) could not be imported      // show error message box when some sample(s) could not be imported
1530      if (error_files.size()) {      if (!error_files.empty()) {
1531          Glib::ustring txt = _("Could not import the following sample(s):\n") + error_files;          Glib::ustring txt = _("Could not import the following sample(s):\n") + error_files;
1532          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);          Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1533          msg.run();          msg.run();
# Line 781  void MainWindow::on_action_file_properti Line 1540  void MainWindow::on_action_file_properti
1540      propDialog.deiconify();      propDialog.deiconify();
1541  }  }
1542    
1543    void MainWindow::on_action_warn_user_on_extensions() {
1544        Settings::singleton()->warnUserOnExtensions =
1545            !Settings::singleton()->warnUserOnExtensions;
1546    }
1547    
1548    void MainWindow::on_action_sync_sampler_instrument_selection() {
1549        Settings::singleton()->syncSamplerInstrumentSelection =
1550            !Settings::singleton()->syncSamplerInstrumentSelection;
1551    }
1552    
1553    void MainWindow::on_action_move_root_note_with_region_moved() {
1554        Settings::singleton()->moveRootNoteWithRegionMoved =
1555            !Settings::singleton()->moveRootNoteWithRegionMoved;
1556    }
1557    
1558  void MainWindow::on_action_help_about()  void MainWindow::on_action_help_about()
1559  {  {
 #ifdef ABOUT_DIALOG  
1560      Gtk::AboutDialog dialog;      Gtk::AboutDialog dialog;
1561    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 12) || GTKMM_MAJOR_VERSION > 2
1562        dialog.set_program_name("Gigedit");
1563    #else
1564        dialog.set_name("Gigedit");
1565    #endif
1566      dialog.set_version(VERSION);      dialog.set_version(VERSION);
1567        dialog.set_copyright("Copyright (C) 2006-2017 Andreas Persson");
1568        const std::string sComment =
1569            _("Built " __DATE__ "\nUsing ") +
1570            ::gig::libraryName() + " " + ::gig::libraryVersion() + "\n\n" +
1571            _(
1572                "Gigedit is released under the GNU General Public License.\n"
1573                "\n"
1574                "This program is distributed WITHOUT ANY WARRANTY; So better "
1575                "backup your Gigasampler/GigaStudio files before editing them with "
1576                "this application.\n"
1577                "\n"
1578                "Please report bugs to: http://bugs.linuxsampler.org"
1579            );
1580        dialog.set_comments(sComment.c_str());
1581        dialog.set_website("http://www.linuxsampler.org");
1582        dialog.set_website_label("http://www.linuxsampler.org");
1583      dialog.run();      dialog.run();
 #endif  
1584  }  }
1585    
1586  PropDialog::PropDialog()  PropDialog::PropDialog()
1587      : table(2,1)      : eFileFormat(_("File Format")),
1588  {        eName(_("Name")),
1589          eCreationDate(_("Creation date")),
1590          eComments(_("Comments")),
1591          eProduct(_("Product")),
1592          eCopyright(_("Copyright")),
1593          eArtists(_("Artists")),
1594          eGenre(_("Genre")),
1595          eKeywords(_("Keywords")),
1596          eEngineer(_("Engineer")),
1597          eTechnician(_("Technician")),
1598          eSoftware(_("Software")),
1599          eMedium(_("Medium")),
1600          eSource(_("Source")),
1601          eSourceForm(_("Source form")),
1602          eCommissioned(_("Commissioned")),
1603          eSubject(_("Subject")),
1604          quitButton(_("_Close"), true),
1605          table(2, 1),
1606          m_file(NULL)
1607    {
1608        set_title(_("File Properties"));
1609        eName.set_width_chars(50);
1610    
1611        connect(eName, &DLS::Info::Name);
1612        connect(eCreationDate, &DLS::Info::CreationDate);
1613        connect(eComments, &DLS::Info::Comments);
1614        connect(eProduct, &DLS::Info::Product);
1615        connect(eCopyright, &DLS::Info::Copyright);
1616        connect(eArtists, &DLS::Info::Artists);
1617        connect(eGenre, &DLS::Info::Genre);
1618        connect(eKeywords, &DLS::Info::Keywords);
1619        connect(eEngineer, &DLS::Info::Engineer);
1620        connect(eTechnician, &DLS::Info::Technician);
1621        connect(eSoftware, &DLS::Info::Software);
1622        connect(eMedium, &DLS::Info::Medium);
1623        connect(eSource, &DLS::Info::Source);
1624        connect(eSourceForm, &DLS::Info::SourceForm);
1625        connect(eCommissioned, &DLS::Info::Commissioned);
1626        connect(eSubject, &DLS::Info::Subject);
1627    
1628        table.add(eFileFormat);
1629        table.add(eName);
1630        table.add(eCreationDate);
1631        table.add(eComments);
1632        table.add(eProduct);
1633        table.add(eCopyright);
1634        table.add(eArtists);
1635        table.add(eGenre);
1636        table.add(eKeywords);
1637        table.add(eEngineer);
1638        table.add(eTechnician);
1639        table.add(eSoftware);
1640        table.add(eMedium);
1641        table.add(eSource);
1642        table.add(eSourceForm);
1643        table.add(eCommissioned);
1644        table.add(eSubject);
1645    
1646      table.set_col_spacings(5);      table.set_col_spacings(5);
1647      const char* propLabels[] = {      add(vbox);
1648          "Name:",      table.set_border_width(5);
1649          "CreationDate:",      vbox.add(table);
1650          "Comments:", // TODO: multiline      vbox.pack_start(buttonBox, Gtk::PACK_SHRINK);
1651          "Product:",      buttonBox.set_layout(Gtk::BUTTONBOX_END);
1652          "Copyright:",      buttonBox.set_border_width(5);
1653          "Artists:",      buttonBox.show();
1654          "Genre:",      buttonBox.pack_start(quitButton);
1655          "Keywords:",      quitButton.set_can_default();
1656          "Engineer:",      quitButton.grab_focus();
1657          "Technician:",      quitButton.signal_clicked().connect(
1658          "Software:", // TODO: readonly          sigc::mem_fun(*this, &PropDialog::hide));
1659          "Medium:",      eFileFormat.signal_value_changed().connect(
1660          "Source:",          sigc::mem_fun(*this, &PropDialog::onFileFormatChanged));
         "SourceForm:",  
         "Commissioned:",  
         "Subject:"  
     };  
     for (int i = 0 ; i < sizeof(propLabels) / sizeof(char*) ; i++) {  
         label[i].set_text(propLabels[i]);  
         label[i].set_alignment(Gtk::ALIGN_LEFT);  
         table.attach(label[i], 0, 1, i, i + 1, Gtk::FILL, Gtk::SHRINK);  
         table.attach(entry[i], 1, 2, i, i + 1, Gtk::FILL | Gtk::EXPAND,  
                      Gtk::SHRINK);  
     }  
1661    
1662      add(table);      quitButton.show();
1663      // add_button(Gtk::Stock::CANCEL, 0);      vbox.show();
     // add_button(Gtk::Stock::OK, 1);  
1664      show_all_children();      show_all_children();
1665  }  }
1666    
1667    void PropDialog::set_file(gig::File* file)
1668    {
1669        m_file = file;
1670    
1671        // update file format version combo box
1672        const std::string sGiga = "Gigasampler/GigaStudio v";
1673        const int major = file->pVersion->major;
1674        std::vector<std::string> txts;
1675        std::vector<int> values;
1676        txts.push_back(sGiga + "2"); values.push_back(2);
1677        txts.push_back(sGiga + "3/v4"); values.push_back(3);
1678        if (major != 2 && major != 3) {
1679            txts.push_back(sGiga + ToString(major)); values.push_back(major);
1680        }
1681        std::vector<const char*> texts;
1682        for (int i = 0; i < txts.size(); ++i) texts.push_back(txts[i].c_str());
1683        texts.push_back(NULL); values.push_back(0);
1684        eFileFormat.set_choices(&texts[0], &values[0]);
1685        eFileFormat.set_value(major);
1686    }
1687    
1688    void PropDialog::onFileFormatChanged() {
1689        const int major = eFileFormat.get_value();
1690        if (m_file) m_file->pVersion->major = major;
1691    }
1692    
1693  void PropDialog::set_info(DLS::Info* info)  void PropDialog::set_info(DLS::Info* info)
1694  {  {
1695      entry[0].set_text(info->Name);      update(info);
1696      entry[1].set_text(info->CreationDate);  }
1697      entry[2].set_text(Glib::convert(info->Comments, "UTF-8", "ISO-8859-1"));  
1698      entry[3].set_text(info->Product);  
1699      entry[4].set_text(info->Copyright);  void InstrumentProps::set_Name(const gig::String& name)
1700      entry[5].set_text(info->Artists);  {
1701      entry[6].set_text(info->Genre);      m->pInfo->Name = name;
1702      entry[7].set_text(info->Keywords);  }
1703      entry[8].set_text(info->Engineer);  
1704      entry[9].set_text(info->Technician);  void InstrumentProps::update_name()
1705      entry[10].set_text(info->Software);  {
1706      entry[11].set_text(info->Medium);      update_model++;
1707      entry[12].set_text(info->Source);      eName.set_value(m->pInfo->Name);
1708      entry[13].set_text(info->SourceForm);      update_model--;
1709      entry[14].set_text(info->Commissioned);  }
1710      entry[15].set_text(info->Subject);  
1711  }  void InstrumentProps::set_IsDrum(bool value)
1712    {
1713  void InstrumentProps::add_prop(BoolEntry& boolentry)      m->IsDrum = value;
1714  {  }
1715      table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
1716                   Gtk::FILL, Gtk::SHRINK);  void InstrumentProps::set_MIDIBank(uint16_t value)
1717      rowno++;  {
1718      boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());      m->MIDIBank = value;
1719  }  }
1720    
1721  void InstrumentProps::add_prop(BoolEntryPlus6& boolentry)  void InstrumentProps::set_MIDIProgram(uint32_t value)
 {  
     table.attach(boolentry.widget, 0, 2, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     rowno++;  
     boolentry.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 void InstrumentProps::add_prop(LabelWidget& prop)  
 {  
     table.attach(prop.label, 0, 1, rowno, rowno + 1,  
                  Gtk::FILL, Gtk::SHRINK);  
     table.attach(prop.widget, 1, 2, rowno, rowno + 1,  
                  Gtk::FILL | Gtk::EXPAND, Gtk::SHRINK);  
     rowno++;  
     prop.signal_changed_by_user().connect(instrument_changed.make_slot());  
 }  
   
 InstrumentProps::InstrumentProps()  
     : table(2,1),  
       quitButton(Gtk::Stock::CLOSE),  
       eName("Name"),  
       eIsDrum("Is drum"),  
       eMIDIBank("MIDI bank", 0, 16383),  
       eMIDIProgram("MIDI program"),  
       eAttenuation("Attenuation", 0, 96, 0, 1),  
       eGainPlus6("Gain +6dB", eAttenuation, -6),  
       eEffectSend("Effect send", 0, 65535),  
       eFineTune("Fine tune", -8400, 8400),  
       ePitchbendRange("Pitchbend range", 0, 12),  
       ePianoReleaseMode("Piano release mode"),  
       eDimensionKeyRangeLow("Dimension key range low"),  
       eDimensionKeyRangeHigh("Dimension key range high")  
1722  {  {
1723      set_title("Instrument properties");      m->MIDIProgram = value;
1724    }
1725    
1726    InstrumentProps::InstrumentProps() :
1727        quitButton(_("_Close"), true),
1728        table(2,1),
1729        eName(_("Name")),
1730        eIsDrum(_("Is drum")),
1731        eMIDIBank(_("MIDI bank"), 0, 16383),
1732        eMIDIProgram(_("MIDI program")),
1733        eAttenuation(_("Attenuation"), 0, 96, 0, 1),
1734        eGainPlus6(_("Gain +6dB"), eAttenuation, -6),
1735        eEffectSend(_("Effect send"), 0, 65535),
1736        eFineTune(_("Fine tune"), -8400, 8400),
1737        ePitchbendRange(_("Pitchbend range"), 0, 12),
1738        ePianoReleaseMode(_("Piano release mode")),
1739        eDimensionKeyRangeLow(_("Keyswitching range low")),
1740        eDimensionKeyRangeHigh(_("Keyswitching range high"))
1741    {
1742        set_title(_("Instrument Properties"));
1743    
1744        eDimensionKeyRangeLow.set_tip(
1745            _("start of the keyboard area which should switch the "
1746              "\"keyswitching\" dimension")
1747        );
1748        eDimensionKeyRangeHigh.set_tip(
1749            _("end of the keyboard area which should switch the "
1750              "\"keyswitching\" dimension")
1751        );
1752    
1753        connect(eName, &InstrumentProps::set_Name);
1754        connect(eIsDrum, &InstrumentProps::set_IsDrum);
1755        connect(eMIDIBank, &InstrumentProps::set_MIDIBank);
1756        connect(eMIDIProgram, &InstrumentProps::set_MIDIProgram);
1757        connect(eAttenuation, &gig::Instrument::Attenuation);
1758        connect(eGainPlus6, &gig::Instrument::Attenuation);
1759        connect(eEffectSend, &gig::Instrument::EffectSend);
1760        connect(eFineTune, &gig::Instrument::FineTune);
1761        connect(ePitchbendRange, &gig::Instrument::PitchbendRange);
1762        connect(ePianoReleaseMode, &gig::Instrument::PianoReleaseMode);
1763        connect(eDimensionKeyRangeLow, eDimensionKeyRangeHigh,
1764                &gig::Instrument::DimensionKeyRange);
1765    
1766        eName.signal_value_changed().connect(sig_name_changed.make_slot());
1767    
     rowno = 0;  
1768      table.set_col_spacings(5);      table.set_col_spacings(5);
1769    
1770      add_prop(eName);      table.add(eName);
1771      add_prop(eIsDrum);      table.add(eIsDrum);
1772      add_prop(eMIDIBank);      table.add(eMIDIBank);
1773      add_prop(eMIDIProgram);      table.add(eMIDIProgram);
1774      add_prop(eAttenuation);      table.add(eAttenuation);
1775      add_prop(eGainPlus6);      table.add(eGainPlus6);
1776      add_prop(eEffectSend);      table.add(eEffectSend);
1777      add_prop(eFineTune);      table.add(eFineTune);
1778      add_prop(ePitchbendRange);      table.add(ePitchbendRange);
1779      add_prop(ePianoReleaseMode);      table.add(ePianoReleaseMode);
1780      add_prop(eDimensionKeyRangeLow);      table.add(eDimensionKeyRangeLow);
1781      add_prop(eDimensionKeyRangeHigh);      table.add(eDimensionKeyRangeHigh);
   
     eDimensionKeyRangeLow.signal_changed_by_user().connect(  
         sigc::mem_fun(*this, &InstrumentProps::key_range_low_changed));  
     eDimensionKeyRangeHigh.signal_changed_by_user().connect(  
         sigc::mem_fun(*this, &InstrumentProps::key_range_high_changed));  
1782    
1783      add(vbox);      add(vbox);
1784      table.set_border_width(5);      table.set_border_width(5);
# Line 920  InstrumentProps::InstrumentProps() Line 1789  InstrumentProps::InstrumentProps()
1789      buttonBox.set_border_width(5);      buttonBox.set_border_width(5);
1790      buttonBox.show();      buttonBox.show();
1791      buttonBox.pack_start(quitButton);      buttonBox.pack_start(quitButton);
1792      quitButton.set_flags(Gtk::CAN_DEFAULT);      quitButton.set_can_default();
1793      quitButton.grab_focus();      quitButton.grab_focus();
1794    
1795      quitButton.signal_clicked().connect(      quitButton.signal_clicked().connect(
# Line 933  InstrumentProps::InstrumentProps() Line 1802  InstrumentProps::InstrumentProps()
1802    
1803  void InstrumentProps::set_instrument(gig::Instrument* instrument)  void InstrumentProps::set_instrument(gig::Instrument* instrument)
1804  {  {
1805      eName.set_ptr(&instrument->pInfo->Name);      update(instrument);
     eIsDrum.set_ptr(&instrument->IsDrum);  
     eMIDIBank.set_ptr(&instrument->MIDIBank);  
     eMIDIProgram.set_ptr(&instrument->MIDIProgram);  
     eAttenuation.set_ptr(&instrument->Attenuation);  
     eGainPlus6.set_ptr(&instrument->Attenuation);  
     eEffectSend.set_ptr(&instrument->EffectSend);  
     eFineTune.set_ptr(&instrument->FineTune);  
     ePitchbendRange.set_ptr(&instrument->PitchbendRange);  
     ePianoReleaseMode.set_ptr(&instrument->PianoReleaseMode);  
     eDimensionKeyRangeLow.set_ptr(0);  
     eDimensionKeyRangeHigh.set_ptr(0);  
     eDimensionKeyRangeLow.set_ptr(&instrument->DimensionKeyRange.low);  
     eDimensionKeyRangeHigh.set_ptr(&instrument->DimensionKeyRange.high);  
 }  
1806    
1807  void InstrumentProps::key_range_low_changed()      update_model++;
1808  {      eName.set_value(instrument->pInfo->Name);
1809      double l = eDimensionKeyRangeLow.get_value();      eIsDrum.set_value(instrument->IsDrum);
1810      double h = eDimensionKeyRangeHigh.get_value();      eMIDIBank.set_value(instrument->MIDIBank);
1811      if (h < l) eDimensionKeyRangeHigh.set_value(l);      eMIDIProgram.set_value(instrument->MIDIProgram);
1812        update_model--;
1813  }  }
1814    
 void InstrumentProps::key_range_high_changed()  
 {  
     double l = eDimensionKeyRangeLow.get_value();  
     double h = eDimensionKeyRangeHigh.get_value();  
     if (h < l) eDimensionKeyRangeLow.set_value(h);  
 }  
   
 sigc::signal<void>& InstrumentProps::signal_instrument_changed()  
 {  
     return instrument_changed;  
 }  
1815    
1816  void MainWindow::file_changed()  void MainWindow::file_changed()
1817  {  {
# Line 976  void MainWindow::file_changed() Line 1821  void MainWindow::file_changed()
1821      }      }
1822  }  }
1823    
1824    void MainWindow::updateSampleRefCountMap(gig::File* gig) {
1825        sample_ref_count.clear();
1826        
1827        if (!gig) return;
1828    
1829        for (gig::Instrument* instrument = gig->GetFirstInstrument(); instrument;
1830             instrument = gig->GetNextInstrument())
1831        {
1832            for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
1833                 rgn = instrument->GetNextRegion())
1834            {
1835                for (int i = 0; i < 256; ++i) {
1836                    if (!rgn->pDimensionRegions[i]) continue;
1837                    if (rgn->pDimensionRegions[i]->pSample) {
1838                        sample_ref_count[rgn->pDimensionRegions[i]->pSample]++;
1839                    }
1840                }
1841            }
1842        }
1843    }
1844    
1845  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)  void MainWindow::load_gig(gig::File* gig, const char* filename, bool isSharedInstrument)
1846  {  {
1847      file = 0;      file = 0;
1848      set_file_is_shared(isSharedInstrument);      set_file_is_shared(isSharedInstrument);
1849    
1850      this->filename = filename ? filename : _("Unsaved Gig File");      this->filename =
1851            (filename && strlen(filename) > 0) ?
1852                filename : (!gig->GetFileName().empty()) ?
1853                    gig->GetFileName() : _("Unsaved Gig File");
1854      set_title(Glib::filename_display_basename(this->filename));      set_title(Glib::filename_display_basename(this->filename));
1855      file_has_name = filename;      file_has_name = filename;
1856      file_is_changed = false;      file_is_changed = false;
1857    
1858        propDialog.set_file(gig);
1859      propDialog.set_info(gig->pInfo);      propDialog.set_info(gig->pInfo);
1860    
1861      Gtk::MenuItem* instrument_menu =      instrument_name_connection.block();
1862          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuInstrument"));      int index = 0;
   
     int instrument_index = 0;  
     Gtk::RadioMenuItem::Group instrument_group;  
1863      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;      for (gig::Instrument* instrument = gig->GetFirstInstrument() ; instrument ;
1864           instrument = gig->GetNextInstrument()) {           instrument = gig->GetNextInstrument(), ++index) {
1865            Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
1866    
1867          Gtk::TreeModel::iterator iter = m_refTreeModel->append();          Gtk::TreeModel::iterator iter = m_refTreeModel->append();
1868          Gtk::TreeModel::Row row = *iter;          Gtk::TreeModel::Row row = *iter;
1869          row[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();          row[m_Columns.m_col_nr] = index;
1870            row[m_Columns.m_col_name] = name;
1871          row[m_Columns.m_col_instr] = instrument;          row[m_Columns.m_col_instr] = instrument;
1872          // create a menu item for this instrument  
1873          Gtk::RadioMenuItem* item =          add_instrument_to_menu(name);
             new Gtk::RadioMenuItem(instrument_group, instrument->pInfo->Name.c_str());  
         instrument_menu->get_submenu()->append(*item);  
         item->signal_activate().connect(  
             sigc::bind(  
                 sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),  
                 instrument_index  
             )  
         );  
         instrument_index++;  
1874      }      }
1875      instrument_menu->show();      instrument_name_connection.unblock();
1876      instrument_menu->get_submenu()->show_all_children();      uiManager->get_widget("/MenuBar/MenuInstrument/AllInstruments")->show();
1877    
1878        updateSampleRefCountMap(gig);
1879    
1880      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {      for (gig::Group* group = gig->GetFirstGroup(); group; group = gig->GetNextGroup()) {
1881          if (group->Name != "") {          if (group->Name != "") {
1882              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();              Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
1883              Gtk::TreeModel::Row rowGroup = *iterGroup;              Gtk::TreeModel::Row rowGroup = *iterGroup;
1884              rowGroup[m_SamplesModel.m_col_name]   = group->Name.c_str();              rowGroup[m_SamplesModel.m_col_name]   = gig_to_utf8(group->Name);
1885              rowGroup[m_SamplesModel.m_col_group]  = group;              rowGroup[m_SamplesModel.m_col_group]  = group;
1886              rowGroup[m_SamplesModel.m_col_sample] = NULL;              rowGroup[m_SamplesModel.m_col_sample] = NULL;
1887              for (gig::Sample* sample = group->GetFirstSample();              for (gig::Sample* sample = group->GetFirstSample();
# Line 1026  void MainWindow::load_gig(gig::File* gig Line 1889  void MainWindow::load_gig(gig::File* gig
1889                  Gtk::TreeModel::iterator iterSample =                  Gtk::TreeModel::iterator iterSample =
1890                      m_refSamplesTreeModel->append(rowGroup.children());                      m_refSamplesTreeModel->append(rowGroup.children());
1891                  Gtk::TreeModel::Row rowSample = *iterSample;                  Gtk::TreeModel::Row rowSample = *iterSample;
1892                  rowSample[m_SamplesModel.m_col_name]   = sample->pInfo->Name.c_str();                  rowSample[m_SamplesModel.m_col_name] =
1893                        gig_to_utf8(sample->pInfo->Name);
1894                  rowSample[m_SamplesModel.m_col_sample] = sample;                  rowSample[m_SamplesModel.m_col_sample] = sample;
1895                  rowSample[m_SamplesModel.m_col_group]  = NULL;                  rowSample[m_SamplesModel.m_col_group]  = NULL;
1896                    int refcount = sample_ref_count.count(sample) ? sample_ref_count[sample] : 0;
1897                    rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
1898                    rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
1899              }              }
1900          }          }
1901      }      }
1902        
1903        for (int i = 0; gig->GetScriptGroup(i); ++i) {
1904            gig::ScriptGroup* group = gig->GetScriptGroup(i);
1905    
1906            Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
1907            Gtk::TreeModel::Row rowGroup = *iterGroup;
1908            rowGroup[m_ScriptsModel.m_col_name]   = gig_to_utf8(group->Name);
1909            rowGroup[m_ScriptsModel.m_col_group]  = group;
1910            rowGroup[m_ScriptsModel.m_col_script] = NULL;
1911            for (int s = 0; group->GetScript(s); ++s) {
1912                gig::Script* script = group->GetScript(s);
1913    
1914                Gtk::TreeModel::iterator iterScript =
1915                    m_refScriptsTreeModel->append(rowGroup.children());
1916                Gtk::TreeModel::Row rowScript = *iterScript;
1917                rowScript[m_ScriptsModel.m_col_name] = gig_to_utf8(script->Name);
1918                rowScript[m_ScriptsModel.m_col_script] = script;
1919                rowScript[m_ScriptsModel.m_col_group]  = NULL;
1920            }
1921        }
1922        // unfold all sample groups & script groups by default
1923        m_TreeViewSamples.expand_all();
1924        m_TreeViewScripts.expand_all();
1925    
1926      file = gig;      file = gig;
1927    
1928      // select the first instrument      // select the first instrument
1929      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      m_TreeView.get_selection()->select(Gtk::TreePath("0"));
1930      tree_sel_ref->select(Gtk::TreePath("0"));  
1931        instr_props_set_instrument();
1932        gig::Instrument* instrument = get_instrument();
1933        if (instrument) {
1934            midiRules.set_instrument(instrument);
1935        }
1936    }
1937    
1938    bool MainWindow::instr_props_set_instrument()
1939    {
1940        instrumentProps.signal_name_changed().clear();
1941    
1942        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
1943        if (rows.empty()) {
1944            instrumentProps.hide();
1945            return false;
1946        }
1947        Gtk::TreeModel::const_iterator it = m_refTreeModel->get_iter(rows[0]);
1948        if (it) {
1949            Gtk::TreeModel::Row row = *it;
1950            gig::Instrument* instrument = row[m_Columns.m_col_instr];
1951    
1952            instrumentProps.set_instrument(instrument);
1953    
1954            // make sure instrument tree is updated when user changes the
1955            // instrument name in instrument properties window
1956            instrumentProps.signal_name_changed().connect(
1957                sigc::bind(
1958                    sigc::mem_fun(*this,
1959                                  &MainWindow::instr_name_changed_by_instr_props),
1960                    it));
1961        } else {
1962            instrumentProps.hide();
1963        }
1964        return it;
1965  }  }
1966    
1967  void MainWindow::show_instr_props()  void MainWindow::show_instr_props()
1968  {  {
1969      Glib::RefPtr<Gtk::TreeSelection> tree_sel_ref = m_TreeView.get_selection();      if (instr_props_set_instrument()) {
1970      Gtk::TreeModel::iterator it = tree_sel_ref->get_selected();          instrumentProps.show();
1971      if (it)          instrumentProps.deiconify();
1972        }
1973    }
1974    
1975    void MainWindow::instr_name_changed_by_instr_props(Gtk::TreeModel::iterator& it)
1976    {
1977        Gtk::TreeModel::Row row = *it;
1978        Glib::ustring name = row[m_Columns.m_col_name];
1979    
1980        gig::Instrument* instrument = row[m_Columns.m_col_instr];
1981        Glib::ustring gigname(gig_to_utf8(instrument->pInfo->Name));
1982        if (gigname != name) {
1983            row[m_Columns.m_col_name] = gigname;
1984        }
1985    }
1986    
1987    void MainWindow::show_midi_rules()
1988    {
1989        if (gig::Instrument* instrument = get_instrument())
1990      {      {
1991          Gtk::TreeModel::Row row = *it;          midiRules.set_instrument(instrument);
1992          if (row[m_Columns.m_col_instr])          midiRules.show();
1993          {          midiRules.deiconify();
             instrumentProps.set_instrument(row[m_Columns.m_col_instr]);  
             instrumentProps.show();  
             instrumentProps.deiconify();  
         }  
1994      }      }
1995  }  }
1996    
1997    void MainWindow::show_script_slots() {
1998        if (!file) return;
1999        // get selected instrument
2000        std::vector<Gtk::TreeModel::Path> rows = m_TreeView.get_selection()->get_selected_rows();
2001        if (rows.empty()) return;
2002        Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
2003        if (!it) return;
2004        Gtk::TreeModel::Row row = *it;
2005        gig::Instrument* instrument = row[m_Columns.m_col_instr];
2006        if (!instrument) return;
2007    
2008        ScriptSlots* window = new ScriptSlots;
2009        window->setInstrument(instrument);
2010        //window->reparent(*this);
2011        window->show();
2012    }
2013    
2014    void MainWindow::on_action_refresh_all() {
2015        __refreshEntireGUI();
2016    }
2017    
2018  void MainWindow::on_action_view_status_bar() {  void MainWindow::on_action_view_status_bar() {
2019      Gtk::CheckMenuItem* item =      Gtk::CheckMenuItem* item =
2020          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));          dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/Statusbar"));
# Line 1067  void MainWindow::on_action_view_status_b Line 2026  void MainWindow::on_action_view_status_b
2026      else                    m_StatusBar.hide();      else                    m_StatusBar.hide();
2027  }  }
2028    
2029    void MainWindow::on_auto_restore_win_dim() {
2030        Gtk::CheckMenuItem* item =
2031            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuView/AutoRestoreWinDim"));
2032        if (!item) {
2033            std::cerr << "/MenuBar/MenuView/AutoRestoreWinDim == NULL\n";
2034            return;
2035        }
2036        Settings::singleton()->autoRestoreWindowDimension = item->get_active();
2037    }
2038    
2039    void MainWindow::on_save_with_temporary_file() {
2040        Gtk::CheckMenuItem* item =
2041            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuSettings/SaveWithTemporaryFile"));
2042        if (!item) {
2043            std::cerr << "/MenuBar/MenuSettings/SaveWithTemporaryFile == NULL\n";
2044            return;
2045        }
2046        Settings::singleton()->saveWithTemporaryFile = item->get_active();
2047    }
2048    
2049    bool MainWindow::is_copy_samples_unity_note_enabled() const {
2050        Gtk::CheckMenuItem* item =
2051            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleUnity"));
2052        if (!item) {
2053            std::cerr << "/MenuBar/MenuEdit/CopySampleUnity == NULL\n";
2054            return true;
2055        }
2056        return item->get_active();
2057    }
2058    
2059    bool MainWindow::is_copy_samples_fine_tune_enabled() const {
2060        Gtk::CheckMenuItem* item =
2061            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleTune"));
2062        if (!item) {
2063            std::cerr << "/MenuBar/MenuEdit/CopySampleTune == NULL\n";
2064            return true;
2065        }
2066        return item->get_active();
2067    }
2068    
2069    bool MainWindow::is_copy_samples_loop_enabled() const {
2070        Gtk::CheckMenuItem* item =
2071            dynamic_cast<Gtk::CheckMenuItem*>(uiManager->get_widget("/MenuBar/MenuEdit/CopySampleLoop"));
2072        if (!item) {
2073            std::cerr << "/MenuBar/MenuEdit/CopySampleLoop == NULL\n";
2074            return true;
2075        }
2076        return item->get_active();
2077    }
2078    
2079  void MainWindow::on_button_release(GdkEventButton* button)  void MainWindow::on_button_release(GdkEventButton* button)
2080  {  {
2081      if (button->type == GDK_2BUTTON_PRESS) {      if (button->type == GDK_2BUTTON_PRESS) {
2082          show_instr_props();          show_instr_props();
2083      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      } else if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2084            // gig v2 files have no midi rules
2085            const bool bEnabled = !(file->pVersion && file->pVersion->major == 2);
2086            static_cast<Gtk::MenuItem*>(
2087                uiManager->get_widget("/MenuBar/MenuInstrument/MidiRules"))->set_sensitive(
2088                    bEnabled
2089                );
2090            static_cast<Gtk::MenuItem*>(
2091                uiManager->get_widget("/PopupMenu/MidiRules"))->set_sensitive(
2092                    bEnabled
2093                );
2094          popup_menu->popup(button->button, button->time);          popup_menu->popup(button->button, button->time);
2095      }      }
2096  }  }
2097    
2098  void MainWindow::on_instrument_selection_change(int index) {  void MainWindow::on_instrument_selection_change(Gtk::RadioMenuItem* item) {
2099      m_RegionChooser.set_instrument(file->GetInstrument(index));      if (item->get_active()) {
2100            const std::vector<Gtk::Widget*> children =
2101                instrument_menu->get_children();
2102            std::vector<Gtk::Widget*>::const_iterator it =
2103                find(children.begin(), children.end(), item);
2104            if (it != children.end()) {
2105                int index = it - children.begin();
2106                m_TreeView.get_selection()->select(Gtk::TreePath(ToString(index)));
2107    
2108                m_RegionChooser.set_instrument(file->GetInstrument(index));
2109            }
2110        }
2111    }
2112    
2113    void MainWindow::select_instrument(gig::Instrument* instrument) {
2114        if (!instrument) return;
2115    
2116        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2117        for (int i = 0; i < model->children().size(); ++i) {
2118            Gtk::TreeModel::Row row = model->children()[i];
2119            if (row[m_Columns.m_col_instr] == instrument) {
2120                // select and show the respective instrument in the list view
2121                show_intruments_tab();
2122                m_TreeView.get_selection()->unselect_all();
2123                m_TreeView.get_selection()->select(model->children()[i]);
2124                std::vector<Gtk::TreeModel::Path> rows =
2125                    m_TreeView.get_selection()->get_selected_rows();
2126                if (!rows.empty())
2127                    m_TreeView.scroll_to_row(rows[0]);
2128                on_sel_change(); // the regular instrument selection change callback
2129            }
2130        }
2131    }
2132    
2133    /// Returns true if requested dimension region was successfully selected and scrolled to in the list view, false on error.
2134    bool MainWindow::select_dimension_region(gig::DimensionRegion* dimRgn) {
2135        gig::Region* pRegion = (gig::Region*) dimRgn->GetParent();
2136        gig::Instrument* pInstrument = (gig::Instrument*) pRegion->GetParent();
2137    
2138        Glib::RefPtr<Gtk::TreeModel> model = m_TreeView.get_model();
2139        for (int i = 0; i < model->children().size(); ++i) {
2140            Gtk::TreeModel::Row row = model->children()[i];
2141            if (row[m_Columns.m_col_instr] == pInstrument) {
2142                // select and show the respective instrument in the list view
2143                show_intruments_tab();
2144                m_TreeView.get_selection()->unselect_all();
2145                m_TreeView.get_selection()->select(model->children()[i]);
2146                std::vector<Gtk::TreeModel::Path> rows =
2147                    m_TreeView.get_selection()->get_selected_rows();
2148                if (!rows.empty())
2149                    m_TreeView.scroll_to_row(rows[0]);
2150                on_sel_change(); // the regular instrument selection change callback
2151    
2152                // select respective region in the region selector
2153                m_RegionChooser.set_region(pRegion);
2154    
2155                // select and show the respective dimension region in the editor
2156                //update_dimregs();
2157                if (!m_DimRegionChooser.select_dimregion(dimRgn)) return false;
2158                //dimreg_edit.set_dim_region(dimRgn);
2159    
2160                return true;
2161            }
2162        }
2163    
2164        return false;
2165    }
2166    
2167    void MainWindow::select_sample(gig::Sample* sample) {
2168        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
2169        for (int g = 0; g < model->children().size(); ++g) {
2170            Gtk::TreeModel::Row rowGroup = model->children()[g];
2171            for (int s = 0; s < rowGroup.children().size(); ++s) {
2172                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
2173                if (rowSample[m_SamplesModel.m_col_sample] == sample) {
2174                    show_samples_tab();
2175                    m_TreeViewSamples.get_selection()->unselect_all();
2176                    m_TreeViewSamples.get_selection()->select(rowGroup.children()[s]);
2177                    std::vector<Gtk::TreeModel::Path> rows =
2178                        m_TreeViewSamples.get_selection()->get_selected_rows();
2179                    if (rows.empty()) return;
2180                    m_TreeViewSamples.scroll_to_row(rows[0]);
2181                    return;
2182                }
2183            }
2184        }
2185  }  }
2186    
2187  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {  void MainWindow::on_sample_treeview_button_release(GdkEventButton* button) {
2188      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2189            // by default if Ctrl keys is pressed down, then a mouse right-click
2190            // does not select the respective row, so we must assure this
2191            // programmatically ...
2192            /*{
2193                Gtk::TreeModel::Path path;
2194                Gtk::TreeViewColumn* pColumn = NULL;
2195                int cellX, cellY;
2196                bool bSuccess = m_TreeViewSamples.get_path_at_pos(
2197                    (int)button->x, (int)button->y,
2198                    path, pColumn, cellX, cellY
2199                );
2200                if (bSuccess) {
2201                    if (m_TreeViewSamples.get_selection()->count_selected_rows() <= 0) {
2202                        printf("not selected !!!\n");
2203                        m_TreeViewSamples.get_selection()->select(path);
2204                    }
2205                }
2206            }*/
2207    
2208          Gtk::Menu* sample_popup =          Gtk::Menu* sample_popup =
2209              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/SamplePopupMenu"));
2210          // update enabled/disabled state of sample popup items          // update enabled/disabled state of sample popup items
2211          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2212          Gtk::TreeModel::iterator it = sel->get_selected();          std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2213          bool group_selected  = false;          const int n = rows.size();
2214          bool sample_selected = false;          int nGroups  = 0;
2215          if (it) {          int nSamples = 0;
2216            for (int r = 0; r < n; ++r) {
2217                Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2218                if (!it) continue;
2219              Gtk::TreeModel::Row row = *it;              Gtk::TreeModel::Row row = *it;
2220              group_selected  = row[m_SamplesModel.m_col_group];              if (row[m_SamplesModel.m_col_group]) nGroups++;
2221              sample_selected = row[m_SamplesModel.m_col_sample];              if (row[m_SamplesModel.m_col_sample]) nSamples++;
2222          }          }
2223    
2224          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/SampleProperties"))->
2225              set_sensitive(group_selected || sample_selected);              set_sensitive(n == 1);
2226          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddSample"))->
2227              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2228          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/AddGroup"))->
2229              set_sensitive(file);              set_sensitive(file);
2230            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/ShowSampleRefs"))->
2231                set_sensitive(nSamples == 1);
2232          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->          dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/SamplePopupMenu/RemoveSample"))->
2233              set_sensitive(group_selected || sample_selected);              set_sensitive(n);
2234          // show sample popup          // show sample popup
2235          sample_popup->popup(button->button, button->time);          sample_popup->popup(button->button, button->time);
2236    
2237            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/SampleProperties"))->
2238                set_sensitive(n == 1);
2239            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddSample"))->
2240                set_sensitive(n);
2241            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/AddGroup"))->
2242                set_sensitive(file);
2243            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/ShowSampleRefs"))->
2244                set_sensitive(nSamples == 1);
2245            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuSample/RemoveSample"))->
2246                set_sensitive(n);
2247      }      }
2248  }  }
2249    
2250  void MainWindow::on_action_add_instrument() {  void MainWindow::on_script_treeview_button_release(GdkEventButton* button) {
2251      static int __instrument_indexer = 0;      if (button->type == GDK_BUTTON_PRESS && button->button == 3) {
2252      if (!file) return;          Gtk::Menu* script_popup =
2253      gig::Instrument* instrument = file->AddInstrument();              dynamic_cast<Gtk::Menu*>(uiManager->get_widget("/ScriptPopupMenu"));
2254      __instrument_indexer++;          // update enabled/disabled state of sample popup items
2255      instrument->pInfo->Name =          Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2256          "Unnamed Instrument " + ToString(__instrument_indexer);          Gtk::TreeModel::iterator it = sel->get_selected();
2257            bool group_selected  = false;
2258            bool script_selected = false;
2259            if (it) {
2260                Gtk::TreeModel::Row row = *it;
2261                group_selected  = row[m_ScriptsModel.m_col_group];
2262                script_selected = row[m_ScriptsModel.m_col_script];
2263            }
2264            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScript"))->
2265                set_sensitive(group_selected || script_selected);
2266            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/AddScriptGroup"))->
2267                set_sensitive(file);
2268            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/EditScript"))->
2269                set_sensitive(script_selected);    
2270            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/ScriptPopupMenu/RemoveScript"))->
2271                set_sensitive(group_selected || script_selected);
2272            // show sample popup
2273            script_popup->popup(button->button, button->time);
2274    
2275            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScript"))->
2276                set_sensitive(group_selected || script_selected);
2277            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/AddScriptGroup"))->
2278                set_sensitive(file);
2279            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/EditScript"))->
2280                set_sensitive(script_selected);    
2281            dynamic_cast<Gtk::MenuItem*>(uiManager->get_widget("/MenuBar/MenuScript/RemoveScript"))->
2282                set_sensitive(group_selected || script_selected);
2283        }
2284    }
2285    
2286    Gtk::RadioMenuItem* MainWindow::add_instrument_to_menu(
2287        const Glib::ustring& name, int position) {
2288    
2289        Gtk::RadioMenuItem::Group instrument_group;
2290        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
2291        if (!children.empty()) {
2292            instrument_group =
2293                static_cast<Gtk::RadioMenuItem*>(children[0])->get_group();
2294        }
2295        Gtk::RadioMenuItem* item =
2296            new Gtk::RadioMenuItem(instrument_group, name);
2297        if (position < 0) {
2298            instrument_menu->append(*item);
2299        } else {
2300            instrument_menu->insert(*item, position);
2301        }
2302        item->show();
2303        item->signal_activate().connect(
2304            sigc::bind(
2305                sigc::mem_fun(*this, &MainWindow::on_instrument_selection_change),
2306                item));
2307        return item;
2308    }
2309    
2310    void MainWindow::remove_instrument_from_menu(int index) {
2311        const std::vector<Gtk::Widget*> children =
2312            instrument_menu->get_children();
2313        Gtk::Widget* child = children[index];
2314        instrument_menu->remove(*child);
2315        delete child;
2316    }
2317    
2318    void MainWindow::add_instrument(gig::Instrument* instrument) {
2319        const Glib::ustring name(gig_to_utf8(instrument->pInfo->Name));
2320    
2321      // update instrument tree view      // update instrument tree view
2322        instrument_name_connection.block();
2323      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();      Gtk::TreeModel::iterator iterInstr = m_refTreeModel->append();
2324      Gtk::TreeModel::Row rowInstr = *iterInstr;      Gtk::TreeModel::Row rowInstr = *iterInstr;
2325      rowInstr[m_Columns.m_col_name] = instrument->pInfo->Name.c_str();      rowInstr[m_Columns.m_col_nr] = m_refTreeModel->children().size() - 1;
2326        rowInstr[m_Columns.m_col_name] = name;
2327      rowInstr[m_Columns.m_col_instr] = instrument;      rowInstr[m_Columns.m_col_instr] = instrument;
2328        instrument_name_connection.unblock();
2329    
2330        add_instrument_to_menu(name);
2331    
2332        m_TreeView.get_selection()->select(iterInstr);
2333    
2334      file_changed();      file_changed();
2335  }  }
2336    
2337    void MainWindow::on_action_add_instrument() {
2338        static int __instrument_indexer = 0;
2339        if (!file) return;
2340        gig::Instrument* instrument = file->AddInstrument();
2341        __instrument_indexer++;
2342        instrument->pInfo->Name = gig_from_utf8(_("Unnamed Instrument ") +
2343                                                ToString(__instrument_indexer));
2344    
2345        add_instrument(instrument);
2346    }
2347    
2348    void MainWindow::on_action_duplicate_instrument() {
2349        if (!file) return;
2350    
2351        // retrieve the currently selected instrument
2352        // (being the original instrument to be duplicated)
2353        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2354        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2355        for (int r = 0; r < rows.size(); ++r) {
2356            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2357            if (it) {
2358                Gtk::TreeModel::Row row = *it;
2359                gig::Instrument* instrOrig = row[m_Columns.m_col_instr];
2360                if (instrOrig) {
2361                    // duplicate the orginal instrument
2362                    gig::Instrument* instrNew = file->AddDuplicateInstrument(instrOrig);
2363                    instrNew->pInfo->Name =
2364                        instrOrig->pInfo->Name +
2365                        gig_from_utf8(Glib::ustring(" (") + _("Copy") + ")");
2366    
2367                    add_instrument(instrNew);
2368                }
2369            }
2370        }
2371    }
2372    
2373  void MainWindow::on_action_remove_instrument() {  void MainWindow::on_action_remove_instrument() {
2374      if (!file) return;      if (!file) return;
2375      if (file_is_shared) {      if (file_is_shared) {
# Line 1136  void MainWindow::on_action_remove_instru Line 2384  void MainWindow::on_action_remove_instru
2384      }      }
2385    
2386      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
2387      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2388      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2389            Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[r]);
2390            if (!it) continue;
2391          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2392          gig::Instrument* instr = row[m_Columns.m_col_instr];          gig::Instrument* instr = row[m_Columns.m_col_instr];
2393          try {          try {
2394                Gtk::TreePath path(it);
2395                int index = path[0];
2396    
2397              // remove instrument from the gig file              // remove instrument from the gig file
2398              if (instr) file->DeleteInstrument(instr);              if (instr) file->DeleteInstrument(instr);
             // remove respective row from instruments tree view  
             m_refTreeModel->erase(it);  
2399              file_changed();              file_changed();
2400    
2401                remove_instrument_from_menu(index);
2402    
2403                // remove row from instruments tree view
2404                m_refTreeModel->erase(it);
2405                // update "Nr" column of all instrument rows
2406                {
2407                    int index = 0;
2408                    for (Gtk::TreeModel::iterator it = m_refTreeModel->children().begin();
2409                         it != m_refTreeModel->children().end(); ++it, ++index)
2410                    {
2411                        Gtk::TreeModel::Row row = *it;
2412                        row[m_Columns.m_col_nr] = index;
2413                    }
2414                }
2415    
2416    #if GTKMM_MAJOR_VERSION < 3
2417                // select another instrument (in gtk3 this is done
2418                // automatically)
2419                if (!m_refTreeModel->children().empty()) {
2420                    if (index == m_refTreeModel->children().size()) {
2421                        index--;
2422                    }
2423                    m_TreeView.get_selection()->select(
2424                        Gtk::TreePath(ToString(index)));
2425                }
2426    #endif
2427                instr_props_set_instrument();
2428                instr = get_instrument();
2429                if (instr) {
2430                    midiRules.set_instrument(instr);
2431                } else {
2432                    midiRules.hide();
2433                }
2434          } catch (RIFF::Exception e) {          } catch (RIFF::Exception e) {
2435              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2436              msg.run();              msg.run();
# Line 1156  void MainWindow::on_action_remove_instru Line 2441  void MainWindow::on_action_remove_instru
2441  void MainWindow::on_action_sample_properties() {  void MainWindow::on_action_sample_properties() {
2442      //TODO: show a dialog where the selected sample's properties can be edited      //TODO: show a dialog where the selected sample's properties can be edited
2443      Gtk::MessageDialog msg(      Gtk::MessageDialog msg(
2444          *this, "Sorry, yet to be implemented!", false, Gtk::MESSAGE_INFO          *this, _("Sorry, yet to be implemented!"), false, Gtk::MESSAGE_INFO
2445      );      );
2446      msg.run();      msg.run();
2447  }  }
2448    
2449    void MainWindow::on_action_add_script_group() {
2450        static int __script_indexer = 0;
2451        if (!file) return;
2452        gig::ScriptGroup* group = file->AddScriptGroup();
2453        group->Name = gig_from_utf8(_("Unnamed Group"));
2454        if (__script_indexer) group->Name += " " + ToString(__script_indexer);
2455        __script_indexer++;
2456        // update sample tree view
2457        Gtk::TreeModel::iterator iterGroup = m_refScriptsTreeModel->append();
2458        Gtk::TreeModel::Row rowGroup = *iterGroup;
2459        rowGroup[m_ScriptsModel.m_col_name] = gig_to_utf8(group->Name);
2460        rowGroup[m_ScriptsModel.m_col_script] = NULL;
2461        rowGroup[m_ScriptsModel.m_col_group] = group;
2462        file_changed();
2463    }
2464    
2465    void MainWindow::on_action_add_script() {
2466        if (!file) return;
2467        // get selected group
2468        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2469        Gtk::TreeModel::iterator it = sel->get_selected();
2470        if (!it) return;
2471        Gtk::TreeModel::Row row = *it;
2472        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2473        if (!group) { // not a group, but a script is selected (probably)
2474            gig::Script* script = row[m_ScriptsModel.m_col_script];
2475            if (!script) return;
2476            it = row.parent(); // resolve parent (that is the script's group)
2477            if (!it) return;
2478            row = *it;
2479            group = row[m_ScriptsModel.m_col_group];
2480            if (!group) return;
2481        }
2482    
2483        // add a new script to the .gig file
2484        gig::Script* script = group->AddScript();    
2485        Glib::ustring name = _("Unnamed Script");
2486        script->Name = gig_from_utf8(name);
2487    
2488        // add script to the tree view
2489        Gtk::TreeModel::iterator iterScript =
2490            m_refScriptsTreeModel->append(row.children());
2491        Gtk::TreeModel::Row rowScript = *iterScript;
2492        rowScript[m_ScriptsModel.m_col_name] = name;
2493        rowScript[m_ScriptsModel.m_col_script] = script;
2494        rowScript[m_ScriptsModel.m_col_group]  = NULL;
2495    
2496        // unfold group of new script item in treeview
2497        Gtk::TreeModel::Path path(iterScript);
2498        m_TreeViewScripts.expand_to_path(path);
2499    }
2500    
2501    void MainWindow::on_action_edit_script() {
2502        if (!file) return;
2503        // get selected script
2504        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2505        Gtk::TreeModel::iterator it = sel->get_selected();
2506        if (!it) return;
2507        Gtk::TreeModel::Row row = *it;
2508        gig::Script* script = row[m_ScriptsModel.m_col_script];
2509        if (!script) return;
2510    
2511        ScriptEditor* editor = new ScriptEditor;
2512        editor->signal_script_to_be_changed.connect(
2513            signal_script_to_be_changed.make_slot()
2514        );
2515        editor->signal_script_changed.connect(
2516            signal_script_changed.make_slot()
2517        );
2518        editor->setScript(script);
2519        //editor->reparent(*this);
2520        editor->show();
2521    }
2522    
2523    void MainWindow::on_action_remove_script() {
2524        if (!file) return;
2525        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
2526        Gtk::TreeModel::iterator it = sel->get_selected();
2527        if (it) {
2528            Gtk::TreeModel::Row row = *it;
2529            gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
2530            gig::Script* script     = row[m_ScriptsModel.m_col_script];
2531            Glib::ustring name      = row[m_ScriptsModel.m_col_name];
2532            try {
2533                // remove script group or script from the gig file
2534                if (group) {
2535                    // notify everybody that we're going to remove these samples
2536    //TODO:         scripts_to_be_removed_signal.emit(members);
2537                    // delete the group in the .gig file including the
2538                    // samples that belong to the group
2539                    file->DeleteScriptGroup(group);
2540                    // notify that we're done with removal
2541    //TODO:         scripts_removed_signal.emit();
2542                    file_changed();
2543                } else if (script) {
2544                    // notify everybody that we're going to remove this sample
2545    //TODO:         std::list<gig::Script*> lscripts;
2546    //TODO:         lscripts.push_back(script);
2547    //TODO:         scripts_to_be_removed_signal.emit(lscripts);
2548                    // remove sample from the .gig file
2549                    script->GetGroup()->DeleteScript(script);
2550                    // notify that we're done with removal
2551    //TODO:         scripts_removed_signal.emit();
2552                    dimreg_changed();
2553                    file_changed();
2554                }
2555                // remove respective row(s) from samples tree view
2556                m_refScriptsTreeModel->erase(it);
2557            } catch (RIFF::Exception e) {
2558                // pretend we're done with removal (i.e. to avoid dead locks)
2559    //TODO:     scripts_removed_signal.emit();
2560                // show error message
2561                Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
2562                msg.run();
2563            }
2564        }
2565    }
2566    
2567  void MainWindow::on_action_add_group() {  void MainWindow::on_action_add_group() {
2568      static int __sample_indexer = 0;      static int __sample_indexer = 0;
2569      if (!file) return;      if (!file) return;
2570      gig::Group* group = file->AddGroup();      gig::Group* group = file->AddGroup();
2571      group->Name = "Unnamed Group";      group->Name = gig_from_utf8(_("Unnamed Group"));
2572      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);      if (__sample_indexer) group->Name += " " + ToString(__sample_indexer);
2573      __sample_indexer++;      __sample_indexer++;
2574      // update sample tree view      // update sample tree view
2575      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();      Gtk::TreeModel::iterator iterGroup = m_refSamplesTreeModel->append();
2576      Gtk::TreeModel::Row rowGroup = *iterGroup;      Gtk::TreeModel::Row rowGroup = *iterGroup;
2577      rowGroup[m_SamplesModel.m_col_name] = group->Name.c_str();      rowGroup[m_SamplesModel.m_col_name] = gig_to_utf8(group->Name);
2578      rowGroup[m_SamplesModel.m_col_sample] = NULL;      rowGroup[m_SamplesModel.m_col_sample] = NULL;
2579      rowGroup[m_SamplesModel.m_col_group] = group;      rowGroup[m_SamplesModel.m_col_group] = group;
2580      file_changed();      file_changed();
2581  }  }
2582    
2583    void MainWindow::on_action_replace_sample() {
2584        add_or_replace_sample(true);
2585    }
2586    
2587  void MainWindow::on_action_add_sample() {  void MainWindow::on_action_add_sample() {
2588        add_or_replace_sample(false);
2589    }
2590    
2591    void MainWindow::add_or_replace_sample(bool replace) {
2592      if (!file) return;      if (!file) return;
2593      // get selected group  
2594        // get selected group (and probably selected sample)
2595      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2596      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2597        if (rows.empty()) return;
2598        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
2599      if (!it) return;      if (!it) return;
2600      Gtk::TreeModel::Row row = *it;      Gtk::TreeModel::Row row = *it;
2601        gig::Sample* sample = NULL;
2602      gig::Group* group = row[m_SamplesModel.m_col_group];      gig::Group* group = row[m_SamplesModel.m_col_group];
2603      if (!group) { // not a group, but a sample is selected (probably)      if (!group) { // not a group, but a sample is selected (probably)
2604          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          if (replace) sample = row[m_SamplesModel.m_col_sample];
2605          if (!sample) return;          if (!row[m_SamplesModel.m_col_sample]) return;
2606          it = row.parent(); // resolve parent (that is the sample's group)          it = row.parent(); // resolve parent (that is the sample's group)
2607          if (!it) return;          if (!it) return;
2608          row = *it;          if (!replace) row = *it;
2609          group = row[m_SamplesModel.m_col_group];          group = (*it)[m_SamplesModel.m_col_group];
2610          if (!group) return;          if (!group) return;
2611      }      }
2612        if (replace && !sample) return;
2613    
2614      // show 'browse for file' dialog      // show 'browse for file' dialog
2615      Gtk::FileChooserDialog dialog(*this, _("Add Sample(s)"));      Gtk::FileChooserDialog dialog(*this, replace ? _("Replace Sample with") : _("Add Sample(s)"));
2616      dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);      dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2617      dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);      dialog.add_button(_("_Open"), Gtk::RESPONSE_OK);
2618      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
2619      Gtk::FileFilter soundfilter; // matches all file types supported by libsndfile  
2620        // matches all file types supported by libsndfile
2621    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2622        Gtk::FileFilter soundfilter;
2623    #else
2624        Glib::RefPtr<Gtk::FileFilter> soundfilter = Gtk::FileFilter::create();
2625    #endif
2626      const char* const supportedFileTypes[] = {      const char* const supportedFileTypes[] = {
2627          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",          "*.wav", "*.WAV", "*.aiff", "*.AIFF", "*.aifc", "*.AIFC", "*.snd",
2628          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",          "*.SND", "*.au", "*.AU", "*.paf", "*.PAF", "*.iff", "*.IFF",
# Line 1207  void MainWindow::on_action_add_sample() Line 2630  void MainWindow::on_action_add_sample()
2630          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",          "*.W64", "*.pvf", "*.PVF", "*.xi", "*.XI", "*.htk", "*.HTK",
2631          "*.caf", "*.CAF", NULL          "*.caf", "*.CAF", NULL
2632      };      };
2633        const char* soundfiles = _("Sound Files");
2634        const char* allfiles = _("All Files");
2635    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
2636      for (int i = 0; supportedFileTypes[i]; i++)      for (int i = 0; supportedFileTypes[i]; i++)
2637          soundfilter.add_pattern(supportedFileTypes[i]);          soundfilter.add_pattern(supportedFileTypes[i]);
2638      soundfilter.set_name("Sound Files");      soundfilter.set_name(soundfiles);
2639      Gtk::FileFilter allpassfilter; // matches every file  
2640        // matches every file
2641        Gtk::FileFilter allpassfilter;
2642      allpassfilter.add_pattern("*.*");      allpassfilter.add_pattern("*.*");
2643      allpassfilter.set_name("All Files");      allpassfilter.set_name(allfiles);
2644    #else
2645        for (int i = 0; supportedFileTypes[i]; i++)
2646            soundfilter->add_pattern(supportedFileTypes[i]);
2647        soundfilter->set_name(soundfiles);
2648    
2649        // matches every file
2650        Glib::RefPtr<Gtk::FileFilter> allpassfilter = Gtk::FileFilter::create();
2651        allpassfilter->add_pattern("*.*");
2652        allpassfilter->set_name(allfiles);
2653    #endif
2654      dialog.add_filter(soundfilter);      dialog.add_filter(soundfilter);
2655      dialog.add_filter(allpassfilter);      dialog.add_filter(allpassfilter);
2656        if (current_sample_dir != "") {
2657            dialog.set_current_folder(current_sample_dir);
2658        }
2659      if (dialog.run() == Gtk::RESPONSE_OK) {      if (dialog.run() == Gtk::RESPONSE_OK) {
2660            current_sample_dir = dialog.get_current_folder();
2661          Glib::ustring error_files;          Glib::ustring error_files;
2662          Glib::SListHandle<Glib::ustring> filenames = dialog.get_filenames();          std::vector<std::string> filenames = dialog.get_filenames();
2663          for (Glib::SListHandle<Glib::ustring>::iterator iter = filenames.begin();          for (std::vector<std::string>::iterator iter = filenames.begin();
2664               iter != filenames.end(); ++iter) {               iter != filenames.end(); ++iter) {
2665              printf("Adding sample %s\n",(*iter).c_str());              printf("Adding sample %s\n",(*iter).c_str());
2666              // use libsndfile to retrieve file informations              // use libsndfile to retrieve file informations
# Line 1226  void MainWindow::on_action_add_sample() Line 2668  void MainWindow::on_action_add_sample()
2668              info.format = 0;              info.format = 0;
2669              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);              SNDFILE* hFile = sf_open((*iter).c_str(), SFM_READ, &info);
2670              try {              try {
2671                  if (!hFile) throw std::string("could not open file");                  if (!hFile) throw std::string(_("could not open file"));
2672                  int bitdepth;                  int bitdepth;
2673                  switch (info.format & 0xff) {                  switch (info.format & 0xff) {
2674                      case SF_FORMAT_PCM_S8:                      case SF_FORMAT_PCM_S8:
# Line 1242  void MainWindow::on_action_add_sample() Line 2684  void MainWindow::on_action_add_sample()
2684                          break;                          break;
2685                      default:                      default:
2686                          sf_close(hFile); // close sound file                          sf_close(hFile); // close sound file
2687                          throw std::string("format not supported"); // unsupported subformat (yet?)                          throw std::string(_("format not supported")); // unsupported subformat (yet?)
2688                  }                  }
2689                  // add a new sample to the .gig file                  // add a new sample to the .gig file (if adding is requested actually)
2690                  gig::Sample* sample = file->AddSample();                  if (!replace) sample = file->AddSample();
2691                  // file name without path                  // file name without path
2692                  Glib::ustring filename = Glib::filename_display_basename(*iter);                  Glib::ustring filename = Glib::filename_display_basename(*iter);
2693                  // remove file extension if there is one                  // remove file extension if there is one
# Line 1255  void MainWindow::on_action_add_sample() Line 2697  void MainWindow::on_action_add_sample()
2697                          break;                          break;
2698                      }                      }
2699                  }                  }
2700                  sample->pInfo->Name = filename;                  sample->pInfo->Name = gig_from_utf8(filename);
2701                  sample->Channels = info.channels;                  sample->Channels = info.channels;
2702                  sample->BitDepth = bitdepth;                  sample->BitDepth = bitdepth;
2703                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;                  sample->FrameSize = bitdepth / 8/*1 byte are 8 bits*/ * info.channels;
# Line 1269  void MainWindow::on_action_add_sample() Line 2711  void MainWindow::on_action_add_sample()
2711                                 &instrument, sizeof(instrument)) != SF_FALSE)                                 &instrument, sizeof(instrument)) != SF_FALSE)
2712                  {                  {
2713                      sample->MIDIUnityNote = instrument.basenote;                      sample->MIDIUnityNote = instrument.basenote;
2714                        sample->FineTune      = instrument.detune;
2715    
 #if HAVE_SF_INSTRUMENT_LOOPS  
2716                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {                      if (instrument.loop_count && instrument.loops[0].mode != SF_LOOP_NONE) {
2717                          sample->Loops = 1;                          sample->Loops = 1;
2718    
# Line 1290  void MainWindow::on_action_add_sample() Line 2732  void MainWindow::on_action_add_sample()
2732                          sample->LoopPlayCount = instrument.loops[0].count;                          sample->LoopPlayCount = instrument.loops[0].count;
2733                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;                          sample->LoopSize = sample->LoopEnd - sample->LoopStart + 1;
2734                      }                      }
 #endif  
2735                  }                  }
2736    
2737                  // schedule resizing the sample (which will be done                  // schedule resizing the sample (which will be done
2738                  // physically when File::Save() is called)                  // physically when File::Save() is called)
2739                  sample->Resize(info.frames);                  sample->Resize(info.frames);
2740                  // make sure sample is part of the selected group                  // make sure sample is part of the selected group
2741                  group->AddSample(sample);                  if (!replace) group->AddSample(sample);
2742                  // schedule that physical resize and sample import                  // schedule that physical resize and sample import
2743                  // (data copying), performed when "Save" is requested                  // (data copying), performed when "Save" is requested
2744                  SampleImportItem sched_item;                  SampleImportItem sched_item;
# Line 1305  void MainWindow::on_action_add_sample() Line 2746  void MainWindow::on_action_add_sample()
2746                  sched_item.sample_path = *iter;                  sched_item.sample_path = *iter;
2747                  m_SampleImportQueue.push_back(sched_item);                  m_SampleImportQueue.push_back(sched_item);
2748                  // add sample to the tree view                  // add sample to the tree view
2749                  Gtk::TreeModel::iterator iterSample =                  if (replace) {
2750                      m_refSamplesTreeModel->append(row.children());                      row[m_SamplesModel.m_col_name] = gig_to_utf8(sample->pInfo->Name);
2751                  Gtk::TreeModel::Row rowSample = *iterSample;                  } else {
2752                  rowSample[m_SamplesModel.m_col_name]   = filename;                      Gtk::TreeModel::iterator iterSample =
2753                  rowSample[m_SamplesModel.m_col_sample] = sample;                          m_refSamplesTreeModel->append(row.children());
2754                  rowSample[m_SamplesModel.m_col_group]  = NULL;                      Gtk::TreeModel::Row rowSample = *iterSample;
2755                        rowSample[m_SamplesModel.m_col_name] =
2756                            gig_to_utf8(sample->pInfo->Name);
2757                        rowSample[m_SamplesModel.m_col_sample] = sample;
2758                        rowSample[m_SamplesModel.m_col_group]  = NULL;
2759                    }
2760                  // close sound file                  // close sound file
2761                  sf_close(hFile);                  sf_close(hFile);
2762                  file_changed();                  file_changed();
2763              } catch (std::string what) { // remember the files that made trouble (and their cause)              } catch (std::string what) { // remember the files that made trouble (and their cause)
2764                  if (error_files.size()) error_files += "\n";                  if (!error_files.empty()) error_files += "\n";
2765                  error_files += *iter += " (" + what + ")";                  error_files += *iter += " (" + what + ")";
2766              }              }
2767          }          }
2768          // 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
2769          if (error_files.size()) {          if (!error_files.empty()) {
2770              Glib::ustring txt = _("Could not add the following sample(s):\n") + error_files;              Glib::ustring txt =
2771                    (replace
2772                        ? _("Failed to replace sample with:\n")
2773                        : _("Could not add the following sample(s):\n"))
2774                    + error_files;
2775                Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2776                msg.run();
2777            }
2778        }
2779    }
2780    
2781    void MainWindow::on_action_replace_all_samples_in_all_groups()
2782    {
2783        if (!file) return;
2784        Gtk::FileChooserDialog dialog(*this, _("Select Folder"),
2785                                      Gtk::FILE_CHOOSER_ACTION_SELECT_FOLDER);
2786        const char* str =
2787            _("This is a very specific function. It tries to replace all samples "
2788              "in the current gig file by samples located in the chosen "
2789              "directory.\n\n"
2790              "It works like this: For each sample in the gig file, it tries to "
2791              "find a sample file in the selected directory with the same name as "
2792              "the sample in the gig file. Optionally, you can add a filename "
2793              "extension below, which will be added to the filename expected to be "
2794              "found. That is, assume you have a gig file with a sample called "
2795              "'Snare', if you enter '.wav' below (like it's done by default), it "
2796              "expects to find a sample file called 'Snare.wav' and will replace "
2797              "the sample in the gig file accordingly. If you don't need an "
2798              "extension, blank the field below. Any gig sample where no "
2799              "appropriate sample file could be found will be reported and left "
2800              "untouched.\n");
2801    #if GTKMM_MAJOR_VERSION < 3
2802        view::WrapLabel description(str);
2803    #else
2804        Gtk::Label description(str);
2805        description.set_line_wrap();
2806    #endif
2807        Gtk::HBox entryArea;
2808        Gtk::Label entryLabel( _("Add filename extension: "), Gtk::ALIGN_START);
2809        Gtk::Entry postfixEntryBox;
2810        postfixEntryBox.set_text(".wav");
2811        entryArea.pack_start(entryLabel);
2812        entryArea.pack_start(postfixEntryBox);
2813        dialog.get_vbox()->pack_start(description, Gtk::PACK_SHRINK);
2814        dialog.get_vbox()->pack_start(entryArea, Gtk::PACK_SHRINK);
2815        description.show();
2816        entryArea.show_all();
2817        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
2818        dialog.add_button(_("Select"), Gtk::RESPONSE_OK);
2819        dialog.set_select_multiple(false);
2820        if (current_sample_dir != "") {
2821            dialog.set_current_folder(current_sample_dir);
2822        }
2823        if (dialog.run() == Gtk::RESPONSE_OK)
2824        {
2825            current_sample_dir = dialog.get_current_folder();
2826            Glib::ustring error_files;
2827            std::string folder = dialog.get_filename();
2828            for (gig::Sample* sample = file->GetFirstSample();
2829                 sample; sample = file->GetNextSample())
2830            {
2831                std::string filename =
2832                    folder + G_DIR_SEPARATOR_S +
2833                    Glib::filename_from_utf8(gig_to_utf8(sample->pInfo->Name) +
2834                                             postfixEntryBox.get_text());
2835                SF_INFO info;
2836                info.format = 0;
2837                SNDFILE* hFile = sf_open(filename.c_str(), SFM_READ, &info);
2838                try
2839                {
2840                    if (!hFile) throw std::string(_("could not open file"));
2841                    switch (info.format & 0xff) {
2842                        case SF_FORMAT_PCM_S8:
2843                        case SF_FORMAT_PCM_16:
2844                        case SF_FORMAT_PCM_U8:
2845                        case SF_FORMAT_PCM_24:
2846                        case SF_FORMAT_PCM_32:
2847                        case SF_FORMAT_FLOAT:
2848                        case SF_FORMAT_DOUBLE:
2849                            break;
2850                        default:
2851                            sf_close(hFile);
2852                            throw std::string(_("format not supported"));
2853                    }
2854                    SampleImportItem sched_item;
2855                    sched_item.gig_sample  = sample;
2856                    sched_item.sample_path = filename;
2857                    m_SampleImportQueue.push_back(sched_item);
2858                    sf_close(hFile);
2859                    file_changed();
2860                }
2861                catch (std::string what)
2862                {
2863                    if (!error_files.empty()) error_files += "\n";
2864                    error_files += Glib::filename_to_utf8(filename) +
2865                        " (" + what + ")";
2866                }
2867            }
2868            // show error message box when some file(s) could not be opened / added
2869            if (!error_files.empty()) {
2870                Glib::ustring txt =
2871                    _("Could not replace the following sample(s):\n") + error_files;
2872              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);              Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
2873              msg.run();              msg.run();
2874          }          }
# Line 1331  void MainWindow::on_action_add_sample() Line 2878  void MainWindow::on_action_add_sample()
2878  void MainWindow::on_action_remove_sample() {  void MainWindow::on_action_remove_sample() {
2879      if (!file) return;      if (!file) return;
2880      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
2881      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
2882      if (it) {      for (int r = rows.size() - 1; r >= 0; --r) {
2883            Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[r]);
2884            if (!it) continue;
2885          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::Row row = *it;
2886          gig::Group* group   = row[m_SamplesModel.m_col_group];          gig::Group* group   = row[m_SamplesModel.m_col_group];
2887          gig::Sample* sample = row[m_SamplesModel.m_col_sample];          gig::Sample* sample = row[m_SamplesModel.m_col_sample];
# Line 1340  void MainWindow::on_action_remove_sample Line 2889  void MainWindow::on_action_remove_sample
2889          try {          try {
2890              // remove group or sample from the gig file              // remove group or sample from the gig file
2891              if (group) {              if (group) {
2892                  // temporarily remember the samples that bolong to                  // temporarily remember the samples that belong to
2893                  // that group (we need that to clean the queue)                  // that group (we need that to clean the queue)
2894                  std::list<gig::Sample*> members;                  std::list<gig::Sample*> members;
2895                  for (gig::Sample* pSample = group->GetFirstSample();                  for (gig::Sample* pSample = group->GetFirstSample();
# Line 1404  void MainWindow::on_action_remove_sample Line 2953  void MainWindow::on_action_remove_sample
2953      }      }
2954  }  }
2955    
2956    void MainWindow::on_action_remove_unused_samples() {
2957        if (!file) return;
2958    
2959        // collect all samples that are not referenced by any instrument
2960        std::list<gig::Sample*> lsamples;
2961        for (int iSample = 0; file->GetSample(iSample); ++iSample) {
2962            gig::Sample* sample = file->GetSample(iSample);
2963            bool isUsed = false;
2964            for (gig::Instrument* instrument = file->GetFirstInstrument(); instrument;
2965                                  instrument = file->GetNextInstrument())
2966            {
2967                for (gig::Region* rgn = instrument->GetFirstRegion(); rgn;
2968                                  rgn = instrument->GetNextRegion())
2969                {
2970                    for (int i = 0; i < 256; ++i) {
2971                        if (!rgn->pDimensionRegions[i]) continue;
2972                        if (rgn->pDimensionRegions[i]->pSample != sample) continue;
2973                        isUsed = true;
2974                        goto endOfRefSearch;
2975                    }
2976                }
2977            }
2978            endOfRefSearch:
2979            if (!isUsed) lsamples.push_back(sample);
2980        }
2981    
2982        if (lsamples.empty()) return;
2983    
2984        // notify everybody that we're going to remove these samples
2985        samples_to_be_removed_signal.emit(lsamples);
2986    
2987        // remove collected samples
2988        try {
2989            for (std::list<gig::Sample*>::iterator itSample = lsamples.begin();
2990                 itSample != lsamples.end(); ++itSample)
2991            {
2992                gig::Sample* sample = *itSample;
2993                // remove sample from the .gig file
2994                file->DeleteSample(sample);
2995                // if sample was just previously added, remove it fro the import queue
2996                for (std::list<SampleImportItem>::iterator iter = m_SampleImportQueue.begin();
2997                     iter != m_SampleImportQueue.end(); ++iter)
2998                {
2999                    if ((*iter).gig_sample == sample) {
3000                        printf("Removing previously added sample '%s'\n",
3001                               (*iter).sample_path.c_str());
3002                        m_SampleImportQueue.erase(iter);
3003                        break;
3004                    }
3005                }
3006            }
3007        } catch (RIFF::Exception e) {
3008            // show error message
3009            Gtk::MessageDialog msg(*this, e.Message.c_str(), false, Gtk::MESSAGE_ERROR);
3010            msg.run();
3011        }
3012    
3013        // notify everybody that we're done with removal
3014        samples_removed_signal.emit();
3015    
3016        dimreg_changed();
3017        file_changed();
3018        __refreshEntireGUI();
3019    }
3020    
3021    // see comment on on_sample_treeview_drag_begin()
3022    void MainWindow::on_scripts_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3023    {
3024        first_call_to_drag_data_get = true;
3025    }
3026    
3027    void MainWindow::on_scripts_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3028                                                       Gtk::SelectionData& selection_data, guint, guint)
3029    {
3030        if (!first_call_to_drag_data_get) return;
3031        first_call_to_drag_data_get = false;
3032    
3033        // get selected script
3034        gig::Script* script = NULL;
3035        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewScripts.get_selection();
3036        Gtk::TreeModel::iterator it = sel->get_selected();
3037        if (it) {
3038            Gtk::TreeModel::Row row = *it;
3039            script = row[m_ScriptsModel.m_col_script];
3040        }
3041        // pass the gig::Script as pointer
3042        selection_data.set(selection_data.get_target(), 0/*unused*/,
3043                           (const guchar*)&script,
3044                           sizeof(script)/*length of data in bytes*/);
3045    }
3046    
3047    // see comment on on_sample_treeview_drag_begin()
3048    void MainWindow::on_instruments_treeview_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
3049    {
3050        first_call_to_drag_data_get = true;
3051    }
3052    
3053    void MainWindow::on_instruments_treeview_drag_data_get(const Glib::RefPtr<Gdk::DragContext>&,
3054                                                           Gtk::SelectionData& selection_data, guint, guint)
3055    {
3056        if (!first_call_to_drag_data_get) return;
3057        first_call_to_drag_data_get = false;
3058    
3059        // get selected source instrument
3060        gig::Instrument* src = NULL;
3061        {
3062            Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeView.get_selection();
3063            std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3064            if (!rows.empty()) {
3065                Gtk::TreeModel::iterator it = m_refTreeModel->get_iter(rows[0]);
3066                if (it) {
3067                    Gtk::TreeModel::Row row = *it;
3068                    src = row[m_Columns.m_col_instr];
3069                }
3070            }
3071        }
3072        if (!src) return;
3073    
3074        // pass the source gig::Instrument as pointer
3075        selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
3076                           sizeof(src)/*length of data in bytes*/);
3077    }
3078    
3079    void MainWindow::on_instruments_treeview_drop_drag_data_received(
3080        const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
3081        const Gtk::SelectionData& selection_data, guint, guint time)
3082    {
3083        gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
3084        if (!src || selection_data.get_length() != sizeof(gig::Instrument*))
3085            return;
3086    
3087        gig::Instrument* dst = NULL;
3088        {
3089            Gtk::TreeModel::Path path;
3090            const bool found = m_TreeView.get_path_at_pos(x, y, path);
3091            if (!found) return;
3092    
3093            Gtk::TreeModel::iterator iter = m_refTreeModel->get_iter(path);
3094            if (!iter) return;
3095            Gtk::TreeModel::Row row = *iter;
3096            dst = row[m_Columns.m_col_instr];
3097        }
3098        if (!dst) return;
3099    
3100        //printf("dragdrop received src=%s dst=%s\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
3101        src->MoveTo(dst);
3102        __refreshEntireGUI();
3103        select_instrument(src);
3104    }
3105    
3106  // For some reason drag_data_get gets called two times for each  // For some reason drag_data_get gets called two times for each
3107  // 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
3108  // 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 1422  void MainWindow::on_sample_treeview_drag Line 3121  void MainWindow::on_sample_treeview_drag
3121      // get selected sample      // get selected sample
3122      gig::Sample* sample = NULL;      gig::Sample* sample = NULL;
3123      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();      Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3124      Gtk::TreeModel::iterator it = sel->get_selected();      std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3125      if (it) {      if (!rows.empty()) {
3126          Gtk::TreeModel::Row row = *it;          Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3127          sample = row[m_SamplesModel.m_col_sample];          if (it) {
3128                Gtk::TreeModel::Row row = *it;
3129                sample = row[m_SamplesModel.m_col_sample];
3130            }
3131      }      }
3132      // pass the gig::Sample as pointer      // pass the gig::Sample as pointer
3133      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 1462  void MainWindow::on_sample_label_drop_dr Line 3164  void MainWindow::on_sample_label_drop_dr
3164          bool channels_changed = false;          bool channels_changed = false;
3165          if (sample->Channels == 1 && stereo_dimension) {          if (sample->Channels == 1 && stereo_dimension) {
3166              // remove the samplechannel dimension              // remove the samplechannel dimension
3167    /* commented out, because it makes it impossible building up an instrument from scratch using two separate L/R samples
3168              region->DeleteDimension(stereo_dimension);              region->DeleteDimension(stereo_dimension);
3169              channels_changed = true;              channels_changed = true;
3170              region_changed();              region_changed();
3171    */
3172          }          }
3173          dimreg_edit.set_sample(sample);          dimreg_edit.set_sample(
3174                sample,
3175                is_copy_samples_unity_note_enabled(),
3176                is_copy_samples_fine_tune_enabled(),
3177                is_copy_samples_loop_enabled()
3178            );
3179    
3180          if (sample->Channels == 2 && !stereo_dimension) {          if (sample->Channels == 2 && !stereo_dimension) {
3181              // add samplechannel dimension              // add samplechannel dimension
# Line 1494  void MainWindow::on_sample_label_drop_dr Line 3203  void MainWindow::on_sample_label_drop_dr
3203          // notify we're done with altering          // notify we're done with altering
3204          region_changed_signal.emit(region);          region_changed_signal.emit(region);
3205    
3206            file_changed();
3207    
3208          return;          return;
3209      }      }
3210      // drop failed      // drop failed
# Line 1507  void MainWindow::sample_name_changed(con Line 3218  void MainWindow::sample_name_changed(con
3218      Glib::ustring name  = row[m_SamplesModel.m_col_name];      Glib::ustring name  = row[m_SamplesModel.m_col_name];
3219      gig::Group* group   = row[m_SamplesModel.m_col_group];      gig::Group* group   = row[m_SamplesModel.m_col_group];
3220      gig::Sample* sample = row[m_SamplesModel.m_col_sample];      gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3221        gig::String gigname(gig_from_utf8(name));
3222      if (group) {      if (group) {
3223          if (group->Name != name) {          if (group->Name != gigname) {
3224              group->Name = name;              group->Name = gigname;
3225              printf("group name changed\n");              printf("group name changed\n");
3226              file_changed();              file_changed();
3227          }          }
3228      } else if (sample) {      } else if (sample) {
3229          if (sample->pInfo->Name != name.raw()) {          if (sample->pInfo->Name != gigname) {
3230              sample->pInfo->Name = name.raw();              sample->pInfo->Name = gigname;
3231              printf("sample name changed\n");              printf("sample name changed\n");
3232              file_changed();              file_changed();
3233          }          }
3234      }      }
3235  }  }
3236    
3237    void MainWindow::script_name_changed(const Gtk::TreeModel::Path& path,
3238                                         const Gtk::TreeModel::iterator& iter) {
3239        if (!iter) return;
3240        Gtk::TreeModel::Row row = *iter;
3241        Glib::ustring name      = row[m_ScriptsModel.m_col_name];
3242        gig::ScriptGroup* group = row[m_ScriptsModel.m_col_group];
3243        gig::Script* script     = row[m_ScriptsModel.m_col_script];
3244        gig::String gigname(gig_from_utf8(name));
3245        if (group) {
3246            if (group->Name != gigname) {
3247                group->Name = gigname;
3248                printf("script group name changed\n");
3249                file_changed();
3250            }
3251        } else if (script) {
3252            if (script->Name != gigname) {
3253                script->Name = gigname;
3254                printf("script name changed\n");
3255                file_changed();
3256            }
3257        }
3258    }
3259    
3260    void MainWindow::script_double_clicked(const Gtk::TreeModel::Path& path,
3261                                           Gtk::TreeViewColumn* column)
3262    {
3263        Gtk::TreeModel::iterator iter = m_refScriptsTreeModel->get_iter(path);
3264        if (!iter) return;
3265        Gtk::TreeModel::Row row = *iter;
3266        gig::Script* script = row[m_ScriptsModel.m_col_script];
3267        if (!script) return;
3268    
3269        ScriptEditor* editor = new ScriptEditor;
3270        editor->signal_script_to_be_changed.connect(
3271            signal_script_to_be_changed.make_slot()
3272        );
3273        editor->signal_script_changed.connect(
3274            signal_script_changed.make_slot()
3275        );
3276        editor->setScript(script);
3277        //editor->reparent(*this);
3278        editor->show();
3279    }
3280    
3281  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,  void MainWindow::instrument_name_changed(const Gtk::TreeModel::Path& path,
3282                                           const Gtk::TreeModel::iterator& iter) {                                           const Gtk::TreeModel::iterator& iter) {
3283      if (!iter) return;      if (!iter) return;
3284      Gtk::TreeModel::Row row = *iter;      Gtk::TreeModel::Row row = *iter;
3285      Glib::ustring name = row[m_Columns.m_col_name];      Glib::ustring name = row[m_Columns.m_col_name];
3286    
3287        // change name in instrument menu
3288        int index = path[0];
3289        const std::vector<Gtk::Widget*> children = instrument_menu->get_children();
3290        if (index < children.size()) {
3291    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION >= 16) || GTKMM_MAJOR_VERSION > 2
3292            static_cast<Gtk::RadioMenuItem*>(children[index])->set_label(name);
3293    #else
3294            remove_instrument_from_menu(index);
3295            Gtk::RadioMenuItem* item = add_instrument_to_menu(name, index);
3296            item->set_active();
3297    #endif
3298        }
3299    
3300        // change name in gig
3301      gig::Instrument* instrument = row[m_Columns.m_col_instr];      gig::Instrument* instrument = row[m_Columns.m_col_instr];
3302      if (instrument && instrument->pInfo->Name != name.raw()) {      gig::String gigname(gig_from_utf8(name));
3303          instrument->pInfo->Name = name.raw();      if (instrument && instrument->pInfo->Name != gigname) {
3304            instrument->pInfo->Name = gigname;
3305    
3306            // change name in the instrument properties window
3307            if (instrumentProps.get_instrument() == instrument) {
3308                instrumentProps.update_name();
3309            }
3310    
3311          file_changed();          file_changed();
3312      }      }
3313  }  }
3314    
3315    void MainWindow::on_action_combine_instruments() {
3316        CombineInstrumentsDialog* d = new CombineInstrumentsDialog(*this, file);
3317        d->show_all();
3318        d->resize(500, 400);
3319        d->run();
3320        if (d->fileWasChanged()) {
3321            // update GUI with new instrument just created
3322            add_instrument(d->newCombinedInstrument());
3323        }
3324        delete d;
3325    }
3326    
3327    void MainWindow::on_action_view_references() {
3328        Glib::RefPtr<Gtk::TreeSelection> sel = m_TreeViewSamples.get_selection();
3329        std::vector<Gtk::TreeModel::Path> rows = sel->get_selected_rows();
3330        if (rows.empty()) return;
3331        Gtk::TreeModel::iterator it = m_refSamplesTreeModel->get_iter(rows[0]);
3332        if (!it) return;
3333        Gtk::TreeModel::Row row = *it;
3334        gig::Sample* sample = row[m_SamplesModel.m_col_sample];
3335        if (!sample) return;
3336    
3337        ReferencesView* d = new ReferencesView(*this);
3338        d->setSample(sample);
3339        d->dimension_region_selected.connect(
3340            sigc::mem_fun(*this, &MainWindow::select_dimension_region)
3341        );
3342        d->show_all();
3343        d->resize(500, 400);
3344        d->run();
3345        delete d;
3346    }
3347    
3348    void MainWindow::mergeFiles(const std::vector<std::string>& filenames) {
3349        struct _Source {
3350            std::vector<RIFF::File*> riffs;
3351            std::vector<gig::File*> gigs;
3352            
3353            ~_Source() {
3354                for (int k = 0; k < gigs.size(); ++k) delete gigs[k];
3355                for (int k = 0; k < riffs.size(); ++k) delete riffs[k];
3356                riffs.clear();
3357                gigs.clear();
3358            }
3359        } sources;
3360    
3361        if (filenames.empty())
3362            throw RIFF::Exception(_("No files selected, so nothing done."));
3363    
3364        // first open all input files (to avoid output file corruption)
3365        int i;
3366        try {
3367            for (i = 0; i < filenames.size(); ++i) {
3368                const std::string& filename = filenames[i];
3369                printf("opening file=%s\n", filename.c_str());
3370    
3371                RIFF::File* riff = new RIFF::File(filename);
3372                sources.riffs.push_back(riff);
3373    
3374                gig::File* gig = new gig::File(riff);
3375                sources.gigs.push_back(gig);
3376            }
3377        } catch (RIFF::Exception e) {
3378            throw RIFF::Exception(
3379                _("Error occurred while opening '") +
3380                filenames[i] +
3381                "': " +
3382                e.Message
3383            );
3384        } catch (...) {
3385            throw RIFF::Exception(
3386                _("Unknown exception occurred while opening '") +
3387                filenames[i] + "'"
3388            );
3389        }
3390    
3391        // now merge the opened .gig files to the main .gig file currently being
3392        // open in gigedit
3393        try {
3394            for (i = 0; i < filenames.size(); ++i) {
3395                const std::string& filename = filenames[i];
3396                printf("merging file=%s\n", filename.c_str());
3397                assert(i < sources.gigs.size());
3398    
3399                this->file->AddContentOf(sources.gigs[i]);
3400            }
3401        } catch (RIFF::Exception e) {
3402            throw RIFF::Exception(
3403                _("Error occurred while merging '") +
3404                filenames[i] +
3405                "': " +
3406                e.Message
3407            );
3408        } catch (...) {
3409            throw RIFF::Exception(
3410                _("Unknown exception occurred while merging '") +
3411                filenames[i] + "'"
3412            );
3413        }
3414    
3415        // Finally save gig file persistently to disk ...
3416        //NOTE: requires that this gig file already has a filename !
3417        {
3418            std::cout << "Saving file\n" << std::flush;
3419            file_structure_to_be_changed_signal.emit(this->file);
3420    
3421            progress_dialog = new ProgressDialog( //FIXME: memory leak!
3422                _("Saving") +  Glib::ustring(" '") +
3423                Glib::filename_display_basename(this->filename) + "' ...",
3424                *this
3425            );
3426            progress_dialog->show_all();
3427            saver = new Saver(this->file); //FIXME: memory leak!
3428            saver->signal_progress().connect(
3429                sigc::mem_fun(*this, &MainWindow::on_saver_progress));
3430            saver->signal_finished().connect(
3431                sigc::mem_fun(*this, &MainWindow::on_saver_finished));
3432            saver->signal_error().connect(
3433                sigc::mem_fun(*this, &MainWindow::on_saver_error));
3434            saver->launch();
3435        }
3436    }
3437    
3438    void MainWindow::on_action_merge_files() {
3439        if (this->file->GetFileName().empty()) {
3440            Glib::ustring txt = _(
3441                "You seem to have a new .gig file open that has not been saved "
3442                "yet. You must save it somewhere before starting to merge it with "
3443                "other .gig files though, because during the merge operation the "
3444                "other files' sample data must be written on file level to the "
3445                "target .gig file."
3446            );
3447            Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
3448            msg.run();
3449            return;
3450        }
3451    
3452        Gtk::FileChooserDialog dialog(*this, _("Merge .gig files"));
3453        dialog.add_button(_("_Cancel"), Gtk::RESPONSE_CANCEL);
3454        dialog.add_button(_("Merge"), Gtk::RESPONSE_OK);
3455        dialog.set_default_response(Gtk::RESPONSE_CANCEL);
3456    #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
3457        Gtk::FileFilter filter;
3458        filter.add_pattern("*.gig");
3459    #else
3460        Glib::RefPtr<Gtk::FileFilter> filter = Gtk::FileFilter::create();
3461        filter->add_pattern("*.gig");
3462    #endif
3463        dialog.set_filter(filter);
3464        if (current_gig_dir != "") {
3465            dialog.set_current_folder(current_gig_dir);
3466        }
3467        dialog.set_select_multiple(true);
3468    
3469        // show warning in the file picker dialog
3470        Gtk::HBox descriptionArea;
3471        descriptionArea.set_spacing(15);
3472        Gtk::Image warningIcon;
3473        warningIcon.set_from_icon_name("dialog-warning",
3474                                       Gtk::IconSize(Gtk::ICON_SIZE_DIALOG));
3475        descriptionArea.pack_start(warningIcon, Gtk::PACK_SHRINK);
3476    #if GTKMM_MAJOR_VERSION < 3
3477        view::WrapLabel description;
3478    #else
3479        Gtk::Label description;
3480        description.set_line_wrap();
3481    #endif
3482        description.set_markup(_(
3483            "\nSelect at least one .gig file that shall be merged to the .gig file "
3484            "currently being open in gigedit.\n\n"
3485            "<b>Please Note:</b> Merging with other files will modify your "
3486            "currently open .gig file on file level! And be aware that the current "
3487            "merge algorithm does not detect duplicate samples yet. So if you are "
3488            "merging files which are using equivalent sample data, those "
3489            "equivalent samples will currently be treated as separate samples and "
3490            "will accordingly be stored separately in the target .gig file!"
3491        ));
3492        descriptionArea.pack_start(description);
3493        dialog.get_vbox()->pack_start(descriptionArea, Gtk::PACK_SHRINK);
3494        descriptionArea.show_all();
3495    
3496        if (dialog.run() == Gtk::RESPONSE_OK) {
3497            printf("on_action_merge_files self=%p\n",
3498                   static_cast<void*>(Glib::Threads::Thread::self()));
3499            std::vector<std::string> filenames = dialog.get_filenames();
3500    
3501            // merge the selected files to the currently open .gig file
3502            try {
3503                mergeFiles(filenames);
3504            } catch (RIFF::Exception e) {
3505                Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
3506                msg.run();
3507            }
3508    
3509            // update GUI
3510            __refreshEntireGUI();
3511        }
3512    }
3513    
3514  void MainWindow::set_file_is_shared(bool b) {  void MainWindow::set_file_is_shared(bool b) {
3515      this->file_is_shared = b;      this->file_is_shared = b;
3516    
# Line 1548  void MainWindow::set_file_is_shared(bool Line 3525  void MainWindow::set_file_is_shared(bool
3525              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)              Gdk::Pixbuf::create_from_xpm_data(status_detached_xpm)
3526          );          );
3527      }      }
3528    
3529        {
3530            Gtk::MenuItem* item = dynamic_cast<Gtk::MenuItem*>(
3531                uiManager->get_widget("/MenuBar/MenuSettings/SyncSamplerInstrumentSelection"));
3532            if (item) item->set_sensitive(b);
3533        }
3534    }
3535    
3536    void MainWindow::on_sample_ref_count_incremented(gig::Sample* sample, int offset) {
3537        if (!sample) return;
3538        sample_ref_count[sample] += offset;
3539        const int refcount = sample_ref_count[sample];
3540    
3541        Glib::RefPtr<Gtk::TreeModel> model = m_TreeViewSamples.get_model();
3542        for (int g = 0; g < model->children().size(); ++g) {
3543            Gtk::TreeModel::Row rowGroup = model->children()[g];
3544            for (int s = 0; s < rowGroup.children().size(); ++s) {
3545                Gtk::TreeModel::Row rowSample = rowGroup.children()[s];
3546                if (rowSample[m_SamplesModel.m_col_sample] != sample) continue;
3547                rowSample[m_SamplesModel.m_col_refcount] = ToString(refcount) + " " + _("Refs.");
3548                rowSample[m_SamplesModel.m_color] = refcount ? "black" : "red";
3549            }
3550        }
3551    }
3552    
3553    void MainWindow::on_sample_ref_changed(gig::Sample* oldSample, gig::Sample* newSample) {
3554        on_sample_ref_count_incremented(oldSample, -1);
3555        on_sample_ref_count_incremented(newSample, +1);
3556    }
3557    
3558    void MainWindow::on_samples_to_be_removed(std::list<gig::Sample*> samples) {
3559        // just in case a new sample is added later with exactly the same memory
3560        // address, which would lead to incorrect refcount if not deleted here
3561        for (std::list<gig::Sample*>::const_iterator it = samples.begin();
3562             it != samples.end(); ++it)
3563        {
3564            sample_ref_count.erase(*it);
3565        }
3566    }
3567    
3568    void MainWindow::show_samples_tab() {
3569        m_TreeViewNotebook.set_current_page(0);
3570    }
3571    
3572    void MainWindow::show_intruments_tab() {
3573        m_TreeViewNotebook.set_current_page(1);
3574    }
3575    
3576    void MainWindow::show_scripts_tab() {
3577        m_TreeViewNotebook.set_current_page(2);
3578  }  }
3579    
3580  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 1574  sigc::signal<void, gig::Region*>& MainWi Line 3601  sigc::signal<void, gig::Region*>& MainWi
3601      return region_changed_signal;      return region_changed_signal;
3602  }  }
3603    
3604    sigc::signal<void, gig::Sample*>& MainWindow::signal_sample_changed() {
3605        return sample_changed_signal;
3606    }
3607    
3608  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {  sigc::signal<void, gig::Sample*/*old*/, gig::Sample*/*new*/>& MainWindow::signal_sample_ref_changed() {
3609      return sample_ref_changed_signal;      return sample_ref_changed_signal;
3610  }  }
# Line 1585  sigc::signal<void, gig::DimensionRegion* Line 3616  sigc::signal<void, gig::DimensionRegion*
3616  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {  sigc::signal<void, gig::DimensionRegion*>& MainWindow::signal_dimreg_changed() {
3617      return dimreg_changed_signal;      return dimreg_changed_signal;
3618  }  }
3619    
3620    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_on() {
3621        return note_on_signal;
3622    }
3623    
3624    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_note_off() {
3625        return note_off_signal;
3626    }
3627    
3628    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_hit() {
3629        return m_RegionChooser.signal_keyboard_key_hit();
3630    }
3631    
3632    sigc::signal<void, int/*key*/, int/*velocity*/>& MainWindow::signal_keyboard_key_released() {
3633        return m_RegionChooser.signal_keyboard_key_released();
3634    }
3635    
3636    sigc::signal<void, gig::Instrument*>& MainWindow::signal_switch_sampler_instrument() {
3637        return switch_sampler_instrument_signal;
3638    }

Legend:
Removed from v.1415  
changed lines
  Added in v.3106

  ViewVC Help
Powered by ViewVC