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
|
// This file is part of Golly.
// See docs/License.html for the copyright notice.
#include "wx/wxprec.h" // for compilers that support precompilation
#ifndef WX_PRECOMP
#include "wx/wx.h" // for all others include the necessary headers
#endif
#include "wx/file.h" // for wxFile
#include "wx/filename.h" // for wxFileName
#include "wx/menuitem.h" // for SetText
#include "wx/clipbrd.h" // for wxTheClipboard
#include "wx/dataobj.h" // for wxTextDataObject
#include "wx/zipstrm.h" // for wxZipEntry, wxZipInputStream
#include "wx/wfstream.h" // for wxFFileInputStream
#include "bigint.h"
#include "lifealgo.h"
#include "qlifealgo.h"
#include "hlifealgo.h"
#include "readpattern.h" // for readpattern
#include "writepattern.h" // for writepattern, pattern_format
#include "wxgolly.h" // for wxGetApp, statusptr, viewptr, bigview
#include "wxutils.h" // for Warning
#include "wxprefs.h" // for SavePrefs, allowundo, userrules, etc
#include "wxrule.h" // for GetRuleName
#include "wxinfo.h" // for GetInfoFrame
#include "wxstatus.h" // for statusptr->...
#include "wxview.h" // for viewptr->...
#include "wxscript.h" // for RunScript, inscript, scripttitle
#include "wxmain.h" // for MainFrame, etc
#include "wxundo.h" // for currlayer->undoredo->...
#include "wxalgos.h" // for CreateNewUniverse, algo_type, algoinfo, etc
#include "wxlayer.h" // for currlayer, etc
#include "wxoverlay.h" // for curroverlay
#include "wxhelp.h" // for ShowHelp, LoadRule
#include "wxtimeline.h" // for InitTimelineFrame, ToggleTimelineBar, etc
#ifdef __WXMAC__
// convert path to decomposed UTF8 so fopen will work
#define FILEPATH path.fn_str()
#else
#define FILEPATH path.mb_str(wxConvLocal)
#endif
#if wxCHECK_VERSION(2,9,0)
// some wxMenuItem method names have changed in wx 2.9
#define GetText GetItemLabel
#define SetText SetItemLabel
#endif
// File menu functions:
// -----------------------------------------------------------------------------
wxString MainFrame::GetBaseName(const wxString& path)
{
// extract basename from given path
return path.AfterLast(wxFILE_SEP_PATH);
}
// -----------------------------------------------------------------------------
void MainFrame::SetWindowTitle(const wxString& filename)
{
if ( !scripttitle.IsEmpty() ) {
// script has called settitle command
return;
}
if ( !filename.IsEmpty() ) {
// remember current file name
currlayer->currname = filename;
// show currname in current layer's menu item
UpdateLayerItem(currindex);
}
if (inscript) {
// avoid window title flashing; eg. script might be switching layers
ShowTitleLater();
return;
}
wxString prefix = wxEmptyString;
// display asterisk if pattern has been modified
if (currlayer->dirty) prefix += wxT("*");
int cid = currlayer->cloneid;
while (cid > 0) {
// display one or more "=" chars to indicate this is a cloned layer
prefix += wxT("=");
cid--;
}
wxString rule = GetRuleName( wxString(currlayer->algo->getrule(),wxConvLocal) );
wxString wtitle;
#ifdef __WXMAC__
wtitle.Printf(_("%s%s [%s]"),
prefix.c_str(), currlayer->currname.c_str(), rule.c_str());
#else
wtitle.Printf(_("%s%s [%s] - Golly"),
prefix.c_str(), currlayer->currname.c_str(), rule.c_str());
#endif
// nicer to truncate a really long title???
SetTitle(wtitle);
}
// -----------------------------------------------------------------------------
void MainFrame::CreateUniverse()
{
// save current rule
wxString oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);
// delete old universe and create new one of same type
delete currlayer->algo;
currlayer->algo = CreateNewUniverse(currlayer->algtype);
// ensure new universe uses same rule (and thus same # of cell states)
RestoreRule(oldrule);
// increment has been reset to 1 but that's probably not always desirable
// so set increment using current step size
SetGenIncrement();
}
// -----------------------------------------------------------------------------
void MainFrame::NewPattern(const wxString& title)
{
if (generating) {
command_pending = true;
cmdevent.SetId(wxID_NEW);
Stop();
return;
}
if (askonnew && currlayer->dirty && !SaveCurrentLayer()) return;
if (inscript) stop_after_script = true;
currlayer->savestart = false;
currlayer->currfile.Clear();
currlayer->startgen = 0;
// reset step size before CreateUniverse calls SetGenIncrement
currlayer->currbase = algoinfo[currlayer->algtype]->defbase;
currlayer->currexpo = 0;
// create new, empty universe of same type and using same rule
CreateUniverse();
// reset timing info used in DisplayTimingInfo
endtime = begintime = 0;
// clear all undo/redo history
currlayer->undoredo->ClearUndoRedo();
if (newremovesel) currlayer->currsel.Deselect();
if (newcurs) currlayer->curs = newcurs;
viewptr->SetPosMag(bigint::zero, bigint::zero, newmag);
// best to restore true origin
if (currlayer->originx != bigint::zero || currlayer->originy != bigint::zero) {
currlayer->originx = 0;
currlayer->originy = 0;
statusptr->SetMessage(origin_restored);
}
// restore default colors for current algo/rule
UpdateLayerColors();
MarkLayerClean(title); // calls SetWindowTitle
UpdateEverything();
}
// -----------------------------------------------------------------------------
static bool IsImageFile(const wxString& path)
{
wxString ext = path.AfterLast('.');
// if path has no extension then ext == path
if (ext == path) return false;
// supported extensions match image handlers added in GollyApp::OnInit()
return ext.IsSameAs(wxT("bmp"),false) ||
ext.IsSameAs(wxT("gif"),false) ||
ext.IsSameAs(wxT("png"),false) ||
ext.IsSameAs(wxT("tif"),false) ||
ext.IsSameAs(wxT("tiff"),false) ||
ext.IsSameAs(wxT("icons"),false) ||
// we don't actually support JPEG files but let LoadImage handle them
ext.IsSameAs(wxT("jpg"),false) ||
ext.IsSameAs(wxT("jpeg"),false);
}
// -----------------------------------------------------------------------------
bool MainFrame::LoadImage(const wxString& path)
{
// don't try to load JPEG file
wxString ext = path.AfterLast('.');
if ( ext.IsSameAs(wxT("jpg"),false) ||
ext.IsSameAs(wxT("jpeg"),false) ) {
Warning(_("Golly cannot import JPEG data, only BMP/GIF/PNG/TIFF."));
// pattern will be empty
return true;
}
wxImage image;
if ( image.LoadFile(path) ) {
// don't change the current rule here -- that way the image can
// be loaded into any algo
unsigned char maskr, maskg, maskb;
bool hasmask = image.GetOrFindMaskColour(&maskr, &maskg, &maskb);
int wd = image.GetWidth();
int ht = image.GetHeight();
unsigned char* idata = image.GetData();
int x, y;
lifealgo* curralgo = currlayer->algo;
for (y = 0; y < ht; y++) {
for (x = 0; x < wd; x++) {
long pos = (y * wd + x) * 3;
unsigned char r = idata[pos];
unsigned char g = idata[pos+1];
unsigned char b = idata[pos+2];
if ( hasmask && r == maskr && g == maskg && b == maskb ) {
// treat transparent pixel as a dead cell
} else if ( r < 255 || g < 255 || b < 255 ) {
// treat non-white pixel as a live cell
curralgo->setcell(x, y, 1);
}
}
}
curralgo->endofpattern();
} else {
Warning(_("Could not load image from file!"));
}
return true;
}
// -----------------------------------------------------------------------------
void MainFrame::LoadPattern(const wxString& path, const wxString& newtitle,
bool updatestatus, bool updateall)
{
if ( !wxFileName::FileExists(path) ) {
Warning(_("The file does not exist:\n") + path);
return;
}
// newtitle is only empty if called from ResetPattern/RestorePattern
if (!newtitle.IsEmpty()) {
if (askonload && currlayer->dirty && !SaveCurrentLayer()) return;
if (inscript) stop_after_script = true;
currlayer->savestart = false;
currlayer->currfile = path;
// reset step size now in case UpdateStatus is called below
currlayer->currbase = algoinfo[currlayer->algtype]->defbase;
currlayer->currexpo = 0;
if (GetInfoFrame()) {
// comments will no longer be relevant so close info window
GetInfoFrame()->Close(true);
}
// reset timing info used in DisplayTimingInfo
endtime = begintime = 0;
// clear all undo/redo history
currlayer->undoredo->ClearUndoRedo();
}
if (!showbanner) statusptr->ClearMessage();
// set nopattupdate BEFORE UpdateStatus() call so we see gen=0 and pop=0;
// in particular, it avoids getPopulation being called which would
// slow down hlife pattern loading
viewptr->nopattupdate = true;
if (updatestatus) {
// update all of status bar so we don't see different colored lines;
// on Mac, DrawView also gets called if there are pending updates
UpdateStatus();
}
// save current algo and rule
algo_type oldalgo = currlayer->algtype;
wxString oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);
// delete old universe and create new one of same type
delete currlayer->algo;
currlayer->algo = CreateNewUniverse(currlayer->algtype);
if (!newtitle.IsEmpty() && !inscript) {
// show new file name in window title but no rule (which readpattern can change);
// nicer if user can see file name while loading a very large pattern
SetTitle(_("Loading ") + newtitle);
}
if (IsImageFile(path)) {
// ensure new universe uses same rule
RestoreRule(oldrule);
LoadImage(path);
viewptr->nopattupdate = false;
} else {
const char* err = readpattern(FILEPATH, *currlayer->algo);
if (err) {
wxString bigerr = _("File could not be loaded by any algorithm.");
wxString algoname = wxString(GetAlgoName(currlayer->algtype), wxConvLocal);
bigerr += wxString::Format(_("\n\nError from %s:\n"), algoname.c_str());
bigerr += wxString(err, wxConvLocal);
// cycle thru all other algos until readpattern succeeds
for (int i = 0; i < NumAlgos(); i++) {
if (i != oldalgo) {
currlayer->algtype = i;
delete currlayer->algo;
currlayer->algo = CreateNewUniverse(currlayer->algtype);
// readpattern will call setrule
err = readpattern(FILEPATH, *currlayer->algo);
if (err) {
algoname = wxString(GetAlgoName(currlayer->algtype), wxConvLocal);
bigerr += wxString::Format(_("\n\nError from %s:\n"), algoname.c_str());
bigerr += wxString(err, wxConvLocal);
} else {
break;
}
}
}
viewptr->nopattupdate = false;
if (err) {
// no algo could read pattern so restore original algo and rule
currlayer->algtype = oldalgo;
delete currlayer->algo;
currlayer->algo = CreateNewUniverse(currlayer->algtype);
RestoreRule(oldrule);
// also show full path to file (useful when debugging!)
bigerr += wxString::Format(_("\n\nFile path:\n%s"), wxString(FILEPATH,wxConvLocal).c_str());
Warning(bigerr);
}
}
viewptr->nopattupdate = false;
}
if (!newtitle.IsEmpty()) {
MarkLayerClean(newtitle); // calls SetWindowTitle
if (TimelineExists()) {
// we've loaded a .mc file with a timeline so go to 1st frame
InitTimelineFrame();
if (!showtimeline) ToggleTimelineBar();
// switch to the base step and exponent used to record the timeline
pair<int, int> be = currlayer->algo->getbaseexpo();
currlayer->currbase = be.first;
currlayer->currexpo = be.second;
} else {
// restore default base step for current algo
// (currlayer->currexpo was set to 0 above)
currlayer->currbase = algoinfo[currlayer->algtype]->defbase;
}
SetGenIncrement();
// restore default colors for current algo/rule
UpdateLayerColors();
if (openremovesel) currlayer->currsel.Deselect();
if (opencurs) currlayer->curs = opencurs;
viewptr->FitInView(1);
currlayer->startgen = currlayer->algo->getGeneration(); // might be > 0
if (updateall) UpdateEverything();
showbanner = false;
} else {
// ResetPattern/RestorePattern does the update
}
}
// -----------------------------------------------------------------------------
void MainFrame::CheckBeforeRunning(const wxString& scriptpath, bool remember,
const wxString& zippath)
{
bool ask;
if (zippath.IsEmpty()) {
// script was downloaded via "get:" link (script is in downloaddir --
// see GetURL in wxhelp.cpp) so always ask user if it's okay to run
ask = true;
} else {
// script is included in zip file (scriptpath starts with tempdir) so only
// ask user if zip file was downloaded via "get:" link
ask = zippath.StartsWith(downloaddir);
}
if (ask) {
UpdateEverything(); // in case OpenZipFile called LoadPattern
// create our own dialog with a View button??? probably no need now that
// user can ctrl/right-click on link to open script in their text editor
wxString msg = scriptpath + _("\n\nClick \"No\" if the script is from an untrusted source.");
int answer = wxMessageBox(msg, _("Do you want to run this script?"),
wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT,
wxGetActiveWindow());
switch (answer) {
case wxYES: break;
case wxNO: return;
default: return; // No
}
}
// also do this???
// save script info (download path or zip path + script entry) in list of safe scripts
// (stored in prefs file) so we can search for this script and not ask again
Raise();
if (remember) AddRecentScript(scriptpath);
RunScript(scriptpath);
}
// -----------------------------------------------------------------------------
bool MainFrame::ExtractZipEntry(const wxString& zippath,
const wxString& entryname,
const wxString& outfile)
{
wxFFileInputStream instream(zippath);
if (!instream.Ok()) {
Warning(_("Could not create input stream for zip file:\n") + zippath);
return false;
}
wxZipInputStream zip(instream);
wxZipEntry* entry;
while ((entry = zip.GetNextEntry()) != NULL) {
wxString thisname = entry->GetName();
if (thisname == entryname) {
// we've found the desired entry so copy entry data to given output file
wxFileOutputStream outstream(outfile);
if (outstream.Ok()) {
// read and write in chunks so we can show a progress dialog
const int BUFFER_SIZE = 4000;
char buf[BUFFER_SIZE];
size_t incount = 0;
size_t outcount = 0;
size_t lastread, lastwrite;
double filesize = (double) entry->GetSize();
if (filesize <= 0.0) filesize = -1.0; // show indeterminate progress
BeginProgress(_("Extracting file"));
while (true) {
zip.Read(buf, BUFFER_SIZE);
lastread = zip.LastRead();
if (lastread == 0) break;
outstream.Write(buf, lastread);
lastwrite = outstream.LastWrite();
incount += lastread;
outcount += lastwrite;
if (incount != outcount) {
Warning(_("Error occurred while writing file:\n") + outfile);
break;
}
char msg[128];
sprintf(msg, "File size: %.2f MB", double(incount) / 1048576.0);
if (AbortProgress((double)incount / filesize, wxString(msg,wxConvLocal))) {
outcount = 0;
break;
}
}
EndProgress();
if (incount == outcount) {
// successfully copied entry data to outfile
delete entry;
return true;
} else {
// delete incomplete outfile
if (wxFileExists(outfile)) wxRemoveFile(outfile);
}
} else {
Warning(_("Could not open output stream for file:\n") + outfile);
}
delete entry;
return false;
}
delete entry;
}
// should not get here
Warning(_("Could not find zip file entry:\n") + entryname);
return false;
}
// -----------------------------------------------------------------------------
static bool RuleInstalled(wxZipInputStream& zip, const wxString& rulepath)
{
wxFileOutputStream outstream(rulepath);
bool ok = outstream.Ok();
if (ok) {
zip.Read(outstream);
ok = (outstream.GetLastError() == wxSTREAM_NO_ERROR);
}
return ok;
}
// -----------------------------------------------------------------------------
void MainFrame::OpenZipFile(const wxString& zippath)
{
// Process given zip file in the following manner:
// - If it contains any .rule files then extract and install those
// files into userrules (the user's rules directory).
// - If the zip file is "complex" (contains any folders, rule files, text files,
// or more than one pattern, or more than one script), build a temporary html
// file with clickable links to each file entry and show it in the help window.
// - If the zip file contains at most one pattern and at most one script (both
// at the root level) then load the pattern (if present) and then run the script
// (if present and if allowed).
const wxString indent = wxT(" ");
bool dirseen = false;
bool diffdirs = (userrules != rulesdir);
wxString firstdir = wxEmptyString;
wxString lastpattern = wxEmptyString;
wxString lastscript = wxEmptyString;
int patternseps = 0; // # of separators in lastpattern
int scriptseps = 0; // # of separators in lastscript
int patternfiles = 0;
int scriptfiles = 0;
int textfiles = 0; // includes html files
int rulefiles = 0;
int deprecated = 0; // # of .table/tree/colors/icons files
wxSortedArrayString deplist; // list of installed deprecated files
wxSortedArrayString rulelist; // list of installed .rule files
// note that we need to create the HTML file with UTF-8 encoding
// in case zippath contains non-ASCII characters
wxString contents = wxT("<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
contents += wxT("<title>") + GetBaseName(zippath);
contents += wxT("</title>\n");
contents += wxT("<body bgcolor=\"#FFFFCE\">\n");
contents += wxT("<p>\n");
contents += wxT("Zip file: ");
contents += zippath;
contents += wxT("<p>\n");
contents += wxT("Contents:<br>\n");
wxFFileInputStream instream(zippath);
if (!instream.Ok()) {
Warning(_("Could not create input stream for zip file:\n") + zippath);
return;
}
wxZipInputStream zip(instream);
// examine each entry in zip file and build contents string;
// also install any .rule files
wxZipEntry* entry;
while ((entry = zip.GetNextEntry()) != NULL) {
wxString name = entry->GetName();
if (name.StartsWith(wxT("__MACOSX")) || name.EndsWith(wxT(".DS_Store"))) {
// ignore meta-data stuff in zip file created on Mac
} else {
// indent depending on # of separators in name
unsigned int sepcount = 0;
unsigned int i = 0;
unsigned int len = (unsigned int)name.length();
while (i < len) {
if (name[i] == wxFILE_SEP_PATH) sepcount++;
i++;
}
// check if 1st directory has multiple separators (eg. in jslife.zip)
if (entry->IsDir() && !dirseen && sepcount > 1) {
firstdir = name.BeforeFirst(wxFILE_SEP_PATH);
contents += firstdir;
contents += wxT("<br>\n");
}
for (i = 1; i < sepcount; i++) contents += indent;
if (entry->IsDir()) {
// remove terminating separator from directory name
name = name.BeforeLast(wxFILE_SEP_PATH);
name = name.AfterLast(wxFILE_SEP_PATH);
if (dirseen && name == firstdir) {
// ignore dir already output earlier (eg. in jslife.zip)
} else {
contents += name;
contents += wxT("<br>\n");
}
dirseen = true;
} else {
// entry is for some sort of file
wxString filename = name.AfterLast(wxFILE_SEP_PATH);
if (dirseen) contents += indent;
if ( IsRuleFile(filename) && !filename.EndsWith(wxT(".rule")) ) {
// this is a deprecated .table/tree/colors/icons file
contents += filename;
contents += indent;
contents += wxT("[deprecated]");
deprecated++;
// install it into userrules so it can be used below to create a .rule file
wxString outfile = userrules + filename;
if (RuleInstalled(zip, outfile)) {
deplist.Add(filename);
} else {
contents += indent;
contents += wxT("INSTALL FAILED!");
}
} else {
// user can extract file via special "unzip:" link
contents += wxT("<a href=\"unzip:");
contents += zippath;
contents += wxT(":");
contents += name;
contents += wxT("\">");
contents += filename;
contents += wxT("</a>");
if ( IsRuleFile(filename) ) {
// extract and install .rule file into userrules
wxString outfile = userrules + filename;
if (RuleInstalled(zip, outfile)) {
// file successfully installed
rulelist.Add(filename);
contents += indent;
contents += wxT("[installed]");
if (diffdirs) {
// check if this file overrides similarly named file in rulesdir
wxString clashfile = rulesdir + filename;
if (wxFileExists(clashfile)) {
contents += indent;
contents += wxT("(overrides file in Rules folder)");
}
}
} else {
// file could not be installed
contents += indent;
contents += wxT("[NOT installed]");
// file is probably incomplete so best to delete it
if (wxFileExists(outfile)) wxRemoveFile(outfile);
}
rulefiles++;
} else if ( IsHTMLFile(filename) || IsTextFile(filename) ) {
textfiles++;
} else if ( IsScriptFile(filename) ) {
scriptfiles++;
lastscript = name;
scriptseps = sepcount;
} else {
patternfiles++;
lastpattern = name;
patternseps = sepcount;
}
}
contents += wxT("<br>\n");
}
}
delete entry;
} // end while
if (rulefiles > 0) {
contents += wxT("<p>Files marked as \"[installed]\" have been stored in your rules folder:<br>\n");
contents += userrules;
contents += wxT("\n");
}
if (deprecated > 0) {
wxString newrules = CreateRuleFiles(deplist, rulelist);
if (newrules.length() > 0) {
contents += wxT("<p>Files marked as \"[deprecated]\" have been used to create new .rule files:<br>\n");
contents += newrules;
}
}
contents += wxT("\n</body></html>");
if (dirseen || rulefiles > 0 || deprecated > 0 || textfiles > 0 || patternfiles > 1 || scriptfiles > 1) {
// complex zip, so write contents to a temporary html file and display it in help window;
// use a unique file name so user can go back/forwards
wxString htmlfile = wxFileName::CreateTempFileName(tempdir + wxT("zip_contents_"));
wxRemoveFile(htmlfile);
htmlfile += wxT(".html");
wxFile outfile(htmlfile, wxFile::write);
if (outfile.IsOpened()) {
outfile.Write(contents);
outfile.Close();
ShowHelp(htmlfile);
} else {
Warning(_("Could not create html file:\n") + htmlfile);
}
}
if (patternfiles <= 1 && scriptfiles <= 1 && patternseps == 0 && scriptseps == 0) {
// load lastpattern (if present), then run lastscript (if present);
// the script might be a long-running one that allows user interaction,
// so it's best to run it AFTER calling ShowHelp above
if (patternfiles == 1) {
wxString tempfile = tempdir + lastpattern.AfterLast(wxFILE_SEP_PATH);
if (ExtractZipEntry(zippath, lastpattern, tempfile)) {
Raise();
// don't call AddRecentPattern(tempfile) here; OpenFile has added
// zippath to recent patterns
LoadPattern(tempfile, GetBaseName(tempfile), true, scriptfiles == 0);
}
}
if (scriptfiles == 1) {
wxString tempfile = tempdir + lastscript.AfterLast(wxFILE_SEP_PATH);
if (ExtractZipEntry(zippath, lastscript, tempfile)) {
// run script depending on safety check
CheckBeforeRunning(tempfile, false, zippath);
} else {
// should never happen but play safe
UpdateEverything();
}
}
}
}
// -----------------------------------------------------------------------------
static bool RuleCanBeFound(const wxString& path)
{
// ensure given path to .rule file is a full path
wxString fullpath = path;
wxFileName fname(fullpath);
if (!fname.IsAbsolute()) fullpath = gollydir + path;
// check that .rule file is in userrules or rulesdir
wxString dir = fullpath.BeforeLast(wxFILE_SEP_PATH);
dir += wxFILE_SEP_PATH;
if (dir == userrules || dir == rulesdir) {
return true;
} else {
wxString msg = _("You need to move ");
msg += fullpath.AfterLast(wxFILE_SEP_PATH);
msg += _(" into your rules folder (");
msg += userrules;
msg += _(") so the RuleLoader algorithm can find it.");
Warning(msg);
return false;
}
}
// -----------------------------------------------------------------------------
void MainFrame::OpenFile(const wxString& path, bool remember)
{
if (IsHTMLFile(path)) {
// show HTML file in help window
ShowHelp(path);
return;
}
if (IsTextFile(path)) {
// open text file in user's preferred text editor
EditFile(path);
return;
}
if (generating) {
command_pending = true;
// assume remember is true (should only be false if called from a script)
if ( IsScriptFile(path) ) {
AddRecentScript(path);
cmdevent.SetId(ID_RUN_RECENT + 1);
} else {
AddRecentPattern(path);
cmdevent.SetId(ID_OPEN_RECENT + 1);
}
Stop();
return;
}
// note that pass_file_events is false if OpenFile was called from GSF_open
if (inscript && pass_file_events) {
// ensure path is a full path
wxString newpath = path;
wxFileName fname(newpath);
if (!fname.IsAbsolute()) newpath = gollydir + path;
PassFileToScript(newpath);
return;
}
if (!inscript && path.EndsWith(wxT(".rle3"))) {
if (remember) AddRecentPattern(path);
// create a full path in rle3path for GSF_getevent to use
rle3path = path;
wxFileName fname(rle3path);
if (!fname.IsAbsolute()) rle3path = gollydir + path;
// start up 3D.lua (it will get a file event containing rle3path)
wxString path3D = gollydir + wxT("Scripts");
path3D += wxFILE_SEP_PATH;
path3D += wxT("Lua");
path3D += wxFILE_SEP_PATH;
path3D += wxT("3D.lua");
RunScript(path3D);
return;
}
if (IsScriptFile(path)) {
// execute script
if (remember) AddRecentScript(path);
RunScript(path);
} else if (IsZipFile(path)) {
// process zip file
if (remember) AddRecentPattern(path); // treat it like a pattern
OpenZipFile(path);
} else if (IsRuleFile(path)) {
// switch to rule, but only if it's in rulesdir or userrules
if (RuleCanBeFound(path))
LoadRule(path.AfterLast(wxFILE_SEP_PATH).BeforeLast('.'));
} else {
// load pattern
if (remember) AddRecentPattern(path);
// ensure path is a full path because a script might want to reset() to it
// (in which case the cwd is the script's directory, not gollydir)
wxString newpath = path;
wxFileName fname(newpath);
if (!fname.IsAbsolute()) newpath = gollydir + path;
LoadPattern(newpath, GetBaseName(path));
}
}
// -----------------------------------------------------------------------------
void MainFrame::AddRecentPattern(const wxString& inpath)
{
if (inpath.IsEmpty()) return;
wxString path = inpath;
if (path.StartsWith(gollydir)) {
// remove gollydir from start of path
path.erase(0, gollydir.length());
}
// duplicate any ampersands so they appear in menu
path.Replace(wxT("&"), wxT("&&"));
// put given path at start of patternSubMenu
#ifdef __WXGTK__
// avoid wxGTK bug in FindItem if path contains underscores
int id = wxNOT_FOUND;
for (int i = 0; i < numpatterns; i++) {
wxMenuItem* item = patternSubMenu->FindItemByPosition(i);
wxString temp = item->GetText();
temp.Replace(wxT("__"), wxT("_"));
temp.Replace(wxT("&"), wxT("&&"));
if (temp == path) {
id = ID_OPEN_RECENT + 1 + i;
break;
}
}
#else
int id = patternSubMenu->FindItem(path);
#endif
if ( id == wxNOT_FOUND ) {
if ( numpatterns < maxpatterns ) {
// add new path
numpatterns++;
id = ID_OPEN_RECENT + numpatterns;
patternSubMenu->Insert(numpatterns - 1, id, path);
} else {
// replace last item with new path
wxMenuItem* item = patternSubMenu->FindItemByPosition(maxpatterns - 1);
item->SetText(path);
id = ID_OPEN_RECENT + maxpatterns;
}
}
// path exists in patternSubMenu
if ( id > ID_OPEN_RECENT + 1 ) {
// move path to start of menu
wxMenuItem* item;
while ( id > ID_OPEN_RECENT + 1 ) {
wxMenuItem* previtem = patternSubMenu->FindItem(id - 1);
wxString prevpath = previtem->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
prevpath.Replace(wxT("__"), wxT("_"));
prevpath.Replace(wxT("&"), wxT("&&"));
#endif
item = patternSubMenu->FindItem(id);
item->SetText(prevpath);
id--;
}
item = patternSubMenu->FindItem(id);
item->SetText(path);
}
}
// -----------------------------------------------------------------------------
void MainFrame::AddRecentScript(const wxString& inpath)
{
if (inpath.IsEmpty()) return;
wxString path = inpath;
if (path.StartsWith(gollydir)) {
// remove gollydir from start of path
path.erase(0, gollydir.length());
}
// duplicate ampersands so they appear in menu
path.Replace(wxT("&"), wxT("&&"));
// put given path at start of scriptSubMenu
#ifdef __WXGTK__
// avoid wxGTK bug in FindItem if path contains underscores
int id = wxNOT_FOUND;
for (int i = 0; i < numscripts; i++) {
wxMenuItem* item = scriptSubMenu->FindItemByPosition(i);
wxString temp = item->GetText();
temp.Replace(wxT("__"), wxT("_"));
temp.Replace(wxT("&"), wxT("&&"));
if (temp == path) {
id = ID_RUN_RECENT + 1 + i;
break;
}
}
#else
int id = scriptSubMenu->FindItem(path);
#endif
if ( id == wxNOT_FOUND ) {
if ( numscripts < maxscripts ) {
// add new path
numscripts++;
id = ID_RUN_RECENT + numscripts;
scriptSubMenu->Insert(numscripts - 1, id, path);
} else {
// replace last item with new path
wxMenuItem* item = scriptSubMenu->FindItemByPosition(maxscripts - 1);
item->SetText(path);
id = ID_RUN_RECENT + maxscripts;
}
}
// path exists in scriptSubMenu
if ( id > ID_RUN_RECENT + 1 ) {
// move path to start of menu
wxMenuItem* item;
while ( id > ID_RUN_RECENT + 1 ) {
wxMenuItem* previtem = scriptSubMenu->FindItem(id - 1);
wxString prevpath = previtem->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
prevpath.Replace(wxT("__"), wxT("_"));
prevpath.Replace(wxT("&"), wxT("&&"));
#endif
item = scriptSubMenu->FindItem(id);
item->SetText(prevpath);
id--;
}
item = scriptSubMenu->FindItem(id);
item->SetText(path);
}
}
// -----------------------------------------------------------------------------
void MainFrame::OpenPattern()
{
if (generating) {
command_pending = true;
cmdevent.SetId(wxID_OPEN);
Stop();
return;
}
wxString filetypes = _("All files (*)|*");
filetypes += _("|RLE (*.rle)|*.rle");
filetypes += _("|RLE3 (*.rle3)|*.rle3");
filetypes += _("|Macrocell (*.mc)|*.mc");
filetypes += _("|Gzip (*.gz)|*.gz");
filetypes += _("|Life 1.05/1.06 (*.lif)|*.lif");
filetypes += _("|dblife (*.l)|*.l");
filetypes += _("|MCell (*.mcl)|*.mcl");
filetypes += _("|Zip (*.zip;*.gar)|*.zip;*.gar");
filetypes += _("|BMP (*.bmp)|*.bmp");
filetypes += _("|GIF (*.gif)|*.gif");
filetypes += _("|PNG (*.png)|*.png");
filetypes += _("|TIFF (*.tiff;*.tif)|*.tiff;*.tif");
wxFileDialog opendlg(this, _("Choose a pattern"),
opensavedir, wxEmptyString, filetypes,
wxFD_OPEN | wxFD_FILE_MUST_EXIST);
int button = opendlg.ShowModal();
viewptr->ResetMouseDown();
if (button == wxID_OK) {
wxFileName fullpath( opendlg.GetPath() );
opensavedir = fullpath.GetPath();
OpenFile( opendlg.GetPath() );
}
}
// -----------------------------------------------------------------------------
void MainFrame::OpenScript()
{
if (generating) {
command_pending = true;
cmdevent.SetId(ID_RUN_SCRIPT);
Stop();
return;
}
wxString filetypes = _("Lua or Python (*.lua;*.py)|*.lua;*.py");
filetypes += _("|Lua (*.lua)|*.lua");
filetypes += _("|Python (*.py)|*.py");
#ifdef ENABLE_PERL
filetypes += _("|Perl (*.pl)|*.pl");
#endif
wxFileDialog opendlg(this, _("Choose a script"),
rundir, wxEmptyString, filetypes,
wxFD_OPEN | wxFD_FILE_MUST_EXIST);
int button = opendlg.ShowModal();
viewptr->ResetMouseDown();
if (button == wxID_OK) {
wxFileName fullpath( opendlg.GetPath() );
rundir = fullpath.GetPath();
AddRecentScript( opendlg.GetPath() );
RunScript( opendlg.GetPath() );
}
}
// -----------------------------------------------------------------------------
bool MainFrame::CopyTextToClipboard(const wxString& text)
{
bool result = true;
if (wxTheClipboard->Open()) {
if ( !wxTheClipboard->SetData(new wxTextDataObject(text)) ) {
Warning(_("Could not copy text to clipboard!"));
result = false;
}
wxTheClipboard->Close();
} else {
Warning(_("Could not open clipboard!"));
result = false;
}
return result;
}
// -----------------------------------------------------------------------------
#if wxCHECK_VERSION(2,9,0)
// wxTextDataObject also has GetText and SetText methods so don't change them
#undef GetText
#undef SetText
#endif
bool MainFrame::GetTextFromClipboard(wxTextDataObject* textdata)
{
bool gotdata = false;
if ( wxTheClipboard->Open() ) {
if ( wxTheClipboard->IsSupported( wxDF_TEXT ) ) {
gotdata = wxTheClipboard->GetData( *textdata );
if (!gotdata) {
statusptr->ErrorMessage(_("Could not get clipboard text!"));
}
} else if ( wxTheClipboard->IsSupported( wxDF_BITMAP ) ) {
wxBitmapDataObject bmapdata;
gotdata = wxTheClipboard->GetData( bmapdata );
if (gotdata) {
// convert bitmap data to text data
wxString str;
wxBitmap bmap = bmapdata.GetBitmap();
wxImage image = bmap.ConvertToImage();
if (image.Ok()) {
/* there doesn't seem to be any mask or alpha info, at least on Mac
if (bmap.GetMask() != NULL) Warning(_("Bitmap has mask!"));
if (image.HasMask()) Warning(_("Image has mask!"));
if (image.HasAlpha()) Warning(_("Image has alpha!"));
*/
int wd = image.GetWidth();
int ht = image.GetHeight();
unsigned char* idata = image.GetData();
int x, y;
for (y = 0; y < ht; y++) {
for (x = 0; x < wd; x++) {
long pos = (y * wd + x) * 3;
if ( idata[pos] < 255 || idata[pos+1] < 255 || idata[pos+2] < 255 ) {
// non-white pixel is a live cell
str += 'o';
} else {
// white pixel is a dead cell
str += '.';
}
}
str += '\n';
}
textdata->SetText(str);
} else {
statusptr->ErrorMessage(_("Could not convert clipboard bitmap!"));
gotdata = false;
}
} else {
statusptr->ErrorMessage(_("Could not get clipboard bitmap!"));
}
} else {
statusptr->ErrorMessage(_("No data in clipboard."));
}
wxTheClipboard->Close();
} else {
statusptr->ErrorMessage(_("Could not open clipboard!"));
}
return gotdata;
}
// -----------------------------------------------------------------------------
bool MainFrame::ClipboardContainsRule()
{
wxTextDataObject data;
if (!GetTextFromClipboard(&data)) return false;
wxString cliptext = data.GetText();
if (!cliptext.StartsWith(wxT("@RULE "))) return false;
// extract rule name
wxString rulename;
int i = 6;
while (cliptext[i] > ' ') {
rulename += cliptext[i];
i++;
}
// check if rulename.rule already exists
wxString rulepath = userrules + rulename;
rulepath += wxT(".rule");
if (wxFileExists(rulepath)) {
wxString question = _("Do you want to replace the existing ") + rulename;
question += _(".rule with the version in the clipboard?");
int answer = wxMessageBox(question, _("Replace existing .rule file?"),
wxICON_QUESTION | wxYES_NO | wxNO_DEFAULT, wxGetActiveWindow());
if (answer == wxNO) {
// don't overwrite existing .rule file
return true;
}
}
// create rulename.rule in user-specific rules folder
wxFile rulefile(rulepath, wxFile::write);
if (!rulefile.IsOpened()) {
Warning(_("Could not open .rule file for writing:\n") + rulepath);
return true;
}
if (!rulefile.Write(data.GetText())) {
Warning(_("Could not write clipboard data to .rule file!"));
rulefile.Close();
return true;
}
rulefile.Close();
statusptr->DisplayMessage(_("Created ") + rulepath);
// now switch to the newly created rule
LoadRule(rulename);
return true;
}
// -----------------------------------------------------------------------------
bool MainFrame::ClipboardContainsRLE3()
{
wxTextDataObject data;
if (!GetTextFromClipboard(&data)) return false;
wxString cliptext = data.GetText();
if (!cliptext.StartsWith(wxT("3D version"))) return false;
// copy clipboard data to a temporary .rle3 file
wxString filepath = tempdir + wxT("clipboard.rle3");
wxFile rle3file(filepath, wxFile::write);
if (!rle3file.IsOpened()) {
Warning(_("Could not open clipboard.rle3 for writing!"));
return true;
}
if (!rle3file.Write(data.GetText())) {
Warning(_("Could not write clipboard data to file!"));
rle3file.Close();
return true;
}
rle3file.Close();
// set rle3path for GSF_getevent
rle3path = filepath;
// start up 3D.lua (it will get a file event containing rle3path)
wxString path3D = gollydir + wxT("Scripts");
path3D += wxFILE_SEP_PATH;
path3D += wxT("Lua");
path3D += wxFILE_SEP_PATH;
path3D += wxT("3D.lua");
RunScript(path3D);
return true;
}
// -----------------------------------------------------------------------------
void MainFrame::OpenClipboard()
{
if (generating) {
command_pending = true;
cmdevent.SetId(ID_OPEN_CLIP);
Stop();
return;
}
// if clipboard text starts with "@RULE rulename" then install rulename.rule
// and switch to that rule
if (ClipboardContainsRule()) return;
// if clipboard text starts with "3D version" then start up 3D.lua
// and load the RLE3 pattern
if (ClipboardContainsRLE3()) return;
// load and view pattern data stored in clipboard
wxTextDataObject data;
if (GetTextFromClipboard(&data)) {
// copy clipboard data to tempstart so we can handle all formats
// supported by readpattern
wxFile outfile(currlayer->tempstart, wxFile::write);
if ( outfile.IsOpened() ) {
outfile.Write( data.GetText() );
outfile.Close();
LoadPattern(currlayer->tempstart, _("clipboard"));
// do NOT delete tempstart -- it can be reloaded by ResetPattern
// or used by ShowPatternInfo
} else {
statusptr->ErrorMessage(_("Could not create tempstart file!"));
}
}
}
// -----------------------------------------------------------------------------
wxString MainFrame::GetScriptFileName(const wxString& text)
{
// examine given text to see if it contains Lua, Perl or Python code:
// if "--" or "local" or "require" is at start of line then we assume Lua,
// if "use" or "my" is at start of line then we assume Perl,
// if "import" or "from" is at start of line then we assume Python,
// otherwise we compare counts for dollars + semicolons vs colons
int dollars = 0;
int semicolons = 0;
int colons = 0;
int linelen = 0;
// need to be careful converting Unicode wxString to char*
wxCharBuffer buff = text.mb_str(wxConvUTF8);
const char* p = (const char*) buff;
while (*p) {
switch (*p) {
case '#':
// probably a comment, so ignore rest of line
while (*p && *p != 13 && *p != 10) p++;
linelen = 0;
if (*p) p++;
break;
case 34: // double quote -- ignore until quote closes, even multiple lines
p++;
while (*p && *p != 34) p++;
linelen = 0;
if (*p) p++;
break;
case 39: // single quote -- ignore until quote closes
p++;
while (*p && *p != 39 && *p != 13 && *p != 10) p++;
linelen = 0;
if (*p) p++;
break;
case '$': dollars++; linelen++; p++;
break;
case ':': colons++; linelen++; p++;
break;
case ';': semicolons++; linelen++; p++;
break;
case 13: case 10:
// if colon/semicolon is at eol then count it twice
if (linelen > 0 && p[-1] == ':') colons++;
if (linelen > 0 && p[-1] == ';') semicolons++;
linelen = 0;
p++;
break;
case '-':
if (linelen == 1 && p[-1] == '-') return luafile; // Lua comment at start of line
linelen++; p++;
break;
case ' ':
// look for language-specific keyword at start of line
if (linelen == 2 && strncmp(p-2,"my",2) == 0) return perlfile;
if (linelen == 3 && strncmp(p-3,"use",3) == 0) return perlfile;
if (linelen == 5 && strncmp(p-5,"local",5) == 0) return luafile;
if (linelen == 7 && strncmp(p-7,"require",7) == 0) return luafile;
if (linelen == 4 && strncmp(p-4,"from",4) == 0) return pythonfile;
if (linelen == 6 && strncmp(p-6,"import",6) == 0) return pythonfile;
// don't break
default:
if (linelen == 0 && (*p == ' ' || *p == 9)) {
// ignore spaces/tabs at start of line
} else {
linelen++;
}
p++;
}
}
/* check totals:
char msg[128];
sprintf(msg, "dollars=%d semicolons=%d colons=%d", dollars, semicolons, colons);
Note(wxString(msg,wxConvLocal));
*/
if (dollars + semicolons > colons)
return perlfile;
else
return pythonfile;
}
// -----------------------------------------------------------------------------
void MainFrame::RunClipboard()
{
if (generating) {
command_pending = true;
cmdevent.SetId(ID_RUN_CLIP);
Stop();
return;
}
// run script stored in clipboard
wxTextDataObject data;
if (GetTextFromClipboard(&data)) {
// scriptfile extension depends on whether the clipboard data
// contains Perl or Python code
wxString scriptfile = GetScriptFileName( data.GetText() );
// copy clipboard data to scriptfile
wxFile outfile(scriptfile, wxFile::write);
if (outfile.IsOpened()) {
outfile.Write( data.GetText() );
outfile.Close();
RunScript(scriptfile);
} else {
statusptr->ErrorMessage(_("Could not create script file!"));
}
}
}
#if wxCHECK_VERSION(2,9,0)
// restore new wxMenuItem method names in wx 2.9
#define GetText GetItemLabel
#define SetText SetItemLabel
#endif
// -----------------------------------------------------------------------------
void MainFrame::OpenRecentPattern(int id)
{
if (generating) {
command_pending = true;
cmdevent.SetId(id);
Stop();
return;
}
wxMenuItem* item = patternSubMenu->FindItem(id);
if (item) {
wxString path = item->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
path.Replace(wxT("__"), wxT("_"));
#endif
// remove duplicate ampersands
path.Replace(wxT("&&"), wxT("&"));
// if path isn't absolute then prepend Golly directory
wxFileName fname(path);
if (!fname.IsAbsolute()) path = gollydir + path;
// path might be a zip file so call OpenFile rather than LoadPattern
OpenFile(path);
}
}
// -----------------------------------------------------------------------------
void MainFrame::OpenRecentScript(int id)
{
if (generating) {
command_pending = true;
cmdevent.SetId(id);
Stop();
return;
}
wxMenuItem* item = scriptSubMenu->FindItem(id);
if (item) {
wxString path = item->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
path.Replace(wxT("__"), wxT("_"));
#endif
// remove duplicate ampersands
path.Replace(wxT("&&"), wxT("&"));
// if path isn't absolute then prepend Golly directory
wxFileName fname(path);
if (!fname.IsAbsolute()) path = gollydir + path;
AddRecentScript(path);
RunScript(path);
}
}
// -----------------------------------------------------------------------------
void MainFrame::ClearMissingPatterns()
{
int pos = 0;
while (pos < numpatterns) {
wxMenuItem* item = patternSubMenu->FindItemByPosition(pos);
wxString path = item->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
path.Replace(wxT("__"), wxT("_"));
#endif
// remove duplicate ampersands
path.Replace(wxT("&&"), wxT("&"));
// if path isn't absolute then prepend Golly directory
wxFileName fname(path);
if (!fname.IsAbsolute()) path = gollydir + path;
if (wxFileExists(path)) {
// keep this item
pos++;
} else {
// remove this item by shifting up later items
int nextpos = pos + 1;
while (nextpos < numpatterns) {
wxMenuItem* nextitem = patternSubMenu->FindItemByPosition(nextpos);
#ifdef __WXGTK__
// avoid wxGTK bug if item contains underscore
wxString temp = nextitem->GetText();
temp.Replace(wxT("__"), wxT("_"));
temp.Replace(wxT("&"), wxT("&&"));
item->SetText( temp );
#else
item->SetText( nextitem->GetText() );
#endif
item = nextitem;
nextpos++;
}
// delete last item
patternSubMenu->Delete(item);
numpatterns--;
}
}
wxMenuBar* mbar = GetMenuBar();
if (mbar) mbar->Enable(ID_OPEN_RECENT, numpatterns > 0);
}
// -----------------------------------------------------------------------------
void MainFrame::ClearMissingScripts()
{
int pos = 0;
while (pos < numscripts) {
wxMenuItem* item = scriptSubMenu->FindItemByPosition(pos);
wxString path = item->GetText();
#ifdef __WXGTK__
// remove duplicate underscores
path.Replace(wxT("__"), wxT("_"));
#endif
// remove duplicate ampersands
path.Replace(wxT("&&"), wxT("&"));
// if path isn't absolute then prepend Golly directory
wxFileName fname(path);
if (!fname.IsAbsolute()) path = gollydir + path;
if (wxFileExists(path)) {
// keep this item
pos++;
} else {
// remove this item by shifting up later items
int nextpos = pos + 1;
while (nextpos < numscripts) {
wxMenuItem* nextitem = scriptSubMenu->FindItemByPosition(nextpos);
#ifdef __WXGTK__
// avoid wxGTK bug if item contains underscore
wxString temp = nextitem->GetText();
temp.Replace(wxT("__"), wxT("_"));
temp.Replace(wxT("&"), wxT("&&"));
item->SetText( temp );
#else
item->SetText( nextitem->GetText() );
#endif
item = nextitem;
nextpos++;
}
// delete last item
scriptSubMenu->Delete(item);
numscripts--;
}
}
wxMenuBar* mbar = GetMenuBar();
if (mbar) mbar->Enable(ID_RUN_RECENT, numscripts > 0);
}
// -----------------------------------------------------------------------------
void MainFrame::ClearAllPatterns()
{
while (numpatterns > 0) {
patternSubMenu->Delete( patternSubMenu->FindItemByPosition(0) );
numpatterns--;
}
wxMenuBar* mbar = GetMenuBar();
if (mbar) mbar->Enable(ID_OPEN_RECENT, false);
}
// -----------------------------------------------------------------------------
void MainFrame::ClearAllScripts()
{
while (numscripts > 0) {
scriptSubMenu->Delete( scriptSubMenu->FindItemByPosition(0) );
numscripts--;
}
wxMenuBar* mbar = GetMenuBar();
if (mbar) mbar->Enable(ID_RUN_RECENT, false);
}
// -----------------------------------------------------------------------------
const char* MainFrame::WritePattern(const wxString& path,
pattern_format format,
output_compression compression,
int top, int left, int bottom, int right)
{
// if the format is RLE_format and the grid is bounded then force XRLE_format so that
// position info is recorded (this position will be used when the file is read)
if (format == RLE_format && (currlayer->algo->gridwd > 0 || currlayer->algo->gridht > 0))
format = XRLE_format;
const char* err = writepattern(FILEPATH, *currlayer->algo, format,
compression, top, left, bottom, right);
return err;
}
// -----------------------------------------------------------------------------
bool MainFrame::SavePattern()
{
if (generating) {
command_pending = true;
cmdevent.SetId(wxID_SAVE);
Stop();
return false;
}
if (warn_on_save && currlayer->dirty && currlayer->algo->getGeneration() > currlayer->startgen &&
!TimelineExists()) {
wxString msg = _("Saving this generation will not save the changes you made earlier, ");
msg += _("so you might want to select Reset or Undo and save those changes.");
msg += _("\n\n(This warning can be disabled in Preferences > Layer.)");
Warning(msg);
}
wxString filetypes;
int MCindex, RLEindex;
// initially all formats are not allowed (use any -ve number)
MCindex = RLEindex = -1;
// adding "*.gz" to the file types avoids a duplication bug in the wxOSX app
wxString MCfiles, RLEfiles;
MCfiles = _("Macrocell (*.mc)|*.mc");
MCfiles += _("|Compressed Macrocell (*.mc.gz)|*.mc.gz;*.gz");
if (savexrle) {
RLEfiles = _("Extended RLE (*.rle)|*.rle");
RLEfiles += _("|Compressed Extended RLE (*.rle.gz)|*.rle.gz;*.gz");
} else {
RLEfiles = _("RLE (*.rle)|*.rle");
RLEfiles += _("|Compressed RLE (*.rle.gz)|*.rle.gz;*.gz");
}
bigint top, left, bottom, right;
int itop, ileft, ibottom, iright;
currlayer->algo->findedges(&top, &left, &bottom, &right);
if (currlayer->algo->hyperCapable()) {
// algorithm uses hashlife
if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
// too big so only allow saving as MC file
itop = ileft = ibottom = iright = 0;
filetypes = MCfiles;
MCindex = 0;
} else {
// allow saving as MC or RLE file
itop = top.toint();
ileft = left.toint();
ibottom = bottom.toint();
iright = right.toint();
filetypes = MCfiles;
filetypes += _("|");
filetypes += RLEfiles;
MCindex = 0;
RLEindex = 1;
}
} else {
// allow saving file only if pattern is small enough
if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
statusptr->ErrorMessage(_("Pattern is outside +/- 10^9 boundary."));
return false;
}
itop = top.toint();
ileft = left.toint();
ibottom = bottom.toint();
iright = right.toint();
filetypes = RLEfiles;
RLEindex = 0;
}
wxFileDialog savedlg( this, _("Save pattern"),
opensavedir, currlayer->currname, filetypes,
wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
int button = savedlg.ShowModal();
viewptr->ResetMouseDown();
if (button == wxID_OK) {
wxFileName fullpath( savedlg.GetPath() );
opensavedir = fullpath.GetPath();
wxString ext = fullpath.GetExt();
pattern_format format;
output_compression compression = no_compression;
// detect if user supplied a compression suffix (.gz)
if ( ext.IsSameAs(wxT("gz"),false) ) {
compression = gzip_compression;
ext = wxFileName(fullpath.GetName()).GetExt();
}
// if user supplied a known extension then use that format if it is
// allowed, otherwise use current format specified in filter menu
if ( ext.IsSameAs(wxT("rle"),false) && RLEindex >= 0 ) {
format = savexrle ? XRLE_format : RLE_format;
} else if ( ext.IsSameAs(wxT("mc"),false) && MCindex >= 0 ) {
format = MC_format;
} else if ( savedlg.GetFilterIndex()/2 == MCindex ) {
format = MC_format;
if (savedlg.GetFilterIndex()%2) compression = gzip_compression;
} else if ( savedlg.GetFilterIndex()/2 == RLEindex ) {
format = savexrle ? XRLE_format : RLE_format;
if (savedlg.GetFilterIndex()%2) compression = gzip_compression;
} else {
statusptr->ErrorMessage(_("Bug in SavePattern!"));
return false;
}
const char* err = WritePattern(savedlg.GetPath(), format, compression,
itop, ileft, ibottom, iright);
if (err) {
statusptr->ErrorMessage(wxString(err,wxConvLocal));
} else {
statusptr->DisplayMessage(_("Pattern saved in file: ") + savedlg.GetPath());
AddRecentPattern(savedlg.GetPath());
SaveSucceeded(savedlg.GetPath());
return true;
}
}
return false;
}
// -----------------------------------------------------------------------------
// called by script command to save current pattern to given file
const char* MainFrame::SaveFile(const wxString& path, const wxString& fileformat, bool remember)
{
bigint top, left, bottom, right;
int itop, ileft, ibottom, iright;
currlayer->algo->findedges(&top, &left, &bottom, &right);
wxString format = fileformat.Lower();
output_compression compression = no_compression;
if (format.EndsWith(wxT(".gz"))) {
compression = gzip_compression;
}
// check that given file format is valid
pattern_format pattfmt;
if (format.StartsWith(wxT("rle"))) {
if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
return "Pattern is too big to save as RLE.";
}
pattfmt = savexrle ? XRLE_format : RLE_format;
itop = top.toint();
ileft = left.toint();
ibottom = bottom.toint();
iright = right.toint();
} else if (format.StartsWith(wxT("mc"))) {
if (!currlayer->algo->hyperCapable()) {
return "Macrocell format is not supported by the current algorithm.";
}
pattfmt = MC_format;
// writepattern will ignore itop, ileft, ibottom, iright
itop = ileft = ibottom = iright = 0;
} else {
return "Unknown pattern format.";
}
const char* err = WritePattern(path, pattfmt, compression,
itop, ileft, ibottom, iright);
if (!err) {
if (remember) AddRecentPattern(path);
SaveSucceeded(path);
}
return err;
}
// -----------------------------------------------------------------------------
void MainFrame::SaveSucceeded(const wxString& path)
{
// save old info for RememberNameChange
wxString oldname = currlayer->currname;
wxString oldfile = currlayer->currfile;
bool oldsave = currlayer->savestart;
bool olddirty = currlayer->dirty;
if (allowundo && !currlayer->stayclean && inscript) {
SavePendingChanges();
}
if ( currlayer->algo->getGeneration() == currlayer->startgen ) {
// no need to save starting pattern (ResetPattern can load currfile)
currlayer->currfile = path;
currlayer->savestart = false;
}
// set dirty flag false and update currlayer->currname
MarkLayerClean(GetBaseName(path));
if (allowundo && !currlayer->stayclean) {
currlayer->undoredo->RememberNameChange(oldname, oldfile, oldsave, olddirty);
}
}
// -----------------------------------------------------------------------------
void MainFrame::SaveOverlay()
{
if (showoverlay && curroverlay->GetOverlayData()) {
wxFileDialog savedlg(this, _("Save overlay as PNG file"),
overlaydir, _("overlay.png"), _("PNG (*.png)|*.png"),
wxFD_SAVE | wxFD_OVERWRITE_PROMPT);
int button = savedlg.ShowModal();
viewptr->ResetMouseDown();
if (button == wxID_OK) {
wxString pngpath = savedlg.GetPath();
wxFileName fullpath(pngpath);
overlaydir = fullpath.GetPath();
curroverlay->SaveOverlay(pngpath);
}
}
}
// -----------------------------------------------------------------------------
static wxString oldfiledir;
void MainFrame::ToggleShowFiles()
{
if (splitwin->IsSplit()) dirwinwd = splitwin->GetSashPosition();
showfiles = !showfiles;
if (splitwin->IsSplit()) {
// hide left pane
splitwin->Unsplit(filectrl);
oldfiledir = filedir;
} else {
splitwin->SplitVertically(filectrl, RightPane(), dirwinwd);
}
if (showfiles && filedir != oldfiledir) {
// show new file directory
SimplifyTree(filedir, filectrl->GetTreeCtrl(), filectrl->GetRootId());
}
viewptr->SetFocus();
}
// -----------------------------------------------------------------------------
void MainFrame::ChangeFileDir()
{
wxDirDialog dirdlg(this, _("Choose a new file folder"), filedir, wxDD_NEW_DIR_BUTTON);
int button = dirdlg.ShowModal();
viewptr->ResetMouseDown();
if (button == wxID_OK) {
SetFileDir(dirdlg.GetPath());
}
}
// -----------------------------------------------------------------------------
void MainFrame::SetFileDir(const wxString& newdir)
{
if (filedir != newdir) {
filedir = newdir;
if (showfiles) {
// show new file directory
SimplifyTree(filedir, filectrl->GetTreeCtrl(), filectrl->GetRootId());
}
}
}
// -----------------------------------------------------------------------------
void MainFrame::ShowPrefsDialog(const wxString& page)
{
if (viewptr->waitingforclick) return;
if (generating) {
command_pending = true;
cmdevent.SetId(wxID_PREFERENCES);
Stop();
return;
}
if (inscript) {
// safe to allow prefs dialog while script is running???
// if so, maybe we need some sort of warning like this:
// Warning(_("The currently running script might clobber any changes you make."));
}
int oldtileborder = tileborder;
int oldcontrolspos = controlspos;
if (ChangePrefs(page)) {
// user hit OK button
// if maxpatterns was reduced then we may need to remove some paths
while (numpatterns > maxpatterns) {
numpatterns--;
patternSubMenu->Delete( patternSubMenu->FindItemByPosition(numpatterns) );
}
// if maxscripts was reduced then we may need to remove some paths
while (numscripts > maxscripts) {
numscripts--;
scriptSubMenu->Delete( scriptSubMenu->FindItemByPosition(numscripts) );
}
// randomfill might have changed
SetRandomFillPercentage();
// if mindelay/maxdelay changed then may need to change minexpo and currexpo
UpdateStepExponent();
// maximum memory might have changed
for (int i = 0; i < numlayers; i++) {
Layer* layer = GetLayer(i);
AlgoData* ad = algoinfo[layer->algtype];
if (ad->algomem >= 0)
layer->algo->setMaxMemory(ad->algomem);
}
// tileborder might have changed
if (tilelayers && numlayers > 1 && tileborder != oldtileborder) {
int wd, ht;
bigview->GetClientSize(&wd, &ht);
// wd or ht might be < 1 on Windows
if (wd < 1) wd = 1;
if (ht < 1) ht = 1;
ResizeLayers(wd, ht);
}
// position of translucent controls might have changed
if (controlspos != oldcontrolspos) {
int wd, ht;
if (tilelayers && numlayers > 1) {
for (int i = 0; i < numlayers; i++) {
Layer* layer = GetLayer(i);
layer->tilewin->GetClientSize(&wd, &ht);
layer->tilewin->SetViewSize(wd, ht);
}
}
bigview->GetClientSize(&wd, &ht);
bigview->SetViewSize(wd, ht);
}
SavePrefs();
}
// safer to update everything even if user hit Cancel
UpdateEverything();
}
|