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

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

  ViewVC Help
Powered by ViewVC