/[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 3300 - (hide annotations) (download)
Sun Jul 9 18:15:02 2017 UTC (6 years, 8 months ago) by schoenebeck
File size: 52164 byte(s)
* Combine Tool: Added a vertical list which represents the order of the
  selected instruments to be combined; dragging them modifies their order.
* Combine Tool: After returning from the combine tool dialog,
  automatically scroll to the newly added (combined) instrument.
* Bumped version (1.0.0.svn55).

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

  ViewVC Help
Powered by ViewVC