File: wxcontrol.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 (1231 lines) | stat: -rw-r--r-- 42,749 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
                        /*** /

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 "bigint.h"
#include "lifealgo.h"
#include "qlifealgo.h"
#include "hlifealgo.h"

#include "wxgolly.h"       // for wxGetApp, statusptr, viewptr, bigview
#include "wxutils.h"       // for BeginProgress, GetString, etc
#include "wxprefs.h"       // for allowundo, etc
#include "wxrule.h"        // for ChangeRule
#include "wxhelp.h"        // for LoadLexiconPattern
#include "wxstatus.h"      // for statusptr->...
#include "wxselect.h"      // for Selection
#include "wxview.h"        // for viewptr->...
#include "wxscript.h"      // for inscript, PassKeyToScript
#include "wxmain.h"        // for MainFrame
#include "wxundo.h"        // for undoredo->...
#include "wxalgos.h"       // for *_ALGO, algo_type, CreateNewUniverse, etc
#include "wxlayer.h"       // for currlayer, etc
#include "wxrender.h"      // for DrawView

// This module implements Control menu functions.

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

bool MainFrame::SaveStartingPattern()
{
   if ( currlayer->algo->getGeneration() > currlayer->startgen ) {
      // don't do anything if current gen count > starting gen
      return true;
   }
   
   // save current rule, dirty flag, scale, location, etc
   currlayer->startname = currlayer->currname;
   currlayer->startrule = wxString(currlayer->algo->getrule(), wxConvLocal);
   currlayer->startdirty = currlayer->dirty;
   currlayer->startmag = viewptr->GetMag();
   viewptr->GetPos(currlayer->startx, currlayer->starty);
   currlayer->startbase = currlayer->currbase;
   currlayer->startexpo = currlayer->currexpo;
   currlayer->startalgo = currlayer->algtype;
   
   // if this layer is a clone then save some settings in other clones
   if (currlayer->cloneid > 0) {
      for ( int i = 0; i < numlayers; i++ ) {
         Layer* cloneptr = GetLayer(i);
         if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
            cloneptr->startname = cloneptr->currname;
            cloneptr->startx = cloneptr->view->x;
            cloneptr->starty = cloneptr->view->y;
            cloneptr->startmag = cloneptr->view->getmag();
            cloneptr->startbase = cloneptr->currbase;
            cloneptr->startexpo = cloneptr->currexpo;
         }
      }
   }
   
   // save current selection
   currlayer->startsel = currlayer->currsel;
   
   if ( !currlayer->savestart ) {
      // no need to save pattern; ResetPattern will load currfile
      currlayer->startfile.Clear();
      return true;
   }

   // save starting pattern in tempstart file
   //!!! use CanWriteFormat(MC_format)???
   if ( currlayer->algo->hyperCapable() ) {
      // much faster to save pattern in a macrocell file
      const char* err = WritePattern(currlayer->tempstart, MC_format, 0, 0, 0, 0);
      if (err) {
         statusptr->ErrorMessage(wxString(err,wxConvLocal));
         // don't allow user to continue generating
         return false;
      }
   } else {
      // can only save as RLE if edges are within getcell/setcell limits
      bigint top, left, bottom, right;
      currlayer->algo->findedges(&top, &left, &bottom, &right);      
      if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
         statusptr->ErrorMessage(_("Starting pattern is outside +/- 10^9 boundary."));
         // don't allow user to continue generating
         return false;
      }
      int itop = top.toint();
      int ileft = left.toint();
      int ibottom = bottom.toint();
      int iright = right.toint();      
      // use XRLE format so the pattern's top left location and the current
      // generation count are stored in the file
      const char* err = WritePattern(currlayer->tempstart, XRLE_format,
                                     itop, ileft, ibottom, iright);
      if (err) {
         statusptr->ErrorMessage(wxString(err,wxConvLocal));
         // don't allow user to continue generating
         return false;
      }
   }
   
   currlayer->startfile = currlayer->tempstart;   // ResetPattern will load tempstart
   return true;
}

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

void MainFrame::ResetPattern(bool resetundo)
{
   if (currlayer->algo->getGeneration() == currlayer->startgen) return;
   
   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_RESET);
      /* can't use wxPostEvent here because Yield processes all pending events:
      // send Reset command to event queue
      wxCommandEvent resetevt(wxEVT_COMMAND_MENU_SELECTED, ID_RESET);
      wxPostEvent(this->GetEventHandler(), resetevt);
      */
      return;
   }

   if (inscript) stop_after_script = true;
   
   if (currlayer->algo->getGeneration() < currlayer->startgen) {
      // if this happens then startgen logic is wrong
      Warning(_("Current gen < starting gen!"));
      return;
   }
   
   if (currlayer->startfile.IsEmpty() && currlayer->currfile.IsEmpty()) {
      // if this happens then savestart logic is wrong
      Warning(_("Starting pattern cannot be restored!"));
      return;
   }
   
   if (allowundo && !currlayer->stayclean && inscript) {
      // script called reset()
      SavePendingChanges();
      currlayer->undoredo->RememberGenStart();
   }

   // save current algo and rule
   algo_type oldalgo = currlayer->algtype;
   wxString oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);
   
   // restore pattern and settings saved by SaveStartingPattern;
   // first restore algorithm
   currlayer->algtype = currlayer->startalgo;

   // restore starting pattern
   if ( currlayer->startfile.IsEmpty() ) {
      // restore pattern from currfile
      LoadPattern(currlayer->currfile, wxEmptyString);
   } else {
      // restore pattern from startfile
      LoadPattern(currlayer->startfile, wxEmptyString);
   }
   // gen count has been reset to startgen
   
   // ensure savestart flag is correct
   currlayer->savestart = !currlayer->startfile.IsEmpty();
   
   // restore settings saved by SaveStartingPattern
   currlayer->currname = currlayer->startname;
   currlayer->algo->setrule(currlayer->startrule.mb_str(wxConvLocal));
   currlayer->dirty = currlayer->startdirty;
   if (restoreview) {
      viewptr->SetPosMag(currlayer->startx, currlayer->starty, currlayer->startmag);
   }

   // restore step size and set increment
   currlayer->currbase = currlayer->startbase;
   currlayer->currexpo = currlayer->startexpo;
   SetGenIncrement();

   // if this layer is a clone then restore some settings in other clones
   if (currlayer->cloneid > 0) {
      for ( int i = 0; i < numlayers; i++ ) {
         Layer* cloneptr = GetLayer(i);
         if (cloneptr != currlayer && cloneptr->cloneid == currlayer->cloneid) {
            cloneptr->currname = cloneptr->startname;
            if (restoreview) {
               cloneptr->view->setpositionmag(cloneptr->startx, cloneptr->starty,
                                              cloneptr->startmag);
            }
            cloneptr->currbase = cloneptr->startbase;
            cloneptr->currexpo = cloneptr->startexpo;
            // also synchronize dirty flags and update items in Layer menu
            cloneptr->dirty = currlayer->dirty;
            mainptr->UpdateLayerItem(i);
         }
      }
   }

   // restore selection
   currlayer->currsel = currlayer->startsel;

   // switch to default colors if algo/rule changed
   wxString newrule = wxString(currlayer->algo->getrule(), wxConvLocal);
   if (oldalgo != currlayer->algtype || oldrule != newrule) {
      UpdateLayerColors();
   }

   // update window title in case currname, rule or dirty flag changed;
   // note that UpdateLayerItem(currindex) gets called
   SetWindowTitle(currlayer->currname);
   UpdateEverything();
   
   if (allowundo && !currlayer->stayclean) {
      if (inscript) {
         // script called reset() so remember gen change
         // (RememberGenStart was called above)
         currlayer->undoredo->RememberGenFinish();
      } else if (resetundo) {
         // wind back the undo history to the starting pattern
         currlayer->undoredo->SyncUndoHistory();
      }
   }
}

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

void MainFrame::RestorePattern(bigint& gen, const wxString& filename,
                               bigint& x, bigint& y, int mag, int base, int expo)
{
   // called to undo/redo a generating change
   if (gen == currlayer->startgen) {
      // restore starting pattern (false means don't call SyncUndoHistory)
      ResetPattern(false);
   } else {
      // restore pattern in given filename;
      // false means don't update status bar (algorithm should NOT change)
      LoadPattern(filename, wxEmptyString, false);
      
      if (gen != currlayer->algo->getGeneration()) {
         // current gen will be 0 if filename could not be loaded
         // for some reason, so best to set correct gen count
         currlayer->algo->setGeneration(gen);
      }

      // restore step size and set increment
      currlayer->currbase = base;
      currlayer->currexpo = expo;
      SetGenIncrement();
      
      // restore position and scale, if allowed
      if (restoreview) viewptr->SetPosMag(x, y, mag);
      
      UpdatePatternAndStatus();
   }
}

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

const char* MainFrame::ChangeGenCount(const char* genstring, bool inundoredo)
{
   // disallow alphabetic chars in genstring
   for (unsigned int i = 0; i < strlen(genstring); i++)
      if ( (genstring[i] >= 'a' && genstring[i] <= 'z') ||
           (genstring[i] >= 'A' && genstring[i] <= 'Z') )
         return "Alphabetic character is not allowed in generation string.";
   
   bigint oldgen = currlayer->algo->getGeneration();
   bigint newgen(genstring);

   if (genstring[0] == '+' || genstring[0] == '-') {
      // leading +/- sign so make newgen relative to oldgen
      bigint relgen = newgen;
      newgen = oldgen;
      newgen += relgen;
      if (newgen < bigint::zero) newgen = bigint::zero;
   }

   // set stop_after_script BEFORE testing newgen == oldgen so scripts
   // can call setgen("+0") to prevent further generating
   if (inscript) stop_after_script = true;
   
   if (newgen == oldgen) return NULL;

   if (!inundoredo && allowundo && !currlayer->stayclean && inscript) {
      // script called setgen()
      SavePendingChanges();
   }

   //!!! need IsParityShifted() method???
   if (currlayer->algtype == QLIFE_ALGO && newgen.odd() != oldgen.odd()) {
      // qlife stores pattern in different bits depending on gen parity,
      // so we need to create a new qlife universe, set its gen, copy the
      // current pattern to the new universe, then switch to that universe
      bigint top, left, bottom, right;
      currlayer->algo->findedges(&top, &left, &bottom, &right);
      if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
         return "Pattern is too big to copy.";
      }
      // create a new universe of same type and same rule
      lifealgo* newalgo = CreateNewUniverse(currlayer->algtype);
      newalgo->setrule(currlayer->algo->getrule());
      newalgo->setGeneration(newgen);
      // copy pattern
      if ( !viewptr->CopyRect(top.toint(), left.toint(), bottom.toint(), right.toint(),
                              currlayer->algo, newalgo, false, _("Copying pattern")) ) {
         delete newalgo;
         return "Failed to copy pattern.";
      }
      // switch to new universe
      delete currlayer->algo;
      currlayer->algo = newalgo;
      SetGenIncrement();
   } else {
      currlayer->algo->setGeneration(newgen);
   }
   
   if (!inundoredo) {
      // save some settings for RememberSetGen below
      bigint oldstartgen = currlayer->startgen;
      bool oldsave = currlayer->savestart;
      
      // may need to change startgen and savestart
      if (oldgen == currlayer->startgen || newgen <= currlayer->startgen) {
         currlayer->startgen = newgen;
         currlayer->savestart = true;
      }
   
      if (allowundo && !currlayer->stayclean) {
         currlayer->undoredo->RememberSetGen(oldgen, newgen, oldstartgen, oldsave);
      }
   }
   
   UpdateStatus();
   return NULL;
}

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

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

   bigint oldgen = currlayer->algo->getGeneration();
   wxString result;
   wxString prompt = _("Enter a new generation count:");
   prompt += _("\n(+n/-n is relative to current count)");
   if ( GetString(_("Set Generation"), prompt,
                  wxString(oldgen.tostring(), wxConvLocal), result) ) {

      const char* err = ChangeGenCount(result.mb_str(wxConvLocal));
      
      if (err) {
         Warning(wxString(err,wxConvLocal));
      } else {
         // Reset/Undo/Redo items might become enabled or disabled
         // (we need to do this if user clicked "Generation=..." text)
         UpdateMenuItems(IsActive());
      }
   }
}

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

void MainFrame::GoFaster()
{
   currlayer->currexpo++;
   SetGenIncrement();
   // only need to refresh status bar
   UpdateStatus();
   if (generating && currlayer->currexpo < 0) {
      whentosee -= statusptr->GetCurrentDelay();
   }
}

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

void MainFrame::GoSlower()
{
   if (currlayer->currexpo > minexpo) {
      currlayer->currexpo--;
      SetGenIncrement();
      // only need to refresh status bar
      UpdateStatus();
      if (generating && currlayer->currexpo < 0) {
         if (currlayer->currexpo == -1) {
            // need to initialize whentosee rather than increment it
            whentosee = stopwatch->Time() + statusptr->GetCurrentDelay();
         } else {
            whentosee += statusptr->GetCurrentDelay();
         }
      }
   } else {
      wxBell();
   }
}

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

void MainFrame::SetBaseStep()
{
   int i;
   if ( GetInteger(_("Set Base Step"),
                   _("Temporarily change the current base step:"),
                   currlayer->currbase, 2, MAX_BASESTEP, &i) ) {
      currlayer->currbase = i;
      SetGenIncrement();
      UpdateStatus();
   }
}

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

void MainFrame::DisplayPattern()
{
   // this routine is similar to UpdatePatternAndStatus() but if tiled windows
   // exist it only updates the current tile if possible; ie. it's not a clone
   // and tile views aren't synchronized
   
   if (!IsIconized()) {
      if (tilelayers && numlayers > 1 && !syncviews && currlayer->cloneid == 0) {
         // only update the current tile
         #if defined(__WXMAC__) && (MAC_OS_X_VERSION_MIN_REQUIRED != 1030)
            // Refresh + Update is too slow on Mac
            wxClientDC dc(viewptr);
            DrawView(dc, viewptr->tileindex);
         #else
            viewptr->Refresh(false);
            viewptr->Update();
         #endif
      } else {
         // update main viewport window, possibly including all tile windows
         // (tile windows are children of bigview)
         if (numlayers > 1 && (stacklayers || tilelayers)) {
            bigview->Refresh(false);
            bigview->Update();
         } else {
            #if defined(__WXMAC__) && (MAC_OS_X_VERSION_MIN_REQUIRED != 1030)
               // Refresh + Update is too slow on Mac
               wxClientDC dc(viewptr);
               DrawView(dc, viewptr->tileindex);
            #else
               viewptr->Refresh(false);
               viewptr->Update();
            #endif
         }
      }
      if (showstatus) {
         statusptr->CheckMouseLocation(IsActive());
         statusptr->Refresh(false);
         statusptr->Update();
      }
   }
}

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

bool MainFrame::StepPattern()
{
   if (wxGetApp().Poller()->checkevents()) return false;
   
   currlayer->algo->step();
   if (currlayer->autofit) viewptr->FitInView(0);
   DisplayPattern();
   
   /*!!!
   if (autostop) {
      int period = currlayer->algo->isPeriodic();
      if (period > 0) {
         if (period == 1) {
            if (currlayer->algo->isEmpty()) {
               statusptr->DisplayMessage(_("Pattern is empty."));
            } else {
               statusptr->DisplayMessage(_("Pattern is stable."));
            }
         } else {
            wxString s;
            s.Printf(_("Pattern is oscillating (period = %d)."), period);
            statusptr->DisplayMessage(s);
         }
         return false;
      }
   }
   */
   
   return true;
}

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

void MainFrame::GeneratePattern()
{
   if (generating || viewptr->drawingcells || viewptr->waitingforclick) {
      wxBell();
      return;
   }

   if (currlayer->algo->isEmpty()) {
      statusptr->ErrorMessage(empty_pattern);
      return;
   }
   
   if (!SaveStartingPattern()) {
      return;
   }
      
   // GeneratePattern is never called while running a script so no need
   // to test inscript or currlayer->stayclean
   if (allowundo) currlayer->undoredo->RememberGenStart();

   // for DisplayTimingInfo
   begintime = stopwatch->Time();
   begingen = currlayer->algo->getGeneration().todouble();

   // for hyperspeed
   int hypdown = 64;
   
   generating = true;               // avoid re-entry
   wxGetApp().PollerReset();
   
   #ifdef __WXMSW__
   wxMenuBar* mbar = GetMenuBar();
   if (mbar) {
      // remove any accelerators from the Next Gen and Next Step menu items
      // so their keyboard shortcuts can be used to stop generating;
      // this is necessary on Windows because Golly won't see any
      // key events for a disabled menu item
      RemoveAccelerator(mbar, ID_NEXT, DO_NEXTGEN);
      RemoveAccelerator(mbar, ID_STEP, DO_NEXTSTEP);
   }
   #endif
   UpdateUserInterface(IsActive());
   
   // only show hashing info while generating, otherwise Mac app can crash
   // after a paste due to hlifealgo::resize() calling lifestatus() which
   // then causes the viewport to be repainted for some inexplicable reason
   lifealgo::setVerbose( currlayer->showhashinfo );

   if (currlayer->currexpo < 0)
      whentosee = stopwatch->Time() + statusptr->GetCurrentDelay();
   
   while (true) {
      if (currlayer->currexpo < 0) {
         // slow down by only doing one gen every GetCurrentDelay() millisecs
         long currmsec = stopwatch->Time();
         if (currmsec >= whentosee) {
            if (!StepPattern()) break;
            // add delay to current time rather than currmsec
            whentosee = stopwatch->Time() + statusptr->GetCurrentDelay();
         } else {
            // process events while we wait
            if (wxGetApp().Poller()->checkevents()) break;
            // don't hog CPU but keep sleep duration short (ie. <= mindelay)
            wxMilliSleep(1);
         }
      } else {
         // currexpo >= 0 so advance pattern by currlayer->algo->getIncrement() gens
         if (!StepPattern()) break;
         if (currlayer->hyperspeed && currlayer->algo->hyperCapable()) {
            hypdown--;
            if (hypdown == 0) {
               hypdown = 64;
               GoFaster();
            }
         }
      }
   }

   generating = false;

   lifealgo::setVerbose(0);

   // for DisplayTimingInfo
   endtime = stopwatch->Time();
   endgen = currlayer->algo->getGeneration().todouble();
   
   #ifdef __WXMSW__
   if (mbar) {
      // restore accelerators removed above
      SetAccelerator(mbar, ID_NEXT, DO_NEXTGEN);
      SetAccelerator(mbar, ID_STEP, DO_NEXTSTEP);
   }
   #endif
   
   // display the final pattern
   if (currlayer->autofit) viewptr->FitInView(0);
   if (command_pending || draw_pending) {
      // let the pending command/draw do the update below
   } else {
      UpdateEverything();
   }

   // GeneratePattern is never called while running a script so no need
   // to test inscript or currlayer->stayclean; note that we must call
   // RememberGenFinish BEFORE processing any pending command
   if (allowundo) currlayer->undoredo->RememberGenFinish();
   
   DoPendingAction(true);     // true means can restart generating loop
}

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

void MainFrame::DoPendingAction(bool restart)
{
   if (command_pending) {
      command_pending = false;
      
      int id = cmdevent.GetId();
      switch (id) {
         // don't restart the generating loop after some commands
         case wxID_NEW:          NewPattern(); break;
         case wxID_OPEN:         OpenPattern(); break;
         case ID_OPEN_CLIP:      OpenClipboard(); break;
         case ID_RESET:          ResetPattern(); break;
         case ID_SETGEN:         SetGeneration(); break;
         case wxID_UNDO:         currlayer->undoredo->UndoChange(); break;
         case ID_ADD_LAYER:      AddLayer(); break;
         case ID_DUPLICATE:      DuplicateLayer(); break;
         case ID_LOAD_LEXICON:   LoadLexiconPattern(); break;
         default:
            if ( id > ID_OPEN_RECENT && id <= ID_OPEN_RECENT + numpatterns ) {
               OpenRecentPattern(id);

            } else if ( id > ID_RUN_RECENT && id <= ID_RUN_RECENT + numscripts ) {
               OpenRecentScript(id);
               if (restart && !stop_after_script) {
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
                  // avoid clearing status message due to script like density.py
                  keepmessage = true;
               }

            } else if ( id == ID_RUN_SCRIPT ) {
               OpenScript();
               if (restart && !stop_after_script) {
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
                  // avoid clearing status message due to script like density.py
                  keepmessage = true;
               }

            } else if ( id == ID_RUN_CLIP ) {
               RunClipboard();
               if (restart && !stop_after_script) {
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
                  // avoid clearing status message due to script like density.py
                  keepmessage = true;
               }

            } else if ( id >= ID_LAYER0 && id <= ID_LAYERMAX ) {
               int oldcloneid = currlayer->cloneid;
               SetLayer(id - ID_LAYER0);
               // continue generating if new layer is a clone of old layer
               if (restart && currlayer->cloneid > 0 && currlayer->cloneid == oldcloneid) {
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
               }

            } else if ( id == ID_DEL_LAYER ) {
               int wasclone = currlayer->cloneid > 0 &&
                     ((currindex == 0 && currlayer->cloneid == GetLayer(1)->cloneid) ||
                      (currindex > 0 && currlayer->cloneid == GetLayer(currindex-1)->cloneid));
               DeleteLayer();
               // continue generating if new layer is/was a clone of old layer
               if (restart && wasclone) {
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
               }

            } else {
               // temporarily pretend the tool/layer/edit bars are not showing
               // to avoid Update[Tool/Layer/Edit]Bar changing button states
               bool saveshowtool = showtool;    showtool = false;
               bool saveshowlayer = showlayer;  showlayer = false;
               bool saveshowedit = showedit;    showedit = false;
               
               // process the pending command
               cmdevent.SetEventType(wxEVT_COMMAND_MENU_SELECTED);
               cmdevent.SetEventObject(mainptr);
               mainptr->ProcessEvent(cmdevent);
               
               // restore tool/layer/edit bar flags
               showtool = saveshowtool;
               showlayer = saveshowlayer;
               showedit = saveshowedit;
               
               if (restart) {
                  // call GeneratePattern again
                  wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
                  wxPostEvent(this->GetEventHandler(), goevt);
               }
            }
      }
   }
   
   if (draw_pending) {
      draw_pending = false;

      // temporarily pretend the tool/layer/edit bars are not showing
      // to avoid Update[Tool/Layer/Edit]Bar changing button states
      bool saveshowtool = showtool;    showtool = false;
      bool saveshowlayer = showlayer;  showlayer = false;
      bool saveshowedit = showedit;    showedit = false;
      
      UpdateEverything();
      
      // do the drawing
      mouseevent.SetEventType(wxEVT_LEFT_DOWN);
      mouseevent.SetEventObject(viewptr);
      viewptr->ProcessEvent(mouseevent);
      while (viewptr->drawingcells) {
         wxGetApp().Yield(true);
         wxMilliSleep(5);             // don't hog CPU
      }
      
      // restore tool/layer/edit bar flags
      showtool = saveshowtool;
      showlayer = saveshowlayer;
      showedit = saveshowedit;
      
      if (restart) {
         // call GeneratePattern again
         wxCommandEvent goevt(wxEVT_COMMAND_MENU_SELECTED, ID_START);
         wxPostEvent(this->GetEventHandler(), goevt);
      }
   }
}

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

void MainFrame::DisplayTimingInfo()
{
   if (viewptr->waitingforclick) return;
   if (generating) {
      endtime = stopwatch->Time();
      endgen = currlayer->algo->getGeneration().todouble();
   }
   if (endtime > begintime) {
      double secs = (double)(endtime - begintime) / 1000.0;
      double gens = endgen - begingen;
      wxString s;
      s.Printf(_("%g gens in %g secs (%g gens/sec)."), gens, secs, gens / secs);
      statusptr->DisplayMessage(s);
   }
}

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

void MainFrame::Stop()
{
   if (inscript) {
      PassKeyToScript(WXK_ESCAPE);
   } else if (generating) {
      wxGetApp().PollerInterrupt();
   }
}

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

// this global flag is used to avoid re-entrancy in NextGeneration()
// due to holding down the space/tab key
static bool inNextGen = false;

void MainFrame::NextGeneration(bool useinc)
{
   if (inNextGen) return;
   inNextGen = true;

   if (!inscript && generating) {
      // we must be in GeneratePattern() loop, so abort it
      Stop();
      inNextGen = false;
      return;
   }

   if (viewptr->drawingcells || viewptr->waitingforclick) {
      wxBell();
      inNextGen = false;
      return;
   }

   // best if generating stops after running a script like oscar.py or goto.py
   if (inscript) stop_after_script = true;

   lifealgo* curralgo = currlayer->algo;
   if (curralgo->isEmpty()) {
      statusptr->ErrorMessage(empty_pattern);
      inNextGen = false;
      return;
   }
   
   if (!SaveStartingPattern()) {
      inNextGen = false;
      return;
   }

   if (allowundo) {
      if (currlayer->stayclean) {
         // script has called run/step after a new/open command has set
         // stayclean true by calling MarkLayerClean
         if (curralgo->getGeneration() == currlayer->startgen) {
            // starting pattern has just been saved so we need to remember
            // this gen change in case user does a Reset after script ends
            // (RememberGenFinish will be called at the end of RunScript)
            if (currlayer->undoredo->savegenchanges) {
               // script must have called reset command, so we need to call
               // RememberGenFinish to match earlier RememberGenStart
               currlayer->undoredo->savegenchanges = false;
               currlayer->undoredo->RememberGenFinish();
            }
            currlayer->undoredo->RememberGenStart();
         }
      } else {
         // !currlayer->stayclean
         if (inscript) {
            // pass in false so we don't test savegenchanges flag;
            // ie. we only want to save pending cell changes here
            SavePendingChanges(false);
         }
         currlayer->undoredo->RememberGenStart();
      }
   }

   // curralgo->step() calls checkevents() so set generating flag
   generating = true;

   // only show hashing info while generating
   lifealgo::setVerbose( currlayer->showhashinfo );
   
   // avoid doing some things if NextGeneration is called from a script;
   // ie. by a run/step command
   if (!inscript) {
      wxGetApp().PollerReset();
      viewptr->CheckCursor(IsActive());
   }

   if (useinc) {
      // step by current increment
      if (curralgo->getIncrement() > bigint::one && !inscript) {
         UpdateToolBar(IsActive());
         UpdateMenuItems(IsActive());
      }
      curralgo->step();
   } else {
      // make sure we only step by one gen
      bigint saveinc = curralgo->getIncrement();
      curralgo->setIncrement(1);
      curralgo->step();
      curralgo->setIncrement(saveinc);
   }

   generating = false;

   lifealgo::setVerbose(0);
   
   if (!inscript) {
      // autofit is only used when doing many gens
      if (currlayer->autofit && useinc && curralgo->getIncrement() > bigint::one)
         viewptr->FitInView(0);
      UpdateEverything();
   }

   // we must call RememberGenFinish BEFORE processing any pending command
   if (allowundo && !currlayer->stayclean)
      currlayer->undoredo->RememberGenFinish();
   
   // process any pending command seen via checkevents() in curralgo->step()
   if (!inscript)
      DoPendingAction(false);     // false means don't restart generating loop
   
   inNextGen = false;
}

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

void MainFrame::ToggleAutoFit()
{
   currlayer->autofit = !currlayer->autofit;
   
   // we only use autofit when generating; that's why the Auto Fit item
   // is in the Control menu and not in the View menu
   if (generating && currlayer->autofit) {
      viewptr->FitInView(0);
      UpdateEverything();
   }
}

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

void MainFrame::ToggleHyperspeed()
{
   currlayer->hyperspeed = !currlayer->hyperspeed;
}

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

void MainFrame::ToggleHashInfo()
{
   currlayer->showhashinfo = !currlayer->showhashinfo;
   
   // only show hashing info while generating
   if (generating) lifealgo::setVerbose( currlayer->showhashinfo );
}

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

void MainFrame::ReduceCellStates(int newmaxstate)
{
   // check current pattern and reduce any cell states > newmaxstate
   bool patternchanged = false;
   bool savechanges = allowundo && !currlayer->stayclean;

   // check if current pattern is too big to use nextcell/setcell
   bigint top, left, bottom, right;
   currlayer->algo->findedges(&top, &left, &bottom, &right);
   if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
      statusptr->ErrorMessage(_("Pattern too big to check (outside +/- 10^9 boundary)."));
      return;
   }
   
   int itop = top.toint();
   int ileft = left.toint();
   int ibottom = bottom.toint();
   int iright = right.toint();
   int ht = ibottom - itop + 1;
   int cx, cy;

   // for showing accurate progress we need to add pattern height to pop count
   // in case this is a huge pattern with many blank rows
   double maxcount = currlayer->algo->getPopulation().todouble() + ht;
   double accumcount = 0;
   int currcount = 0;
   bool abort = false;
   int v = 0;
   BeginProgress(_("Checking cell states"));
   
   lifealgo* curralgo = currlayer->algo;
   for ( cy=itop; cy<=ibottom; cy++ ) {
      currcount++;
      for ( cx=ileft; cx<=iright; cx++ ) {
         int skip = curralgo->nextcell(cx, cy, v);
         if (skip >= 0) {
            // found next live cell in this row
            cx += skip;
            if (v > newmaxstate) {
               // reduce cell's current state to largest state
               if (savechanges) currlayer->undoredo->SaveCellChange(cx, cy, v, newmaxstate);
               curralgo->setcell(cx, cy, newmaxstate);
               patternchanged = true;
            }
            currcount++;
         } else {
            cx = iright;  // done this row
         }
         if (currcount > 1024) {
            accumcount += currcount;
            currcount = 0;
            abort = AbortProgress(accumcount / maxcount, wxEmptyString);
            if (abort) break;
         }
      }
      if (abort) break;
   }
   
   curralgo->endofpattern();
   EndProgress();

   if (patternchanged) {
      statusptr->ErrorMessage(_("Pattern has changed (new rule has fewer states)."));
   }
}

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

void MainFrame::ShowRuleDialog()
{
   if (inscript || viewptr->waitingforclick) return;

   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_SETRULE);
      return;
   }

   algo_type oldalgo = currlayer->algtype;
   wxString oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);
   int oldmaxstate = currlayer->algo->NumCellStates() - 1;

   if (ChangeRule()) {
      // if ChangeAlgorithm was called then we're done
      if (currlayer->algtype != oldalgo) {
         // except we have to call UpdateEverything here now that the main window is active
         UpdateEverything();
         return;
      }
      
      // show new rule in window title (but don't change file name);
      // even if the rule didn't change we still need to do this because
      // the user might have simply added/deleted a named rule
      SetWindowTitle(wxEmptyString);
      
      // check if rule actually changed
      wxString newrule = wxString(currlayer->algo->getrule(), wxConvLocal);
      if (oldrule != newrule) {
         // rule change might have changed the number of cell states;
         // if there are fewer states then pattern might change
         int newmaxstate = currlayer->algo->NumCellStates() - 1;
         if (newmaxstate < oldmaxstate && !currlayer->algo->isEmpty()) {
            ReduceCellStates(newmaxstate);
         }
         
         // pattern might have changed or new rule might have changed colors
         UpdateEverything();
         
         if (allowundo) {
            currlayer->undoredo->RememberRuleChange(oldrule);
         }
      }
   }
}

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

void MainFrame::ChangeAlgorithm(algo_type newalgotype, const wxString& newrule, bool inundoredo)
{
   if (newalgotype == currlayer->algtype) return;

   // check if current pattern is too big to use nextcell/setcell
   bigint top, left, bottom, right;
   if ( !currlayer->algo->isEmpty() ) {
      currlayer->algo->findedges(&top, &left, &bottom, &right);
      if ( viewptr->OutsideLimits(top, left, bottom, right) ) {
         statusptr->ErrorMessage(_("Pattern cannot be converted (outside +/- 10^9 boundary)."));
         return;
      }
   }

   if (generating) {
      // terminate generating loop and set command_pending flag
      Stop();
      command_pending = true;
      cmdevent.SetId(ID_ALGO0 + newalgotype);
      return;
   }

   // save changes if undo/redo is enabled and script isn't constructing a pattern
   // and we're not undoing/redoing an earlier algo change
   bool savechanges = allowundo && !currlayer->stayclean && !inundoredo;
   if (savechanges && inscript) {
      // note that we must save pending gen changes BEFORE changing algo type
      // otherwise temporary files won't be the correct type (mc or rle)
      SavePendingChanges();
   }
   
   bool rulechanged = false;
   wxString oldrule = wxString(currlayer->algo->getrule(), wxConvLocal);

   // change algorithm type, reset step size, and update status bar immediately
   algo_type oldalgo = currlayer->algtype;
   currlayer->algtype = newalgotype;
   currlayer->currbase = algoinfo[newalgotype]->defbase;
   currlayer->currexpo = 0;
   UpdateStatus();

   // create a new universe of the requested flavor
   lifealgo* newalgo = CreateNewUniverse(newalgotype);
   
   if (inundoredo) {
      // switch to given newrule (no error should occur)
      const char* err = newalgo->setrule( newrule.mb_str(wxConvLocal) );
      if (err) Warning(_("Bug detected in ChangeAlgorithm!"));
   } else {
      const char* err;
      if (newrule.IsEmpty()) {
         // try to use same rule
         err = newalgo->setrule( currlayer->algo->getrule() );
      } else {
         // switch to newrule (ChangeRule has called ChangeAlgorithm)
         err = newalgo->setrule( newrule.mb_str(wxConvLocal) );
         rulechanged = true;
      }
      if (err) {
         // switch to new algo's default rule
         newalgo->setrule( newalgo->DefaultRule() );
         rulechanged = true;
      }
   }
   
   // set same gen count
   newalgo->setGeneration( currlayer->algo->getGeneration() );

   bool patternchanged = false;
   if ( !currlayer->algo->isEmpty() ) {
      // copy pattern in current universe to new universe
      int itop = top.toint();
      int ileft = left.toint();
      int ibottom = bottom.toint();
      int iright = right.toint();
      int ht = ibottom - itop + 1;
      int cx, cy;
   
      // for showing accurate progress we need to add pattern height to pop count
      // in case this is a huge pattern with many blank rows
      double maxcount = currlayer->algo->getPopulation().todouble() + ht;
      double accumcount = 0;
      int currcount = 0;
      bool abort = false;
      int v = 0;
      BeginProgress(_("Converting pattern"));
      
      lifealgo* curralgo = currlayer->algo;
      
      // need to check for state change if new algo has fewer states than old algo
      int newmaxstate = newalgo->NumCellStates() - 1;
   
      for ( cy=itop; cy<=ibottom; cy++ ) {
         currcount++;
         for ( cx=ileft; cx<=iright; cx++ ) {
            int skip = curralgo->nextcell(cx, cy, v);
            if (skip >= 0) {
               // found next live cell in this row
               cx += skip;
               if (v > newmaxstate) {
                  // reduce v to largest state in new algo
                  if (savechanges) currlayer->undoredo->SaveCellChange(cx, cy, v, newmaxstate);
                  v = newmaxstate;
                  patternchanged = true;
               }
               newalgo->setcell(cx, cy, v);
               currcount++;
            } else {
               cx = iright;  // done this row
            }
            if (currcount > 1024) {
               accumcount += currcount;
               currcount = 0;
               abort = AbortProgress(accumcount / maxcount, wxEmptyString);
               if (abort) break;
            }
         }
         if (abort) break;
      }
      
      newalgo->endofpattern();
      EndProgress();
   }
   
   // delete old universe and point current universe to new universe
   delete currlayer->algo;
   currlayer->algo = newalgo;   
   SetGenIncrement();
   
   // switch to default colors for new algo+rule
   UpdateLayerColors();

   if (!inundoredo) {
      if (rulechanged) {
         // show new rule in window title (but don't change file name)
         SetWindowTitle(wxEmptyString);
         
         // if pattern exists and is at starting gen then set savestart true
         // so that SaveStartingPattern will save pattern to suitable file
         // (and thus ResetPattern will work correctly)
         if ( currlayer->algo->getGeneration() == currlayer->startgen &&
              !currlayer->algo->isEmpty() ) {
            currlayer->savestart = true;
         }
         
         if (newrule.IsEmpty()) {
            if (patternchanged) {
               statusptr->ErrorMessage(_("Rule has changed and pattern has changed (new algorithm has fewer states)."));
            } else {
               // don't beep
               statusptr->DisplayMessage(_("Rule has changed."));
            }
         } else {
            // ChangeRule called ChangeAlgorithm
            if (patternchanged) {
               statusptr->ErrorMessage(_("Algorithm has changed and pattern has changed (new algorithm has fewer states)."));
            } else {
               // don't beep
               statusptr->DisplayMessage(_("Algorithm has changed."));
            }
         }
      } else if (patternchanged) {
         statusptr->ErrorMessage(_("Pattern has changed (new algorithm has fewer states)."));
      }
      
      if (!inscript) {
         UpdateEverything();
      }
   }

   if (savechanges) {
      currlayer->undoredo->RememberAlgoChange(oldalgo, oldrule);
   }
}