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

Annotation of /gigedit/trunk/src/gigedit/CombineInstrumentsDialog.cpp

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3782 - (hide annotations) (download)
Fri May 29 23:25:06 2020 UTC (3 years, 10 months ago) by schoenebeck
File size: 54952 byte(s)
Combi Tool: Minor correction to debug message
(make it clear shown dimension type is a hex value).

1 schoenebeck 2548 /*
2 schoenebeck 3762 Copyright (c) 2014-2020 Christian Schoenebeck
3    
4 schoenebeck 2548 This file is part of "gigedit" and released under the terms of the
5     GNU General Public License version 2.
6     */
7    
8 persson 3202 #include "global.h"
9 schoenebeck 2548 #include "CombineInstrumentsDialog.h"
10    
11     // enable this for debug messages being printed while combining the instruments
12     #define DEBUG_COMBINE_INSTRUMENTS 0
13    
14 schoenebeck 2558 #include "compat.h"
15 schoenebeck 2548
16     #include <set>
17     #include <iostream>
18     #include <assert.h>
19 schoenebeck 2552 #include <stdarg.h>
20     #include <string.h>
21 schoenebeck 2548
22     #include <glibmm/ustring.h>
23 schoenebeck 3364 #if HAS_GTKMM_STOCK
24     # include <gtkmm/stock.h>
25     #endif
26 schoenebeck 2548 #include <gtkmm/messagedialog.h>
27 schoenebeck 2558 #include <gtkmm/label.h>
28 schoenebeck 3301 #include <gtk/gtkwidget.h> // for gtk_widget_modify_*()
29 schoenebeck 2548
30 schoenebeck 2558 Glib::ustring dimTypeAsString(gig::dimension_t d);
31 schoenebeck 2548
32 schoenebeck 2558 typedef std::vector< std::pair<gig::Instrument*, gig::Region*> > OrderedRegionGroup;
33 schoenebeck 2548 typedef std::map<gig::Instrument*, gig::Region*> RegionGroup;
34     typedef std::map<DLS::range_t,RegionGroup> RegionGroups;
35    
36     typedef std::vector<DLS::range_t> DimensionZones;
37     typedef std::map<gig::dimension_t,DimensionZones> Dimensions;
38    
39     typedef std::map<gig::dimension_t, int> DimensionRegionUpperLimits;
40    
41 schoenebeck 2552 typedef std::set<Glib::ustring> Warnings;
42    
43 schoenebeck 2548 ///////////////////////////////////////////////////////////////////////////
44 schoenebeck 2552 // private static data
45    
46     static Warnings g_warnings;
47    
48     ///////////////////////////////////////////////////////////////////////////
49 schoenebeck 2548 // private functions
50    
51     #if DEBUG_COMBINE_INSTRUMENTS
52     static void printRanges(const RegionGroups& regions) {
53     std::cout << "{ ";
54     for (RegionGroups::const_iterator it = regions.begin(); it != regions.end(); ++it) {
55     if (it != regions.begin()) std::cout << ", ";
56     std::cout << (int)it->first.low << ".." << (int)it->first.high;
57     }
58     std::cout << " }" << std::flush;
59     }
60     #endif
61    
62     /**
63 schoenebeck 2552 * Store a warning message that shall be stored and displayed to the user as a
64     * list of warnings after the overall operation has finished. Duplicate warning
65     * messages are automatically eliminated.
66     */
67     inline void addWarning(const char* fmt, ...) {
68     va_list arg;
69     va_start(arg, fmt);
70     const int SZ = 255 + strlen(fmt);
71     char* buf = new char[SZ];
72     vsnprintf(buf, SZ, fmt, arg);
73     Glib::ustring s = buf;
74     delete [] buf;
75     va_end(arg);
76     std::cerr << _("WARNING:") << " " << s << std::endl << std::flush;
77     g_warnings.insert(s);
78     }
79    
80     /**
81 schoenebeck 2548 * If the two ranges overlap, then this function returns the smallest point
82     * within that overlapping zone. If the two ranges do not overlap, then this
83     * function will return -1 instead.
84     */
85     inline int smallestOverlapPoint(const DLS::range_t& r1, const DLS::range_t& r2) {
86     if (r1.overlaps(r2.low)) return r2.low;
87     if (r2.overlaps(r1.low)) return r1.low;
88     return -1;
89     }
90    
91     /**
92     * Get the most smallest region point (not necessarily its region start point)
93     * of all regions of the given instruments, start searching at keyboard
94     * position @a iStart.
95     *
96     * @returns very first region point >= iStart, or -1 if no region could be
97     * found with a range member point >= iStart
98     */
99     static int findLowestRegionPoint(std::vector<gig::Instrument*>& instruments, int iStart) {
100 persson 2841 DLS::range_t searchRange = { uint16_t(iStart), 127 };
101 schoenebeck 2548 int result = -1;
102     for (uint i = 0; i < instruments.size(); ++i) {
103     gig::Instrument* instr = instruments[i];
104     for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
105     if (rgn->KeyRange.overlaps(searchRange)) {
106     int lowest = smallestOverlapPoint(rgn->KeyRange, searchRange);
107     if (result == -1 || lowest < result) result = lowest;
108     }
109     }
110     }
111     return result;
112     }
113    
114     /**
115     * Get the most smallest region end of all regions of the given instruments,
116     * start searching at keyboard position @a iStart.
117     *
118     * @returns very first region end >= iStart, or -1 if no region could be found
119     * with a range end >= iStart
120     */
121     static int findFirstRegionEnd(std::vector<gig::Instrument*>& instruments, int iStart) {
122 persson 2841 DLS::range_t searchRange = { uint16_t(iStart), 127 };
123 schoenebeck 2548 int result = -1;
124     for (uint i = 0; i < instruments.size(); ++i) {
125     gig::Instrument* instr = instruments[i];
126     for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
127     if (rgn->KeyRange.overlaps(searchRange)) {
128     if (result == -1 || rgn->KeyRange.high < result)
129     result = rgn->KeyRange.high;
130     }
131     }
132     }
133     return result;
134     }
135    
136     /**
137     * Returns a list of all regions of the given @a instrument where the respective
138     * region's key range overlaps the given @a range.
139     */
140     static std::vector<gig::Region*> getAllRegionsWhichOverlapRange(gig::Instrument* instrument, DLS::range_t range) {
141     //std::cout << "All regions which overlap { " << (int)range.low << ".." << (int)range.high << " } : " << std::flush;
142     std::vector<gig::Region*> v;
143     for (gig::Region* rgn = instrument->GetFirstRegion(); rgn; rgn = instrument->GetNextRegion()) {
144     if (rgn->KeyRange.overlaps(range)) {
145     v.push_back(rgn);
146     //std::cout << (int)rgn->KeyRange.low << ".." << (int)rgn->KeyRange.high << ", " << std::flush;
147     }
148     }
149     //std::cout << " END." << std::endl;
150     return v;
151     }
152    
153     /**
154     * Returns all regions of the given @a instruments where the respective region's
155     * key range overlaps the given @a range. The regions returned are ordered (in a
156     * map) by their instrument pointer.
157     */
158     static RegionGroup getAllRegionsWhichOverlapRange(std::vector<gig::Instrument*>& instruments, DLS::range_t range) {
159     RegionGroup group;
160     for (uint i = 0; i < instruments.size(); ++i) {
161     gig::Instrument* instr = instruments[i];
162     std::vector<gig::Region*> v = getAllRegionsWhichOverlapRange(instr, range);
163     if (v.empty()) continue;
164     if (v.size() > 1) {
165 schoenebeck 2552 addWarning("More than one region found!");
166 schoenebeck 2548 }
167     group[instr] = v[0];
168     }
169     return group;
170     }
171    
172     /** @brief Identify required regions.
173     *
174     * Takes a list of @a instruments as argument (which are planned to be combined
175 schoenebeck 2558 * as separate dimension zones of a certain dimension into one single new
176     * instrument) and fulfills the following tasks:
177 schoenebeck 2548 *
178     * - 1. Identification of total amount of regions required to create a new
179 schoenebeck 2558 * instrument to become a combined version of the given instruments.
180 schoenebeck 2548 * - 2. Precise key range of each of those identified required regions to be
181     * created in that new instrument.
182     * - 3. Grouping the original source regions of the given original instruments
183     * to the respective target key range (new region) of the instrument to be
184     * created.
185     *
186     * @param instruments - list of instruments that are planned to be combined
187     * @returns structured result of the tasks described above
188     */
189     static RegionGroups groupByRegionIntersections(std::vector<gig::Instrument*>& instruments) {
190     RegionGroups groups;
191    
192     // find all region intersections of all instruments
193     std::vector<DLS::range_t> intersections;
194     for (int iStart = 0; iStart <= 127; ) {
195     iStart = findLowestRegionPoint(instruments, iStart);
196     if (iStart < 0) break;
197     const int iEnd = findFirstRegionEnd(instruments, iStart);
198 persson 2841 DLS::range_t range = { uint16_t(iStart), uint16_t(iEnd) };
199 schoenebeck 2548 intersections.push_back(range);
200     iStart = iEnd + 1;
201     }
202    
203     // now sort all regions to those found intersections
204     for (uint i = 0; i < intersections.size(); ++i) {
205     const DLS::range_t& range = intersections[i];
206     RegionGroup group = getAllRegionsWhichOverlapRange(instruments, range);
207     if (!group.empty())
208     groups[range] = group;
209     else
210 schoenebeck 2552 addWarning("Empty region group!");
211 schoenebeck 2548 }
212    
213     return groups;
214     }
215    
216     /** @brief Identify required dimensions.
217     *
218     * Takes a planned new region (@a regionGroup) as argument and identifies which
219     * precise dimensions would have to be created for that new region, along with
220 schoenebeck 3781 * the amount of dimension zones.
221 schoenebeck 2548 *
222     * @param regionGroup - planned new region for a new instrument
223     * @returns set of dimensions that shall be created for the given planned region
224     */
225     static Dimensions getDimensionsForRegionGroup(RegionGroup& regionGroup) {
226     std::map<gig::dimension_t, std::set<int> > dimUpperLimits;
227    
228 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
229     printf("dimUpperLimits = {\n");
230     #endif
231 schoenebeck 2548 // collect all dimension region zones' upper limits
232     for (RegionGroup::iterator it = regionGroup.begin();
233     it != regionGroup.end(); ++it)
234     {
235     gig::Region* rgn = it->second;
236     int previousBits = 0;
237     for (uint d = 0; d < rgn->Dimensions; ++d) {
238     const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
239 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
240     printf("\t[rgn=%p,dim=%#x] = {", rgn, def.dimension);
241     #endif
242 schoenebeck 2548 for (uint z = 0; z < def.zones; ++z) {
243     int dr = z << previousBits;
244     gig::DimensionRegion* dimRgn = rgn->pDimensionRegions[dr];
245 schoenebeck 3781 // NOTE: Originally this function collected dimensions' upper
246     // limits. However that caused combined instruments (e.g. with
247     // unequal dimension zone counts, not being a power of two) to
248     // end up having too many dimension zones and those extra zones
249     // containing no sample. For that reason we simply collect the
250     // required amount of output dimension zones here now instead.
251 schoenebeck 3780 const int upperLimit =
252 schoenebeck 3781 /*
253 schoenebeck 2548 (def.dimension == gig::dimension_velocity) ?
254     z : (def.split_type == gig::split_type_bit) ?
255 schoenebeck 3780 ((z+1) * 128/def.zones - 1) : dimRgn->DimensionUpperLimits[dr];
256 schoenebeck 3781 */
257     z;
258 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
259     printf(" %d,", upperLimit);
260     #endif
261     dimUpperLimits[def.dimension].insert(upperLimit);
262 schoenebeck 2548 }
263     previousBits += def.bits;
264 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
265     printf(" }\n");
266     #endif
267 schoenebeck 2548 }
268     }
269 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
270     printf("}\n");
271     #endif
272 schoenebeck 2548
273     // convert upper limit set to range vector
274     Dimensions dims;
275 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
276     printf("dims = {\n");
277     #endif
278 schoenebeck 2548 for (std::map<gig::dimension_t, std::set<int> >::const_iterator it = dimUpperLimits.begin();
279     it != dimUpperLimits.end(); ++it)
280     {
281     gig::dimension_t type = it->first;
282 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
283     printf("\t[dim=%#x] = {", type);
284     #endif
285 schoenebeck 2548 int iLow = 0;
286     for (std::set<int>::const_iterator itNums = it->second.begin();
287     itNums != it->second.end(); ++itNums)
288     {
289     const int iUpperLimit = *itNums;
290 persson 2841 DLS::range_t range = { uint16_t(iLow), uint16_t(iUpperLimit) };
291 schoenebeck 2548 dims[type].push_back(range);
292 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
293     printf(" %d..%d,", iLow, iUpperLimit);
294     #endif
295 schoenebeck 2548 iLow = iUpperLimit + 1;
296     }
297 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
298     printf(" }\n");
299     #endif
300 schoenebeck 2548 }
301 schoenebeck 3780 #if DEBUG_COMBINE_INSTRUMENTS
302     printf("}\n");
303     #endif
304 schoenebeck 2548
305     return dims;
306     }
307    
308     static void fillDimValues(uint* values/*[8]*/, DimensionCase dimCase, gig::Region* rgn, bool bShouldHaveAllDimensionsPassed) {
309 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
310     printf("dimvalues = { ");
311     fflush(stdout);
312     #endif
313 schoenebeck 2548 for (DimensionCase::iterator it = dimCase.begin(); it != dimCase.end(); ++it) {
314     gig::dimension_t type = it->first;
315     int iDimIndex = getDimensionIndex(type, rgn);
316     if (bShouldHaveAllDimensionsPassed) assert(iDimIndex >= 0);
317     else if (iDimIndex < 0) continue;
318     values[iDimIndex] = it->second;
319 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
320 schoenebeck 3782 printf("0x%x=%d, ", type, it->second);
321 schoenebeck 2550 #endif
322 schoenebeck 2548 }
323 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
324 schoenebeck 2558 printf("}\n");
325 schoenebeck 2550 #endif
326 schoenebeck 2548 }
327    
328     static DimensionRegionUpperLimits getDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn) {
329     DimensionRegionUpperLimits limits;
330     gig::Region* rgn = dimRgn->GetParent();
331 schoenebeck 2549 for (uint d = 0; d < rgn->Dimensions; ++d) {
332 schoenebeck 2548 const gig::dimension_def_t& def = rgn->pDimensionDefinitions[d];
333     limits[def.dimension] = dimRgn->DimensionUpperLimits[d];
334     }
335     return limits;
336     }
337    
338     static void restoreDimensionRegionUpperLimits(gig::DimensionRegion* dimRgn, const DimensionRegionUpperLimits& limits) {
339     gig::Region* rgn = dimRgn->GetParent();
340     for (DimensionRegionUpperLimits::const_iterator it = limits.begin();
341     it != limits.end(); ++it)
342     {
343     int index = getDimensionIndex(it->first, rgn);
344     assert(index >= 0);
345     dimRgn->DimensionUpperLimits[index] = it->second;
346     }
347     }
348    
349     inline int dimensionRegionIndex(gig::DimensionRegion* dimRgn) {
350     gig::Region* rgn = dimRgn->GetParent();
351     int sz = sizeof(rgn->pDimensionRegions) / sizeof(gig::DimensionRegion*);
352     for (int i = 0; i < sz; ++i)
353     if (rgn->pDimensionRegions[i] == dimRgn)
354     return i;
355     return -1;
356     }
357    
358     /** @brief Get exact zone ranges of given dimension.
359     *
360     * This function is useful for the velocity type dimension. In contrast to other
361     * dimension types, this dimension can have different zone ranges (that is
362     * different individual start and end points of its dimension zones) depending
363     * on which zones of other dimensions (on that gig::Region) are currently
364     * selected.
365     *
366     * @param type - dimension where the zone ranges should be retrieved for
367     * (usually the velocity dimension in this context)
368     * @param dimRgn - reflects the exact cases (zone selections) of all other
369     * dimensions than the given one in question
370     * @returns individual ranges for each zone of the questioned dimension type,
371     * it returns an empty result on errors instead
372     */
373     static DimensionZones preciseDimensionZonesFor(gig::dimension_t type, gig::DimensionRegion* dimRgn) {
374     DimensionZones zones;
375     gig::Region* rgn = dimRgn->GetParent();
376     int iDimension = getDimensionIndex(type, rgn);
377     if (iDimension < 0) return zones;
378     const gig::dimension_def_t& def = rgn->pDimensionDefinitions[iDimension];
379     int iDimRgn = dimensionRegionIndex(dimRgn);
380     int iBaseBits = baseBits(type, rgn);
381 schoenebeck 3089 assert(iBaseBits >= 0);
382 schoenebeck 2548 int mask = ~(((1 << def.bits) - 1) << iBaseBits);
383    
384 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
385     printf("velo zones { ");
386     fflush(stdout);
387     #endif
388 schoenebeck 2548 int iLow = 0;
389     for (int z = 0; z < def.zones; ++z) {
390     gig::DimensionRegion* dimRgn2 =
391     rgn->pDimensionRegions[ (iDimRgn & mask) | ( z << iBaseBits) ];
392     int iHigh = dimRgn2->DimensionUpperLimits[iDimension];
393 persson 2841 DLS::range_t range = { uint16_t(iLow), uint16_t(iHigh) };
394 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
395     printf("%d..%d, ", iLow, iHigh);
396     fflush(stdout);
397     #endif
398 schoenebeck 2548 zones.push_back(range);
399     iLow = iHigh + 1;
400     }
401 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
402     printf("}\n");
403     #endif
404 schoenebeck 2548 return zones;
405     }
406    
407 schoenebeck 2550 struct CopyAssignSchedEntry {
408     gig::DimensionRegion* src;
409     gig::DimensionRegion* dst;
410     int velocityZone;
411     int totalSrcVelocityZones;
412     };
413     typedef std::vector<CopyAssignSchedEntry> CopyAssignSchedule;
414 schoenebeck 2549
415 schoenebeck 2558 /** @brief Schedule copying DimensionRegions from source Region to target Region.
416 schoenebeck 2548 *
417 schoenebeck 2558 * Schedules copying the entire articulation informations (including sample
418     * reference) from all individual DimensionRegions of source Region @a inRgn to
419     * target Region @a outRgn. It is expected that the required dimensions (thus
420     * the required dimension regions) were already created before calling this
421     * function.
422 schoenebeck 2548 *
423 schoenebeck 2558 * To be precise, it does the task above only for the dimension zones defined by
424     * the three arguments @a mainDim, @a iSrcMainBit, @a iDstMainBit, which reflect
425     * a selection which dimension zones shall be copied. All other dimension zones
426     * will not be scheduled to be copied by a single call of this function. So this
427     * function needs to be called several time in case all dimension regions shall
428     * be copied of the entire region (@a inRgn, @a outRgn).
429 schoenebeck 2548 *
430     * @param outRgn - where the dimension regions shall be copied to
431     * @param inRgn - all dimension regions that shall be copied from
432 schoenebeck 2550 * @param dims - precise dimension definitions of target region
433 schoenebeck 2558 * @param mainDim - this dimension type, in combination with @a iSrcMainBit and
434     * @a iDstMainBit defines a selection which dimension region
435     * zones shall be copied by this call of this function
436     * @param iDstMainBit - destination bit of @a mainDim
437     * @param iSrcMainBit - source bit of @a mainDim
438     * @param schedule - list of all DimensionRegion copy operations which is filled
439     * during the nested loops / recursions of this function call
440 schoenebeck 2548 * @param dimCase - just for internal purpose (function recursion), don't pass
441     * anything here, this function will call itself recursively
442     * will fill this container with concrete dimension values for
443     * selecting the precise dimension regions during its task
444     */
445 schoenebeck 2558 static void scheduleCopyDimensionRegions(gig::Region* outRgn, gig::Region* inRgn,
446     Dimensions dims, gig::dimension_t mainDim,
447     int iDstMainBit, int iSrcMainBit,
448     CopyAssignSchedule* schedule,
449     DimensionCase dimCase = DimensionCase())
450     {
451 schoenebeck 2550 if (dims.empty()) { // reached deepest level of function recursion ...
452     CopyAssignSchedEntry e;
453    
454 schoenebeck 2548 // resolve the respective source & destination DimensionRegion ...
455     uint srcDimValues[8] = {};
456     uint dstDimValues[8] = {};
457     DimensionCase srcDimCase = dimCase;
458     DimensionCase dstDimCase = dimCase;
459 schoenebeck 2617 srcDimCase[mainDim] = iSrcMainBit;
460     dstDimCase[mainDim] = iDstMainBit;
461 schoenebeck 2548
462 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
463     printf("-------------------------------\n");
464 schoenebeck 2558 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
465 schoenebeck 2550 #endif
466    
467 schoenebeck 2548 // first select source & target dimension region with an arbitrary
468     // velocity split zone, to get access to the precise individual velocity
469     // split zone sizes (if there is actually a velocity dimension at all,
470     // otherwise we already select the desired source & target dimension
471     // region here)
472 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
473     printf("src "); fflush(stdout);
474     #endif
475 schoenebeck 2548 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
476 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
477     printf("dst "); fflush(stdout);
478     #endif
479 schoenebeck 2617 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
480 schoenebeck 2548 gig::DimensionRegion* srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
481     gig::DimensionRegion* dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
482 schoenebeck 2549 #if DEBUG_COMBINE_INSTRUMENTS
483 schoenebeck 2558 printf("iDstMainBit=%d iSrcMainBit=%d\n", iDstMainBit, iSrcMainBit);
484 schoenebeck 2549 printf("srcDimRgn=%lx dstDimRgn=%lx\n", (uint64_t)srcDimRgn, (uint64_t)dstDimRgn);
485 schoenebeck 2550 printf("srcSample='%s' dstSample='%s'\n",
486     (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str()),
487     (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str())
488     );
489 schoenebeck 2549 #endif
490 schoenebeck 2548
491 schoenebeck 2550 assert(srcDimRgn->GetParent() == inRgn);
492     assert(dstDimRgn->GetParent() == outRgn);
493    
494 schoenebeck 2548 // now that we have access to the precise velocity split zone upper
495     // limits, we can select the actual source & destination dimension
496     // regions we need to copy (assuming that source or target region has
497     // a velocity dimension)
498     if (outRgn->GetDimensionDefinition(gig::dimension_velocity)) {
499 schoenebeck 2550 // re-select target dimension region (with correct velocity zone)
500     DimensionZones dstZones = preciseDimensionZonesFor(gig::dimension_velocity, dstDimRgn);
501 schoenebeck 2549 assert(dstZones.size() > 1);
502 schoenebeck 2558 const int iDstZoneIndex =
503     (mainDim == gig::dimension_velocity)
504     ? iDstMainBit : dstDimCase[gig::dimension_velocity]; // (mainDim == gig::dimension_velocity) exception case probably unnecessary here
505     e.velocityZone = iDstZoneIndex;
506 schoenebeck 2549 #if DEBUG_COMBINE_INSTRUMENTS
507 schoenebeck 2558 printf("dst velocity zone: %d/%d\n", iDstZoneIndex, (int)dstZones.size());
508 schoenebeck 2549 #endif
509 schoenebeck 2558 assert(uint(iDstZoneIndex) < dstZones.size());
510     dstDimCase[gig::dimension_velocity] = dstZones[iDstZoneIndex].low; // arbitrary value between low and high
511 schoenebeck 2549 #if DEBUG_COMBINE_INSTRUMENTS
512     printf("dst velocity value = %d\n", dstDimCase[gig::dimension_velocity]);
513 schoenebeck 2550 printf("dst refilled "); fflush(stdout);
514 schoenebeck 2549 #endif
515 schoenebeck 2617 fillDimValues(dstDimValues, dstDimCase, outRgn, false);
516 schoenebeck 2548 dstDimRgn = outRgn->GetDimensionRegionByValue(dstDimValues);
517 schoenebeck 2549 #if DEBUG_COMBINE_INSTRUMENTS
518     printf("reselected dstDimRgn=%lx\n", (uint64_t)dstDimRgn);
519 schoenebeck 2558 printf("dstSample='%s'%s\n",
520     (!dstDimRgn->pSample ? "NULL" : dstDimRgn->pSample->pInfo->Name.c_str()),
521     (dstDimRgn->pSample ? " <--- ERROR ERROR ERROR !!!!!!!!! " : "")
522 schoenebeck 2550 );
523 schoenebeck 2549 #endif
524 schoenebeck 2548
525 schoenebeck 2550 // re-select source dimension region with correct velocity zone
526     // (if it has a velocity dimension that is)
527 schoenebeck 2548 if (inRgn->GetDimensionDefinition(gig::dimension_velocity)) {
528 schoenebeck 2549 DimensionZones srcZones = preciseDimensionZonesFor(gig::dimension_velocity, srcDimRgn);
529 schoenebeck 2550 e.totalSrcVelocityZones = srcZones.size();
530 schoenebeck 2552 assert(srcZones.size() > 0);
531     if (srcZones.size() <= 1) {
532     addWarning("Input region has a velocity dimension with only ONE zone!");
533     }
534 schoenebeck 2558 int iSrcZoneIndex =
535     (mainDim == gig::dimension_velocity)
536     ? iSrcMainBit : iDstZoneIndex;
537     if (uint(iSrcZoneIndex) >= srcZones.size())
538     iSrcZoneIndex = srcZones.size() - 1;
539     srcDimCase[gig::dimension_velocity] = srcZones[iSrcZoneIndex].low; // same zone as used above for target dimension region (no matter what the precise zone ranges are)
540 schoenebeck 2550 #if DEBUG_COMBINE_INSTRUMENTS
541     printf("src refilled "); fflush(stdout);
542     #endif
543 schoenebeck 2548 fillDimValues(srcDimValues, srcDimCase, inRgn, false);
544     srcDimRgn = inRgn->GetDimensionRegionByValue(srcDimValues);
545 schoenebeck 2549 #if DEBUG_COMBINE_INSTRUMENTS
546     printf("reselected srcDimRgn=%lx\n", (uint64_t)srcDimRgn);
547 schoenebeck 2550 printf("srcSample='%s'\n",
548     (!srcDimRgn->pSample ? "NULL" : srcDimRgn->pSample->pInfo->Name.c_str())
549     );
550 schoenebeck 2549 #endif
551 schoenebeck 2548 }
552     }
553    
554 schoenebeck 2558 // Schedule copy operation of source -> target DimensionRegion for the
555 schoenebeck 2550 // time after all nested loops have been traversed. We have to postpone
556     // the actual copy operations this way, because otherwise it would
557     // overwrite informations inside the destination DimensionRegion object
558     // that we need to read in the code block above.
559     e.src = srcDimRgn;
560     e.dst = dstDimRgn;
561     schedule->push_back(e);
562 schoenebeck 2548
563 schoenebeck 2550 return; // returning from deepest level of function recursion
564 schoenebeck 2548 }
565    
566 schoenebeck 2549 // Copying n dimensions requires n nested loops. That's why this function
567     // is calling itself recursively to provide the required amount of nested
568     // loops. With each call it pops from argument 'dims' and pushes to
569     // argument 'dimCase'.
570    
571 schoenebeck 2548 Dimensions::iterator itDimension = dims.begin();
572     gig::dimension_t type = itDimension->first;
573     DimensionZones zones = itDimension->second;
574     dims.erase(itDimension);
575    
576     int iZone = 0;
577     for (DimensionZones::iterator itZone = zones.begin();
578     itZone != zones.end(); ++itZone, ++iZone)
579     {
580     DLS::range_t zoneRange = *itZone;
581     gig::dimension_def_t* def = outRgn->GetDimensionDefinition(type);
582     dimCase[type] = (def->split_type == gig::split_type_bit) ? iZone : zoneRange.low;
583 schoenebeck 2550
584 schoenebeck 2548 // recurse until 'dims' is exhausted (and dimCase filled up with concrete value)
585 schoenebeck 2558 scheduleCopyDimensionRegions(outRgn, inRgn, dims, mainDim, iDstMainBit, iSrcMainBit, schedule, dimCase);
586 schoenebeck 2548 }
587 schoenebeck 2558 }
588 schoenebeck 2550
589 schoenebeck 2558 static OrderedRegionGroup sortRegionGroup(const RegionGroup& group, const std::vector<gig::Instrument*>& instruments) {
590     OrderedRegionGroup result;
591     for (std::vector<gig::Instrument*>::const_iterator it = instruments.begin();
592     it != instruments.end(); ++it)
593     {
594     RegionGroup::const_iterator itRgn = group.find(*it);
595     if (itRgn == group.end()) continue;
596     result.push_back(
597     std::pair<gig::Instrument*, gig::Region*>(
598     itRgn->first, itRgn->second
599     )
600     );
601 schoenebeck 2550 }
602 schoenebeck 2558 return result;
603 schoenebeck 2548 }
604    
605     /** @brief Combine given list of instruments to one instrument.
606     *
607     * Takes a list of @a instruments as argument and combines them to one single
608 schoenebeck 2558 * new @a output instrument. For this task, it will create a dimension of type
609     * given by @a mainDimension in the new instrument and copies the source
610     * instruments to those dimension zones.
611 schoenebeck 2548 *
612     * @param instruments - (input) list of instruments that shall be combined,
613     * they will only be read, so they will be left untouched
614     * @param gig - (input/output) .gig file where the new combined instrument shall
615     * be created
616     * @param output - (output) on success this pointer will be set to the new
617     * instrument being created
618 schoenebeck 2558 * @param mainDimension - the dimension that shall be used to combine the
619     * instruments
620 schoenebeck 2548 * @throw RIFF::Exception on any kinds of errors
621     */
622 schoenebeck 2558 static void combineInstruments(std::vector<gig::Instrument*>& instruments, gig::File* gig, gig::Instrument*& output, gig::dimension_t mainDimension) {
623 schoenebeck 2548 output = NULL;
624    
625     // divide the individual regions to (probably even smaller) groups of
626     // regions, coping with the fact that the source regions of the instruments
627     // might have quite different range sizes and start and end points
628     RegionGroups groups = groupByRegionIntersections(instruments);
629     #if DEBUG_COMBINE_INSTRUMENTS
630     std::cout << std::endl << "New regions: " << std::flush;
631     printRanges(groups);
632     std::cout << std::endl;
633     #endif
634    
635     if (groups.empty())
636     throw gig::Exception(_("No regions found to create a new instrument with."));
637    
638     // create a new output instrument
639     gig::Instrument* outInstr = gig->AddInstrument();
640 schoenebeck 2549 outInstr->pInfo->Name = _("NEW COMBINATION");
641 schoenebeck 2548
642     // Distinguishing in the following code block between 'horizontal' and
643     // 'vertical' regions. The 'horizontal' ones are meant to be the key ranges
644     // in the output instrument, while the 'vertical' regions are meant to be
645     // the set of source regions that shall be layered to that 'horizontal'
646     // region / key range. It is important to know, that the key ranges defined
647     // in the 'horizontal' and 'vertical' regions might differ.
648    
649     // merge the instruments to the new output instrument
650     for (RegionGroups::iterator itGroup = groups.begin();
651     itGroup != groups.end(); ++itGroup) // iterate over 'horizontal' / target regions ...
652     {
653     gig::Region* outRgn = outInstr->AddRegion();
654     outRgn->SetKeyRange(itGroup->first.low, itGroup->first.high);
655 schoenebeck 2552 #if DEBUG_COMBINE_INSTRUMENTS
656     printf("---> Start target region %d..%d\n", itGroup->first.low, itGroup->first.high);
657     #endif
658 schoenebeck 2548
659 schoenebeck 2558 // detect the total amount of zones required for the given main
660     // dimension to build up this combi for current key range
661     int iTotalZones = 0;
662 schoenebeck 2548 for (RegionGroup::iterator itRgn = itGroup->second.begin();
663     itRgn != itGroup->second.end(); ++itRgn)
664     {
665     gig::Region* inRgn = itRgn->second;
666 schoenebeck 2558 gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
667     iTotalZones += (def) ? def->zones : 1;
668 schoenebeck 2548 }
669 schoenebeck 2552 #if DEBUG_COMBINE_INSTRUMENTS
670 schoenebeck 2616 printf("Required total zones: %d, vertical regions: %d\n", iTotalZones, itGroup->second.size());
671 schoenebeck 2552 #endif
672 schoenebeck 2558
673 schoenebeck 2548 // create all required dimensions for this output region
674 schoenebeck 2558 // (except the main dimension used for separating the individual
675     // instruments, we create that particular dimension as next step)
676 schoenebeck 2548 Dimensions dims = getDimensionsForRegionGroup(itGroup->second);
677 schoenebeck 2558 // the given main dimension which is used to combine the instruments is
678     // created separately after the next code block, and the main dimension
679     // should not be part of dims here, because it also used for iterating
680     // all dimensions zones, which would lead to this dimensions being
681     // iterated twice
682     dims.erase(mainDimension);
683 schoenebeck 2548 {
684 schoenebeck 2552 std::vector<gig::dimension_t> skipTheseDimensions; // used to prevent a misbehavior (i.e. crash) of the combine algorithm in case one of the source instruments has a dimension with only one zone, which is not standard conform
685 schoenebeck 2548
686 schoenebeck 2552 for (Dimensions::iterator itDim = dims.begin();
687     itDim != dims.end(); ++itDim)
688     {
689     gig::dimension_def_t def;
690     def.dimension = itDim->first; // dimension type
691     def.zones = itDim->second.size();
692     def.bits = zoneCountToBits(def.zones);
693     if (def.zones < 2) {
694     addWarning(
695     "Attempt to create dimension with type=0x%x with only "
696     "ONE zone (because at least one of the source "
697     "instruments seems to have such a velocity dimension "
698     "with only ONE zone, which is odd)! Skipping this "
699     "dimension for now.",
700     (int)itDim->first
701     );
702     skipTheseDimensions.push_back(itDim->first);
703     continue;
704     }
705     #if DEBUG_COMBINE_INSTRUMENTS
706     std::cout << "Adding new regular dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
707     #endif
708     outRgn->AddDimension(&def);
709     #if DEBUG_COMBINE_INSTRUMENTS
710     std::cout << "OK" << std::endl << std::flush;
711     #endif
712     }
713     // prevent the following dimensions to be processed further below
714     // (since the respective dimension was not created above)
715     for (int i = 0; i < skipTheseDimensions.size(); ++i)
716     dims.erase(skipTheseDimensions[i]);
717 schoenebeck 2548 }
718    
719 schoenebeck 2558 // create the main dimension (if necessary for current key range)
720     if (iTotalZones > 1) {
721 schoenebeck 2548 gig::dimension_def_t def;
722 schoenebeck 2558 def.dimension = mainDimension; // dimension type
723     def.zones = iTotalZones;
724 schoenebeck 2548 def.bits = zoneCountToBits(def.zones);
725     #if DEBUG_COMBINE_INSTRUMENTS
726 schoenebeck 2558 std::cout << "Adding new main combi dimension type=" << std::hex << (int)def.dimension << std::dec << ", zones=" << (int)def.zones << ", bits=" << (int)def.bits << " ... " << std::flush;
727 schoenebeck 2548 #endif
728     outRgn->AddDimension(&def);
729     #if DEBUG_COMBINE_INSTRUMENTS
730     std::cout << "OK" << std::endl << std::flush;
731     #endif
732 schoenebeck 2616 } else {
733     dims.erase(mainDimension);
734 schoenebeck 2548 }
735    
736 schoenebeck 2558 // for the next task we need to have the current RegionGroup to be
737     // sorted by instrument in the same sequence as the 'instruments' vector
738     // argument passed to this function (because the std::map behind the
739     // 'RegionGroup' type sorts by memory address instead, and that would
740     // sometimes lead to the source instruments' region to be sorted into
741     // the wrong target layer)
742     OrderedRegionGroup currentGroup = sortRegionGroup(itGroup->second, instruments);
743    
744     // schedule copying the source dimension regions to the target dimension
745     // regions
746     CopyAssignSchedule schedule;
747     int iDstMainBit = 0;
748     for (OrderedRegionGroup::iterator itRgn = currentGroup.begin();
749     itRgn != currentGroup.end(); ++itRgn) // iterate over 'vertical' / source regions ...
750 schoenebeck 2548 {
751     gig::Region* inRgn = itRgn->second;
752 schoenebeck 2552 #if DEBUG_COMBINE_INSTRUMENTS
753     printf("[source region of '%s']\n", inRgn->GetParent()->pInfo->Name.c_str());
754     #endif
755 schoenebeck 2558
756     // determine how many main dimension zones this input region requires
757     gig::dimension_def_t* def = inRgn->GetDimensionDefinition(mainDimension);
758     const int inRgnMainZones = (def) ? def->zones : 1;
759    
760     for (uint iSrcMainBit = 0; iSrcMainBit < inRgnMainZones; ++iSrcMainBit, ++iDstMainBit) {
761     scheduleCopyDimensionRegions(
762     outRgn, inRgn, dims, mainDimension,
763     iDstMainBit, iSrcMainBit, &schedule
764     );
765 schoenebeck 2548 }
766     }
767 schoenebeck 2558
768     // finally copy the scheduled source -> target dimension regions
769     for (uint i = 0; i < schedule.size(); ++i) {
770     CopyAssignSchedEntry& e = schedule[i];
771    
772     // backup the target DimensionRegion's current dimension zones upper
773     // limits (because the target DimensionRegion's upper limits are
774     // already defined correctly since calling AddDimension(), and the
775     // CopyAssign() call next, will overwrite those upper limits
776     // unfortunately
777     DimensionRegionUpperLimits dstUpperLimits = getDimensionRegionUpperLimits(e.dst);
778     DimensionRegionUpperLimits srcUpperLimits = getDimensionRegionUpperLimits(e.src);
779    
780     // now actually copy over the current DimensionRegion
781     const gig::Region* const origRgn = e.dst->GetParent(); // just for sanity check below
782     e.dst->CopyAssign(e.src);
783     assert(origRgn == e.dst->GetParent()); // if gigedit is crashing here, then you must update libgig (to at least SVN r2547, v3.3.0.svn10)
784    
785     // restore all original dimension zone upper limits except of the
786     // velocity dimension, because the velocity dimension zone sizes are
787     // allowed to differ for individual DimensionRegions in gig v3
788     // format
789     //
790     // if the main dinension is the 'velocity' dimension, then skip
791     // restoring the source's original velocity zone limits, because
792     // dealing with merging that is not implemented yet
793     // TODO: merge custom velocity splits if main dimension is the velocity dimension (for now equal sized velocity zones are used if mainDim is 'velocity')
794     if (srcUpperLimits.count(gig::dimension_velocity) && mainDimension != gig::dimension_velocity) {
795     if (!dstUpperLimits.count(gig::dimension_velocity)) {
796     addWarning("Source instrument seems to have a velocity dimension whereas new target instrument doesn't!");
797     } else {
798     dstUpperLimits[gig::dimension_velocity] =
799     (e.velocityZone >= e.totalSrcVelocityZones)
800     ? 127 : srcUpperLimits[gig::dimension_velocity];
801     }
802     }
803     restoreDimensionRegionUpperLimits(e.dst, dstUpperLimits);
804     }
805 schoenebeck 2548 }
806    
807     // success
808     output = outInstr;
809     }
810    
811     ///////////////////////////////////////////////////////////////////////////
812     // class 'CombineInstrumentsDialog'
813    
814     CombineInstrumentsDialog::CombineInstrumentsDialog(Gtk::Window& parent, gig::File* gig)
815 schoenebeck 2894 : ManagedDialog(_("Combine Instruments"), parent, true),
816 schoenebeck 2548 m_gig(gig), m_fileWasChanged(false), m_newCombinedInstrument(NULL),
817 schoenebeck 3364 #if HAS_GTKMM_STOCK
818 schoenebeck 3158 m_cancelButton(Gtk::Stock::CANCEL), m_OKButton(Gtk::Stock::OK),
819 schoenebeck 3364 #else
820     m_cancelButton(_("_Cancel"), true), m_OKButton(_("_OK"), true),
821     #endif
822     m_descriptionLabel(),
823     #if USE_GTKMM_GRID
824     m_tableDimCombo(),
825     #else
826     m_tableDimCombo(2, 2),
827     #endif
828     m_comboDimType(),
829 persson 2579 m_labelDimType(Glib::ustring(_("Combine by Dimension:")) + " ", Gtk::ALIGN_END)
830 schoenebeck 2548 {
831 schoenebeck 3225 if (!Settings::singleton()->autoRestoreWindowDimension) {
832     set_default_size(500, 600);
833     set_position(Gtk::WIN_POS_MOUSE);
834     }
835    
836 schoenebeck 2616 m_scrolledWindow.add(m_treeView);
837     m_scrolledWindow.set_policy(Gtk::POLICY_AUTOMATIC, Gtk::POLICY_AUTOMATIC);
838    
839 schoenebeck 3364 #if USE_GTKMM_BOX
840     get_content_area()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
841     get_content_area()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
842     get_content_area()->pack_start(m_scrolledWindow);
843     get_content_area()->pack_start(m_labelOrder, Gtk::PACK_SHRINK);
844     get_content_area()->pack_start(m_iconView, Gtk::PACK_SHRINK);
845     get_content_area()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
846     #else
847 schoenebeck 2548 get_vbox()->pack_start(m_descriptionLabel, Gtk::PACK_SHRINK);
848 schoenebeck 2558 get_vbox()->pack_start(m_tableDimCombo, Gtk::PACK_SHRINK);
849 schoenebeck 2616 get_vbox()->pack_start(m_scrolledWindow);
850 schoenebeck 3300 get_vbox()->pack_start(m_labelOrder, Gtk::PACK_SHRINK);
851     get_vbox()->pack_start(m_iconView, Gtk::PACK_SHRINK);
852 schoenebeck 2548 get_vbox()->pack_start(m_buttonBox, Gtk::PACK_SHRINK);
853 schoenebeck 3364 #endif
854 schoenebeck 2548
855     #if GTKMM_MAJOR_VERSION >= 3
856 persson 2579 m_descriptionLabel.set_line_wrap();
857 schoenebeck 2548 #endif
858     m_descriptionLabel.set_text(_(
859 schoenebeck 2558 "Select at least two instruments below that shall be combined (as "
860     "separate dimension zones of the selected dimension type) as a new "
861     "instrument. The original instruments remain untouched.\n\n"
862     "You may use this tool for example to combine solo instruments into "
863     "a combi sound arrangement by selecting the 'layer' dimension, or you "
864     "might combine similar sounding solo sounds into separate velocity "
865     "split layers by using the 'velocity' dimension, and so on."
866     ));
867 schoenebeck 2548
868 schoenebeck 2558 // add dimension type combo box
869     {
870     int iLayerDimIndex = -1;
871     Glib::RefPtr<Gtk::ListStore> refComboModel = Gtk::ListStore::create(m_comboDimsModel);
872     for (int i = 0x01, iRow = 0; i < 0xff; i++) {
873     Glib::ustring sType =
874     dimTypeAsString(static_cast<gig::dimension_t>(i));
875     if (sType.find("Unknown") != 0) {
876     Gtk::TreeModel::Row row = *(refComboModel->append());
877     row[m_comboDimsModel.m_type_id] = i;
878     row[m_comboDimsModel.m_type_name] = sType;
879     if (i == gig::dimension_layer) iLayerDimIndex = iRow;
880     iRow++;
881     }
882     }
883     m_comboDimType.set_model(refComboModel);
884     m_comboDimType.pack_start(m_comboDimsModel.m_type_id);
885     m_comboDimType.pack_start(m_comboDimsModel.m_type_name);
886     m_tableDimCombo.attach(m_labelDimType, 0, 1, 0, 1);
887     m_tableDimCombo.attach(m_comboDimType, 1, 2, 0, 1);
888     m_comboDimType.set_active(iLayerDimIndex); // preselect "layer" dimension
889     }
890    
891 schoenebeck 2548 m_refTreeModel = Gtk::ListStore::create(m_columns);
892     m_treeView.set_model(m_refTreeModel);
893 schoenebeck 2550 m_treeView.set_tooltip_text(_(
894     "Use SHIFT + left click or CTRL + left click to select the instruments "
895     "you want to combine."
896     ));
897 schoenebeck 3299 m_treeView.append_column(_("Nr"), m_columns.m_col_index);
898     m_treeView.append_column(_("Instrument"), m_columns.m_col_name);
899     m_treeView.set_headers_visible(true);
900 schoenebeck 2548 m_treeView.get_selection()->set_mode(Gtk::SELECTION_MULTIPLE);
901     m_treeView.get_selection()->signal_changed().connect(
902     sigc::mem_fun(*this, &CombineInstrumentsDialog::onSelectionChanged)
903     );
904     m_treeView.show();
905    
906     for (int i = 0; true; ++i) {
907     gig::Instrument* instr = gig->GetInstrument(i);
908     if (!instr) break;
909    
910     #if DEBUG_COMBINE_INSTRUMENTS
911     {
912     std::cout << "Instrument (" << i << ") '" << instr->pInfo->Name << "' Regions: " << std::flush;
913     for (gig::Region* rgn = instr->GetFirstRegion(); rgn; rgn = instr->GetNextRegion()) {
914     std::cout << rgn->KeyRange.low << ".." << rgn->KeyRange.high << ", " << std::flush;
915     }
916     std::cout << std::endl;
917     }
918     std::cout << std::endl;
919     #endif
920    
921     Glib::ustring name(gig_to_utf8(instr->pInfo->Name));
922     Gtk::TreeModel::iterator iter = m_refTreeModel->append();
923     Gtk::TreeModel::Row row = *iter;
924 schoenebeck 3299 row[m_columns.m_col_index] = i;
925 schoenebeck 2548 row[m_columns.m_col_name] = name;
926     row[m_columns.m_col_instr] = instr;
927     }
928    
929 schoenebeck 3300 m_refOrderModel = Gtk::ListStore::create(m_orderColumns);
930     m_iconView.set_model(m_refOrderModel);
931     m_iconView.set_tooltip_text(_("Use drag & drop to change the order."));
932     m_iconView.set_markup_column(1);
933     m_iconView.set_selection_mode(Gtk::SELECTION_SINGLE);
934     // force background to retain white also on selections
935     // (this also fixes a bug with GTK 2 which often causes visibility issue
936     // with the text of the selected item)
937     {
938 schoenebeck 3364 #if (GTKMM_MAJOR_VERSION == 2 && GTKMM_MINOR_VERSION < 90) || GTKMM_MAJOR_VERSION < 2
939 schoenebeck 3300 Gdk::Color white;
940 schoenebeck 3364 #else
941     Gdk::RGBA white;
942     #endif
943 schoenebeck 3300 white.set("#ffffff");
944 schoenebeck 3301 GtkWidget* widget = (GtkWidget*) m_iconView.gobj();
945 schoenebeck 3364 #if GTK_MAJOR_VERSION < 3
946 schoenebeck 3301 gtk_widget_modify_base(widget, GTK_STATE_SELECTED, white.gobj());
947     gtk_widget_modify_base(widget, GTK_STATE_ACTIVE, white.gobj());
948     gtk_widget_modify_bg(widget, GTK_STATE_SELECTED, white.gobj());
949     gtk_widget_modify_bg(widget, GTK_STATE_ACTIVE, white.gobj());
950 schoenebeck 3364 #endif
951 schoenebeck 3300 }
952    
953     m_labelOrder.set_text(_("Order of the instruments to be combined:"));
954    
955     // establish drag&drop within the instrument tree view, allowing to reorder
956     // the sequence of instruments within the gig file
957     {
958     std::vector<Gtk::TargetEntry> drag_target_instrument;
959     drag_target_instrument.push_back(Gtk::TargetEntry("gig::Instrument"));
960     m_iconView.drag_source_set(drag_target_instrument);
961     m_iconView.drag_dest_set(drag_target_instrument);
962     m_iconView.signal_drag_begin().connect(
963     sigc::mem_fun(*this, &CombineInstrumentsDialog::on_order_drag_begin)
964     );
965     m_iconView.signal_drag_data_get().connect(
966     sigc::mem_fun(*this, &CombineInstrumentsDialog::on_order_drag_data_get)
967     );
968     m_iconView.signal_drag_data_received().connect(
969     sigc::mem_fun(*this, &CombineInstrumentsDialog::on_order_drop_drag_data_received)
970     );
971     }
972    
973 schoenebeck 2548 m_buttonBox.set_layout(Gtk::BUTTONBOX_END);
974 schoenebeck 3450 #if GTKMM_MAJOR_VERSION > 3 || (GTKMM_MAJOR_VERSION == 3 && GTKMM_MINOR_VERSION > 24)
975 schoenebeck 3364 m_buttonBox.set_margin(5);
976     #else
977 schoenebeck 2548 m_buttonBox.set_border_width(5);
978 schoenebeck 3364 #endif
979 schoenebeck 2548 m_buttonBox.pack_start(m_cancelButton, Gtk::PACK_SHRINK);
980     m_buttonBox.pack_start(m_OKButton, Gtk::PACK_SHRINK);
981     m_buttonBox.show();
982    
983     m_cancelButton.show();
984     m_OKButton.set_sensitive(false);
985     m_OKButton.show();
986    
987     m_cancelButton.signal_clicked().connect(
988     sigc::mem_fun(*this, &CombineInstrumentsDialog::hide)
989     );
990    
991     m_OKButton.signal_clicked().connect(
992     sigc::mem_fun(*this, &CombineInstrumentsDialog::combineSelectedInstruments)
993     );
994    
995 schoenebeck 3364 #if HAS_GTKMM_SHOW_ALL_CHILDREN
996 schoenebeck 2548 show_all_children();
997 schoenebeck 3364 #endif
998 schoenebeck 2550
999 schoenebeck 3409 Settings::singleton()->showTooltips.get_proxy().signal_changed().connect(
1000     sigc::mem_fun(*this, &CombineInstrumentsDialog::on_show_tooltips_changed)
1001     );
1002     on_show_tooltips_changed();
1003    
1004 schoenebeck 2550 // show a warning to user if he uses a .gig in v2 format
1005     if (gig->pVersion->major < 3) {
1006     Glib::ustring txt = _(
1007     "You are currently using a .gig file in old v2 format. The current "
1008     "combine algorithm will most probably fail trying to combine "
1009     "instruments in this old format. So better save the file in new v3 "
1010     "format before trying to combine your instruments."
1011     );
1012     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
1013     msg.run();
1014     }
1015 schoenebeck 3339
1016     // OK button should have focus by default for quick combining with Return key
1017     m_OKButton.grab_focus();
1018 schoenebeck 2548 }
1019    
1020 schoenebeck 3300 void CombineInstrumentsDialog::on_order_drag_begin(const Glib::RefPtr<Gdk::DragContext>& context)
1021     {
1022 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1023 schoenebeck 3300 printf("Drag begin\n");
1024 schoenebeck 3762 #endif
1025 schoenebeck 3300 first_call_to_drag_data_get = true;
1026     }
1027    
1028     void CombineInstrumentsDialog::on_order_drag_data_get(const Glib::RefPtr<Gdk::DragContext>& context,
1029     Gtk::SelectionData& selection_data, guint, guint)
1030     {
1031 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1032 schoenebeck 3300 printf("Drag data get\n");
1033 schoenebeck 3762 #endif
1034 schoenebeck 3300 if (!first_call_to_drag_data_get) return;
1035     first_call_to_drag_data_get = false;
1036    
1037     // get selected source instrument
1038     gig::Instrument* src = NULL;
1039     {
1040     std::vector<Gtk::TreeModel::Path> rows = m_iconView.get_selected_items();
1041     if (!rows.empty()) {
1042     Gtk::TreeModel::iterator it = m_refOrderModel->get_iter(rows[0]);
1043     if (it) {
1044     Gtk::TreeModel::Row row = *it;
1045     src = row[m_orderColumns.m_col_instr];
1046     }
1047     }
1048     }
1049     if (!src) {
1050     printf("Drag data get: !src\n");
1051     return;
1052     }
1053 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1054 schoenebeck 3300 printf("src=%ld\n", (size_t)src);
1055 schoenebeck 3762 #endif
1056 schoenebeck 3300
1057     // pass the source gig::Instrument as pointer
1058     selection_data.set(selection_data.get_target(), 0/*unused*/, (const guchar*)&src,
1059     sizeof(src)/*length of data in bytes*/);
1060     }
1061    
1062     void CombineInstrumentsDialog::on_order_drop_drag_data_received(
1063     const Glib::RefPtr<Gdk::DragContext>& context, int x, int y,
1064     const Gtk::SelectionData& selection_data, guint, guint time)
1065     {
1066 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1067 schoenebeck 3300 printf("Drag data received\n");
1068 schoenebeck 3762 #endif
1069 schoenebeck 3300 if (!selection_data.get_data()) {
1070     printf("selection_data.get_data() == NULL\n");
1071     return;
1072     }
1073    
1074     gig::Instrument* src = *((gig::Instrument**) selection_data.get_data());
1075     if (!src || selection_data.get_length() != sizeof(gig::Instrument*)) {
1076     printf("!src\n");
1077     return;
1078     }
1079 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1080 persson 3456 printf("src=%ld\n", (size_t)src);
1081 schoenebeck 3762 #endif
1082 schoenebeck 3300
1083     gig::Instrument* dst = NULL;
1084     {
1085     Gtk::TreeModel::Path path = m_iconView.get_path_at_pos(x, y);
1086     if (!path) return;
1087    
1088     Gtk::TreeModel::iterator iter = m_refOrderModel->get_iter(path);
1089     if (!iter) return;
1090     Gtk::TreeModel::Row row = *iter;
1091     dst = row[m_orderColumns.m_col_instr];
1092     }
1093     if (!dst) {
1094     printf("!dst\n");
1095     return;
1096     }
1097    
1098 schoenebeck 3762 #if DEBUG_COMBINE_INSTRUMENTS
1099 schoenebeck 3300 printf("dragdrop received src='%s' dst='%s'\n", src->pInfo->Name.c_str(), dst->pInfo->Name.c_str());
1100 schoenebeck 3762 #endif
1101 schoenebeck 3300
1102     // swap the two items
1103     typedef Gtk::TreeModel::Children Children;
1104     Children children = m_refOrderModel->children();
1105     Children::iterator itSrc, itDst;
1106     int i = 0, iSrc = -1, iDst = -1;
1107     for (Children::iterator iter = children.begin();
1108     iter != children.end(); ++iter, ++i)
1109     {
1110     Gtk::TreeModel::Row row = *iter;
1111     if (row[m_orderColumns.m_col_instr] == src) {
1112     itSrc = iter;
1113     iSrc = i;
1114     } else if (row[m_orderColumns.m_col_instr] == dst) {
1115     itDst = iter;
1116     iDst = i;
1117     }
1118     }
1119     if (itSrc && itDst) {
1120     // swap elements
1121     m_refOrderModel->iter_swap(itSrc, itDst);
1122     // update markup
1123     Gtk::TreeModel::Row rowSrc = *itSrc;
1124     Gtk::TreeModel::Row rowDst = *itDst;
1125     {
1126     Glib::ustring name = rowSrc[m_orderColumns.m_col_name];
1127     Glib::ustring markup =
1128     "<span foreground='black' background='white'>" + ToString(iDst+1) + ".</span>\n<span foreground='green' background='white'>" + name + "</span>";
1129     rowSrc[m_orderColumns.m_col_markup] = markup;
1130     }
1131     {
1132     Glib::ustring name = rowDst[m_orderColumns.m_col_name];
1133     Glib::ustring markup =
1134     "<span foreground='black' background='white'>" + ToString(iSrc+1) + ".</span>\n<span foreground='green' background='white'>" + name + "</span>";
1135     rowDst[m_orderColumns.m_col_markup] = markup;
1136     }
1137     }
1138     }
1139    
1140 schoenebeck 3299 void CombineInstrumentsDialog::setSelectedInstruments(const std::set<int>& instrumentIndeces) {
1141     typedef Gtk::TreeModel::Children Children;
1142     Children children = m_refTreeModel->children();
1143     for (Children::iterator iter = children.begin();
1144     iter != children.end(); ++iter)
1145     {
1146     Gtk::TreeModel::Row row = *iter;
1147     int index = row[m_columns.m_col_index];
1148     if (instrumentIndeces.count(index))
1149     m_treeView.get_selection()->select(iter);
1150     }
1151 schoenebeck 3339 // hack: OK button lost focus after doing the above, it should have focus by default for quick combining with Return key
1152     m_OKButton.grab_focus();
1153 schoenebeck 3299 }
1154    
1155 schoenebeck 2548 void CombineInstrumentsDialog::combineSelectedInstruments() {
1156     std::vector<gig::Instrument*> instruments;
1157 schoenebeck 3300 {
1158     typedef Gtk::TreeModel::Children Children;
1159     int i = 0;
1160     Children selection = m_refOrderModel->children();
1161     for (Children::iterator it = selection.begin();
1162     it != selection.end(); ++it, ++i)
1163     {
1164     Gtk::TreeModel::Row row = *it;
1165     Glib::ustring name = row[m_orderColumns.m_col_name];
1166     gig::Instrument* instrument = row[m_orderColumns.m_col_instr];
1167     #if DEBUG_COMBINE_INSTRUMENTS
1168 schoenebeck 3779 printf("Selection %d. '%s' %p\n\n", (i+1), name.c_str(), instrument);
1169 schoenebeck 3300 #endif
1170     instruments.push_back(instrument);
1171     }
1172 schoenebeck 2548 }
1173    
1174 schoenebeck 2552 g_warnings.clear();
1175    
1176 schoenebeck 2548 try {
1177 schoenebeck 2558 // which main dimension was selected in the combo box?
1178     gig::dimension_t mainDimension;
1179     {
1180     Gtk::TreeModel::iterator iterType = m_comboDimType.get_active();
1181     if (!iterType) throw gig::Exception("No dimension selected");
1182     Gtk::TreeModel::Row rowType = *iterType;
1183     if (!rowType) throw gig::Exception("Something is wrong regarding dimension selection");
1184     int iTypeID = rowType[m_comboDimsModel.m_type_id];
1185     mainDimension = static_cast<gig::dimension_t>(iTypeID);
1186     }
1187    
1188 schoenebeck 3300 // now start the actual combination task ...
1189 schoenebeck 2558 combineInstruments(instruments, m_gig, m_newCombinedInstrument, mainDimension);
1190 schoenebeck 2548 } catch (RIFF::Exception e) {;
1191     Gtk::MessageDialog msg(*this, e.Message, false, Gtk::MESSAGE_ERROR);
1192     msg.run();
1193     return;
1194 schoenebeck 2553 } catch (...) {
1195     Glib::ustring txt = _("An unknown exception occurred!");
1196     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_ERROR);
1197     msg.run();
1198     return;
1199 schoenebeck 2548 }
1200    
1201 schoenebeck 2552 if (!g_warnings.empty()) {
1202     Glib::ustring txt = _(
1203     "Combined instrument was created successfully, but there were warnings:"
1204     );
1205     txt += "\n\n";
1206     for (Warnings::const_iterator itWarn = g_warnings.begin();
1207     itWarn != g_warnings.end(); ++itWarn)
1208     {
1209     txt += "-> " + *itWarn + "\n";
1210     }
1211     txt += "\n";
1212     txt += _(
1213     "You might also want to check the console for further warnings and "
1214     "error messages."
1215     );
1216     Gtk::MessageDialog msg(*this, txt, false, Gtk::MESSAGE_WARNING);
1217     msg.run();
1218     }
1219    
1220 schoenebeck 2548 // no error occurred
1221     m_fileWasChanged = true;
1222     hide();
1223     }
1224    
1225     void CombineInstrumentsDialog::onSelectionChanged() {
1226     std::vector<Gtk::TreeModel::Path> v = m_treeView.get_selection()->get_selected_rows();
1227     m_OKButton.set_sensitive(v.size() >= 2);
1228 schoenebeck 3300
1229     typedef Gtk::TreeModel::Children Children;
1230    
1231     // update horizontal selection list (icon view) ...
1232    
1233     // remove items which are not part of the new selection anymore
1234     {
1235     Children allOrdered = m_refOrderModel->children();
1236     for (Children::iterator itOrder = allOrdered.begin();
1237 schoenebeck 3677 itOrder != allOrdered.end(); )
1238 schoenebeck 3300 {
1239     Gtk::TreeModel::Row rowOrder = *itOrder;
1240     gig::Instrument* instr = rowOrder[m_orderColumns.m_col_instr];
1241     for (uint i = 0; i < v.size(); ++i) {
1242     Gtk::TreeModel::iterator itSel = m_refTreeModel->get_iter(v[i]);
1243     Gtk::TreeModel::Row rowSel = *itSel;
1244     if (rowSel[m_columns.m_col_instr] == instr)
1245     goto nextOrderedItem;
1246     }
1247     goto removeOrderedItem;
1248     nextOrderedItem:
1249 schoenebeck 3677 ++itOrder;
1250 schoenebeck 3300 continue;
1251     removeOrderedItem:
1252 schoenebeck 3677 // postfix increment here to avoid iterator invalidation
1253     m_refOrderModel->erase(itOrder++);
1254 schoenebeck 3300 }
1255     }
1256    
1257     // add items newly added to the selection
1258     for (uint i = 0; i < v.size(); ++i) {
1259     Gtk::TreeModel::iterator itSel = m_refTreeModel->get_iter(v[i]);
1260     Gtk::TreeModel::Row rowSel = *itSel;
1261     gig::Instrument* instr = rowSel[m_columns.m_col_instr];
1262     Children allOrdered = m_refOrderModel->children();
1263     for (Children::iterator itOrder = allOrdered.begin();
1264     itOrder != allOrdered.end(); ++itOrder)
1265     {
1266     Gtk::TreeModel::Row rowOrder = *itOrder;
1267     if (rowOrder[m_orderColumns.m_col_instr] == instr)
1268     goto nextSelectionItem;
1269     }
1270     goto addNewSelectionItem;
1271     nextSelectionItem:
1272     continue;
1273     addNewSelectionItem:
1274     Glib::ustring name = gig_to_utf8(instr->pInfo->Name);
1275     Gtk::TreeModel::iterator iterOrder = m_refOrderModel->append();
1276     Gtk::TreeModel::Row rowOrder = *iterOrder;
1277     rowOrder[m_orderColumns.m_col_name] = name;
1278     rowOrder[m_orderColumns.m_col_instr] = instr;
1279     }
1280    
1281     // update markup
1282     {
1283     int i = 0;
1284     Children allOrdered = m_refOrderModel->children();
1285     for (Children::iterator itOrder = allOrdered.begin();
1286     itOrder != allOrdered.end(); ++itOrder, ++i)
1287     {
1288     Gtk::TreeModel::Row rowOrder = *itOrder;
1289     Glib::ustring name = rowOrder[m_orderColumns.m_col_name];
1290     Glib::ustring markup =
1291     "<span foreground='black' background='white'>" + ToString(i+1) + ".</span>\n<span foreground='green' background='white'>" + name + "</span>";
1292     rowOrder[m_orderColumns.m_col_markup] = markup;
1293     }
1294     }
1295 schoenebeck 2548 }
1296    
1297 schoenebeck 3409 void CombineInstrumentsDialog::on_show_tooltips_changed() {
1298     const bool b = Settings::singleton()->showTooltips;
1299    
1300     m_treeView.set_has_tooltip(b);
1301     m_iconView.set_has_tooltip(b);
1302    
1303     set_has_tooltip(b);
1304     }
1305    
1306 schoenebeck 2548 bool CombineInstrumentsDialog::fileWasChanged() const {
1307     return m_fileWasChanged;
1308     }
1309    
1310     gig::Instrument* CombineInstrumentsDialog::newCombinedInstrument() const {
1311     return m_newCombinedInstrument;
1312     }

  ViewVC Help
Powered by ViewVC