/[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 3301 - (hide annotations) (download)
Sun Jul 9 19:00:46 2017 UTC (6 years, 8 months ago) by schoenebeck
File size: 52336 byte(s)
- Fixed compilation error with GTK 3.

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

  ViewVC Help
Powered by ViewVC