File: wxfile.cpp

package info (click to toggle)
golly 2.1-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 9,560 kB
  • ctags: 5,064
  • sloc: cpp: 38,119; python: 3,203; perl: 1,121; makefile: 58; java: 49; sh: 22
file content (1849 lines) | stat: -rw-r--r-- 61,942 bytes parent folder | download
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
                        /*** /

This file is part of Golly, a Game of Life Simulator.
Copyright (C) 2009 Andrew Trevorrow and Tomas Rokicki.

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

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

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

 Web site:  http://sourceforge.net/projects/golly
 Authors:   rokicki@gmail.com  andrew@trevorrow.com

                        / ***/

#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 "wxrender.h"      // for SetSelectionColor
#include "wxscript.h"      // for RunScript, inscript
#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 "wxhelp.h"        // for ShowHelp

#ifdef __WXMAC__
   #include <Carbon/Carbon.h>                      // for OpaqueWindowPtr, etc
   #include "wx/mac/corefoundation/cfstring.h"     // for wxMacCFStringHolder
#endif

#ifdef __WXMAC__
   // convert path to decomposed UTF8 so fopen will work
   #define FILEPATH path.fn_str()
#else
   #define FILEPATH path.mb_str(wxConvLocal)
#endif

// File menu functions:

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

wxString MainFrame::GetBaseName(const wxString& path)
{
   // extract basename from given path
   return path.AfterLast(wxFILE_SEP_PATH);
}

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

void MainFrame::MySetTitle(const wxString& title)
{
   #ifdef __WXMAC__
      // avoid wxMac's SetTitle call -- it causes an undesirable window refresh
      SetWindowTitleWithCFString((OpaqueWindowPtr*)this->MacGetWindowRef(),
                                 wxMacCFStringHolder(title, wxFONTENCODING_DEFAULT));
   #else
      SetTitle(title);
   #endif
}

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

void MainFrame::SetWindowTitle(const wxString& filename)
{
   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???
   MySetTitle(wtitle);
}

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

void MainFrame::SetGenIncrement()
{
   if (currlayer->currexpo > 0) {
      bigint inc = 1;
      // set increment to currbase^currexpo
      int i = currlayer->currexpo;
      while (i > 0) {
         inc.mul_smallint(currlayer->currbase);
         i--;
      }
      currlayer->algo->setIncrement(inc);
   } else {
      currlayer->algo->setIncrement(1);
   }
}

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

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)
   currlayer->algo->setrule( oldrule.mb_str(wxConvLocal) );

   // 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) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(wxID_NEW);
      return;
   }
   
   if (askonnew && !inscript && 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();

   // rule doesn't change so no need to call setrule

   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();
}

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

bool MainFrame::LoadImage(const wxString& path)
{
   wxString ext = path.AfterLast('.');
   // if path has no extension then ext == path
   if (ext == path) return false;
   
   // don't try to load JPEG file
   if ( ext.IsSameAs(wxT("jpg"),false) ||
        ext.IsSameAs(wxT("jpeg"),false) ) {
      Warning(_("Golly cannot import JPEG data, only BMP/GIF/PNG/TIFF."));
      // return true so pattern will be empty
      return true;
   }

   // supported extensions match image handlers added in GollyApp::OnInit()
   if ( 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) ) {
      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;
   } else {
      return false;
   }
}

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

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 empty if called from ResetPattern/RestorePattern
   if (!newtitle.IsEmpty()) {
      if (askonload && !inscript && currlayer->dirty && !SaveCurrentLayer()) return;

      if (inscript) stop_after_script = true;
      currlayer->savestart = false;
      
      // 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);

   // ensure new universe uses same rule in case LoadImage succeeds
   currlayer->algo->setrule( oldrule.mb_str(wxConvLocal) );

   if (!newtitle.IsEmpty()) {
      // 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
      MySetTitle(_("Loading ") + newtitle);
   }

   if (LoadImage(path)) {
      viewptr->nopattupdate = false;
   } else {
      const char* err = readpattern(FILEPATH, *currlayer->algo);
      if (err) {
         // 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) 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);
            currlayer->algo->setrule( oldrule.mb_str(wxConvLocal) );
            // Warning( wxString(err,wxConvLocal) );
            // current error and original error are not necessarily meaningful
            // so report a more generic error
            Warning(_("File could not be loaded by any algorithm\n(probably due to an unknown rule)."));
         }
      }
      viewptr->nopattupdate = false;
   }

   if (!newtitle.IsEmpty()) {
      MarkLayerClean(newtitle);     // calls SetWindowTitle
   
      // 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
      #ifdef __WXMAC__
         wxSetCursor(*wxSTANDARD_CURSOR);
      #endif
      // 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];
            int incount = 0;
            int outcount = 0;
            int 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: %.2g 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;
}

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

void MainFrame::OpenZipFile(const wxString& zippath)
{
   // Process given zip file in the following manner:
   // - If it contains any rule files (.table/tree/colors/icons) 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("&nbsp;&nbsp;&nbsp;&nbsp;");
   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 rulefiles = 0;
   int textfiles = 0;                     // includes html files
   
   wxString contents = wxT("<html><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 .table/tree/colors/icons 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 = 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);

            // user can extract file via special "unzip:" link
            if (dirseen) contents += indent;
            contents += wxT("<a href=\"unzip:");
            contents += zippath;
            contents += wxT(":");
            contents += name;
            contents += wxT("\">");
            contents += filename;
            contents += wxT("</a>");
            
            if ( IsRuleFile(filename) ) {
               // extract and install .table/tree/colors/icons file into userrules
               wxString outfile = userrules + filename;
               wxFileOutputStream outstream(outfile);
               bool ok = outstream.Ok();
               if (ok) {
                  zip.Read(outstream);
                  ok = (outstream.GetLastError() == wxSTREAM_NO_ERROR);
               }
               if (ok) {
                  // file successfully installed
                  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 installed into your rules folder<br>\n(");
      contents += userrules;
      contents += wxT(").\n");
   }
   contents += wxT("\n</body></html>");
   
   if (dirseen || rulefiles > 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
            currlayer->currfile = tempfile;
            LoadPattern(currlayer->currfile, 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();
         }
      }
   }
}

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

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) {
      // terminate generating loop and set command_pending flag
      Stop();
      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);
      }
      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 {
      // load pattern
      if (remember) AddRecentPattern(path);
      currlayer->currfile = path;
      LoadPattern(currlayer->currfile, 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) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(wxID_OPEN);
      return;
   }

   wxString filetypes = _("All files (*)|*");
   filetypes +=         _("|RLE (*.rle)|*.rle");
   filetypes +=         _("|Macrocell (*.mc)|*.mc");
   filetypes +=         _("|Life 1.05/1.06 (*.lif)|*.lif");
   filetypes +=         _("|dblife (*.l)|*.l");
   filetypes +=         _("|MCell (*.mcl)|*.mcl");
   filetypes +=         _("|Gzip (*.gz)|*.gz");
   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);

   #ifdef __WXGTK__
      // opensavedir is ignored above (bug in wxGTK 2.8.0???)
      opendlg.SetDirectory(opensavedir);
   #endif

   if ( opendlg.ShowModal() == wxID_OK ) {
      wxFileName fullpath( opendlg.GetPath() );
      opensavedir = fullpath.GetPath();
      OpenFile( opendlg.GetPath() );
   }
}

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

void MainFrame::OpenScript()
{
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_RUN_SCRIPT);
      return;
   }

   wxString filetypes = _("Perl or Python (*.pl;*.py)|*.pl;*.py");
   filetypes +=         _("|Perl (*.pl)|*.pl");
   filetypes +=         _("|Python (*.py)|*.py");

   wxFileDialog opendlg(this, _("Choose a script"),
                        rundir, wxEmptyString, filetypes,
                        wxFD_OPEN | wxFD_FILE_MUST_EXIST);

   #ifdef __WXGTK__
      // rundir is ignored above (bug in wxGTK 2.8.0???)
      opendlg.SetDirectory(rundir);
   #endif

   if ( opendlg.ShowModal() == wxID_OK ) {
      wxFileName fullpath( opendlg.GetPath() );
      rundir = fullpath.GetPath();
      AddRecentScript( opendlg.GetPath() );
      RunScript( opendlg.GetPath() );
   }
}

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

bool MainFrame::CopyTextToClipboard(const wxString& text)
{
   bool result = true;
   #ifdef __WXX11__
      // no global clipboard support on X11 so we save data in a file
      wxFile tmpfile(clipfile, wxFile::write);
      if ( tmpfile.IsOpened() ) {
         size_t textlen = text.Length();
         if ( tmpfile.Write( text.c_str(), textlen ) < textlen ) {
            Warning(_("Could not write all data to clipboard file!"));
            result = false;
         }
         tmpfile.Close();
      } else {
         Warning(_("Could not create clipboard file!"));
         result = false;
      }
   #else
      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;
      }
   #endif
   return result;
}

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

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 {
         #ifdef __WXX11__
            statusptr->ErrorMessage(_("Sorry, but there is no clipboard support for X11."));
            // do X11 apps like xlife or fontforge have clipboard support???
         #else
            statusptr->ErrorMessage(_("No data in clipboard."));
         #endif
      }
      wxTheClipboard->Close();

   } else {
      statusptr->ErrorMessage(_("Could not open clipboard!"));
   }

   return gotdata;
}

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

void MainFrame::OpenClipboard()
{
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_OPEN_CLIP);
      return;
   }

   // load and view pattern data stored in clipboard
   #ifdef __WXX11__
      // on X11 the clipboard data is in non-temporary clipfile, so copy
      // clipfile to tempstart (for use by ResetPattern and ShowPatternInfo)
      if ( wxCopyFile(clipfile, currlayer->tempstart, true) ) {
         currlayer->currfile = currlayer->tempstart;
         LoadPattern(currlayer->currfile, _("clipboard"));
      } else {
         statusptr->ErrorMessage(_("Could not copy clipfile!"));
      }
   #else
      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();
            currlayer->currfile = currlayer->tempstart;
            LoadPattern(currlayer->currfile, _("clipboard"));
            // do NOT delete tempstart -- it can be reloaded by ResetPattern
            // or used by ShowPatternInfo
         } else {
            statusptr->ErrorMessage(_("Could not create tempstart file!"));
         }
      }
   #endif
}

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

wxString MainFrame::GetScriptFileName(const wxString& text)
{
   // examine given text to see if it contains Perl or Python code;
   // if "use" or "my" occurs at start of line then we assume Perl,
   // if "import" or "from" occurs 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(wxConvLocal);
   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 ' ':
            // 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 == 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) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_RUN_CLIP);
      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()) {
         #ifdef __WXMAC__
            if (scriptfile == perlfile) {
               // Perl script, so replace CRs with LFs
               wxString str = data.GetText();
               str.Replace(wxT("\015"), wxT("\012"));
               outfile.Write( str );
            } else {
               outfile.Write( data.GetText() );
            }
         #else
            outfile.Write( data.GetText() );
         #endif
         outfile.Close();
         RunScript(scriptfile);
      } else {
         statusptr->ErrorMessage(_("Could not create script file!"));
      }
   }
}

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

void MainFrame::OpenRecentPattern(int id)
{
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(id);
      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);
      /*
      AddRecentPattern(path);
      currlayer->currfile = path;
      LoadPattern(currlayer->currfile, GetBaseName(path));
      */
   }
}

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

void MainFrame::OpenRecentScript(int id)
{
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(id);
      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,
                                    int top, int left, int bottom, int right)
{
   const char* err = writepattern(FILEPATH, *currlayer->algo, format,
                                  top, left, bottom, right);

   #ifdef __WXMAC__
      if (!err) {
         // set the file's creator and type
         wxFileName filename(path);
         wxUint32 creator = 'GoLy';
         wxUint32 type = 'GoLR';       // RLE or XRLE
         if (format == MC_format) {
            type = 'GoLM';
         } else if (format == L105_format) {
            type = 'GoLL';
         }
         filename.MacSetTypeAndCreator(type, creator);
      }
   #endif

   return err;
}

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

void MainFrame::SavePattern()
{
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(wxID_SAVE);
      return;
   }

   wxString filetypes;
   int RLEindex, L105index, MCindex;

   // initially all formats are not allowed (use any -ve number)
   RLEindex = L105index = MCindex = -1;

   bigint top, left, bottom, right;
   int itop, ileft, ibottom, iright;
   currlayer->algo->findedges(&top, &left, &bottom, &right);

   wxString RLEstring;
   if (savexrle)
      RLEstring = _("Extended RLE (*.rle)|*.rle");
   else
      RLEstring = _("RLE (*.rle)|*.rle");

   //!!! need currlayer->algo->CanWriteMC()???
   if (currlayer->algo->hyperCapable()) {
      if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
         // too big so only allow saving as MC file
         itop = ileft = ibottom = iright = 0;
         filetypes = _("Macrocell (*.mc)|*.mc");
         MCindex = 0;
      } else {
         // allow saving as RLE/MC file
         itop = top.toint();
         ileft = left.toint();
         ibottom = bottom.toint();
         iright = right.toint();
         filetypes = RLEstring;
         RLEindex = 0;
         filetypes += _("|Macrocell (*.mc)|*.mc");
         MCindex = 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;
      }
      itop = top.toint();
      ileft = left.toint();
      ibottom = bottom.toint();
      iright = right.toint();
      filetypes = RLEstring;
      RLEindex = 0;
      /* Life 1.05 format not yet implemented!!!
      filetypes += _("|Life 1.05 (*.lif)|*.lif");
      L105index = 1;
      */
   }

   wxFileDialog savedlg( this, _("Save pattern"),
                         opensavedir, currlayer->currname, filetypes,
                         wxFD_SAVE | wxOVERWRITE_PROMPT );

   #ifdef __WXGTK__
      // opensavedir is ignored above (bug in wxGTK 2.8.0???)
      savedlg.SetDirectory(opensavedir);
   #endif

   if ( savedlg.ShowModal() == wxID_OK ) {
      wxFileName fullpath( savedlg.GetPath() );
      opensavedir = fullpath.GetPath();
      wxString ext = fullpath.GetExt();
      pattern_format format;
      // 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;
      /* Life 1.05 format not yet implemented!!!
      } else if ( ext.IsSameAs("lif",false) && L105index >= 0 ) {
         format = L105_format;
      */
      } else if ( ext.IsSameAs(wxT("mc"),false) && MCindex >= 0 ) {
         format = MC_format;
      } else if ( savedlg.GetFilterIndex() == RLEindex ) {
         format = savexrle ? XRLE_format : RLE_format;
      } else if ( savedlg.GetFilterIndex() == L105index ) {
         format = L105_format;
      } else if ( savedlg.GetFilterIndex() == MCindex ) {
         format = MC_format;
      } else {
         statusptr->ErrorMessage(_("Bug in SavePattern!"));
         return;
      }

      const char* err = WritePattern(savedlg.GetPath(), format,
                                     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());
      }
   }
}

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

// called by script command to save current pattern to given file
const char* MainFrame::SaveFile(const wxString& path, const wxString& format, bool remember)
{
   // check that given format is valid and allowed
   bigint top, left, bottom, right;
   int itop, ileft, ibottom, iright;
   currlayer->algo->findedges(&top, &left, &bottom, &right);

   pattern_format pattfmt;
   if ( format.IsSameAs(wxT("rle"),false) ) {
      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.IsSameAs(wxT("mc"),false) ) {
      //!!! need currlayer->algo->CanWriteMC()???
      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, 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::ToggleShowPatterns()
{
   if (splitwin->IsSplit()) dirwinwd = splitwin->GetSashPosition();
   #ifndef __WXMAC__
      // hide scroll bars
      bigview->SetScrollbar(wxHORIZONTAL, 0, 0, 0, true);
      bigview->SetScrollbar(wxVERTICAL, 0, 0, 0, true);
   #endif

   showpatterns = !showpatterns;
   if (showpatterns && showscripts) {
      showscripts = false;
      splitwin->Unsplit(scriptctrl);
      splitwin->SplitVertically(patternctrl, RightPane(), dirwinwd);
   } else {
      if (splitwin->IsSplit()) {
         // hide left pane
         splitwin->Unsplit(patternctrl);
      } else {
         splitwin->SplitVertically(patternctrl, RightPane(), dirwinwd);
      }
      viewptr->SetFocus();
   }

   #ifndef __WXMAC__
      // restore scroll bars
      bigview->UpdateScrollBars();
   #endif
}

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

void MainFrame::ToggleShowScripts()
{
   if (splitwin->IsSplit()) dirwinwd = splitwin->GetSashPosition();
   #ifndef __WXMAC__
      // hide scroll bars
      bigview->SetScrollbar(wxHORIZONTAL, 0, 0, 0, true);
      bigview->SetScrollbar(wxVERTICAL, 0, 0, 0, true);
   #endif

   showscripts = !showscripts;
   if (showscripts && showpatterns) {
      showpatterns = false;
      splitwin->Unsplit(patternctrl);
      splitwin->SplitVertically(scriptctrl, RightPane(), dirwinwd);
   } else {
      if (splitwin->IsSplit()) {
         // hide left pane
         splitwin->Unsplit(scriptctrl);
      } else {
         splitwin->SplitVertically(scriptctrl, RightPane(), dirwinwd);
      }
      viewptr->SetFocus();
   }

   #ifndef __WXMAC__
      // restore scroll bars
      bigview->UpdateScrollBars();
   #endif
}

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

void MainFrame::ChangePatternDir()
{
   wxDirDialog dirdlg(this, _("Choose a new pattern folder"), patterndir, wxDD_NEW_DIR_BUTTON);
   if (dirdlg.ShowModal() == wxID_OK)
      SetPatternDir(dirdlg.GetPath());
}

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

void MainFrame::ChangeScriptDir()
{
   wxDirDialog dirdlg(this, _("Choose a new script folder"), scriptdir, wxDD_NEW_DIR_BUTTON);
   if (dirdlg.ShowModal() == wxID_OK)
      SetScriptDir(dirdlg.GetPath());
}

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

void MainFrame::SetPatternDir(const wxString& newdir)
{
   if (patterndir != newdir) {
      patterndir = newdir;
      if (showpatterns) {
         // show new pattern directory
         SimplifyTree(patterndir, patternctrl->GetTreeCtrl(), patternctrl->GetRootId());
      }
   }
}

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

void MainFrame::SetScriptDir(const wxString& newdir)
{
   if (scriptdir != newdir) {
      scriptdir = newdir;
      if (showscripts) {
         // show new script directory
         SimplifyTree(scriptdir, scriptctrl->GetTreeCtrl(), scriptctrl->GetRootId());
      }
   }
}

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

void MainFrame::SetStepExponent(int newexpo)
{
   currlayer->currexpo = newexpo;
   if (currlayer->currexpo < minexpo) currlayer->currexpo = minexpo;
   SetGenIncrement();
}

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

void MainFrame::SetMinimumStepExponent()
{
   // set minexpo depending on mindelay and maxdelay
   minexpo = 0;
   if (mindelay > 0) {
      int d = mindelay;
      minexpo--;
      while (d < maxdelay) {
         d *= 2;
         minexpo--;
      }
   }
}

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

void MainFrame::UpdateStepExponent()
{
   SetMinimumStepExponent();
   if (currlayer->currexpo < minexpo) currlayer->currexpo = minexpo;
   SetGenIncrement();
}

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

void MainFrame::ShowPrefsDialog(const wxString& page)
{
   if (viewptr->waitingforclick) return;

   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(wxID_PREFERENCES);
      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

      // selection color may have changed
      SetSelectionColor();

      // 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 Win/X11 platforms
         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();
}