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

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

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3783 - (show annotations) (download)
Sat May 30 00:14:27 2020 UTC (2 months, 2 weeks ago) by schoenebeck
File size: 55955 byte(s)
* Combine Tool: Prevent NULL samples in combined instrument (if source
  dimension had less zones than output dimension).

* Bumped version (1.1.1.svn20).

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

  ViewVC Help
Powered by ViewVC