File: myx_gc_connection.cpp

package info (click to toggle)
mysql-query-browser 1.2.5beta-3
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 63,792 kB
  • ctags: 46,485
  • sloc: pascal: 249,299; ansic: 80,111; cpp: 72,467; sh: 25,271; objc: 20,015; yacc: 10,755; java: 9,917; xml: 4,580; php: 2,806; python: 1,566; sql: 1,563; makefile: 1,452; perl: 3
file content (2518 lines) | stat: -rw-r--r-- 81,937 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
/* Copyright (C) 2004 MySQL AB

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/**
 * @file myx_gc_connection.cpp 
 * @brief Implementation of the connection class.
 * 
 */

#include "myx_gc_connection.h"
#include "myx_gc_canvas.h"

//----------------------------------------------------------------------------------------------------------------------

CConnectionDecor::CConnectionDecor(CGCModel* model, wstring type, wstring layoutClass): CGCBase(model->canvas())
{
  _className = "CConnectionDecor";
  FModel = model;
  FType = type;
  FClass = layoutClass;
}

//----------------------------------------------------------------------------------------------------------------------

CConnectionDecor::~CConnectionDecor(void)
{
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Retrieves the value of the property given by path. The path syntax is must be something like (here expressed as regex)
 * (container)*(property), where container is a slash and the name of a container class (e.g. layers, figures) and
 * property is the name of a simple property of that container.
 *
 * @param name The name of the property to return.
 * @param index The index of the sub property to return if it is located in a list.
 * @return A description of the property value and, if the property is simple, the actual value.
 */
TGCVariant CConnectionDecor::propertyGet(const char* name, unsigned int index)
{
  TGCVariant result;

  switch (getContainerID(name))
  {
    case GC_CONTAINER_UNKNOWN:
      {
        switch (getPropertyID(name))
        {
          case GC_PROPERTY_NAME:
            {
              result = utf16ToUtf8(FType);
              break;
            };
          case GC_PROPERTY_OWNER:
            {
              result = FModel;
              break;
            };
        };

        break;
      };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Sets the value of the given property, which must be a simple property.
 *
 * @param name The name of the property.
 * @param index The index of the sub property to return if it is located in a list.
 * @param value The new value of the property. Automatic conversion is performed where possible.
 */
void CConnectionDecor::propertySet(const char* name, unsigned int index, TGCVariant value)
{
  // There are currently no properties that could be changed. The name is a unique identifier and must not be changed.
}

//----------------- CFigureListener ------------------------------------------------------------------------------------

void CConnection::CFigureListener::onAction(CGCBase* sender, CGCBase* origin, TAction** action)
{
  // Do not forward actions triggered in the figures. They are handled on their own.
}

//----------------------------------------------------------------------------------------------------------------------

void CConnection::CFigureListener::onDestroy(CGCBase* object)
{
  connection->figureDestroyed((CFigure*) object);
}

//----------------------------------------------------------------------------------------------------------------------

void CConnection::CFigureListener::onError(CGCBase* sender, CGCBase* origin, const char* message)
{
  // Let the model report any errors up the chain. This is not our business.
}

//----------------- CConnection ----------------------------------------------------------------------------------------

CConnection::CConnection(CGenericCanvas* canvas, CConnectionDecor* decor, CFigure* endPoint1, CFigure* endPoint2): 
  CGraphicElement(canvas)
{
  _className = "CConnection";
  FDecor = decor;
  FListener.connection = this;
  FEnd1 = endPoint1;
  FEnd1->addListener(&FListener);
  FEnd2 = endPoint2;
  FEnd2->addListener(&FListener);

  FDecorations.end1Decoration = NULL;
  FDecorations.end1Label = NULL;
  FDecorations.end2Decoration = NULL;
  FDecorations.end2Label = NULL;
  FDecorations.centerDecoration = NULL;
  FDecorations.centerLabel = NULL;
}

//----------------------------------------------------------------------------------------------------------------------

CConnection::~CConnection(void)
{
  if (FEnd1)
    FEnd1->removeListener(&FListener);

  if (FEnd2)
    FEnd2->removeListener(&FListener);

  if (FDecorations.end1Decoration != NULL)
    FDecorations.end1Decoration->removeListener(&FListener);
  if (FDecorations.end1Label != NULL)
    FDecorations.end1Label->removeListener(&FListener);
  if (FDecorations.end2Decoration != NULL)
    FDecorations.end2Decoration->removeListener(&FListener);
  if (FDecorations.end2Label != NULL)
    FDecorations.end2Label->removeListener(&FListener);
  if (FDecorations.centerDecoration != NULL)
    FDecorations.centerDecoration->removeListener(&FListener);
  if (FDecorations.centerLabel != NULL)
    FDecorations.centerLabel->removeListener(&FListener);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Core action execution function.
 *
 * @param action The action to be executed.
 * @return The actual action that was executed (can be changed by the application in a callback, but is usually what was passed in).
 */
TAction* CConnection::doAction(TAction* action)
{                                                               
  TAction* result = action;

  // Notify listeners about the action and see if they confirm it.
  // Listeners can set the action to something else (including GC_ACTION_NONE) to control what happens.
  this->action(this, &result);
  if (result != NULL)
  {
    switch (result->type)
    {
      case GC_ACTION_CHANGE_STYLE:
        {
          // Just a place holder. Remove that once an action is executed here.
          break;
        };
    };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Sets all decoration info in one call.
 *
 * @param data A list of CFigure instances that are to be used as decoration for the connection.
 *             Some or all entries can be NULL indicating so there should be no decoration for the corresponding part.
 */
void CConnection::decorationsSet(const TConnectionDecorations& data)
{
  if (FDecorations.end1Decoration != NULL)
    FDecorations.end1Decoration->removeListener(&FListener);
  if (FDecorations.end1Label != NULL)
    FDecorations.end1Label->removeListener(&FListener);
  if (FDecorations.end2Decoration != NULL)
    FDecorations.end2Decoration->removeListener(&FListener);
  if (FDecorations.end2Label != NULL)
    FDecorations.end2Label->removeListener(&FListener);
  if (FDecorations.centerDecoration != NULL)
    FDecorations.centerDecoration->removeListener(&FListener);
  if (FDecorations.centerLabel != NULL)
    FDecorations.centerLabel->removeListener(&FListener);

  FDecorations = data;

  if (FDecorations.end1Decoration != NULL)
    FDecorations.end1Decoration->addListener(&FListener);
  if (FDecorations.end1Label != NULL)
    FDecorations.end1Label->addListener(&FListener);
  if (FDecorations.end2Decoration != NULL)
    FDecorations.end2Decoration->addListener(&FListener);
  if (FDecorations.end2Label != NULL)
    FDecorations.end2Label->addListener(&FListener);
  if (FDecorations.centerDecoration != NULL)
    FDecorations.centerDecoration->addListener(&FListener);
  if (FDecorations.centerLabel != NULL)
    FDecorations.centerLabel->addListener(&FListener);

  change(this, GC_CHANGE_CONNECTION_DECORATION);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Triggers the actions of the figure element that is located at the given location. The given coordinates are
 * already in element space, so no further conversion is needed.
 * Only actions with the correct trigger conditions are executed.
 *
 * @param button The mouse button which triggered the call.
 * @param event The event which triggered the action.
 * @param modifiers Any combination of Alt, Control and Shift key.
 * @param coords The mouse coordinates in element space.
 * @return The last executed action or NULL if none.
 */
TAction* CConnection::executeAssociatedActions(TMouseButton button, TMouseEvent event, TModifiers modifiers, const TVertex& coords)
{
  TAction* result = NULL;

  if (containsPoint(coords.x, coords.y) && FDecor != NULL)
  {
    // None of the child element has had an action that could be used.
    // So execute those assigned to this element, if there are any.
    // Only actions which fit the given trigger conditions are considered.
    if (FDecor->actions().size() > 0)
    {
      for (CActions::iterator iterator = FDecor->actions().begin(); iterator != FDecor->actions().end(); ++iterator)
      {
        TAction* action = (*iterator);

        // If the action has no triggeres assigned then execute it unconditionally.
        if (action->triggers.size() == 0)
          result = doAction(action);
        else
          for (CTriggers::iterator triggerIterator = action->triggers.begin(); triggerIterator != action->triggers.end(); ++triggerIterator)
          {
            if ((triggerIterator->button == GC_MOUSE_BUTTON_IGNORE || triggerIterator->button == button) &&
              (triggerIterator->modifiers == GC_MODIFIER_IGNORE || triggerIterator->modifiers == modifiers) &&
              (triggerIterator->event == GC_MOUSE_IGNORE || triggerIterator->event == event))
            {
              result = doAction(action);

              // Once we found a valid trigger we can continue with the next action.
              break;
            };
          };
      };
    };
  };


  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Called by the figure listener notifying the connection about the destruction of a figure it is using.
 *
 * @param figure The figure that is being destroyed.
 */
void CConnection::figureDestroyed(CFigure* figure)
{
  // Deleting one of the endpoints means the connection is no longer valid, hence destroy it in that case.
  if (FEnd1 == figure)
  {
    FEnd1 = NULL;
    delete this;
  }
  else 
    if (FEnd2 == figure)
    {
      FEnd2 = NULL;
      delete this;
    }
    else
      if (FDecorations.end1Decoration == figure)
        FDecorations.end1Decoration = NULL;
      else
        if (FDecorations.end1Label == figure)
          FDecorations.end1Label = NULL;
        else
          if (FDecorations.centerDecoration == figure)
            FDecorations.centerDecoration = NULL;
          else
            if (FDecorations.centerLabel == figure)
              FDecorations.centerLabel = NULL;
            else
              if (FDecorations.end2Decoration == figure)
                FDecorations.end2Decoration = NULL;
              else
                if (FDecorations.end2Label == figure)
                  FDecorations.end2Label = NULL;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Retrieves the value of the property given by path. The path syntax is must be something like (here expressed as regex)
 * (container)*(property), where container is a slash and the name of a container class (e.g. layers, figures) and
 * property is the name of a simple property of that container.
 *
 * @param name The name of the property to return.
 * @param index The index of the sub property to return if it is located in a list.
 * @return A description of the property value and, if the property is simple, the actual value.
 */
TGCVariant CConnection::propertyGet(const char* name, unsigned int index)
{
  TGCVariant result;

  switch (getContainerID(name))
  {
    case GC_CONTAINER_UNKNOWN:
      {
        switch (getPropertyID(name))
        {
          case GC_PROPERTY_NAME:
            {
              // place holder
              break;
            };
        };

        break;
      };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Sets the value of the given property, which must be a simple property.
 *
 * @param name The name of the property.
 * @param index The index of the sub property to return if it is located in a list.
 * @param value The new value of the property. Automatic conversion is performed where possible.
 */
void CConnection::propertySet(const char* name, unsigned int index, TGCVariant value)
{
  // There are currently no properties that could be changed.
}

//----------------- CConnectionListener --------------------------------------------------------------------------------

void CConnectionInstance::CConnectionListener::onAction(CGCBase* sender, CGCBase* origin, TAction** action)
{
  if (sender->classIs("CConnection"))
    instance->action(origin, action);
}

//----------------------------------------------------------------------------------------------------------------------

void CConnectionInstance::CConnectionListener::onChange(CGCBase* sender, CGCBase* origin, TGCChangeReason reason)
{
  switch (reason)
  {
    case GC_CHANGE_CAPTION_PROPERTY:
      break; // Ignore
    case GC_CHANGE_CONNECTION_DECORATION:
      {
        instance->updateDecorations();
        instance->makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      }
    default:
      instance->makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
  };
}

//----------------------------------------------------------------------------------------------------------------------

void CConnectionInstance::CConnectionListener::onDestroy(CGCBase* object)
{
  delete instance;
}

//----------------- CConnectionInstance --------------------------------------------------------------------------------

/**
 * Constructor of the class.
 *
 * @param canvas The canvas to which this class belongs.
 * @param connection The connection which is instantiated in this class.
 * @param endPoint1 The first endpoint.
 * @param endPoint2 The second endpoint.
 */
CConnectionInstance::CConnectionInstance(CConnectionLayer* layer, CConnection* connection, CFigureInstance* endPoint1, 
                                         CFigureInstance* endPoint2): CGraphicElement(connection->canvas())
{
  _className = "CConnectionInstance";
  FLayer = layer;
  FListener.instance = this;
  FConnection = connection;
  FConnection->addListener(&FListener);
  FEnd1 = endPoint1;
  FEnd1->addListener(&FListener);
  FEnd2 = endPoint2;
  FEnd2->addListener(&FListener);
  FDisplayList = 0;
  FDirection1 = GC_DIR_NONE;
  FDirection2 = GC_DIR_NONE;
  FLineStyle = GC_CONNECTION_STYLE_SOLID;
  FColor[0] = 0;
  FColor[1] = 0;
  FColor[2] = 0;
  FColor[3] = 1;
  FHotColor[0] = 0;
  FHotColor[1] = 0;
  FHotColor[2] = 1;
  FHotColor[3] = 1;

  // Decorations and labels.
  FEnd1Decoration = NULL;
  FEnd1Label = NULL;
  FCenterDecoration = NULL;
  FCenterLabel = NULL;
  FEnd2Decoration = NULL;
  FEnd2Label = NULL;

  // If this connection is self referencing then move the center closer to the (one) end point otherwise center it.
  if (FEnd1 == FEnd2)
    FCenter = 0.01f;
  else
    FCenter = 0.5f;

  updateDecorations();
}

//----------------------------------------------------------------------------------------------------------------------

CConnectionInstance::~CConnectionInstance(void)
{
  FConnection->removeListener(&FListener);
  FEnd1->removeListener(&FListener);
  FEnd2->removeListener(&FListener);

  // Decorations and labels.
  if (FEnd1Decoration != NULL)
  {
    FEnd1Decoration->removeListener(&FListener);
    delete FEnd1Decoration;
  };
  if (FEnd1Label != NULL)
  {
    FEnd1Label->removeListener(&FListener);
    delete FEnd1Label;
  };
  if (FCenterDecoration != NULL)
  { 
    FCenterDecoration->removeListener(&FListener);
    delete FCenterDecoration;
  };
  if (FCenterLabel != NULL)
  { 
    FCenterLabel->removeListener(&FListener);
    delete FCenterLabel;
  };
  if (FEnd2Decoration != NULL)
  {  
    FEnd2Decoration->removeListener(&FListener);
    delete FEnd2Decoration;
  };
  if (FEnd2Label != NULL)
  {
    FEnd2Label->removeListener(&FListener);
    delete FEnd2Label;
  };

  if (FDisplayList != 0)
    glDeleteLists(FDisplayList, 1);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Determines the correct orientation of the target element and applies all necessary transformations.
 *
 * @param target The figure instance that must be transformed.
 * @param position The position to which the target must be moved.
 * @param direction The orientation of the target. This is used to rotation or mirror the figure instance accordingly.
 */
void CConnectionInstance::applyTransformations(CFigureInstance* target, TVertex* position, TConnectionDirection direction)
{
  target->disableEvents();
  target->translate(position->x, position->y, 0);

  switch (direction)
  {
    case GC_DIR_EAST:
      {
        target->rotate(0, 0, 0, 1);
        target->scale(1, 1, 1);
        break;
      };
    case GC_DIR_SOUTH:
      {
        target->rotate(90, 0, 0, 1);
        target->scale(1, 1, 1);
        break;
      };
    case GC_DIR_WEST:
      {
        target->rotate(0, 0, 0, 1);
        target->scale(-1, 1, 1);
        break;
      };
    case GC_DIR_NORTH:
      {
        target->rotate(-90, 0, 0, 1);
        target->scale(1, 1, 1);
        break;
      };
  };

  target->enableEvents();
  target->validate();
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes the current center coordinate depending on the connection orientation, the relative center value and the
 * current end points.
 */
float CConnectionInstance::computeCenterPosition(void)
{
  float result = 0;

  if (FEnd1 == FEnd2)
  {
    // Self referencing, means this connections starts and stops at the same end point.
    float fullWidth;
    float fullHeight;

    // Compute the center as percentage of the entire width/height.
    canvas()->currentViewGet()->getWorkspace(&fullWidth, &fullHeight);

    switch (FDirection1)
    {
      case GC_DIR_SOUTH:
      case GC_DIR_NORTH:
      {
        float offset = (FEnd1Decoration != NULL) ? FEnd1Decoration->height() : 0;
        if ((FEnd2Decoration != NULL) && FEnd2Decoration->height() > offset)
          offset = FEnd2Decoration->height();

        if (FDirection1 == GC_DIR_NORTH)
          result = FEndVertex1.y - offset - FCenter * fullHeight;
        else
          result = FEndVertex1.y + offset + FCenter * fullHeight;
        
        break;
      }
      default:
      {
        // GC_DIR_EAST/GC_DIR_WEST
        float offset = (FEnd1Decoration != NULL) ? FEnd1Decoration->width() : 0;
        if ((FEnd2Decoration != NULL) && FEnd2Decoration->width() > offset)
          offset = FEnd2Decoration->width();

        if (FDirection1 == GC_DIR_WEST)
          result = FEndVertex1.x - offset - FCenter * fullWidth;
        else
          result = FEndVertex1.x + offset + FCenter * fullWidth;

        break;
      };
    };
  }
  else
    switch (FDirection1)
    {
      case GC_DIR_SOUTH:
      case GC_DIR_NORTH:
      {
        float offset1 = (FEnd1Decoration != NULL) ? FEnd1Decoration->height() : 0;
        float offset2 = (FEnd2Decoration != NULL) ? FEnd2Decoration->height() : 0;
        if (FEndVertex1.y <= FEndVertex2.y)
          result = FEndVertex1.y + offset1 + FCenter * (FEndVertex2.y - offset2 - FEndVertex1.y - offset1);
        else
          result = FEndVertex2.y + offset2 + FCenter * (FEndVertex1.y - offset1 - FEndVertex2.y - offset2);

        break;
      }
      default:
      {
        // GC_DIR_EAST/GC_DIR_WEST
        float offset1 = (FEnd1Decoration != NULL) ? FEnd1Decoration->width() : 0;
        float offset2 = (FEnd2Decoration != NULL) ? FEnd2Decoration->width() : 0;
        if (FEndVertex1.x <= FEndVertex2.x)
          result = FEndVertex1.x + offset1 + FCenter * (FEndVertex2.x - offset2 - FEndVertex1.x - offset1);
        else
          result = FEndVertex2.x + offset2 + FCenter * (FEndVertex1.x - offset1 - FEndVertex2.x - offset2);

        break;
      };
    };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Determines the visual orienation of the center decoration, which depends not only on the direction of the 
 * connection but also the relation of its end points.
 */
TConnectionDirection CConnectionInstance::determineCenterDirection(void)
{
  TConnectionDirection result = GC_DIR_NONE;
  TBoundingBox bounds = FCenterDecoration->bounds();
  float centerWidth = bounds.lower.x - bounds.upper.x;
  float dX = FEndVertex2.x - FEndVertex1.x;
  float dY = FEndVertex2.y - FEndVertex1.y;

  // For the center we consider the connection to be oriented in a certain direction (from end point 1 to 2).
  switch (FDirection1)
  {
    case GC_DIR_NORTH:
      {
        // If the second end point is to the right of the first and its horizontal distance is large enough
        // then the center points east. If there is not enough distance to make up a meaningful horizontal
        // direction then point the center upwards. Finally if the second point is placed to the left of the
        // first point the center points to west. Similar for all other cases.
        if (fabs(dX) < centerWidth)
          result = GC_DIR_NORTH;
        else
          if (dX > 0)
            result = GC_DIR_EAST;
          else
            result = GC_DIR_WEST;
        break;
      };
    case GC_DIR_EAST:
      {
        if (fabs(dY) < centerWidth)
          result = GC_DIR_EAST;
        else
          if (dY > 0)
            result = GC_DIR_SOUTH;
          else
            result = GC_DIR_NORTH;
        break;
      };
    case GC_DIR_SOUTH:
      {
        if (fabs(dX) < centerWidth)
          result = GC_DIR_SOUTH;
        else
          if (dX > 0)
            result = GC_DIR_EAST;
          else
            result = GC_DIR_WEST;
        break;
      };
    case GC_DIR_WEST:
      {
        if (fabs(dY) < centerWidth)
          result = GC_DIR_WEST;
        else
          if (dY > 0)
            result = GC_DIR_SOUTH;
          else
            result = GC_DIR_NORTH;
        break;
      };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Triggers the actions of the connection instance that is located at the given location. The given coordinates are
 * in view space but are implicitely converted by the figure instances.
 * Only actions with the correct trigger conditions are executed.
 *
 * @param button The mouse button which triggered the call.
 * @param event The event which triggered the action.
 * @param modifiers Any combination of Alt, Control and Shift key.
 * @param coords The mouse coordinates in element space.
 * @return The last executed action or NULL if none.
 */
TAction* CConnectionInstance::executeAssociatedActions(TMouseButton button, TMouseEvent event, TModifiers modifiers, const TVertex& coords)
{
  TAction* lastAction = NULL;

  // End points. They are always assigned.
  lastAction = FEnd1->executeAssociatedActions(button, event, modifiers, coords);
  if (lastAction == NULL)
    lastAction = FEnd2->executeAssociatedActions(button, event, modifiers, coords);

  // Decorations and labels. They may not always be assigned.
  if (lastAction == NULL && FEnd1Decoration != NULL)
    lastAction = FEnd1Decoration->executeAssociatedActions(button, event, modifiers, coords);
  if (lastAction == NULL && FEnd1Label != NULL)
    lastAction = FEnd1Label->executeAssociatedActions(button, event, modifiers, coords - FLabel1Offset);
  if (lastAction == NULL && FCenterDecoration != NULL)
    lastAction = FCenterDecoration->executeAssociatedActions(button, event, modifiers, coords);
  if (lastAction == NULL && FCenterLabel != NULL)
    lastAction = FCenterLabel->executeAssociatedActions(button, event, modifiers, coords - FCenterLabelOffset);
  if (lastAction == NULL && FEnd2Decoration != NULL)
    lastAction = FEnd2Decoration->executeAssociatedActions(button, event, modifiers, coords);
  if (lastAction == NULL && FEnd2Label != NULL)
    lastAction = FEnd2Label->executeAssociatedActions(button, event, modifiers, coords - FLabel2Offset);

  if (lastAction == NULL && FConnection != NULL)
    lastAction = FConnection->executeAssociatedActions(button, event, modifiers, coords);

  return lastAction;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Renders the given decoration and label if they are assigned.
 *
 * @param part The part to render.
 */
void CConnectionInstance::renderDecoration(TConnectionPart part)
{
  CFigureInstance* decoration = NULL;
  CFigureInstance* label = NULL;
  TVertex offset;

  switch (part)
  {
    case GC_CONNECTION_PART_1:
      {
        decoration = FEnd1Decoration;
        label = FEnd1Label;
        offset = FLabel1Offset;
        break;
      };
    case GC_CONNECTION_PART_CENTER:
      {
        decoration = FCenterDecoration;
        label = FCenterLabel;
        offset = FCenterLabelOffset;
        break;
      };
    case GC_CONNECTION_PART_2:
      {
        decoration = FEnd2Decoration;
        label = FEnd2Label;
        offset = FLabel2Offset;
        break;
      };
  };

  glPushAttrib(GL_ENABLE_BIT);
  glEnable(GL_LINE_SMOOTH);

  if (decoration != NULL)
    decoration->render();
  if (label != NULL)
  {
    glPushMatrix();
    glTranslatef(offset.x, offset.y, offset.z);
    label->render();
    glPopMatrix();
  };

  glPopAttrib();
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes the correct position and orientation of the decoration part indicated by part.
 *
 * @param part Determines the part (ends or center) to update.
 */
void CConnectionInstance::updateDecoration(TConnectionPart part)
{
  // niceDistance is a small offset to avoid packing elements too tightly.
  float niceDistance = 2;
  TBoundingBox decorationBounds;

  if (part == GC_CONNECTION_PART_CENTER)
  {
    if (FDirection1 == GC_DIR_NORTH || FDirection1 == GC_DIR_SOUTH)
    {
      if (FCenterDecoration != NULL)
      {
        TVertex position;
        position.x = (FEndVertex1.x + FEndVertex2.x) / 2;
        position.y = computeCenterPosition();
        applyTransformations(FCenterDecoration, &position, determineCenterDirection());
        decorationBounds = FCenterDecoration->bounds();
      };
      if (FCenterLabel != NULL)
      {
        TBoundingBox labelBounds = FCenterLabel->localBounds();
        float labelWidth = labelBounds.lower.x - labelBounds.upper.x;
        float labelHeight = labelBounds.lower.y - labelBounds.upper.y;
        float centerX = (FEndVertex1.x + FEndVertex2.x) / 2 - labelWidth / 2;
        float centerY = decorationBounds.upper.y - labelHeight - niceDistance;
        FCenterLabel->disableEvents();
        FCenterLabel->translate(centerX, centerY, 0);
        FCenterLabel->enableEvents();
      };
    }
    else
    {
      if (FCenterDecoration != NULL)
      {
        TVertex position;
        position.x = computeCenterPosition();
        position.y = (FEndVertex1.y + FEndVertex2.y) / 2;
        applyTransformations(FCenterDecoration, &position, determineCenterDirection());
        decorationBounds = FCenterDecoration->bounds();
      };
      if (FCenterLabel != NULL)
      {
        TBoundingBox labelBounds = FCenterLabel->localBounds();
        float labelHeight = labelBounds.lower.y - labelBounds.upper.y;
        float centerX = decorationBounds.lower.x + niceDistance;
        float centerY = (FEndVertex1.y + FEndVertex2.y) / 2 - labelHeight / 2;
        FCenterLabel->disableEvents();
        FCenterLabel->translate(centerX, centerY, 0);
        FCenterLabel->enableEvents();
      };
    };
  }
  else
  {
    CFigureInstance* decoration;
    CFigureInstance* label;
    TConnectionDirection direction;
    TVertex* position;

    if (part == GC_CONNECTION_PART_1)
    {
      decoration = FEnd1Decoration;
      label = FEnd1Label;
      direction = FDirection1;
      position = &FEndVertex1;
    }
    else
    {
      decoration = FEnd2Decoration;
      label = FEnd2Label;
      direction = FDirection2;
      position = &FEndVertex2;
    };

    // Start with the decoration figure.
    if (decoration != NULL)
      applyTransformations(decoration, position, direction);

    // Next step is the label.
    if (label != NULL)
    {
      label->validate();
      if (decoration != NULL)
        decorationBounds = decoration->bounds();
      TBoundingBox labelBounds = label->localBounds();
      float labelWidth = labelBounds.lower.x - labelBounds.upper.x;
      float labelHeight = labelBounds.lower.y - labelBounds.upper.y;

      float labelX = 0;
      float labelY = 0;

      // Position computation is based on the idea to keep the label as close as possible to the local origin,
      // that is, the coordinate of the end point.
      switch (direction)
      {
        case GC_DIR_NORTH:
          {
            float dX1 = fabs(position->x - decorationBounds.upper.x);
            float dX2 = fabs(decorationBounds.lower.x - position->x);
            float dY = fabs(position->y - decorationBounds.upper.y);
            float x = (dX1 <= dX2) ? decorationBounds.upper.x : decorationBounds.lower.x;
            if (dX1 < dY || dX2 < dY)
            {
              // Left or right to the decoration is closer.
              if (dX1 <= dX2)
                labelX = x -labelWidth - niceDistance; 
              else
                labelX = x + niceDistance; 
              labelY = position->y - labelHeight - niceDistance;
            }
            else
            {
              // Above the decoration is closer.
              labelX = position->x + niceDistance;
              labelY = decorationBounds.lower.y - labelHeight - niceDistance;
            };
            break;
          };
        case GC_DIR_EAST:
          {
            float dY1 = fabs(decorationBounds.upper.y - position->y);
            float dY2 = fabs(position->y - decorationBounds.lower.y);
            float dX = fabs(decorationBounds.lower.x - position->x);
            float y = (dY1 <= dY2) ? decorationBounds.upper.y : decorationBounds.lower.y;
            if (dY1 < dX || dY2 < dX)
            {
              // Above or below the decoration is closer.
              labelX = position->x + niceDistance;
              if (dY1 <= dY2)
                labelY = y - labelHeight - niceDistance; 
              else
                labelY = y + niceDistance; 
            }
            else
            {
              // To the right of the decoration is closer.
              labelX = decorationBounds.lower.x + niceDistance;
              labelY = position->y + niceDistance;
            };
            break;
          };
        case GC_DIR_SOUTH:
          {
            float dX1 = fabs(position->x - decorationBounds.upper.x);
            float dX2 = fabs(decorationBounds.lower.x - position->x);
            float dY = fabs(decorationBounds.lower.y - position->y);
            float x = (dX1 <= dX2) ? decorationBounds.upper.x : decorationBounds.lower.x;
            if (dX1 < dY || dX2 < dY)
            {
              // Left or right to the decoration is closer.
              if (dX1 <= dX2)
                labelX = x - labelWidth - niceDistance; 
              else
                labelX = x + niceDistance; 
              labelY = position->y + niceDistance;
            }
            else
            {
              // Below the decoration is closer.
              labelX = position->x + niceDistance;
              labelY = decorationBounds.lower.y + niceDistance;
            };
            break;
          };
        case GC_DIR_WEST:
          {
            float dY1 = fabs(decorationBounds.upper.y - position->y);
            float dY2 = fabs(position->y - decorationBounds.lower.y);
            float dX = fabs(position->x - decorationBounds.upper.x);
            float y = (dY1 <= dY2) ? decorationBounds.upper.y : decorationBounds.lower.y;
            if (dY1 < dX || dY2 < dX)
            {
              // Above or below the decoration is closer.
              labelX = position->x - labelWidth - niceDistance;
              if (dY1 <= dY2)
                labelY = y - labelHeight - niceDistance; 
              else
                labelY = y + niceDistance; 
            }
            else
            {
              // To the left of the decoration is closer.
              labelX = decorationBounds.upper.x - labelWidth - niceDistance;
              labelY = position->y + niceDistance;
            };
            break;
          };
      };
      label->disableEvents();
      label->translate(labelX, labelY, 0);
      label->enableEvents();
    };
  };
};

//----------------------------------------------------------------------------------------------------------------------

/**
 * Helper method for CConnectionInstance::updateDecorations. It checks if the given figure instance still corresponds
 * to the figure and if not updates the instance.
 */
void CConnectionInstance::updateFigureInstance(CFigureInstance** instance, CFigure* figure)
{
 if ((*instance != NULL) && (figure != NULL))
  {
    // Both references exist. Check if they refer to the same figure.
    if ((*instance)->figure() != figure)
    {
      // Our connection has a new figure as decoration/label. Delete the instance we created for it.
      // A new figure instance will be created by the following code then.
      (*instance)->removeListener(&FListener);
      delete *instance;
      *instance = NULL;
    };
  };

  if ((*instance == NULL) != (figure == NULL))
  {
    // One of both entries does not yet/no longer exist.
    if (*instance != NULL)
    {
      (*instance)->removeListener(&FListener);
      delete *instance;
      *instance = NULL;
    }
    else
    {
      // A new decoration/label was added, create a figure instance for that.
      *instance = new CFigureInstance(NULL, figure);
      (*instance)->addListener(&FListener);
    };
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Called when the zoom level in the owner view changed. Tell the decorations about it.
 *
 * @param newZoom The new zoom level.
 */
void CConnectionInstance::zoomChanged(float newZoom)
{
  if (FEnd1Decoration != NULL)
    FEnd1Decoration->zoomChanged(newZoom);
  if (FEnd1Label != NULL)
    FEnd1Label->zoomChanged(newZoom);
  if (FCenterDecoration != NULL)
    FCenterDecoration->zoomChanged(newZoom);
  if (FCenterLabel != NULL)
    FCenterLabel->zoomChanged(newZoom);
  if (FEnd2Decoration != NULL)
    FEnd2Decoration->zoomChanged(newZoom);
  if (FEnd2Label != NULL)
    FEnd2Label->zoomChanged(newZoom);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Overrides the hit computation of the base class to precise the result further.
 *
 * @param x Horizontal hit coordinate.
 * @param y Vertical hit coordinate.
 */
bool CConnectionInstance::containsPoint(const float x, const float y)
{
  bool result = CGraphicElement::containsPoint(x, y);
  if (result)
  {
    TVertex vertex = TVertex(x, y, 0);
    result = getFeedbackInfo(GC_MODIFIER_IGNORE, vertex) != GC_FI_NONE;
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes the final coordinates of this connection at the given end point (which must be one of the end points
 * of this connection instance).
 *
 * @param point One of the end points of this connection.
 * @param direction Indicates the edge where the connection leaves the end point.
 * @param slot A distribution offset in the range (0..1) that controls the relative position along the edge.
 * @param alternative Indicates to to use the opposite end point instead what @point would refer to. 
 *                    Used, e.g., for self references.
 */
void CConnectionInstance::computeCoordinates(CFigureInstance* point, TConnectionDirection direction, float slot, 
                                             bool alternative)
{
  TVertex coordinates;

  if ((point == FEnd1) != alternative)
    FDirection1 = direction;
  else
    FDirection2 = direction;

  TBoundingBox bounds = point->bounds();
  switch (direction)
  {
    case GC_DIR_NORTH:
      {
        coordinates.x = (bounds.lower.x - bounds.upper.x) * slot + bounds.upper.x;
        coordinates.y = bounds.upper.y;
        break;
      };
    case GC_DIR_EAST:
      {
        coordinates.x = bounds.lower.x;
        coordinates.y = (bounds.lower.y - bounds.upper.y) * slot + bounds.upper.y;
        break;
      };
    case GC_DIR_SOUTH:
      {
        coordinates.x = (bounds.lower.x - bounds.upper.x) * slot + bounds.upper.x;
        coordinates.y = bounds.lower.y;
        break;
      };
    case GC_DIR_WEST:
      {
        coordinates.x = bounds.upper.x;
        coordinates.y = (bounds.lower.y - bounds.upper.y) * slot + bounds.upper.y;
        break;
      };
  };
  if ((point == FEnd1) != alternative)
    FEndVertex1 = coordinates;
  else
    FEndVertex2 = coordinates;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Determines in which direction this connection leaves the given point. This depends entirely on the positions of the
 * endpoints.
 *
 * @param point The point to consider, must be one of the end points of this connection.
 * @return One of the direction flags.
 */
TConnectionDirection CConnectionInstance::getDirection(CFigureInstance* point)
{
  TConnectionDirection result = GC_DIR_NONE;

  CFigureInstance* from = NULL;
  CFigureInstance* to = NULL;
  if (point == FEnd1)
  {
    from = FEnd1;
    to = FEnd2;
  }
  else
    if (point == FEnd2)
    {
      from = FEnd2;
      to = FEnd1;
    };

  if (from != NULL && to != NULL)
  {
    if (from == to)
      // The connection starts and ends on the same end point.
      result = GC_DIR_SELF;
    else
    {
      TBoundingBox fromBounds = from->bounds();
      TBoundingBox toBounds = to->bounds();

      result = GC_DIR_NORTH;
      float distance = fromBounds.upper.y - toBounds.lower.y;
      if (toBounds.upper.x - fromBounds.lower.x > distance)
      {
        result = GC_DIR_EAST;
        distance = toBounds.upper.x - fromBounds.lower.x;
      };
      if (toBounds.upper.y - fromBounds.lower.y > distance)
      {
        result = GC_DIR_SOUTH;
        distance = toBounds.upper.y - fromBounds.lower.y;
      };
      if (fromBounds.upper.x - toBounds.lower.x > distance)
      {
        result = GC_DIR_WEST;
        distance = toBounds.lower.x - fromBounds.upper.x;
      };
    };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Returns info about the connection at the specified point.
 *
 * @param modifiers Any combination of Alt, Control and Shift key.
 * @param coords The coordinates to check against.
 * @return The requested info.
 */
TFeedbackInfo CConnectionInstance::getFeedbackInfo(TModifiers modifiers, const TVertex& coords)
{
  TFeedbackInfo result;

  // End points. They are always assigned.
  result = FEnd1->getFeedbackInfo(modifiers, coords);
  if (result == GC_FI_NONE)
    result = FEnd2->getFeedbackInfo(modifiers, coords);

  // Decorations and labels. They may not always be assigned.
  if (result == GC_FI_NONE && FEnd1Decoration != NULL)
    result = FEnd1Decoration->getFeedbackInfo(modifiers, coords);
  if (result == GC_FI_NONE && FEnd1Label != NULL)
    result = FEnd1Label->getFeedbackInfo(modifiers, coords - FLabel1Offset);
  if (result == GC_FI_NONE && FCenterDecoration != NULL)
    result = FCenterDecoration->getFeedbackInfo(modifiers, coords);
  if (result == GC_FI_NONE && FCenterLabel != NULL)
    result = FCenterLabel->getFeedbackInfo(modifiers, coords - FCenterLabelOffset);
  if (result == GC_FI_NONE && FEnd2Decoration != NULL)
    result = FEnd2Decoration->getFeedbackInfo(modifiers, coords);
  if (result == GC_FI_NONE && FEnd2Label != NULL)
    result = FEnd2Label->getFeedbackInfo(modifiers, coords - FLabel2Offset);

  if (result == GC_FI_NONE)
  {
    float distance = 10; // Distance to the line segments to be considered as "on line".
    float centerPoint = computeCenterPosition();

    if (FDirection1 == GC_DIR_NORTH || FDirection1 == GC_DIR_SOUTH)
    {
      float minX = MIN(FEndVertex1.x, FEndVertex2.x);
      float maxX = MAX(FEndVertex1.x, FEndVertex2.x);
      if (fabs(centerPoint - coords.y) <= distance && (minX <= coords.x) && (coords.x <= maxX))
        // Close to the center line.
        result = GC_FI_HLINE_MOVE;
      else
      {
        // Check the other two segments.
        if (coords.y < centerPoint)
        {
          // Above the center.
          float actualX = (FEndVertex1.y <= centerPoint) ? FEndVertex1.x : FEndVertex2.x;
          if (fabs(actualX - coords.x) <= distance)
            result = GC_FI_CONNECTION;
        }
        else
        {
          // Below the center
          float actualX = (FEndVertex1.y > centerPoint) ? FEndVertex1.x : FEndVertex2.x;
          if (fabs(actualX - coords.x) <= distance)
            result = GC_FI_CONNECTION;
        };
      };
    }
    else
    {
      float minY = MIN(FEndVertex1.y, FEndVertex2.y);
      float maxY = MAX(FEndVertex1.y, FEndVertex2.y);
      if (fabs(centerPoint - coords.x) <= distance && (minY <= coords.y) && (coords.y <= maxY))
        // Close to the center line.
        result = GC_FI_VLINE_MOVE;
      else
      {
        // Check the other two segments.
        if (coords.x < centerPoint)
        {
          // Left to the center.
          float actualY = (FEndVertex1.x <= centerPoint) ? FEndVertex1.y : FEndVertex2.y;
          if (fabs(actualY - coords.y) <= distance)
            result = GC_FI_CONNECTION;
        }
        else
        {
          // Right to the center
          float actualY = (FEndVertex1.x > centerPoint) ? FEndVertex1.y : FEndVertex2.y;
          if (fabs(actualY - coords.y) <= distance)
            result = GC_FI_CONNECTION;
        };
      };
    };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Returns the connection decoration part whose label is at the given position.
 *
 * @param x The x coordinate to check in layer space.
 * @param y The y coordinate.
 * @return The part that has a label at the given position.
 */
TConnectionPart CConnectionInstance::labelPartFromPoint(float x, float y)
{
  TConnectionPart result = GC_CONNECTION_PART_NONE;
  if (FEnd1Label != NULL && FEnd1Label->containsPoint(x - FLabel1Offset.x, y - FLabel1Offset.y))
    result = GC_CONNECTION_PART_1;
  else
    if (FEnd2Label != NULL && FEnd2Label->containsPoint(x - FLabel2Offset.x, y - FLabel2Offset.y))
      result = GC_CONNECTION_PART_2;
    else
      if (FCenterLabel != NULL && FCenterLabel->containsPoint(x - FCenterLabelOffset.x, y - FCenterLabelOffset.y))
        result = GC_CONNECTION_PART_CENTER;
  
  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Changes the visual style of the connection lines.
 *
 * @param lineStyle The new line style to apply.
 */
void CConnectionInstance::lineStyleSet(TConnectionLineStyle newStyle)
{
  if (FLineStyle != newStyle)
  {
    FLineStyle = newStyle;
    makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Moves the current center point to the given position. This position is converted into a procentual value for the
 * center and only one dimension (depending on the orientation of the connection) is considered.
 *
 * @param position The new position for the center.
 */
void CConnectionInstance::moveCenterTo(TVertex position)
{
  if (FEnd1 == FEnd2)
  {
    // Self referencing, means this connections starts and stops at the same end point.
    float fullWidth;
    float fullHeight;

    // Compute the center as percentage of the entire width/height.
    canvas()->currentViewGet()->getWorkspace(&fullWidth, &fullHeight);

    switch (FDirection1)
    {
      case GC_DIR_SOUTH:
      case GC_DIR_NORTH:
      {
        float offset = (FEnd1Decoration != NULL) ? FEnd1Decoration->height() : 0;
        if ((FEnd2Decoration != NULL) && FEnd2Decoration->height() > offset)
          offset = FEnd2Decoration->height();

        if (FDirection1 == GC_DIR_NORTH)
          FCenter = (FEndVertex1.y - offset - position.y) / fullHeight;
        else
          FCenter = (position.y - FEndVertex1.y - offset) / fullHeight;
        
        break;
      }
      default:
      {
        // GC_DIR_EAST/GC_DIR_WEST
        float offset = (FEnd1Decoration != NULL) ? FEnd1Decoration->width() : 0;
        if ((FEnd2Decoration != NULL) && FEnd2Decoration->width() > offset)
          offset = FEnd2Decoration->width();

        if (FDirection1 == GC_DIR_WEST)
          FCenter = (FEndVertex1.x - offset - position.x) / fullWidth;
        else
          FCenter = (position.x - FEndVertex1.x - offset) / fullWidth;

        break;
      };
    };
  }
  else
    switch (FDirection1)
    {
      case GC_DIR_SOUTH:
      case GC_DIR_NORTH:
      {
        if (FEndVertex1.y <= FEndVertex2.y)
          FCenter = (position.y - FEndVertex1.y) / (FEndVertex2.y - FEndVertex1.y);
        else
          FCenter = (position.y - FEndVertex2.y) / (FEndVertex1.y - FEndVertex2.y);

        break;
      }
      default:
      {
        // GC_DIR_EAST/GC_DIR_WEST
        if (FEndVertex1.x <= FEndVertex2.x)
          FCenter = (position.x - FEndVertex1.x) / (FEndVertex2.x - FEndVertex1.x);
        else
          FCenter = (position.x - FEndVertex2.x) / (FEndVertex1.x - FEndVertex2.x);

        break;
      };
    };

  if (FCenter < 0)
    FCenter = 0;
  if (FCenter > 1)
    FCenter = 1;

  makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Moves the label of the given part by the given amount.
 *
 * @param part The part whose label is to be moved.
 * @param dX The horizontal amount to move the label.
 * @param dY The vertical amount to move the label.
 */
void CConnectionInstance::moveLabel(TConnectionPart part, float dX, float dY)
{
  switch (part)
  {
    case GC_CONNECTION_PART_1:
      {
        FLabel1Offset.x += dX;
        FLabel1Offset.y += dY;
        break;
      };
    case GC_CONNECTION_PART_2:
      {
        FLabel2Offset.x += dX;
        FLabel2Offset.y += dY;
        break;
      };
    case GC_CONNECTION_PART_CENTER:
      {
        FCenterLabelOffset.x += dX;
        FCenterLabelOffset.y += dY;
        break;
      };
  };
  makeDirty(GC_CHANGE_CONNECTION_LABEL);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Retrieves the value of the property given by path. The path syntax is must be something like (here expressed as regex)
 * (container)*(property), where container is a slash and the name of a container class (e.g. layers, figures) and
 * property is the name of a simple property of that container.
 *
 * @param name The name of the property to return.
 * @param index The index of the sub property to return if it is located in a list.
 * @return A description of the property value and, if the property is simple, the actual value.
 */
TGCVariant CConnectionInstance::propertyGet(const char* name, unsigned int index)
{
  TGCVariant result;

  switch (getContainerID(name))
  {
    case GC_CONTAINER_UNKNOWN:
      {
        switch (getPropertyID(name))
        {
          case GC_PROPERTY_CENTER:
          {
            result = FCenter;
            break;
          };
		  case GC_PROPERTY_LABEL1_OFFSET_X:
          {
            result = FLabel1Offset.x;
            break;
          };
          case GC_PROPERTY_LABEL1_OFFSET_Y:
          {
            result = FLabel1Offset.y;
            break;
          };
          case GC_PROPERTY_LABEL2_OFFSET_X:
          {
            result = FLabel2Offset.x;
            break;
          };
          case GC_PROPERTY_LABEL2_OFFSET_Y:
          {
            result = FLabel2Offset.y;
            break;
          };
          case GC_PROPERTY_LABEL_CENTER_OFFSET_X:
          {
            result = FCenterLabelOffset.x;
            break;
          };
          case GC_PROPERTY_LABEL_CENTER_OFFSET_Y:
          {
            result = FCenterLabelOffset.y;
            break;
          };            
        };

        break;
      };
    case GC_CONTAINER_COLOR:
      {
        if (index < 4)
        {
          result = FColor[index];
		};
        break;
      };
    case GC_CONTAINER_HOT_COLOR:
      {
        if (index < 4)
        {
          result = FHotColor[index];
        };
        break;
      };
    case GC_CONTAINER_CONNECTION:
      {
        result = FConnection;
        break;
      };
    case GC_CONTAINER_END1:
      {
        result = FEnd1;
        break;
      };
    case GC_CONTAINER_END1_DECORATION:
      {
        result = FEnd1Decoration;
        break;
      };
    case GC_CONTAINER_END1_LABEL:
      {
        result = FEnd1Label;
        break;
      };
    case GC_CONTAINER_END2:
      {
        result = FEnd2;
        break;
      };
    case GC_CONTAINER_END2_DECORATION:
      {
        result = FEnd2Decoration;
		break;
      };
    case GC_CONTAINER_END2_LABEL:
      {
        result = FEnd2Label;
        break;
      };
    case GC_CONTAINER_CENTER_DECORATION:
      {
        result = FCenterDecoration;
        break;
      };
    case GC_CONTAINER_CENTER_LABEL:
      {
        result = FCenterLabel;
        break;
      };
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Sets the value of the given property, which must be a simple property.
 *
 * @param name The name of the property.
 * @param index The index of the sub property to return if it is located in a list.
 * @param value The new value of the property. Automatic conversion is performed where possible.
 */
void CConnectionInstance::propertySet(const char* name, unsigned int index, TGCVariant value)
{
  switch (getContainerID(name))
  {
	case GC_CONTAINER_UNKNOWN:
	  {
		switch (getPropertyID(name))
		{
		  case GC_PROPERTY_CENTER:
          {
            FCenter = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL1_OFFSET_X:
          {
            FLabel1Offset.x = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL1_OFFSET_Y:
          {
            FLabel1Offset.y = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL2_OFFSET_X:
          {
            FLabel2Offset.x = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL2_OFFSET_Y:
          {
            FLabel2Offset.y = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL_CENTER_OFFSET_X:
          {
            FCenterLabelOffset.x = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };
          case GC_PROPERTY_LABEL_CENTER_OFFSET_Y:
          {
            FCenterLabelOffset.y = value;
            makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
            break;
          };            
        };

        break;
      };
    case GC_CONTAINER_COLOR:
      {
        if (index < 4)
        {
          FColor[index] = value;
          makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        };
        break;
      };
    case GC_CONTAINER_HOT_COLOR:
      {
        if (index < 4)
        {
          FHotColor[index] = value;
          makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        };
        break;
      };
    case GC_CONTAINER_CONNECTION:
      {
        FConnection = value.cast<CConnection>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END1:
      {
        FEnd1 = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END1_DECORATION:
      {
        FEnd1Decoration = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END1_LABEL:
      {
        FEnd1Label = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END2:
      {
        FEnd2 = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END2_DECORATION:
      {
        FEnd2Decoration = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_END2_LABEL:
      {
        FEnd2Label = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_CENTER_DECORATION:
      {
        FCenterDecoration = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
    case GC_CONTAINER_CENTER_LABEL:
      {
        FCenterLabel = value.cast<CFigureInstance>();
        makeDirty(GC_CHANGE_CONNECTION_INSTANCE);
        break;
      };
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Renders this instance.
 *
 * @param isHot A marker if the current instance has the mouse cursor over it.
 */
void CConnectionInstance::render(bool isHot)
{
  if (isHot)
    glColor4fv(FHotColor);
  else
    glColor4fv(FColor);
  glCallList(FDisplayList);

  // Decorations
  renderDecoration(GC_CONNECTION_PART_1);
  renderDecoration(GC_CONNECTION_PART_CENTER);
  renderDecoration(GC_CONNECTION_PART_2);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Called by the listener when something in the connection's decoration changed or any of used figure instance is being 
 * destroyed. Use this notification to (re)build the figure instances we use for decoration.
 */
void CConnectionInstance::updateDecorations(void)
{
  TConnectionDecorations decorations = FConnection->decorationsGet();

  updateFigureInstance(&FEnd1Decoration, decorations.end1Decoration);
  updateFigureInstance(&FEnd1Label, decorations.end1Label);
  updateFigureInstance(&FCenterDecoration, decorations.centerDecoration);
  updateFigureInstance(&FCenterLabel, decorations.centerLabel);
  updateFigureInstance(&FEnd2Decoration, decorations.end2Decoration);
  updateFigureInstance(&FEnd2Label, decorations.end2Label);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes all detail elements for this connection depending on computed start and end point as well as other properties.
 */
void CConnectionInstance::validate(void)
{
  if (dirty())
  {
    if (FLayer != NULL)
    {
      FLayer->validateEndPoint(FEnd1, true);
      FLayer->validateEndPoint(FEnd2, false);
    };
    if (FEnd1Decoration != NULL)
      FEnd1Decoration->validate();
    if (FEnd1Label != NULL)
      FEnd1Label->validate();
    if (FCenterDecoration != NULL)
      FCenterDecoration->validate();
    if (FCenterLabel != NULL)
      FCenterLabel->validate();
    if (FEnd2Decoration != NULL)
      FEnd2Decoration->validate();
    if (FEnd2Label != NULL)
      FEnd2Label->validate();

    if (FDisplayList == 0)
      FDisplayList = glGenLists(1);

    glNewList(FDisplayList, GL_COMPILE);
      glPushMatrix();
      glPushAttrib(GL_ENABLE_BIT);
      glDisable(GL_LINE_SMOOTH);
      glDisable(GL_POLYGON_SMOOTH);
      if (canvas()->supportsExtension(GC_OE_MULTISAMPLING))
        glDisable(GL_MULTISAMPLE_ARB); 

      switch (FLineStyle)
      {
        case GC_CONNECTION_STYLE_SOLID:
          break;
        case GC_CONNECTION_STYLE_DOTTED:
          {
            glEnable(GL_LINE_STIPPLE);
            glLineStipple (1, 0x3333);
            break;
          };
      };

      glBegin(GL_LINE_STRIP);
      float centerPoint = computeCenterPosition();
      if (FDirection1 == GC_DIR_NORTH || FDirection1 == GC_DIR_SOUTH)
      {
        // We need to distinguish here only if we have a vertical or horizontal run.
        // So checking only one direction is enough.
        glVertex2f(FEndVertex1.x, FEndVertex1.y);
        glVertex2f(FEndVertex1.x, centerPoint);
        glVertex2f(FEndVertex2.x, centerPoint);
        glVertex2f(FEndVertex2.x, FEndVertex2.y);
      }
      else
      {
        glVertex2f(FEndVertex1.x, FEndVertex1.y);
        glVertex2f(centerPoint, FEndVertex1.y);
        glVertex2f(centerPoint, FEndVertex2.y);
        glVertex2f(FEndVertex2.x, FEndVertex2.y);
      };
      glEnd();
      glPopAttrib();
      glPopMatrix();
    glEndList();

    // Valdate decoration and compute the overall bounding box.
    boundsNew();
    boundsAdd(FEndVertex1);
    boundsAdd(FEndVertex2);

    updateDecoration(GC_CONNECTION_PART_1);
    if (FEnd1Decoration != NULL)
      boundsAdd(FEnd1Decoration->bounds());
    if (FEnd1Label != NULL)
      boundsAdd(FEnd1Label->bounds(), FLabel1Offset);

    updateDecoration(GC_CONNECTION_PART_CENTER);
    if (FCenterDecoration != NULL)
      boundsAdd(FCenterDecoration->bounds());
    if (FCenterLabel != NULL)
      boundsAdd(FCenterLabel->bounds(), FCenterLabelOffset);

    updateDecoration(GC_CONNECTION_PART_2);
    if (FEnd2Decoration != NULL)
      boundsAdd(FEnd2Decoration->bounds());
    if (FEnd2Label != NULL)
      boundsAdd(FEnd2Label->bounds(), FLabel2Offset);

    boundsFinished();

    FConnection->boundsNew();
    FConnection->boundsAdd(FEndVertex1);
    FConnection->boundsAdd(FEndVertex2);
    FConnection->boundsFinished();

    CGraphicElement::validate();
  };
}

//----------------- CConnectionInstanceListener --------------------------------------------------------------------------

void CConnectionLayer::CConnectionInstanceListener::onChange(CGCBase* sender, CGCBase* origin, TGCChangeReason reason)
{
  layer->handleChange((CConnectionInstance*) sender, reason);
}

//----------------------------------------------------------------------------------------------------------------------

void CConnectionLayer::CConnectionInstanceListener::onDestroy(CGCBase* object)
{
  layer->removeInstance((CConnectionInstance*) object);
}

//----------------------------------------------------------------------------------------------------------------------

void CConnectionLayer::CConnectionInstanceListener::onError(CGCBase* sender, CGCBase* origin, const char* message)
{
  layer->error(origin, message);
}

//----------------- CConnectionLayer ------------------------------------------------------------------------------------

CConnectionLayer::CConnectionLayer(CGCView* view): CLayer("connections", view->canvas())
{
  _className = "CConnectionLayer";
  FView = view;
  FListener.layer = this;
  FHotConnection = NULL;
  FStates = 0;
  FCache = NULL;
  FCurrentFeedback = GC_FI_NONE;
}

//----------------------------------------------------------------------------------------------------------------------

CConnectionLayer::~CConnectionLayer(void)
{
  setDestroying();

  delete FCache;

  for (CConnectionInstanceList::iterator iterator = FConnections.begin(); iterator != FConnections.end(); ++iterator)
    delete *iterator;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Checks for an action that can be executed in the layer.
 *
 * @param button Which button has been pressed (left, middle, right, x1, x2).
 * @param event The mouse event that caused the handling chain to start (up, down etc.).
 * @param modifiers Special flags that control the processing.
 * @param windowX Horizontal mouse coordinate in window space.
 * @param windowY Vertical mouse coordinate in window space.
 * @param viewCoords Mouse coordinates converted to view space.
 * @return True if there was an action to execute, otherwise false.
 */
bool CConnectionLayer::handleAction(TMouseButton button, TMouseEvent event, TModifiers modifiers, int windowX, int windowY, 
                                    TVertex& viewCoords)
{
  bool result = false;
  bool keepHitInfo = false;

  updateCache();
  FLastHit = (CConnectionInstance*) FCache->findElement(viewCoords);
  if (FLastHit != NULL)
  {
    TAction* action = FLastHit->executeAssociatedActions(button, event, modifiers, viewCoords);
    if (action != NULL)
    {
      result = true;
      if (action != NULL)
      {
        if (action->type == GC_ACTION_DRAG)
        {
          FStates |= GC_CLAYER_STATE_DRAG_LABEL_PENDING;

          FLabelPart = FLastHit->labelPartFromPoint(viewCoords.x, viewCoords.y);
          keepHitInfo = true;
        }
      };
    }
    else
    {
      TFeedbackInfo info = FLastHit->getFeedbackInfo(modifiers, viewCoords);
      switch (info)
      {
      case GC_FI_CONNECTION:
        {
          // Select the connection.
          break;
        };
      case GC_FI_HLINE_MOVE:
        {
          FStates |= GC_CLAYER_STATE_HDRAG_PENDING;
          result = true;
          break;
        };
      case GC_FI_VLINE_MOVE:
        {
          FStates |= GC_CLAYER_STATE_VDRAG_PENDING;
          result = true;
          break;
        };
      };
    };
  };

  if (keepHitInfo)
  {
    FLastWindowX = windowX;
    FLastWindowY = windowY;  
    FLastViewX = viewCoords.x;
    FLastViewY = viewCoords.y;
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Marks all connection instances the are connected to the given endpoint as dirty, if they are not already.
 *
 * @param point The endpoint to iterate.
 */
void CConnectionLayer::invalidateEndPoint(CFigureInstance* point)
{
  CFigureConnectionList::iterator pointIterator = FConnectionPointList.find(point);
  for (CConnectionInstanceList::iterator iterator = pointIterator->second.begin(); iterator != pointIterator->second.end(); 
    ++iterator)
  {
    CConnectionInstance* instance = *iterator;
    if (!instance->dirty())
    {
      instance->makeDirty();
      if (instance->endPoint1() == point)
        invalidateEndPoint(instance->endPoint2());
      else
        invalidateEndPoint(instance->endPoint1());
    };
  };
}

//----------------------------------------------------------------------------------------------------------------------

// Binary predicates used to sort the direction lists in the next method.
// Return whether first element is less than the second

bool moreLeft(CConnectionInstance* element1, CConnectionInstance* element2)
{
  // Both connections share one end point. Compare the other two.
  CFigureInstance* point1 = element1->endPoint2();
  CFigureInstance* point2 = element1->endPoint2();
  if (element1->endPoint1() == element2->endPoint2())
    point2 = element2->endPoint1();
  else
    if (element1->endPoint2() == element2->endPoint1())
      point1 = element1->endPoint1();
    else
      if (element1->endPoint2() == element2->endPoint2())
      {
        point1 = element1->endPoint1();
        point2 = element2->endPoint1();
      };

  TBoundingBox bounds1 = point1->bounds();
  float middle1 = (bounds1.lower.x + bounds1.upper.x) / 2;
  TBoundingBox bounds2 = point2->bounds();
  float middle2 = (bounds2.lower.x + bounds2.upper.x) / 2;

  return middle1 < middle2;;
}

//----------------------------------------------------------------------------------------------------------------------

bool moreTop(CConnectionInstance* element1, CConnectionInstance* element2)
{
  // Both connections share one end point. Compare the other two.
  CFigureInstance* point1 = element1->endPoint2();
  CFigureInstance* point2 = element1->endPoint2();
  if (element1->endPoint1() == element2->endPoint2())
    point2 = element2->endPoint1();
  else
    if (element1->endPoint2() == element2->endPoint1())
      point1 = element1->endPoint1();
    else
      if (element1->endPoint2() == element2->endPoint2())
      {
        point1 = element1->endPoint1();
        point2 = element2->endPoint1();
      };

  TBoundingBox bounds1 = point1->bounds();
  float middle1 = (bounds1.lower.y + bounds1.upper.y) / 2;
  TBoundingBox bounds2 = point2->bounds();
  float middle2 = (bounds2.lower.y + bounds2.upper.y) / 2;

  return middle1 < middle2;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Renders all connections, which have been validate before in validateLayerContent.
 */
void CConnectionLayer::renderLayerContent(TBoundingBox bounds)
{
  for (CConnectionInstanceList::iterator iterator = FConnections.begin(); iterator != FConnections.end(); ++iterator)
  {
    CConnectionInstance* instance = *iterator;
    if (instance->overlaps(bounds))
      instance->render(instance == FHotConnection);
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Checks if the layer's element cache must be created and validated.
 */
void CConnectionLayer::updateCache(void)
{
  if (FCache == NULL)
  {
    float width, height;
    FView->getWorkspace(&width, &height);
    FCache = new CElementLookupCache(width, height);
  };

  if (!FCache->isValid())
  {
    for (CConnectionInstanceList::iterator iterator = FConnections.begin(); iterator != FConnections.end(); ++iterator)
      FCache->addElement(*iterator);

    FCache->validate();
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes the layout for all connection instances.
 * Note: the invalidation code (@see invalidateInstance) takes care that either all connection instances connected to an
 *       end point are dirty or none of them.
 */
void CConnectionLayer::validateLayerContent(void)
{
  // Iterate through all dirty connection instances and validates them.
  for (CConnectionInstanceList::iterator iterator = FConnections.begin(); iterator != FConnections.end(); ++iterator)
    (*iterator)->validate();
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Called when the zoom level in the owner view is changed. Forward the call to the connections.
 *
 * @param newZoom The new zoom level.
 */
void CConnectionLayer::zoomChanged(float newZoom)
{
  for (CConnectionInstanceList::iterator iterator = FConnections.begin(); iterator != FConnections.end(); ++iterator)
    (*iterator)->zoomChanged(newZoom);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Creates a new connection instance.
 *
 * @param connection The connection for which the instance is to be created.
 * @param endPoint1 One end point of the instnace.
 * @param endPoint2 The other end point of the instance.
 */
CConnectionInstance* CConnectionLayer::createInstance(CConnection* connection, CFigureInstance* endPoint1, 
                                                      CFigureInstance* endPoint2)
{
  CConnectionInstance* result = new CConnectionInstance(this, connection, endPoint1, endPoint2);
  result->addListener(&FListener);
  FConnections.insert(result);
  FConnectionPointList[endPoint1].insert(result);
  invalidateEndPoint(endPoint1);
  FConnectionPointList[endPoint2].insert(result);
  invalidateEndPoint(endPoint2);
  if (FCache != NULL)
    FCache->addElement(result);
  makeDirty();

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Checks the given position and hit element for a detailed hit information.
 *
 * @param modifiers Any combination of Alt, Control and Shift key.
 * @param coords The position to test against.
 * @return Info about the hit if any.
 */
TFeedbackInfo CConnectionLayer::getFeedbackInfo(TModifiers modifiers, TVertex& coords)
{
  TFeedbackInfo result = GC_FI_NONE;

  if (FStates == 0)
  {
    updateCache();

    CConnectionInstance* instance = (CConnectionInstance*) FCache->findElement(coords);
    if (instance != NULL)
      result = instance->getFeedbackInfo(modifiers, coords);
  }
  else
    result = FCurrentFeedback;

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Takes the given coordinates and tries to find a graphic element that was rendered at this position.
 * Positions are given in view space.
 *
 * @param hits [out] The hit collection that is updated.
 * @param point The point to check given in view space. If necessary convert window coordinates first by using windowToView.
 * @param singleHit If true then search for hits is stopped after the first one was found.
 * @return A hit result class is returned regardless of the actual number of hits. It must be freed by the caller.
 */
void CConnectionLayer::getHitTestInfoAt(CHitResults* hits, TVertex point, bool singleHit)
{
  updateCache();
  if (singleHit)
  {
    CGraphicElement* element = FCache->findElement(point);
    if (element != NULL)
      hits->addHit(element);
  }
  else
    FCache->findElements(point, hits);
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Invalidates all connection instances that are connected to the end point of the given connection instance.
 *
 * @param The connection instance that has changed.
 */
void CConnectionLayer::handleChange(CConnectionInstance* instance, TGCChangeReason reason)
{
  switch (reason)
  {
    case GC_CHANGE_CONNECTION_INSTANCE:
      {
        #if USE_BSP_TREE
          if (FCache)
            FCache->invalidate();
        #endif

        invalidateEndPoint(instance->endPoint1());
        invalidateEndPoint(instance->endPoint2());
        break;
      };
  };
  change(instance, reason);
  makeDirty();
}

//----------------------------------------------------------------------------------------------------------------------

bool CConnectionLayer::handleMouseDown(TMouseButton button, TModifiers modifiers, int windowX, int windowY, TVertex& viewCoords)
{
  bool result = handleAction(button, GC_MOUSE_DOWN, modifiers, windowX, windowY, viewCoords);

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

bool CConnectionLayer::handleMouseMove(TModifiers modifiers, int windowX, int windowY, TVertex& viewCoords)
{
  bool result = false;

  if (FStates == 0)
  {
    // No special action active so highlight the current connection if hot tracking is enabled.
    updateCache();
    CGraphicElement* element = FCache->findElement(viewCoords);
    if (element != NULL)
    {
      if (element->classIs("CConnectionInstance") && element != FHotConnection)
      {
        FHotConnection = (CConnectionInstance*) element;
        canvas()->refresh();
      };
    }
    else
      if (FHotConnection != NULL)
      {
        FHotConnection = NULL;
        canvas()->refresh();
      };
  }
  else
  {
    float threshold = 4; // Empirically found.
    float dX = viewCoords.x - FLastViewX;
    float dY = viewCoords.y - FLastViewY;
    
    // Check for center line dragging.
    if ((FStates & GC_CLAYER_STATE_HDRAG_PENDING) != 0)
    {
      // Drag is still waiting to start. Check if the user moved the mouse a bit.
      if (fabs(dY) >= threshold)
      {
        FStates &= ~GC_CLAYER_STATE_HDRAG_PENDING;
        FStates |= GC_CLAYER_STATE_CENTER_DRAGGING;
        FCurrentFeedback = GC_FI_HLINE_MOVE;
      };
    }
    else
      if ((FStates & GC_CLAYER_STATE_VDRAG_PENDING) != 0)
      {
        // Drag is still waiting to start. Check if the user moved the mouse a bit.
        float threshold = 4; // Empirically found.
        if (fabs(dX) >= threshold)
        {
          FStates &= ~GC_CLAYER_STATE_VDRAG_PENDING;
          FStates |= GC_CLAYER_STATE_CENTER_DRAGGING;
          FCurrentFeedback = GC_FI_VLINE_MOVE;
        };
      }
      else
        if ((FStates & GC_CLAYER_STATE_DRAG_LABEL_PENDING) != 0)
        {
          // Label drag is still waiting to start. Check if the user moved the mouse a bit.
          if (fabs(dX) >= threshold || fabs(dY) >= threshold)
          {
            FStates &= ~GC_CLAYER_STATE_DRAG_LABEL_PENDING;
            FStates |= GC_CLAYER_STATE_DRAG_LABEL;
            FCurrentFeedback = GC_FI_DRAG_FIGURE;
          };
        };

    if ((FStates & GC_CLAYER_STATE_CENTER_DRAGGING) != 0)
    {
      FLastHit->moveCenterTo(viewCoords);
#if USE_BSP_TREE
      FCache->invalidate();
#endif
      result = true;
    }
    else
      if ((FStates & GC_CLAYER_STATE_DRAG_LABEL) != 0)
      {
        FLastHit->moveLabel(FLabelPart, dX, dY);
        result = true;
      };
  };

  if (result)
  {
    FLastViewX = viewCoords.x;
    FLastViewY = viewCoords.y;
  };

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

bool CConnectionLayer::handleMouseUp(TMouseButton button, TModifiers modifiers, int windowX, int windowY, TVertex& viewCoords)
{
  bool result = handleAction(button, GC_MOUSE_UP, modifiers, windowX, windowY, viewCoords);

  FStates &= ~(GC_CLAYER_STATE_HDRAG_PENDING | GC_CLAYER_STATE_VDRAG_PENDING | GC_CLAYER_STATE_DRAG_LABEL_PENDING |
    GC_CLAYER_STATE_CENTER_DRAGGING | GC_CLAYER_STATE_DRAG_LABEL);

  return result;
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Removes the given instance from the internal list. The connection instance is not destroyed, though.
 *
 * @param instance The connection instance to be removed.
 */
void CConnectionLayer::removeInstance(CConnectionInstance* instance)
{
  if (!destroying())
  {
    if (FCache)
      FCache->invalidate();

    if (FHotConnection == instance)
      FHotConnection = NULL;

    CFigureInstance* point = instance->FEnd1;
    FConnectionPointList[point].erase(instance);
    if (FConnectionPointList[point].size() == 0)
      FConnectionPointList.erase(point);

    point = instance->FEnd2;
    FConnectionPointList[point].erase(instance);
    if (FConnectionPointList[point].size() == 0)
      FConnectionPointList.erase(point);

    FConnections.erase(instance);

    makeDirty();
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Computes the coordinates of all connection instances touching the given point.
 *
 * @param point The endpoint to validate.
 * @param handleSelfReferences If true then also consider connections that start and end at the same point.
 */
void CConnectionLayer::validateEndPoint(CFigureInstance* point, bool handleSelfReferences)
{
  typedef vector<CConnectionInstance*> CLocalConnectionList;

  CLocalConnectionList northConnections;
  CLocalConnectionList eastConnections;
  CLocalConnectionList southConnections;
  CLocalConnectionList westConnections;
  CLocalConnectionList selfConnections;

  // In order to validate a connection instance both end points must be validated, that is, all
  // connections attached to these end points must be validated and the coordinates of the connection lines
  // must be computed.
  CFigureConnectionList::iterator pointIterator = FConnectionPointList.find(point);

  // Go through all connections attached to this point and determine the direction of them (i.e. where they are
  // attached to the point).
  for (CConnectionInstanceList::iterator iterator = pointIterator->second.begin(); iterator != pointIterator->second.end(); 
    ++iterator)
  {
    switch ((*iterator)->getDirection(point))
    {
      case GC_DIR_SELF:
        {
          if (handleSelfReferences)
            selfConnections.push_back(*iterator);
          break;
        };
      case GC_DIR_NORTH:
        {
          northConnections.push_back(*iterator);
          break;
        };
      case GC_DIR_EAST:
        {
          eastConnections.push_back(*iterator);
          break;
        };
      case GC_DIR_SOUTH:
        {
          southConnections.push_back(*iterator);
          break;
        };
      case GC_DIR_WEST:
        {
          westConnections.push_back(*iterator);
          break;
        };
    };
  };

  // Sort each direction list so connections do not overlap and compute for each direction the connection coordinates.
  sort(northConnections.begin(), northConnections.end(), moreLeft);
  sort(eastConnections.begin(), eastConnections.end(), moreTop);
  sort(southConnections.begin(), southConnections.end(), moreLeft);
  sort(westConnections.begin(), westConnections.end(), moreTop);

  CLocalConnectionList::iterator instanceIterator;

  // Distribute all self references so that all sides are equally filled.
  for (instanceIterator = selfConnections.begin(); instanceIterator != selfConnections.end(); ++instanceIterator)
  {
    CLocalConnectionList* targetList = &northConnections;

    if (eastConnections.size() < targetList->size())
      targetList = &eastConnections;
    if (southConnections.size() < targetList->size())
      targetList = &southConnections;
    if (westConnections.size() < targetList->size())
      targetList = &westConnections;

    // Add the point twice. We need room for both ends.
    targetList->insert(targetList->begin() + targetList->size() / 2, *instanceIterator);
    targetList->insert(targetList->begin() + targetList->size() / 2, *instanceIterator);
  };

  int index;
  CConnectionInstance* lastInstance = NULL;
  for (instanceIterator = northConnections.begin(), index = 1; instanceIterator != northConnections.end(); 
    ++instanceIterator, ++index)
  {
    bool isSelfReference = lastInstance == *instanceIterator;
    lastInstance = *instanceIterator;
    lastInstance->computeCoordinates(point, GC_DIR_NORTH, (float) index / (northConnections.size() + 1), isSelfReference);
  };

  lastInstance = NULL;
  for (instanceIterator = eastConnections.begin(), index = 1; instanceIterator != eastConnections.end(); 
    ++instanceIterator, ++index)
  {
    bool isSelfReference = lastInstance == *instanceIterator;
    lastInstance = *instanceIterator;
    lastInstance->computeCoordinates(point, GC_DIR_EAST, (float) index / (eastConnections.size() + 1), isSelfReference);
  };

  lastInstance = NULL;
  for (instanceIterator = southConnections.begin(), index = 1; instanceIterator != southConnections.end(); 
    ++instanceIterator, ++index)
  {
    bool isSelfReference = lastInstance == *instanceIterator;
    lastInstance = *instanceIterator;
    lastInstance->computeCoordinates(point, GC_DIR_SOUTH, (float) index / (southConnections.size() + 1), isSelfReference);
  };

  lastInstance = NULL;
  for (instanceIterator = westConnections.begin(), index = 1; instanceIterator != westConnections.end(); 
    ++instanceIterator, ++index)
  {
    bool isSelfReference = lastInstance == *instanceIterator;
    lastInstance = *instanceIterator;
    lastInstance->computeCoordinates(point, GC_DIR_WEST, (float) index / (westConnections.size() + 1), isSelfReference);
  };
}

//----------------------------------------------------------------------------------------------------------------------

/**
 * Called by the owning view to let us know when the workspace size has changed. This directly influences the element cache
 * (if it uses a BSP tree).
 */
void CConnectionLayer::workspaceChanged(void)
{
#if USE_BSP_TREE
  delete FCache;
  FCache = NULL;
#endif
}

//----------------------------------------------------------------------------------------------------------------------