[go: up one dir, main page]

Menu

[80c337]: / lob.cpp  Maximize  Restore  History

Download this file

2136 lines (1965 with data), 71.5 kB

   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
#include "lob.h"
#include "lchange.h"
#include "limits.h"
#include <QRegExp>
#include <QUrl>
#include <QDebug>
#include <unistd.h>
#ifdef MEMORY_LEAK_TEST
#include "leakwatcher.h"
#endif
// Miscellany comes first, then class implementations below.
// comment out this line if you want to assume/require IDs, nicknames, and their references
// to be in the main tree, not in any attributes off that tree.
#define PROCESS_REFS_IN_ATTRIBUTES
QString nameOfOmType ( OmType type )
{
switch ( type )
{
case OmIntegerType: return QString( "Integer" );
case OmBigIntegerType: return QString( "BigInteger" );
case OmFloatType: return QString( "Float" );
case OmByteArrayType: return QString( "ByteArray" );
case OmVariableType: return QString( "Variable" );
case OmStringType: return QString( "String" );
case OmWStringType: return QString( "WString" );
case OmSymbolType: return QString( "Symbol" );
case OmPInstructionType: return QString( "PInstruction" );
case OmCommentType: return QString( "Comment" );
case OmApplicationType: return QString( "Application" );
case OmEndApplicationType: return QString( "EndApplication" );
case OmAttributeType: return QString( "Attribute" );
case OmEndAttributeType: return QString( "EndAttribute" );
case OmAttributeParameterType: return QString( "AttributeParameter" );
case OmEndAttributeParameterType: return QString( "EndAttributeParameter" );
case OmErrorType: return QString( "Error" );
case OmEndErrorType: return QString( "EndError" );
case OmObjectType: return QString( "Object" );
case OmEndObjectType: return QString( "EndObject" );
case OmBindingType: return QString( "Binding" );
case OmEndBindingType: return QString( "EndBinding" );
case OmBindingVariableType: return QString( "BindingVariable" );
case OmEndBindingVariableType: return QString( "EndBindingVariable" );
case OmUnknownType: return QString( "Unknown" );
default: return QString( "type????" );
}
}
#define HRDEBUG(lob,om,verb,context) qDebug() << "In" << context << ":" \
<< ( unsigned long int )(lob) << verb << ( unsigned long int )(om) << ":" \
<< ( om ? nameOfOmType( om->type() ) : QString( "[no type]" ) ) \
<< (lob)->toString().trimmed().left(20) << "from count" \
<< ( referenceCounts.available() ? referenceCounts.data()[om] : -999 );
#define HDEBUG(lob,om,con) HRDEBUG(lob,om,"HELD",con)
#define RDEBUG(lob,om,con) HRDEBUG(lob,om,"RELEASED",con)
#define CDEBUG(lob,om,con) qDebug() << "In" << con << ":" \
<< ( unsigned long int )(lob) << "HELD" << ( unsigned long int )(om) << ":" \
<< ( om ? nameOfOmType( om->type() ) : QString( "[no type]" ) ) \
<< "[no string repr yet; constructing]";
//#define HRDEBUG_ON
QString incrementID ( QString id, unsigned int index )
{
if ( index == 0 )
return incrementID( id, id.length() - 1 );
if ( index == 1 )
return "id1" + id.mid( 2 );
if ( id[index] == '9' ) {
id[index] = '0';
return incrementID( id, index-1 );
}
id[index] = (char)( id[index].toLatin1() + 1 );
return id;
}
bool lessThanID ( const QString& idA, const QString& idB )
{
if ( idA.length() < idB.length() )
return true;
if ( idA.length() > idB.length() )
return false;
for ( int i = 2 ; i < idA.length() ; i++ ) {
if ( idA[i] < idB[i] )
return true;
if ( idA[i] > idB[i] )
return false;
}
return false; // strict comparison
}
QString zeroID ()
{
return "id0";
}
QString escapeXML ( QString notSafeForXML )
{
QString goodStart = notSafeForXML.replace( "&", "&amp;" ).replace( "<", "&lt;" )
.replace( ">", "&gt;" ).replace( "\"", "&quot;" ).replace( "'", "&apos;" );
QString result;
for ( int i = 0 ; i < goodStart.length() ; i++ ) {
const QChar& c = goodStart[i];
if ( c.toLatin1() && ( c.cell() < 0x80 ) )
result += c;
else
result += QString( "&#x%1%2;" ).arg( QString::number( c.row(), 16 ), 2, '0' )
.arg( QString::number( c.cell(), 16 ), 2, '0' );
}
return result;
}
QString unescapeXML ( QString escaped )
{
QString result;
QRegExp re( "&#x([0-9a-fA-F]{2})([0-9a-fA-F]{2});" );
int i = re.indexIn( escaped );
int nextblock = 0;
while ( i != -1 ) {
result += escaped.mid( nextblock, i - nextblock );
int row = re.cap( 1 ).toInt( 0, 16 );
int cell = re.cap( 2 ).toInt( 0, 16 );
result += QChar( cell, row );
nextblock = i + 8;
i = re.indexIn( escaped, nextblock );
}
result += escaped.mid( nextblock );
return result.replace( "&gt;", ">" ).replace( "&lt;", "<" )
.replace( "&apos;", "'" ).replace( "&quot;", "\"" ).replace( "&amp;", "&" );
}
// Lob implementation first, other classes later
Lob::Lob ( OmNode* wrapThis, bool editable )
: QObject(), omobj( wrapThis ), editable( editable )
{
#ifdef HRDEBUG_ON
CDEBUG(this,omobj,"Lob(OmNode*)");
#endif
hold( omobj );
#ifdef MEMORY_LEAK_TEST
LeakWatcher<Lob>::created( this );
#endif
}
Lob::Lob ( const Lob& copyThis )
: QObject(), omobj( copyThis.omobj ), editable( copyThis.editable )
{
#ifdef HRDEBUG_ON
CDEBUG(this,omobj,"Lob(const Lob&)");
#endif
hold( omobj );
#ifdef MEMORY_LEAK_TEST
LeakWatcher<Lob>::created( this );
#endif
}
Lob::~Lob ()
{
#ifdef HRDEBUG_ON
RDEBUG(this,omobj,"~Lob()");
#endif
release( omobj );
#ifdef MEMORY_LEAK_TEST
LeakWatcher<Lob>::deleted( this );
#endif
if ( watchForModifications.available() )
watchForModifications.data().removeAll( this );
}
LobAddress address_aux ( OmNode* descendant, OmNode* ancestor )
{
if ( ( descendant == ancestor ) || ( descendant == NULL ) )
return LobAddress();
LobAddress result = address_aux( descendant->getOwner(), ancestor );
result.addStep( descendant->ownerIndex(), descendant->ownershipType() );
return result;
}
LobAddress Lob::address ( Lob inThis ) const
{
return address_aux( omobj, inThis.omobj );
}
Lob Lob::index ( LobAddress address, unsigned int offset )
{
if ( isEmpty() || ( offset == address.numSteps() ) )
return *this;
if ( address.stepType( offset ) == OmNode::AsChild )
return child( address.stepIndex( offset ) ).index( address, offset + 1 );
if ( address.stepIndex( offset ) >= omobj->countAttributes() )
return Lob();
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( address.stepIndex( offset ), key, value );
return Lob( address.stepType( offset ) == OmNode::AsKey ? key : value )
.index( address, offset + 1 );
}
Lob Lob::fromXML ( QFile& in, QString* message )
{
if ( !in.exists() ) {
if ( message )
*message = "Could not find this file: " + in.fileName();
return Lob();
}
bool wasOpen = in.isOpen();
if ( !wasOpen && !in.open( QIODevice::ReadOnly ) ) {
if ( message )
*message = "Could not open " + in.fileName() + " for reading";
return Lob();
}
OmDocumentNode* result = new OmDocumentNode;
try {
OmInputFileStream inputStream( fdopen( dup( in.handle() ), "r" ) );
OmInputDevice inputDevice( inputStream, OmXmlEncoding, false );
result->load( inputDevice );
if ( message )
*message = QString();
} catch ( OmException& e ) {
if ( message )
*message = "When reading " + in.fileName() + ": " + e.translate();
delete result;
result = NULL;
} catch ( ... ) {
if ( message )
*message = "When reading " + in.fileName() + ": unknown error";
delete result;
result = NULL;
}
if ( !wasOpen )
in.close();
return Lob( result );
}
Lob Lob::fromXML ( QString xml )
{
OmDocumentNode* result = new OmDocumentNode;
try {
OmInputStringStream inputStream( xml.toLatin1().constData() );
OmInputDevice inputDevice( inputStream, OmXmlEncoding, false );
result->load( inputDevice );
/*
} catch ( OmException& e ) {
qDebug() << "in Lob::fromXML(): " << e.translate();
delete result;
result = NULL;
*/
} catch ( ... ) {
delete result;
result = NULL;
}
return Lob( result );
}
QString Lob::toString () const
{
if ( !omobj )
return QString();
OmOutputStringStream outputStream;
OmDocumentNode* tosave = dynamic_cast<OmDocumentNode*>( omobj );
QString result;
try {
OmOutputDevice outputDevice( outputStream, OmXmlEncoding, false );
if ( !tosave ) {
tosave = new OmDocumentNode;
tosave->append( omobj->clone() );
}
tosave->save( outputDevice );
const char* b = outputStream.getBuffer();
int len = outputStream.getBufferLength();
char* copy = new char[len + 1];
memcpy( copy, b, len );
copy[len] = '\0';
result = QString( copy );
} catch ( ... ) {
result = QString();
}
if ( tosave != omobj )
delete tosave;
return result;
}
bool Lob::save ( QFile& out, QString* message )
{
if ( isEmpty() ) {
if ( message )
*message = "Cannot save empty Lurch Object";
return false;
}
bool wasOpen = out.isOpen();
if ( !wasOpen && !out.open( QIODevice::WriteOnly ) ) {
if ( message )
*message = "Could not open " + out.fileName() + " for writing";
return false;
}
OmDocumentNode* tosave = dynamic_cast<OmDocumentNode*>( omobj );
bool result = true;
try {
OmOutputFileStream outputStream( fdopen( dup( out.handle() ), "w" ) );
OmOutputDevice outputDevice( outputStream, OmXmlEncoding, false );
if ( !tosave ) {
tosave = new OmDocumentNode;
tosave->append( omobj->clone() );
}
tosave->save( outputDevice );
} catch ( OmException& e ) {
if ( message )
*message = "When writing " + out.fileName() + ": " + e.translate();
result = false;
} catch ( ... ) {
if ( message )
*message = "When writing " + out.fileName() + ": unknown error";
result = false;
}
if ( !wasOpen )
out.close();
if ( tosave != omobj )
delete tosave;
return result;
}
bool Lob::isEmpty () const
{
return !omobj;
}
bool Lob::isEditable () const
{
return editable;
}
void Lob::setEditable ( bool on )
{
editable = on;
}
Lob Lob::copy ( bool changeIDs ) const
{
Lob result = Lob( omobj ? omobj->clone() : NULL );
if ( changeIDs )
result.changeIDs( *this );
return result;
}
bool operator== ( const Lob& a, const Lob& b )
{
return ( a.omobj == b.omobj );
}
bool operator!= ( const Lob& a, const Lob& b )
{
return ( a.omobj != b.omobj );
}
bool operator< ( const Lob& a, const Lob& b )
{
return ( a.omobj < b.omobj );
}
bool Lob::equivalentTo ( const Lob& other, bool compareAttributes,
QStringList exclusions ) const
{
return equivalent( omobj, other.omobj, compareAttributes, exclusions );
}
Lob& Lob::operator= ( const Lob& rhs )
{
#ifdef HRDEBUG_ON
RDEBUG(this,omobj,"operator=()");
#endif
release( omobj );
omobj = rhs.omobj;
editable = rhs.editable;
#ifdef HRDEBUG_ON
HDEBUG(this,omobj,"operator=()");
#endif
hold( omobj );
return *this;
}
OmType Lob::nodeType () const
{
return omobj ? omobj->type() : OmUnknownType;
}
int Lob::scriptNodeType () const
{
return ( int )nodeType();
}
unsigned int Lob::numChildren () const
{
return omobj ? omobj->count() : 0;
}
Lob Lob::child ( unsigned int index ) const
{
if ( index >= numChildren() )
return Lob();
OmNode::Iterator it = omobj->iterate();
for ( unsigned int i = 0 ; !it.done() && ( i < index ) ; i++ )
it.next();
return Lob( it.get(), editable );
}
Lob Lob::parent () const
{
if ( hasParent() )
return Lob( omobj->getOwner(), editable );
else
return Lob();
}
Lob Lob::container () const
{
if ( hasContainer() )
return Lob( omobj->getOwner(), editable );
else
return Lob();
}
bool Lob::hasParent () const
{
return omobj && ( omobj->ownershipType() == OmNode::AsChild )
&& (bool)( omobj->getOwner() );
}
bool Lob::hasContainer () const
{
return omobj && ( ( omobj->ownershipType() == OmNode::AsKey )
|| ( omobj->ownershipType() == OmNode::AsValue ) )
&& (bool)( omobj->getOwner() );
}
Lob Lob::nextSibling () const
{
if ( !hasNextSibling() )
return Lob();
Lob result = parent().child( omobj->ownerIndex() + 1 );
result.editable = editable;
return result;
}
bool Lob::hasNextSibling () const
{
return omobj && ( omobj->ownerIndex() + 1 < parent().numChildren() );
}
Lob Lob::previousSibling () const
{
if ( !hasPreviousSibling() )
return Lob();
Lob result = parent().child( omobj->ownerIndex() - 1 );
result.editable = editable;
return result;
}
bool Lob::hasPreviousSibling () const
{
return omobj && ( omobj->ownershipType() == OmNode::AsChild )
&& ( omobj->ownerIndex() > 0 );
}
bool Lob::hasAttribute ( QString symbolName, QString symbolCD ) const
{
return !attribute( symbolName, symbolCD ).isEmpty();
}
Lob Lob::attribute ( QString symbolName, QString symbolCD ) const
{
if ( !omobj )
return Lob();
OmSymbolNode* key;
OmNode* value;
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
omobj->consultAttribute( i, key, value );
if ( ( key->getName() == symbolName ) && ( key->getCD() == symbolCD ) )
return Lob( value, editable );
}
return Lob();
}
QList<Lob> Lob::attributeKeys () const
{
QList<Lob> result;
if ( isEmpty() )
return result;
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
result << Lob( new OmSymbolNode( key->getCD(), key->getName() ) );
}
return result;
}
QVariantList Lob::scriptAttributeKeys () const
{
QVariantList result;
foreach ( const Lob& L, attributeKeys() )
result << QVariant::fromValue<Lob>( L );
return result;
}
bool Lob::hasAttribute ( Lob symbolLob ) const
{
if ( symbolLob.nodeType() != OmSymbolType )
return false;
OmSymbolNode* sym = dynamic_cast<OmSymbolNode*>( symbolLob.omobj );
return hasAttribute( sym->getName(), sym->getCD() );
}
Lob Lob::attribute ( const Lob& symbolLob ) const
{
if ( symbolLob.nodeType() != OmSymbolType )
return Lob();
OmSymbolNode* sym = dynamic_cast<OmSymbolNode*>( symbolLob.omobj );
return attribute( sym->getName(), sym->getCD() );
}
void Lob::setAttribute ( Lob key, Lob value )
{
if ( key.nodeType() != OmSymbolType )
return;
OmSymbolNode* sym = dynamic_cast<OmSymbolNode*>( key.omobj );
return setAttribute( sym->getName(), sym->getCD(), value );
}
void Lob::removeAttribute ( Lob symbolLob )
{
if ( symbolLob.nodeType() != OmSymbolType )
return;
OmSymbolNode* sym = dynamic_cast<OmSymbolNode*>( symbolLob.omobj );
return removeAttribute( sym->getName(), sym->getCD() );
}
unsigned int Lob::numAttributes () const
{
return omobj ? omobj->countAttributes() : 0;
}
bool Lob::isBasicType () const
{
if ( !omobj )
return false;
OmType t = omobj->type();
return ( t == OmIntegerType ) || ( t == OmBigIntegerType )
|| ( t == OmFloatType ) || ( t == OmByteArrayType )
|| ( t == OmVariableType ) || ( t == OmStringType )
|| ( t == OmWStringType ) || ( t == OmSymbolType );
}
QVariant Lob::toVariant () const
{
if ( !isBasicType() )
return QVariant();
switch ( omobj->type() )
{
case OmIntegerType:
return dynamic_cast<OmIntegerNode*>( omobj )->getValue();
case OmBigIntegerType:
{
OmBigIntegerNode* bin = dynamic_cast<OmBigIntegerNode*>( omobj );
return QString( "%1%2" ).arg( ( bin->getSign() > 0 ) ? "" : "-" )
.arg( bin->getDigits() );
}
case OmFloatType:
return dynamic_cast<OmFloatNode*>( omobj )->getValue();
case OmByteArrayType:
{
OmByteArrayNode* ban = dynamic_cast<OmByteArrayNode*>( omobj );
const char* buffer;
unsigned int bufsize;
ban->getBuffer( buffer, bufsize );
return QByteArray( buffer, bufsize );
}
case OmVariableType:
return unescapeXML( QString( dynamic_cast<OmVariableNode*>( omobj )->getName() ) );
case OmStringType:
return unescapeXML(
QString( dynamic_cast<OmStringNode*>( omobj )->getBuffer() ) );
case OmWStringType:
return unescapeXML( QString::fromWCharArray(
dynamic_cast<OmWStringNode*>( omobj )->getBuffer() ) );
case OmSymbolType:
{
OmSymbolNode* sym = dynamic_cast<OmSymbolNode*>( omobj );
return QVariant( QStringList() << QString( sym->getName() )
<< QString( sym->getCD() ) );
}
default:
return QVariant(); // this should never happen; it's here for compiler happiness
}
}
Lob Lob::fromVariant ( QVariant v )
{
switch ( v.type() )
{
case QVariant::ByteArray:
{
QByteArray ba = v.toByteArray();
OmByteArrayNode* ban = new OmByteArrayNode;
ban->setBufferLength( ba.data(), ba.length() );
return Lob( ban );
}
case QVariant::Double:
return Lob( new OmFloatNode( v.toDouble() ) );
case QVariant::Int:
return Lob( new OmIntegerNode( v.toInt() ) );
case QVariant::LongLong:
{
qlonglong lli = v.toLongLong();
if ( ( lli <= (qlonglong)INT_MAX ) && ( (qlonglong)INT_MIN <= lli ) )
return Lob( new OmIntegerNode( (int)lli ) );
else
return Lob( new OmBigIntegerNode(
QString::number( abs( lli ) ).toLatin1().constData(),
( lli > 0 ) ? 1 : -1 ) );
}
case QVariant::String:
return Lob( new OmStringNode(
escapeXML( v.toString() ).toLatin1().constData() ) );
case QVariant::UInt:
{
unsigned int ui = v.toUInt();
if ( ui <= (unsigned int)INT_MAX )
return Lob( new OmIntegerNode( (int)ui ) );
else
return Lob( new OmBigIntegerNode(
QString::number( ui ).toLatin1().constData() ) );
}
case QVariant::ULongLong:
{
qulonglong ulli = v.toUInt();
if ( ulli <= (qulonglong)INT_MAX )
return Lob( new OmIntegerNode( (int)ulli ) );
else
return Lob( new OmBigIntegerNode(
QString::number( ulli ).toLatin1().constData() ) );
}
default:
return Lob();
}
}
QString Lob::getStringAttribute ( QString symbolName, QString symbolCD ) const
{
Lob tmp = attribute( symbolName, symbolCD );
if ( tmp.nodeType() != OmStringType )
return QString();
QString result = tmp.toVariant().toString();
return unescapeXML( result );
}
void Lob::setStringAttribute ( QString symbolName, QString symbolCD, QString value )
{
setAttribute( symbolName, symbolCD, Lob::fromVariant( escapeXML( value ) ) );
}
bool Lob::isDocument () const
{
// must be nonempty and have no parent
if ( isEmpty() || hasParent() )
return false;
// must be an application of document:LurchCore to zero or more things
if ( nodeType() != OmApplicationType )
return false;
if ( child().toVariant().toStringList()
!= ( QStringList() << "document" << "LurchCore" ) )
return false;
// must have (author,LurchCore) attribute containing nonempty string
QString author = getStringAttribute( "author", "LurchCore" );
if ( !author.length() )
return false;
// must have (title,LurchCore) attribute containing nonempty string
if ( !getStringAttribute( "title", "LurchCore" ).length() )
return false;
// must have (dependencies,LurchCore) attribute containing space-separated list of URNs
Lob tmp = attribute( "dependencies", "LurchCore" );
if ( tmp.nodeType() != OmStringType )
return false;
QString dependencies = tmp.toVariant().toString();
if ( dependencies.length() > 0 ) // otherwise split gives one-element array containing ""
foreach ( const QString& dependency, dependencies.split( ' ' ) )
if ( !isLurchURN( dependency ) )
return false;
// all passed, so return true
return true;
}
QString Lob::getAuthor () const
{
// rather than calling the expensive isDocument() function, I just make sure the author
// attribute is valid
return getStringAttribute( "author", "LurchCore" );
}
void Lob::setAuthor ( QString author )
{
setAttribute( "author", "LurchCore", Lob::fromVariant( author ) );
}
QString Lob::getTitle () const
{
// rather than calling the expensive isDocument() function, I just make sure the title
// attribute is valid
return getStringAttribute( "title", "LurchCore" );
}
void Lob::setTitle ( QString title )
{
setAttribute( "title", "LurchCore", Lob::fromVariant( title ) );
}
QString Lob::getEncodingLanguage () const
{
// rather than calling the expensive isDocument() function, I just make sure the language
// attribute is valid
return getStringAttribute( "language", "LurchCore" );
}
void Lob::setEncodingLanguage ( QString lang )
{
setAttribute( "language", "LurchCore", Lob::fromVariant( lang ) );
}
QString Lob::getVersion () const
{
// rather than calling the expensive isDocument() function, I just make sure the version
// attribute is valid
QString result = getStringAttribute( "version", "LurchCore" );
return QRegExp( "[A-Za-z0-9.]+" ).exactMatch( result ) ? result : QString();
}
void Lob::setVersion ( QString version )
{
if ( !QRegExp( "[A-Za-z0-9.]+" ).exactMatch( version ) )
return;
setAttribute( "version", "LurchCore", Lob::fromVariant( version ) );
}
QStringList Lob::getDependencies () const
{
// rather than calling the expensive isDocument() function, I just make sure the
// dependencies attribute is valid
Lob tmp = attribute( "dependencies", "LurchCore" );
if ( tmp.nodeType() != OmStringType )
return QStringList();
QString dependencies = tmp.toVariant().toString();
if ( dependencies.length() == 0 )
return QStringList(); // otherwise split gives one-element array containing ""
QStringList splitUp = dependencies.split( ' ' );
foreach ( const QString& dependency, splitUp )
if ( !isLurchURN( dependency ) )
return QStringList();
return splitUp;
}
void Lob::setDependencies ( QStringList dependencies )
{
foreach ( const QString& dependency, dependencies )
if ( !isLurchURN( dependency ) )
return;
setAttribute( "dependencies", "LurchCore", Lob::fromVariant( dependencies.join( " " ) ) );
}
QString Lob::getURN () const
{
QString t = getTitle();
if ( !t.length() )
return QString();
QString a = getAuthor();
if ( !a.length() )
return QString();
return makeLurchURN( t, a, getEncodingLanguage(), getVersion() );
}
void Lob::setURN ( QString urn )
{
if ( !isLurchURN( urn ) )
return;
QStringList bits = splitLurchURN( urn );
setTitle( bits[0] );
setAuthor( bits[1] );
setEncodingLanguage( bits[2] );
setVersion( bits[3] );
}
bool Lob::isLurchURN ( QString testThis )
{
return splitLurchURN( testThis ).count() > 0;
}
QStringList Lob::splitLurchURN ( QString splitThis )
{
// it must start with the following initial segment
static const char* initialSegment = "urn:publicid:-:lurch.sourceforge.net:";
QRegExp identifierRE( "[a-zA-Z][A-Za-z0-9_]*" );
int pos = splitThis.indexOf( initialSegment );
QString ident;
if ( pos == -1 )
return QStringList();
if ( pos > 0 ) {
ident = splitThis.left( pos - 1 );
if ( ( splitThis.mid( pos - 1, 1 ) != "=" ) || !identifierRE.exactMatch( ident ) )
return QStringList();
}
// then comes a colon-separated sequence of three items
QStringList bits = splitThis.mid( pos + strlen( initialSegment ) ).split( ':' );
if ( bits.count() != 3 )
return QStringList();
// the first in that sequence is title+by+author
QStringList authorAndTitle = bits[0].split( "+by+" );
if ( authorAndTitle.count() != 2 )
return QStringList();
QRegExp authorTitleRE( "[A-Za-z0-9._~%-]+" );
if ( !authorTitleRE.exactMatch( authorAndTitle[0] ) )
return QStringList();
if ( !authorTitleRE.exactMatch( authorAndTitle[1] ) )
return QStringList();
// the next is language
if ( ( bits[1].count() > 0 ) && !QRegExp( "[A-Za-z]{2,}" ).exactMatch( bits[1] ) )
return QStringList();
// the last is version
if ( !QRegExp( "[A-Za-z0-9.]*" ).exactMatch( bits[2] ) )
return QStringList();
// all passed, so return the split-up parts
QStringList result;
result << QUrl::fromPercentEncoding( authorAndTitle[0].toLatin1() )
<< QUrl::fromPercentEncoding( authorAndTitle[1].toLatin1() ) << bits[1] << bits[2];
if ( !ident.isEmpty() )
result << ident;
return result;
}
QString Lob::makeLurchURN ( QString title, QString author, QString language, QString version,
QString identifier )
{
return ( identifier.isEmpty() ? QString() : ( identifier + "=" ) )
+ "urn:publicid:-:lurch.sourceforge.net:"
+ QString( QUrl::toPercentEncoding( title ) ) + "+by+"
+ QString( QUrl::toPercentEncoding( author ) ) + ":"
+ language + ":" + version;
}
QString Lob::basicLurchURN ( QString urn )
{
QStringList bits = splitLurchURN( urn );
return makeLurchURN( bits[0], bits[1], bits[2], bits[3] );
}
QString Lob::identifierOfURN ( QString urn )
{
QStringList bits = splitLurchURN( urn );
return ( bits.count() == 5 ) ? bits[4] : QString();
}
Lob Lob::newDocument ( QString urn, QStringList dependencies )
{
Lob result = Lob::fromXML( "<OMA><OMS cd='LurchCore' name='document'/></OMA>\n" )
.child().copy();
result.setURN( Lob::isLurchURN( urn ) ?
urn : Lob::makeLurchURN( "New Document", "unknown", "", "0" ) );
result.setDependencies( dependencies );
return result;
}
bool Lob::isScript () const
{
// must be a string node
if ( nodeType() != OmStringType )
return false;
// and must have a nonempty script language attribute
// (do not make call to scriptLanguage() here, because infinite recursion results)
return getStringAttribute( "script language", "LurchCore" ).length() > 0;
}
bool Lob::containsScript ( QString type ) const
{
if ( isScript() && ( type.isEmpty() || ( scriptType() == type ) ) )
return true;
foreach ( const Lob& key, attributeKeys() )
if ( attribute( key ).containsScript( type ) )
return true;
for ( unsigned int i = 0 ; i < numChildren() ; i++ )
if ( child( i ).containsScript( type ) )
return true;
return false;
}
QString Lob::scriptCode () const
{
return !isScript() ? QString() :
( scriptLanguage() == "CoffeeScript" ) ? ( "# CoffeeScript\n" + toVariant().toString() ) :
toVariant().toString();
}
void Lob::setScriptCode ( QString code )
{
if ( !isEditable() || ( nodeType() != OmStringType ) )
return;
Lob before = copy( false );
OmStringNode* str = dynamic_cast<OmStringNode*>( omobj );
str->setBuffer( escapeXML( code ).toLatin1().constData() );
//maybeEmitModified( before, *this );
maybeEmitModified( LobChange::newChange( before, *this ) );
}
QString Lob::scriptLanguage () const
{
return isScript() ? getStringAttribute( "script language", "LurchCore" ) : QString();
}
void Lob::setScriptLanguage ( QString language )
{
setAttribute( "script language", "LurchCore", Lob::fromVariant( language ) );
}
QString Lob::scriptType () const
{
return isScript() ? getStringAttribute( "script type", "LurchCore" ) : QString();
}
void Lob::setScriptType ( QString type )
{
setAttribute( "script type", "LurchCore", Lob::fromVariant( type ) );
}
bool Lob::isIDReference () const
{
// ensure it is of the right type and labeled as an ID reference
if ( nodeType() != OmStringType )
return false;
if ( getStringAttribute( "reference", "LurchCore" ) != "ID" )
return false;
return QRegExp( "id\\d+" ).exactMatch( toVariant().toString() );
}
bool Lob::isNicknameReference () const
{
// ensure it is of the right type and labeled as a nickname reference
if ( nodeType() != OmStringType )
return false;
if ( getStringAttribute( "reference", "LurchCore" ) != "nickname" )
return false;
return toVariant().toString().length() > 0;
}
QString Lob::getIDReference () const
{
return isIDReference() ? toVariant().toString() : QString();
}
void Lob::setIDReference ( QString id )
{
if ( !isEditable() || ( nodeType() != OmStringType ) )
return;
if ( !QRegExp( "id\\d+" ).exactMatch( id ) )
return;
Lob before = copy( false );
OmStringNode* str = dynamic_cast<OmStringNode*>( omobj );
str->setBuffer( escapeXML( id ).toLatin1().constData() );
//maybeEmitModified( before, *this );
maybeEmitModified( LobChange::newChange( before, *this ) );
}
QString Lob::getNicknameReference () const
{
return isNicknameReference() ? toVariant().toString() : QString();
}
void Lob::setNicknameReference ( QString nickname )
{
if ( !isEditable() || ( nodeType() != OmStringType ) )
return;
Lob before = copy( false );
OmStringNode* str = dynamic_cast<OmStringNode*>( omobj );
str->setBuffer( escapeXML( nickname ).toLatin1().constData() );
//maybeEmitModified( before, *this );
maybeEmitModified( LobChange::newChange( before, *this ) );
}
QStringList Lob::listAllLabels ( QString nicknameOrID ) const
{
QStringList result;
if ( isEmpty() )
return result;
QString thisOne = getStringAttribute( nicknameOrID, "LurchCore" );
if ( thisOne.length() > 0 )
result << thisOne;
#ifdef PROCESS_REFS_IN_ATTRIBUTES
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
result << Lob( value ).listAllLabels( nicknameOrID );
}
#endif
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() )
result << Lob( it.get() ).listAllLabels( nicknameOrID );
return result;
}
bool Lob::checkUnique ( QString nicknameOrID ) const
{
QStringList allWithDuplicates = listAllLabels( nicknameOrID );
while ( allWithDuplicates.count() > 0 ) {
QString first = allWithDuplicates.takeFirst();
if ( allWithDuplicates.contains( first ) )
return false;
}
return true;
}
bool Lob::checkUniqueIDs () const
{
return checkUnique( "ID" );
}
bool Lob::checkUniqueNicknames () const
{
return checkUnique( "nickname" );
}
void Lob::buildIDConversion ( QString& nextID, Lob context,
QMap<QString,QString>& conversion )
{
if ( isEmpty() )
return;
QString oldID = getID();
if ( !oldID.isEmpty() ) {
QString newID;
// how to compute the new ID is based on whether it's a caching situation:
if ( nextID.isEmpty() ) {
// this is only true if it's caching, so we must inform/ask the context
newID = context.getNewID();
} else {
// otherwise, we've got to keep nextID counting upwards on our own
newID = nextID;
nextID = incrementID( nextID );
}
conversion[oldID] = newID;
setID( newID );
}
#ifdef PROCESS_REFS_IN_ATTRIBUTES
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
Lob( value ).buildIDConversion( nextID, context, conversion );
}
#endif
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() )
Lob( it.get() ).buildIDConversion( nextID, context, conversion );
}
void Lob::convertIDReferences ( QMap<QString,QString> conversion )
{
if ( isEmpty() )
return;
if ( isIDReference() ) {
QString ref = getIDReference();
if ( conversion.contains( ref ) )
setIDReference( conversion[ref] );
}
#ifdef PROCESS_REFS_IN_ATTRIBUTES
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
Lob( value ).convertIDReferences( conversion );
}
#endif
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() )
Lob( it.get() ).convertIDReferences( conversion );
}
void Lob::changeIDs ( Lob context )
{
if ( context.isEmpty() )
context = findIDContext();
QString nextID;
if ( !context.isIDContext() )
nextID = context.getNewID();
QMap<QString,QString> conversion;
buildIDConversion( nextID, context, conversion );
convertIDReferences( conversion );
}
void Lob::findReferencedIDs ( QStringList& result )
{
if ( isIDReference() )
result << getIDReference();
#ifdef PROCESS_REFS_IN_ATTRIBUTES
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
Lob( value ).findReferencedIDs( result );
}
#endif
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() )
Lob( it.get() ).findReferencedIDs( result );
}
void Lob::removeUnreferencedIDs ( const QStringList referenced )
{
if ( !referenced.contains( getID() ) )
removeAttribute( "ID", "LurchCore" );
#ifdef PROCESS_REFS_IN_ATTRIBUTES
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
Lob( value ).removeUnreferencedIDs( referenced );
}
#endif
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() )
Lob( it.get() ).removeUnreferencedIDs( referenced );
}
void Lob::removeExtraIDs ()
{
QStringList referenced;
findReferencedIDs( referenced );
removeUnreferencedIDs( referenced );
}
QString Lob::getNickname () const
{
return getStringAttribute( "nickname", "LurchCore" );
}
void Lob::setNickname ( QString nickname )
{
setAttribute( "nickname", "LurchCore", Lob::fromVariant( nickname ) );
}
void Lob::set ( OmNode* s )
{
if ( !isEditable() )
return;
// this ensures that s doesn't accidentally get deleted by the Lob Memory Management
// system during the course of this function, in case I'm ever not so careful with
// creating Lob( s ) inside a block that then dies at the end of the block.
Lob sLob( s );
// now ensure that the assignment makes sense; this involves checking three situations:
// 1) you can't change an attribute key to a non-symbol node
if ( omobj && ( omobj->ownershipType() == OmNode::AsKey )
&& ( s != NULL ) && ( s->type() != OmSymbolType ) )
return;
// 2) you can't make a null node or one of type OmUnknownType a child (or attribute)
// of anything
if ( omobj && ( omobj->ownershipType() != OmNode::None )
&& ( ( s == NULL ) || ( s->type() == OmUnknownType ) ) )
return;
// 3) no cyclicity is introduced in the parenting relationship (omobj's ownership chain
// does not include s)
for ( OmNode* walk = omobj ; walk != NULL ; walk = walk->getOwner() )
if ( walk == s )
return;
// now that we know it makes sense to act, begin by deparenting s if needed
if ( s && ( s->ownershipType() == OmNode::AsChild ) ) {
Lob ownerOwner( s->getOwner() ); // ensure owner stays owned by Lob mem mgt system
unsigned int index = s->ownerIndex();
s->getOwner()->extract( s->getOwner()->iteratorToIndex( index ), s );
ownerOwner.maybeEmitModified( LobChange::newRemove( sLob ), OmNode::AsChild, index );
} else if ( s && ( ( s->ownershipType() == OmNode::AsKey )
|| ( s->ownershipType() == OmNode::AsValue ) ) ) {
OmSymbolNode* key;
OmNode* value;
Lob ownerOwner( s->getOwner() ); // ensure owner stays owned by Lob mem mgt system
bool iskey = ( s->ownershipType() == OmNode::AsKey );
unsigned int index = s->ownerIndex();
s->getOwner()->extractAttribute( index, key, value );
// hand the other half of the pair over to the Lob memory management system:
Lob owner( iskey ? value : ( OmNode* )key );
ownerOwner.maybeEmitModified(
LobChange::newRemovePair( key->getName(), key->getCD(), sLob ),
OmNode::AsValue, index );
}
// for a moment now s has no owner, but that changes below
// now we have to deparent this, if needed, and place s there instead, if it's non-null:
if ( omobj && ( omobj->ownershipType() == OmNode::AsChild ) ) {
OmNode* o = omobj->getOwner();
Lob ownerOwner( o ); // ensure owner stays owned by Lob mem mgt system
OmNode::Iterator next = o->iteratorToIndex( omobj->ownerIndex() + 1 );
o->extract( o->iteratorToIndex( omobj->ownerIndex() ), omobj );
o->insert( next, s );
} else if ( omobj && ( ( omobj->ownershipType() == OmNode::AsKey )
|| ( omobj->ownershipType() == OmNode::AsValue ) ) ) {
OmSymbolNode* key;
OmNode* value;
OmNode* o = omobj->getOwner();
Lob ownerOwner( o ); // ensure owner stays owned by Lob mem mgt system
bool iskey = ( omobj->ownershipType() == OmNode::AsKey );
unsigned int index = omobj->ownerIndex();
o->extractAttribute( index, key, value );
if ( iskey ) {
o->insertAttribute( index, dynamic_cast<OmSymbolNode*>( s ), value );
Lob owner( key );
} else {
o->insertAttribute( index, key, s );
Lob owner( value );
}
}
// release ownership of omobj and take ownership of s
Lob before = copy( false );
*this = sLob;
maybeEmitModified( LobChange::newChange( before, sLob ) );
}
void Lob::set ( Lob s )
{
set( s.omobj );
}
void Lob::remove ()
{
if ( isEmpty() )
return;
if ( hasParent() ) {
Lob p = parent();
unsigned int index = omobj->ownerIndex();
p.omobj->extract( p.omobj->iteratorToIndex( index ), omobj );
p.maybeEmitModified( LobChange::newRemove( *this ), OmNode::AsChild, index );
} else if ( hasContainer() ) {
Lob c = container();
OmSymbolNode* key;
OmNode* value;
unsigned int index = omobj->ownerIndex();
c.omobj->extractAttribute( index, key, value );
c.maybeEmitModified( LobChange::newRemovePair( key->getName(), key->getCD(), *this ),
OmNode::AsValue, index );
// ensure the other half of the pair is cared for by the Lob memory management system
Lob owner( ( omobj == key ) ? value : key );
}
}
void Lob::insertChild ( uint index, Lob newChild )
{
if ( isEmpty() || isBasicType() || ( nodeType() == OmUnknownType )
|| newChild.isEmpty() || ( newChild.nodeType() == OmUnknownType )
|| ( index > numChildren() ) || !isEditable() || hasAsAncestor( newChild ) )
return;
OmNode::Iterator it = omobj->iterate();
for ( uint i = 0 ; !it.done() && ( i < index ) ; i++ )
it.next();
Lob tmp = Lob::fromVariant( 0 );
tmp.set( newChild ); // just to deparent smoothly
omobj->insert( it, tmp.omobj );
//maybeEmitModified( Lob(), newChild );
newChild.maybeEmitModified( LobChange::newInsert( newChild ) );
}
void Lob::addChild ( Lob newChild )
{
if ( isEmpty() || isBasicType() || ( nodeType() == OmUnknownType )
|| newChild.isEmpty() || ( newChild.nodeType() == OmUnknownType )
|| !isEditable() || hasAsAncestor( newChild ) )
return;
Lob tmp = Lob::fromVariant( 0 );
tmp.set( newChild ); // just to deparent smoothly
omobj->append( tmp.omobj );
//maybeEmitModified( Lob(), newChild );
newChild.maybeEmitModified( LobChange::newInsert( newChild ) );
}
void Lob::removeChild ( uint index )
{
if ( isEmpty() || !isEditable() )
return;
OmNode::Iterator it = omobj->iterate();
for ( uint i = 0 ; !it.done() && ( i < index ) ; i++ )
it.next();
if ( it.done() )
return;
OmNode* out;
omobj->extract( it, out );
Lob newOwner( out );
//maybeEmitModified( newOwner, omobj );
maybeEmitModified( LobChange::newRemove( newOwner ), OmNode::AsChild, index );
}
void Lob::insertNextSibling ( Lob newSibling )
{
if ( !hasParent() || !isEditable() || ( parent().nodeType() == OmUnknownType )
|| newSibling.isEmpty() || hasAsAncestor( newSibling ) )
return;
OmNode::Iterator it = omobj->getOwner()->iteratorToIndex( omobj->ownerIndex() );
it.next();
Lob tmp = Lob::fromVariant( 0 );
tmp.set( newSibling ); // just to deparent smoothly
omobj->getOwner()->insert( it, tmp.omobj );
//maybeEmitModified( Lob(), newSibling );
newSibling.maybeEmitModified( LobChange::newInsert( newSibling ) );
}
void Lob::insertPreviousSibling ( Lob newSibling )
{
if ( !hasParent() || !isEditable() || ( parent().nodeType() == OmUnknownType )
|| newSibling.isEmpty() || hasAsAncestor( newSibling ) )
return;
OmNode::Iterator it = omobj->getOwner()->iteratorToIndex( omobj->ownerIndex() );
Lob tmp = Lob::fromVariant( 0 );
tmp.set( newSibling ); // just to deparent smoothly
omobj->getOwner()->insert( it, tmp.omobj );
//maybeEmitModified( Lob(), newSibling );
newSibling.maybeEmitModified( LobChange::newInsert( newSibling ) );
}
void Lob::removeNextSibling ()
{
if ( !hasParent() || !isEditable() || !hasNextSibling() )
return;
unsigned int index = omobj->ownerIndex() + 1;
OmNode::Iterator it = omobj->getOwner()->iteratorToIndex( index );
OmNode* out;
omobj->getOwner()->extract( it, out );
Lob newOwner( out );
//maybeEmitModified( newOwner, omobj->getOwner() );
parent().maybeEmitModified( LobChange::newRemove( newOwner ), OmNode::AsChild, index );
}
void Lob::removePreviousSibling ()
{
if ( !hasParent() || !isEditable() || !hasPreviousSibling() )
return;
unsigned int index = omobj->ownerIndex() - 1;
OmNode::Iterator it = omobj->getOwner()->iteratorToIndex( index );
OmNode* out;
omobj->getOwner()->extract( it, out );
Lob newOwner( out );
//maybeEmitModified( newOwner, omobj->getOwner() );
parent().maybeEmitModified( LobChange::newRemove( newOwner ), OmNode::AsChild, index );
}
unsigned int Lob::numComments ()
{
if ( isEmpty() )
return 0;
return omobj->countComments();
}
QString Lob::comment ( unsigned int i )
{
if ( i >= numComments() )
return QString();
OmComment* c;
omobj->consultComment( i, c );
return unescapeXML( QString( c->getBuffer() ) ).trimmed();
}
void Lob::removeComment ( unsigned int i )
{
if ( i >= numComments() )
return;
omobj->killComment( i );
}
void Lob::changeComment ( unsigned int i, QString text )
{
if ( i >= numComments() )
return;
OmComment* c;
omobj->consultComment( i, c );
c->setBuffer( escapeXML( " " + text + " " ).toLatin1().constData() );
}
void Lob::insertComment ( unsigned int i, QString text )
{
if ( i > numComments() )
return;
omobj->insertComment( i,
new OmComment( escapeXML( " " + text + " " ).toLatin1().constData() ) );
}
void Lob::appendComment ( QString text )
{
if ( isEmpty() )
return;
omobj->appendComment(
new OmComment( escapeXML( " " + text + " " ).toLatin1().constData() ) );
}
QStringList Lob::comments ()
{
if ( isEmpty() )
return QStringList();
QStringList result;
for ( unsigned int i = 0 ; i < omobj->countComments() ; i++ )
result << comment( i );
return result;
}
void Lob::setComments ( QStringList all )
{
if ( isEmpty() )
return;
while ( omobj->countComments() > 0 )
omobj->killComment( 0 );
foreach ( const QString& comment, all )
appendComment( comment );
}
void Lob::setAttribute ( QString keyName, QString keyCD, Lob newValue )
{
if ( isEmpty() || ( nodeType() == OmUnknownType )
|| newValue.isEmpty() || ( newValue.nodeType() == OmUnknownType )
|| !isEditable() )
return;
Lob findAttribute = attribute( keyName, keyCD );
if ( !findAttribute.isEmpty() ) {
findAttribute.set( newValue );
} else {
Lob tmp = Lob::fromVariant( 0 );
tmp.set( newValue );
OmSymbolNode* sym = new OmSymbolNode( keyCD.toLatin1().constData(),
keyName.toLatin1().constData() );
omobj->appendAttribute( sym, tmp.omobj );
maybeEmitModified( LobChange::newInsertPair( keyName, keyCD, newValue ),
OmNode::AsValue, omobj->countAttributes() - 1 );
}
}
void Lob::insertAttribute ( uint index, QString keyName, QString keyCD, Lob value )
{
if ( isEmpty() || ( nodeType() == OmUnknownType )
|| value.isEmpty() || ( value.nodeType() == OmUnknownType )
|| !isEditable() )
return;
if ( index > omobj->countAttributes() )
return;
Lob tmp = Lob::fromVariant( 0 );
tmp.set( value );
OmSymbolNode* sym = new OmSymbolNode( keyCD.toLatin1().constData(),
keyName.toLatin1().constData() );
omobj->insertAttribute( index, sym, tmp.omobj );
//maybeEmitModified( Lob(), Lob( sym ) );
//maybeEmitModified( Lob(), value );
maybeEmitModified( LobChange::newInsertPair( keyName, keyCD, value ),
OmNode::AsValue, index );
}
void Lob::removeAttribute ( QString keyName, QString keyCD )
{
if ( !isEditable() )
return;
Lob findAttribute = attribute( keyName, keyCD );
Lob tmp = Lob::fromVariant( 0 );;
if ( !findAttribute.isEmpty() )
tmp.set( findAttribute );
}
void Lob::removeAttribute ( uint index )
{
if ( isEmpty() || !isEditable() )
return;
if ( index >= omobj->countAttributes() )
return;
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( index, key, value );
Lob tmp = Lob::fromVariant( 0 );
tmp.set( value );
}
bool excludedAttribute ( QString name, QString cd, QStringList exclusions )
{
// check to see if (name,cd) is excluded in the list exclusions, of the form
// [ name1, cd1, name2, cd2, ... , nameN, cdN ] (with the last cdN optional)
for ( int i = 0 ; i < exclusions.count() ; i += 2 )
if ( ( name == exclusions[i] )
&& ( ( i == exclusions.count() - 1 ) || ( cd == exclusions[i+1] ) ) )
return true;
return false;
}
bool equivalentAttributes ( const OmNode* a, const OmNode* b, QStringList exclusions )
{
// for every attribute of a, be sure it's equivalent() to the same attribute of b
for ( unsigned int i = 0 ; i < a->countAttributes() ; i++ ) {
OmSymbolNode* akeyi;
OmNode* avaluei;
a->consultAttribute( i, akeyi, avaluei );
// if this one is excluded, skip it
if ( excludedAttribute( akeyi->getName(), akeyi->getCD(), exclusions ) )
continue;
// if the attribute appeared already in a's list, ignore this duplicate
bool alreadyDidThisOne = false;
for ( unsigned int j = 0 ; j < i ; j++ ) {
OmSymbolNode* akeyj;
OmNode* avaluej;
a->consultAttribute( j, akeyj, avaluej );
if ( !strcmp( akeyj->getName(), akeyi->getName() )
&& !strcmp( akeyj->getCD(), akeyi->getCD() ) ) {
alreadyDidThisOne = true;
break;
}
}
if ( alreadyDidThisOne )
continue;
// this attribute counts, so look the same one up in b
OmSymbolNode* bkeyj;
OmNode* bvaluej;
bool found = false;
for ( unsigned int j = 0 ; j < b->countAttributes() ; j++ ) {
b->consultAttribute( j, bkeyj, bvaluej );
if ( !strcmp( bkeyj->getName(), akeyi->getName() )
&& !strcmp( bkeyj->getCD(), akeyi->getCD() ) ) {
// found the same key in b, so return false if their values don't match
found = true;
if ( !equivalent( avaluei, bvaluej, true, exclusions ) )
return false;
break;
}
}
if ( !found )
return false; // couldn't find the same key in b, so return false
}
// for every attribute of b, just verify that it's in a
for ( unsigned int j = 0 ; j < b->countAttributes() ; j++ ) {
OmSymbolNode* bkeyj;
OmNode* bvaluej;
b->consultAttribute( j, bkeyj, bvaluej );
// if this one excluded, skip it
if ( excludedAttribute( bkeyj->getName(), bkeyj->getCD(), exclusions ) )
continue;
// see if a contains a like-keyed attribute
bool foundInA = false;
for ( unsigned int i = 0 ; i < a->countAttributes() ; i++ ) {
OmSymbolNode* akeyi;
OmNode* avaluei;
a->consultAttribute( i, akeyi, avaluei );
if ( !strcmp( bkeyj->getName(), akeyi->getName() )
&& !strcmp( bkeyj->getCD(), akeyi->getCD() ) ) {
foundInA = true;
break;
}
}
if ( !foundInA )
return false;
}
// found no reason to return false, so return true
return true;
}
bool equivalent ( const OmNode* a, const OmNode* b,
bool compareAttributes, QStringList exclusions )
{
if ( !a && !b )
return true;
if ( !a || !b )
return false;
if ( a->type() != b->type() )
return false;
if ( compareAttributes && !equivalentAttributes( a, b, exclusions ) )
return false;
switch ( a->type() )
{
case OmIntegerType:
return ((OmIntegerNode*)a)->getValue() == ((OmIntegerNode*)b)->getValue();
case OmBigIntegerType:
{
OmBigIntegerNode* bia = (OmBigIntegerNode*)a;
OmBigIntegerNode* bib = (OmBigIntegerNode*)b;
QString digsa = QString( bia->getDigits() ).trimmed();
QString digsb = QString( bib->getDigits() ).trimmed();
if ( ( digsa.count( '0' ) == digsa.length() ) // a is the big integer zero
&& ( digsb.count( '0' ) == digsb.length() ) ) // so is b
return true;
if ( bia->getSign() * bib->getSign() < 0 )
return false;
int i = 0;
while ( ( i < digsa.length() ) && ( digsa[i] == '0' ) ) i++;
int j = 0;
while ( ( j < digsb.length() ) && ( digsb[j] == '0' ) ) j++;
return digsa.mid( i ) == digsb.mid( j );
}
case OmFloatType:
return ((OmFloatNode*)a)->getValue() == ((OmFloatNode*)b)->getValue();
case OmByteArrayType:
{
const char* bufa;
const char* bufb;
unsigned int lena;
unsigned int lenb;
((OmByteArrayNode*)a)->getBuffer( bufa, lena );
((OmByteArrayNode*)b)->getBuffer( bufb, lenb );
if ( lena != lenb )
return false;
for ( unsigned int i = 0 ; i < lena ; i++ )
if ( bufa[i] != bufb[i] )
return false;
return true;
}
case OmStringType:
return !strcmp( ((OmStringNode*)a)->getBuffer(),
((OmStringNode*)b)->getBuffer() );
case OmWStringType:
return QString::fromWCharArray( ((OmWStringNode*)a)->getBuffer() )
== QString::fromWCharArray( ((OmWStringNode*)b)->getBuffer() );
case OmSymbolType:
return !strcmp( ((OmSymbolNode*)a)->getName(), ((OmSymbolNode*)b)->getName() )
&& !strcmp( ((OmSymbolNode*)a)->getCD(), ((OmSymbolNode*)b)->getCD() );
case OmVariableType:
return !strcmp( ((OmVariableNode*)a)->getName(),
((OmVariableNode*)b)->getName() );
case OmPInstructionType:
return !strcmp( ((OmPInstructionNode*)a)->getBuffer(),
((OmPInstructionNode*)b)->getBuffer() );
default:
{
if ( a->count() != b->count() )
return false;
OmNode::ConstIterator ita = a->iterate();
OmNode::ConstIterator itb = b->iterate();
while ( !ita.done() ) {
if ( !equivalent( ita.get(), itb.get(), compareAttributes, exclusions ) )
return false;
ita.next();
itb.next();
}
return true;
}
}
}
void deleteOmNode ( OmNode* node )
{
if ( node->type() == OmUnknownType ) {
OmDocumentNode* maybeDoc = dynamic_cast<OmDocumentNode*>( node );
if ( maybeDoc )
delete maybeDoc; // otherwise we are not authorized to delete it
} else {
OmDocumentNode killer;
killer.append( node ); // this deletes node; it's legal because type != unknown
}
}
SafeSingleton<QMap<OmNode*, unsigned long int> > Lob::referenceCounts;
bool Lob::descendentsUnreferenced ( OmNode* node )
{
if ( ( node == NULL ) || !referenceCounts.available() )
return false;
if ( referenceCounts.data().contains( node ) && ( referenceCounts.data()[node] > 0 ) )
return false;
for ( OmNode::Iterator it = node->iterate() ; !it.done() ; it.next() )
if ( !descendentsUnreferenced( it.get() ) )
return false;
for ( unsigned int i = 0 ; i < node->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
node->consultAttribute( i, key, value );
if ( !descendentsUnreferenced( key ) || !descendentsUnreferenced( value ) )
return false;
}
return true;
}
OmNode* topLevelOwner ( OmNode* node )
{
while ( ( node != NULL ) && ( node->getOwner() != NULL ) )
node = node->getOwner();
return node;
}
void Lob::hold ( OmNode* node )
{
if ( ( node == NULL ) || !referenceCounts.available() )
return;
if ( !referenceCounts.data().contains( node ) )
referenceCounts.data()[node] = 0;
++referenceCounts.data()[node];
}
void Lob::release ( OmNode* node )
{
if ( ( node == NULL ) || !referenceCounts.available() )
return;
if ( referenceCounts.data().contains( node ) ) {
unsigned long int& c = referenceCounts.data()[node];
if ( c == 0 ) {
OmOutputStringStream outputStream;
OmDocumentNode* tosave = dynamic_cast<OmDocumentNode*>( node );
try {
OmOutputDevice outputDevice( outputStream, OmXmlEncoding, false );
if ( !tosave ) {
tosave = new OmDocumentNode;
tosave->append( node->clone() );
}
tosave->save( outputDevice );
const char* b = outputStream.getBuffer();
int len = outputStream.getBufferLength();
char* copy = new char[len + 1];
memcpy( copy, b, len );
copy[len] = '\0';
qDebug( "%s", copy );
} catch ( ... ) {
qDebug( "Lob::release(): c==0 and error computing representation" );
}
if ( tosave != node )
delete tosave;
}
Q_ASSERT_X( c > 0, "Lob::release", "reference counts never become negative" );
c--;
}
node = topLevelOwner( node );
if ( descendentsUnreferenced( node ) )
deleteOmNode( node );
}
SafeSingleton<QList<Lob*> > Lob::watchForModifications;
void Lob::prepareModifiedSignal ()
{
if ( omobj && !watchForModifications.data().contains( this ) )
watchForModifications.data() << this;
}
void Lob::maybeEmitModified ( const LobChange& change,
OmNode::OwnershipType fromHere, unsigned int fromIndex ) const
{
// first, if it was a change that wasn't really a change, don't emit anything
if ( ( change.type() == LobChange::NoChange )
|| ( ( change.type() == LobChange::Change )
&& change.oldData().equivalentTo( change.newData(), true ) ) )
return;
// okay, it was a real change, so emit something
for ( OmNode* o = omobj ; o != NULL ; o = o->getOwner() ) {
foreach ( Lob* Lptr, watchForModifications.data() ) {
if ( Lptr->omobj == o ) {
LobChange toEmit = change;
toEmit.root = *Lptr;
toEmit.addr = address( *Lptr );
toEmit.addr.addStep( fromIndex, fromHere ); // default does nothing
emit Lptr->modified( toEmit );
}
}
}
}
QMap<Lob,QString> Lob::highestIDs;
QString Lob::getID () const
{
QString result = getStringAttribute( "ID", "LurchCore" );
const QRegExp re( "id\\d+" );
return re.exactMatch( result ) ? result : QString();
}
void Lob::setID ( QString id )
{
if ( isEmpty() || !isEditable() )
return;
const QRegExp re( "id\\d+" );
if ( re.exactMatch( id ) )
setAttribute( "ID", "LurchCore", Lob::fromVariant( id ) );
}
void Lob::setIDContext ( bool on )
{
if ( isEmpty() )
return;
if ( on && !isIDContext() ) {
updateHighestID();
connect( this, SIGNAL(modified(const LobChange&)),
this, SLOT(updateHighestID(const LobChange&)) );
}
if ( !on ) {
highestIDs.remove( *this );
disconnect( this, SIGNAL(modified(const LobChange&)),
this, SLOT(updateHighestID(const LobChange&)) );
}
}
bool Lob::isIDContext () const
{
return highestIDs.contains( *this );
}
void Lob::updateHighestID () const
{
QStringList allIDs = listAllLabels( "ID" );
QString max;
foreach ( const QString& id, allIDs )
if ( max.isEmpty() || lessThanID( max, id ) )
max = id;
highestIDs[*this] = max;
}
void Lob::updateHighestID ( const LobChange& change ) const
{
Q_ASSERT_X( isIDContext(), "Lob::updateHighestID",
"Only ID Contexts should have the updateHighestID slot fired." );
if ( !isIDContext() )
return;
// process the change; did new data come in that requires increasing our max id?
if ( ( change.type() == LobChange::Insert ) || ( change.type() == LobChange::InsertPair )
|| ( change.type() == LobChange::Change ) ) {
QString max = highestIDs[*this];
QStringList allIDs = change.result().listAllLabels( "ID" );
foreach ( const QString& id, allIDs )
if ( max.isEmpty() || lessThanID( max, id ) )
max = id;
highestIDs[*this] = max;
}
}
bool Lob::hasAsAncestor ( const Lob maybeAncestor ) const
{
OmNode* walker = omobj;
while ( walker != NULL ) {
if ( walker == maybeAncestor.omobj )
return true;
walker = walker->getOwner();
}
return false;
}
Lob Lob::findIDContext () const
{
return ( isIDContext() || !omobj || !omobj->getOwner() ) ?
*this : Lob( omobj->getOwner() ).findIDContext();
}
QString Lob::getNewID () const
{
Lob context = findIDContext();
// if my context is the efficient kind, do a lookup and keep the table up-to-date
if ( context.isIDContext() ) {
QString highest = highestIDs[context];
highest = highest.isEmpty() ? zeroID() : incrementID( highest );
highestIDs[context] = highest;
return highest;
}
// my context is the inefficient kind, so I better just search
QStringList allIDs = context.listAllLabels( "ID" );
QString max;
foreach ( const QString& id, allIDs )
if ( max.isEmpty() || lessThanID( max, id ) )
max = id;
return max.isEmpty() ? zeroID() : incrementID( max );
}
Lob Lob::reference ()
{
// first ensure we have an ID
if ( getID().isEmpty() )
setID( getNewID() );
// if there was some problem with ensuring that, bomb out with an empty Lob
QString id = getID();
if ( id.isEmpty() )
return Lob();
// create a reference to this
Lob result = Lob::fromVariant( id );
result.setAttribute( "reference", "LurchCore", Lob::fromVariant( "ID" ) );
return result;
}
Lob Lob::referent () const
{
if ( !isIDReference() )
return Lob();
return recursiveReferent( getIDReference() );
}
Lob Lob::recursiveReferent ( QString id, OmNode* skip ) const
{
if ( isEmpty() )
return Lob();
// qDebug() << "recursive dereferencing in " << (unsigned long long int)this
// << " w/skip " << (unsigned long long int)skip;
// have I found it already?
if ( getID() == id ) {
// qDebug() << "found id \"" << id << "\" in " << (unsigned long long int)this;
return *this;
}
#ifdef PROCESS_REFS_IN_ATTRIBUTES
// search in all of my attribute values except skip; if it's there, return it
for ( unsigned int i = 0 ; i < omobj->countAttributes() ; i++ ) {
OmSymbolNode* key;
OmNode* value;
omobj->consultAttribute( i, key, value );
if ( value != skip ) {
// qDebug() << "recurring on attribute " << i
// << ", " << (unsigned long long int)value
// << ", which is not " << (unsigned long long int)skip;
Lob maybe = Lob( value ).recursiveReferent( id, omobj );
if ( !maybe.isEmpty() )
return maybe;
}
}
#endif
// search in all of my children except skip; if it's there, return it
for ( OmNode::Iterator it = omobj->iterate() ; !it.done() ; it.next() ) {
if ( it.get() != skip ) {
// qDebug() << "recurring on child " << (unsigned long long int)it.get()
// << ", which is not " << (unsigned long long int)skip;
Lob maybe = Lob( it.get() ).recursiveReferent( id, omobj );
if ( !maybe.isEmpty() )
return maybe;
}
}
// move the search up one level to my owner
OmNode* owner = omobj->getOwner();
if ( owner != skip ) {
// qDebug() << "up to parent/container...";
return Lob( owner ).recursiveReferent( id, omobj );
}
// if that's not possible, then I've searched my whole tree; return failure
// qDebug() << "giving up: empty result";
return Lob();
}
bool Lob::compareVariables ( Lob var1, Lob var2 ) const
{
return var1.toVariant() == var2.toVariant();
// can be extended later if Ken wants the "equals" parameter in script functions
// related to binding implemented, say like this:
// emit compare(Lob,Lob,bool&) with the last param being the result
// such a signal can be connected by a setVariableComparison() function,
// called by routines in the Lob prototype object in script.
}
bool Lob::variableOnList ( Lob var, QVariantList list ) const
{
foreach ( const QVariant& v, list )
if ( compareVariables( var, v.value<Lob>() ) )
return true;
return false;
}
QVariantList Lob::mergeVariableLists ( QVariantList a, QVariantList b ) const
{
QVariantList result = a;
foreach ( const QVariant& v, b )
if ( !variableOnList( v.value<Lob>(), result ) )
result << QVariant::fromValue( v );
return result;
}
bool Lob::isBinding () const
{
return nodeType() == OmBindingType;
}
bool Lob::binds ( QString var ) const
{
return binds( Lob::fromXML( QString( "<OMV name='%1'/>" ).arg( var ) ).child() );
}
bool Lob::binds ( Lob var ) const
{
if ( !isBinding() )
return false;
for ( unsigned int i = 1 ; i + 1 < numChildren() ; i++ ) {
Lob ch = child( i );
if ( ( ch.nodeType() == OmVariableType ) && compareVariables( ch, var ) )
return true;
}
return false;
}
QVariantList Lob::boundVariables ( Lob context ) const
{
QVariantList result;
if ( isEmpty() )
return result;
// if we haven't recurred up to the context yet, keep going up and getting all its bounds
if ( context != *this )
result = Lob( omobj->getOwner() ).boundVariables( context );
// now add to the list any variables that this particular Lob binds
if ( isBinding() ) {
for ( unsigned int i = 1 ; i + 1 < numChildren() ; i++ ) {
Lob ch = child( i );
if ( !variableOnList( ch, result ) )
result << QVariant::fromValue( ch );
}
}
return result;
}
QStringList Lob::boundVariableNames ( Lob context ) const
{
QVariantList result = boundVariables( context );
QStringList newResult;
foreach ( const QVariant& var, result )
newResult << var.value<Lob>().toVariant().toString();
return newResult;
}
QVariantList Lob::freeVariables ( Lob context, QVariant boundAbove ) const
{
if ( boundAbove.type() != QVariant::List ) {
// if boundAbove data not yet computed, compute it
boundAbove = boundVariables( context );
} else {
// otherwise, just add to it the variables bound at this one particular node
boundAbove = mergeVariableLists( boundAbove.toList(), boundVariables( *this ) );
}
// if this node is a variable, return it as free iff it's not on the boundAbove list
if ( nodeType() == OmVariableType )
return variableOnList( *this, boundAbove.toList() ) ?
QVariantList() :
QVariantList() << QVariant::fromValue( *this );
// otherwise recur on children and compile the results
QVariantList result;
for ( unsigned int i = 0 ; i < numChildren() ; i++ )
result = mergeVariableLists( result,
child( i ).freeVariables( context, boundAbove ) );
return result;
}
QStringList Lob::freeVariableNames ( Lob context ) const
{
QVariantList result = freeVariables( context );
QStringList newResult;
foreach ( const QVariant& var, result )
newResult << var.value<Lob>().toVariant().toString();
return newResult;
}
bool Lob::occursFree ( Lob var, Lob context ) const
{
return variableOnList( var, freeVariables( context ) );
}
bool Lob::occursFree ( QString var, Lob context ) const
{
return freeVariableNames( context ).contains( var );
}
bool Lob::isFree ( Lob context ) const
{
if ( nodeType() != OmVariableType )
return false;
return !variableOnList( *this, boundVariables( context ) );
}
Lob Lob::binderOf ( Lob context ) const
{
if ( nodeType() != OmVariableType )
return Lob();
Lob walker = *this;
while ( !walker.isEmpty() ) {
if ( walker.binds( *this ) )
return walker;
if ( walker == context )
break;
walker = Lob( walker.omobj->getOwner() );
}
return Lob();
}
QVariantList Lob::freeOccurrences ( Lob var, Lob context ) const
{
if ( variableOnList( var, boundVariables( context ) ) )
return QVariantList();
if ( ( nodeType() == OmVariableType ) && compareVariables( *this, var ) )
return QVariantList() << QVariant::fromValue( *this );
QVariantList result;
for ( unsigned int i = 0 ; i < numChildren() ; i++ ) {
Lob ch = child( i );
// can tell the child that its context equals itself, because we've already
// verified that no higher context binds the variables, so let's be efficient
result << ch.freeOccurrences( var, ch );
}
return result;
}
QVariantList Lob::freeOccurrences ( QString var, Lob context ) const
{
return freeOccurrences( Lob::fromXML( QString( "<OMV name='%1'/>" ).arg( var ) ).child(),
context );
}
void Lob::freeSubstitute ( Lob var, Lob term, Lob context )
{
foreach ( QVariant v, freeOccurrences( var, context ) )
v.value<Lob>().set( term.copy() );
}
void Lob::freeSubstitute ( QString var, Lob term, Lob context )
{
freeSubstitute( Lob::fromXML( QString( "<OMV name='%1'/>" ).arg( var ) ).child(),
term, context );
}
bool Lob::freeToSubstitute ( Lob term, Lob context ) const
{
QVariantList bounds = Lob( omobj->getOwner() ).boundVariables( context );
QVariantList frees = term.freeVariables();
foreach ( const QVariant& b, bounds )
if ( variableOnList( b.value<Lob>(), frees ) )
return false;
return true;
}
void Lob::renameBound ( Lob var, Lob newvar )
{
if ( ( nodeType() == OmVariableType ) && compareVariables( *this, var ) ) {
Lob replacement = newvar.copy();
moveAttributesTo( replacement );
set( replacement );
return;
}
for ( unsigned int i = 0 ; i < numChildren() ; i++ ) {
Lob ch = child( i );
if ( !ch.binds( var ) )
// only recur if it's not a nested quantification of the same variable
ch.renameBound( var, newvar );
else
// otherwise, just recur on the quantifier itself, which may be an expression,
// and which technically isn't bound by itself (what a corner case!)
ch.child().renameBound( var, newvar );
}
}
void Lob::renameBound ( QString var, QString newvar )
{
renameBound( Lob::fromXML( QString( "<OMV name='%1'/>" ).arg( var ) ).child(),
Lob::fromXML( QString( "<OMV name='%1'/>" ).arg( newvar ) ).child() );
}
void Lob::moveAttributesTo ( Lob other )
{
foreach ( Lob key, attributeKeys() )
other.setAttribute( key, attribute( key ) );
}