Life! made more WinCE-friendly
[wxWidgets.git] / demos / life / life.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: life.cpp
3 // Purpose: The game of Life, created by J. H. Conway
4 // Author: Guillermo Rodriguez Garcia, <guille@iies.es>
5 // Modified by:
6 // Created: Jan/2000
7 // RCS-ID: $Id$
8 // Copyright: (c) 2000, Guillermo Rodriguez Garcia
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ==========================================================================
13 // headers, declarations, constants
14 // ==========================================================================
15
16 #ifdef __GNUG__
17 #pragma implementation "life.h"
18 #endif
19
20 // For compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #ifndef WX_PRECOMP
28 #include "wx/wx.h"
29 #endif
30
31 #include "wx/statline.h"
32 #include "wx/wfstream.h"
33 #include "wx/filedlg.h"
34 #include "wx/stockitem.h"
35
36 #include "life.h"
37 #include "game.h"
38 #include "dialogs.h"
39 #include "reader.h"
40
41 // --------------------------------------------------------------------------
42 // resources
43 // --------------------------------------------------------------------------
44
45 #if defined(__WXGTK__) || defined(__WXMOTIF__) || defined(__WXMAC__) || defined(__WXMGL__) || defined(__WXX11__)
46 // application icon
47 #include "mondrian.xpm"
48
49 // bitmap buttons for the toolbar
50 #include "bitmaps/reset.xpm"
51 #include "bitmaps/open.xpm"
52 #include "bitmaps/play.xpm"
53 #include "bitmaps/stop.xpm"
54 #include "bitmaps/zoomin.xpm"
55 #include "bitmaps/zoomout.xpm"
56 #include "bitmaps/info.xpm"
57
58 // navigator
59 #include "bitmaps/north.xpm"
60 #include "bitmaps/south.xpm"
61 #include "bitmaps/east.xpm"
62 #include "bitmaps/west.xpm"
63 #include "bitmaps/center.xpm"
64 #endif
65
66 // --------------------------------------------------------------------------
67 // constants
68 // --------------------------------------------------------------------------
69
70 // IDs for the controls and the menu commands. Exluding those already defined
71 // by wxWidgets, such as wxID_NEW.
72 enum
73 {
74 // timer
75 ID_TIMER = wxID_HIGHEST,
76
77 // file menu
78 ID_SAMPLES,
79
80 // view menu
81 ID_SHOWNAV,
82 ID_ORIGIN,
83 ID_CENTER,
84 ID_NORTH,
85 ID_SOUTH,
86 ID_EAST,
87 ID_WEST,
88 ID_INFO,
89
90 // game menu
91 ID_START,
92 ID_STEP,
93 ID_TOPSPEED,
94
95 // speed selection slider
96 ID_SLIDER
97 };
98
99 // --------------------------------------------------------------------------
100 // event tables and other macros for wxWidgets
101 // --------------------------------------------------------------------------
102
103 // Event tables
104 BEGIN_EVENT_TABLE(LifeFrame, wxFrame)
105 EVT_MENU (wxID_NEW, LifeFrame::OnMenu)
106 EVT_MENU (wxID_OPEN, LifeFrame::OnOpen)
107 EVT_MENU (ID_SAMPLES, LifeFrame::OnSamples)
108 EVT_MENU (wxID_ABOUT, LifeFrame::OnMenu)
109 EVT_MENU (wxID_EXIT, LifeFrame::OnMenu)
110 EVT_MENU (ID_SHOWNAV, LifeFrame::OnMenu)
111 EVT_MENU (ID_ORIGIN, LifeFrame::OnNavigate)
112 EVT_BUTTON (ID_CENTER, LifeFrame::OnNavigate)
113 EVT_BUTTON (ID_NORTH, LifeFrame::OnNavigate)
114 EVT_BUTTON (ID_SOUTH, LifeFrame::OnNavigate)
115 EVT_BUTTON (ID_EAST, LifeFrame::OnNavigate)
116 EVT_BUTTON (ID_WEST, LifeFrame::OnNavigate)
117 EVT_MENU (wxID_ZOOM_IN, LifeFrame::OnZoom)
118 EVT_MENU (wxID_ZOOM_OUT,LifeFrame::OnZoom)
119 EVT_MENU (ID_INFO, LifeFrame::OnMenu)
120 EVT_MENU (ID_START, LifeFrame::OnMenu)
121 EVT_MENU (ID_STEP, LifeFrame::OnMenu)
122 EVT_MENU (wxID_STOP, LifeFrame::OnMenu)
123 EVT_MENU (ID_TOPSPEED, LifeFrame::OnMenu)
124 EVT_COMMAND_SCROLL (ID_SLIDER, LifeFrame::OnSlider)
125 EVT_TIMER (ID_TIMER, LifeFrame::OnTimer)
126 EVT_CLOSE ( LifeFrame::OnClose)
127 END_EVENT_TABLE()
128
129 BEGIN_EVENT_TABLE(LifeNavigator, wxMiniFrame)
130 EVT_CLOSE ( LifeNavigator::OnClose)
131 END_EVENT_TABLE()
132
133 BEGIN_EVENT_TABLE(LifeCanvas, wxWindow)
134 EVT_PAINT ( LifeCanvas::OnPaint)
135 EVT_SCROLLWIN ( LifeCanvas::OnScroll)
136 EVT_SIZE ( LifeCanvas::OnSize)
137 EVT_MOTION ( LifeCanvas::OnMouse)
138 EVT_LEFT_DOWN ( LifeCanvas::OnMouse)
139 EVT_LEFT_UP ( LifeCanvas::OnMouse)
140 EVT_LEFT_DCLICK ( LifeCanvas::OnMouse)
141 EVT_ERASE_BACKGROUND( LifeCanvas::OnEraseBackground)
142 END_EVENT_TABLE()
143
144
145 // Create a new application object
146 IMPLEMENT_APP(LifeApp)
147
148
149 // ==========================================================================
150 // implementation
151 // ==========================================================================
152
153 // some shortcuts
154 #define ADD_TOOL(id, bmp, tooltip, help) \
155 toolBar->AddTool(id, bmp, wxNullBitmap, false, wxDefaultCoord, wxDefaultCoord, (wxObject *)NULL, tooltip, help)
156
157
158 // --------------------------------------------------------------------------
159 // LifeApp
160 // --------------------------------------------------------------------------
161
162 // 'Main program' equivalent: the program execution "starts" here
163 bool LifeApp::OnInit()
164 {
165 // create the main application window
166 LifeFrame *frame = new LifeFrame();
167
168 // show it and tell the application that it's our main window
169 frame->Show(true);
170 SetTopWindow(frame);
171
172 // just for Motif
173 #ifdef __WXMOTIF__
174 frame->UpdateInfoText();
175 #endif
176
177 // enter the main message loop and run the app
178 return true;
179 }
180
181 // --------------------------------------------------------------------------
182 // LifeFrame
183 // --------------------------------------------------------------------------
184
185 // frame constructor
186 LifeFrame::LifeFrame() : wxFrame( (wxFrame *) NULL, wxID_ANY,
187 _("Life!"), wxDefaultPosition )
188 {
189 // frame icon
190 SetIcon(wxICON(mondrian));
191
192 // menu bar
193 wxMenu *menuFile = new wxMenu(wxMENU_TEAROFF);
194 wxMenu *menuView = new wxMenu(wxMENU_TEAROFF);
195 wxMenu *menuGame = new wxMenu(wxMENU_TEAROFF);
196 wxMenu *menuHelp = new wxMenu(wxMENU_TEAROFF);
197
198 menuFile->Append(wxID_NEW, wxGetStockLabel(wxID_NEW), _("Start a new game"));
199 menuFile->Append(wxID_OPEN, wxGetStockLabel(wxID_OPEN), _("Open an existing Life pattern"));
200 menuFile->Append(ID_SAMPLES, _("&Sample game..."), _("Select a sample configuration"));
201 menuFile->AppendSeparator();
202 menuFile->Append(wxID_EXIT, wxGetStockLabel(wxID_EXIT, true, _T("Alt-X")), _("Quit this program"));
203
204 menuView->Append(ID_SHOWNAV, _("Navigation &toolbox"), _("Show or hide toolbox"), wxITEM_CHECK);
205 menuView->Check(ID_SHOWNAV, true);
206 menuView->AppendSeparator();
207 menuView->Append(ID_ORIGIN, _("&Absolute origin"), _("Go to (0, 0)"));
208 menuView->Append(ID_CENTER, _("&Center of mass"), _("Find center of mass"));
209 menuView->Append(ID_NORTH, _("&North"), _("Find northernmost cell"));
210 menuView->Append(ID_SOUTH, _("&South"), _("Find southernmost cell"));
211 menuView->Append(ID_EAST, _("&East"), _("Find easternmost cell"));
212 menuView->Append(ID_WEST, _("&West"), _("Find westernmost cell"));
213 menuView->AppendSeparator();
214 menuView->Append(wxID_ZOOM_IN, wxGetStockLabel(wxID_ZOOM_IN, true, _T("Ctrl-I")), _("Zoom in"));
215 menuView->Append(wxID_ZOOM_OUT, wxGetStockLabel(wxID_ZOOM_OUT, true, _T("Ctrl-O")), _("Zoom out"));
216 menuView->Append(ID_INFO, _("&Description\tCtrl-D"), _("View pattern description"));
217
218 menuGame->Append(ID_START, _("&Start\tCtrl-S"), _("Start"));
219 menuGame->Append(ID_STEP, _("&Next\tCtrl-N"), _("Single step"));
220 menuGame->Append(wxID_STOP, wxGetStockLabel(wxID_STOP, true, _T("Ctrl-T")), _("Stop"));
221 menuGame->Enable(wxID_STOP, false);
222 menuGame->AppendSeparator();
223 menuGame->Append(ID_TOPSPEED, _("T&op speed!"), _("Go as fast as possible"));
224
225 menuHelp->Append(wxID_ABOUT, _("&About\tCtrl-A"), _("Show about dialog"));
226
227 wxMenuBar *menuBar = new wxMenuBar();
228 menuBar->Append(menuFile, _("&File"));
229 menuBar->Append(menuView, _("&View"));
230 menuBar->Append(menuGame, _("&Game"));
231 menuBar->Append(menuHelp, _("&Help"));
232 SetMenuBar(menuBar);
233
234 // tool bar
235 wxBitmap tbBitmaps[7];
236
237 tbBitmaps[0] = wxBITMAP(reset);
238 tbBitmaps[1] = wxBITMAP(open);
239 tbBitmaps[2] = wxBITMAP(zoomin);
240 tbBitmaps[3] = wxBITMAP(zoomout);
241 tbBitmaps[4] = wxBITMAP(info);
242 tbBitmaps[5] = wxBITMAP(play);
243 tbBitmaps[6] = wxBITMAP(stop);
244
245 wxToolBar *toolBar = CreateToolBar();
246 toolBar->SetMargins(5, 5);
247 toolBar->SetToolBitmapSize(wxSize(16, 16));
248
249 ADD_TOOL(wxID_NEW, tbBitmaps[0], wxGetStockLabel(wxID_NEW, false), _("Start a new game"));
250 ADD_TOOL(wxID_OPEN, tbBitmaps[1], wxGetStockLabel(wxID_OPEN, false), _("Open an existing Life pattern"));
251
252 // PocketPC only works with standard identifiers, and there's restricted space
253 #ifndef __POCKETPC__
254 toolBar->AddSeparator();
255 ADD_TOOL(wxID_ZOOM_IN, tbBitmaps[2], wxGetStockLabel(wxID_ZOOM_IN, false), _("Zoom in"));
256 ADD_TOOL(wxID_ZOOM_OUT, tbBitmaps[3], wxGetStockLabel(wxID_ZOOM_OUT, false), _("Zoom out"));
257 ADD_TOOL(ID_INFO, tbBitmaps[4], _("Description"), _("Show description"));
258 toolBar->AddSeparator();
259 ADD_TOOL(ID_START, tbBitmaps[5], _("Start"), _("Start"));
260 ADD_TOOL(wxID_STOP, tbBitmaps[6], wxGetStockLabel(wxID_STOP, false), _("Stop"));
261 #endif
262
263 toolBar->Realize();
264 toolBar->EnableTool(wxID_STOP, false); // must be after Realize() !
265
266 #if wxUSE_STATUSBAR
267 // status bar
268 CreateStatusBar(2);
269 SetStatusText(_("Welcome to Life!"));
270 #endif // wxUSE_STATUSBAR
271
272 // game and timer
273 m_life = new Life();
274 m_timer = new wxTimer(this, ID_TIMER);
275 m_running = false;
276 m_topspeed = false;
277 m_interval = 500;
278 m_tics = 0;
279
280 // We use two different panels to reduce flicker in wxGTK, because
281 // some widgets (like wxStaticText) don't have their own X11 window,
282 // and thus updating the text would result in a refresh of the canvas
283 // if they belong to the same parent.
284
285 wxPanel *panel1 = new wxPanel(this, wxID_ANY);
286 wxPanel *panel2 = new wxPanel(this, wxID_ANY);
287
288 // canvas
289 m_canvas = new LifeCanvas(panel1, m_life);
290
291 // info panel
292 m_text = new wxStaticText(panel2, wxID_ANY,
293 wxEmptyString,
294 wxDefaultPosition,
295 wxDefaultSize,
296 wxALIGN_CENTER | wxST_NO_AUTORESIZE);
297
298 wxSlider *slider = new wxSlider(panel2, ID_SLIDER,
299 5, 1, 10,
300 wxDefaultPosition,
301 wxSize(200, wxDefaultCoord),
302 wxSL_HORIZONTAL | wxSL_AUTOTICKS);
303
304 UpdateInfoText();
305
306 // component layout
307 wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL);
308 wxBoxSizer *sizer2 = new wxBoxSizer(wxVERTICAL);
309 wxBoxSizer *sizer3 = new wxBoxSizer(wxVERTICAL);
310
311 #if wxUSE_STATLINE
312 sizer1->Add( new wxStaticLine(panel1, wxID_ANY), 0, wxGROW );
313 #endif // wxUSE_STATLINE
314 sizer1->Add( m_canvas, 1, wxGROW | wxALL, 2 );
315 #if wxUSE_STATLINE
316 sizer1->Add( new wxStaticLine(panel1, wxID_ANY), 0, wxGROW );
317 #endif // wxUSE_STATLINE
318 panel1->SetSizer( sizer1 );
319 sizer1->Fit( panel1 );
320
321 sizer2->Add( m_text, 0, wxGROW | wxTOP, 4 );
322 sizer2->Add( slider, 0, wxCENTRE | wxALL, 4 );
323
324 panel2->SetSizer( sizer2 );
325 sizer2->Fit( panel2 );
326
327 sizer3->Add( panel1, 1, wxGROW );
328 sizer3->Add( panel2, 0, wxGROW );
329 SetSizer( sizer3 );
330 #ifndef __WXWINCE__
331 sizer3->Fit( this );
332
333 // set minimum frame size
334 sizer3->SetSizeHints( this );
335 #endif
336
337 // navigator frame
338 m_navigator = new LifeNavigator(this);
339 }
340
341 LifeFrame::~LifeFrame()
342 {
343 delete m_timer;
344 }
345
346 void LifeFrame::UpdateInfoText()
347 {
348 wxString msg;
349
350 msg.Printf(_(" Generation: %u (T: %u ms), Population: %u "),
351 m_tics,
352 m_topspeed? 0 : m_interval,
353 m_life->GetNumCells());
354 m_text->SetLabel(msg);
355 }
356
357 // Enable or disable tools and menu entries according to the current
358 // state. See also wxEVT_UPDATE_UI events for a slightly different
359 // way to do this.
360 void LifeFrame::UpdateUI()
361 {
362 // start / stop
363 GetToolBar()->EnableTool(ID_START, !m_running);
364 GetToolBar()->EnableTool(wxID_STOP, m_running);
365 GetMenuBar()->Enable(ID_START, !m_running);
366 GetMenuBar()->Enable(ID_STEP, !m_running);
367 GetMenuBar()->Enable(wxID_STOP, m_running);
368 GetMenuBar()->Enable(ID_TOPSPEED, !m_topspeed);
369
370 // zooming
371 int cellsize = m_canvas->GetCellSize();
372 GetToolBar()->EnableTool(wxID_ZOOM_IN, cellsize < 32);
373 GetToolBar()->EnableTool(wxID_ZOOM_OUT, cellsize > 1);
374 GetMenuBar()->Enable(wxID_ZOOM_IN, cellsize < 32);
375 GetMenuBar()->Enable(wxID_ZOOM_OUT, cellsize > 1);
376 }
377
378 // Event handlers -----------------------------------------------------------
379
380 // OnMenu handles all events which don't have their own event handler
381 void LifeFrame::OnMenu(wxCommandEvent& event)
382 {
383 switch (event.GetId())
384 {
385 case wxID_NEW:
386 {
387 // stop if it was running
388 OnStop();
389 m_life->Clear();
390 m_canvas->Recenter(0, 0);
391 m_tics = 0;
392 UpdateInfoText();
393 break;
394 }
395 case wxID_ABOUT:
396 {
397 LifeAboutDialog dialog(this);
398 dialog.ShowModal();
399 break;
400 }
401 case wxID_EXIT:
402 {
403 // true is to force the frame to close
404 Close(true);
405 break;
406 }
407 case ID_SHOWNAV:
408 {
409 bool checked = GetMenuBar()->GetMenu(1)->IsChecked(ID_SHOWNAV);
410 m_navigator->Show(checked);
411 break;
412 }
413 case ID_INFO:
414 {
415 wxString desc = m_life->GetDescription();
416
417 if ( desc.empty() )
418 desc = _("Not available");
419
420 // should we make the description editable here?
421 wxMessageBox(desc, _("Description"), wxOK | wxICON_INFORMATION);
422
423 break;
424 }
425 case ID_START : OnStart(); break;
426 case ID_STEP : OnStep(); break;
427 case wxID_STOP : OnStop(); break;
428 case ID_TOPSPEED:
429 {
430 m_running = true;
431 m_topspeed = true;
432 UpdateUI();
433 while (m_running && m_topspeed)
434 {
435 OnStep();
436 wxYield();
437 }
438 break;
439 }
440 }
441 }
442
443 void LifeFrame::OnOpen(wxCommandEvent& WXUNUSED(event))
444 {
445 wxFileDialog filedlg(this,
446 _("Choose a file to open"),
447 wxEmptyString,
448 wxEmptyString,
449 _("Life patterns (*.lif)|*.lif|All files (*.*)|*.*"),
450 wxOPEN | wxFILE_MUST_EXIST);
451
452 if (filedlg.ShowModal() == wxID_OK)
453 {
454 wxFileInputStream stream(filedlg.GetPath());
455 LifeReader reader(stream);
456
457 // the reader handles errors itself, no need to do anything here
458 if (reader.IsOk())
459 {
460 // stop if running and put the pattern
461 OnStop();
462 m_life->Clear();
463 m_life->SetPattern(reader.GetPattern());
464
465 // recenter canvas
466 m_canvas->Recenter(0, 0);
467 m_tics = 0;
468 UpdateInfoText();
469 }
470 }
471 }
472
473 void LifeFrame::OnSamples(wxCommandEvent& WXUNUSED(event))
474 {
475 // stop if it was running
476 OnStop();
477
478 // dialog box
479 LifeSamplesDialog dialog(this);
480
481 if (dialog.ShowModal() == wxID_OK)
482 {
483 const LifePattern pattern = dialog.GetPattern();
484
485 // put the pattern
486 m_life->Clear();
487 m_life->SetPattern(pattern);
488
489 // recenter canvas
490 m_canvas->Recenter(0, 0);
491 m_tics = 0;
492 UpdateInfoText();
493 }
494 }
495
496 void LifeFrame::OnZoom(wxCommandEvent& event)
497 {
498 int cellsize = m_canvas->GetCellSize();
499
500 if ((event.GetId() == wxID_ZOOM_IN) && cellsize < 32)
501 {
502 m_canvas->SetCellSize(cellsize * 2);
503 UpdateUI();
504 }
505 else if ((event.GetId() == wxID_ZOOM_OUT) && cellsize > 1)
506 {
507 m_canvas->SetCellSize(cellsize / 2);
508 UpdateUI();
509 }
510 }
511
512 void LifeFrame::OnNavigate(wxCommandEvent& event)
513 {
514 LifeCell c;
515
516 switch (event.GetId())
517 {
518 case ID_NORTH: c = m_life->FindNorth(); break;
519 case ID_SOUTH: c = m_life->FindSouth(); break;
520 case ID_WEST: c = m_life->FindWest(); break;
521 case ID_EAST: c = m_life->FindEast(); break;
522 case ID_CENTER: c = m_life->FindCenter(); break;
523 default :
524 wxFAIL;
525 // Fall through!
526 case ID_ORIGIN: c.i = c.j = 0; break;
527 }
528
529 m_canvas->Recenter(c.i, c.j);
530 }
531
532 void LifeFrame::OnSlider(wxScrollEvent& event)
533 {
534 m_interval = event.GetPosition() * 100;
535
536 if (m_running)
537 {
538 OnStop();
539 OnStart();
540 }
541
542 UpdateInfoText();
543 }
544
545 void LifeFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
546 {
547 OnStep();
548 }
549
550 void LifeFrame::OnClose(wxCloseEvent& WXUNUSED(event))
551 {
552 // Stop if it was running; this is absolutely needed because
553 // the frame won't be actually destroyed until there are no
554 // more pending events, and this in turn won't ever happen
555 // if the timer is running faster than the window can redraw.
556 OnStop();
557 Destroy();
558 }
559
560 void LifeFrame::OnStart()
561 {
562 if (!m_running)
563 {
564 m_timer->Start(m_interval);
565 m_running = true;
566 UpdateUI();
567 }
568 }
569
570 void LifeFrame::OnStop()
571 {
572 if (m_running)
573 {
574 m_timer->Stop();
575 m_running = false;
576 m_topspeed = false;
577 UpdateUI();
578 }
579 }
580
581 void LifeFrame::OnStep()
582 {
583 if (m_life->NextTic())
584 m_tics++;
585 else
586 OnStop();
587
588 m_canvas->DrawChanged();
589 UpdateInfoText();
590 }
591
592
593 // --------------------------------------------------------------------------
594 // LifeNavigator miniframe
595 // --------------------------------------------------------------------------
596
597 LifeNavigator::LifeNavigator(wxWindow *parent)
598 : wxMiniFrame(parent, wxID_ANY,
599 _("Navigation"),
600 wxDefaultPosition,
601 wxDefaultSize,
602 wxCAPTION | wxSIMPLE_BORDER)
603 {
604 wxPanel *panel = new wxPanel(this, wxID_ANY);
605 wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL);
606 wxBoxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL);
607
608 // create bitmaps and masks for the buttons
609 wxBitmap
610 bmpn = wxBITMAP(north),
611 bmpw = wxBITMAP(west),
612 bmpc = wxBITMAP(center),
613 bmpe = wxBITMAP(east),
614 bmps = wxBITMAP(south);
615
616 #if !defined(__WXGTK__) && !defined(__WXMOTIF__) && !defined(__WXMAC__)
617 bmpn.SetMask(new wxMask(bmpn, *wxLIGHT_GREY));
618 bmpw.SetMask(new wxMask(bmpw, *wxLIGHT_GREY));
619 bmpc.SetMask(new wxMask(bmpc, *wxLIGHT_GREY));
620 bmpe.SetMask(new wxMask(bmpe, *wxLIGHT_GREY));
621 bmps.SetMask(new wxMask(bmps, *wxLIGHT_GREY));
622 #endif
623
624 // create the buttons and attach tooltips to them
625 wxBitmapButton
626 *bn = new wxBitmapButton(panel, ID_NORTH, bmpn),
627 *bw = new wxBitmapButton(panel, ID_WEST , bmpw),
628 *bc = new wxBitmapButton(panel, ID_CENTER, bmpc),
629 *be = new wxBitmapButton(panel, ID_EAST , bmpe),
630 *bs = new wxBitmapButton(panel, ID_SOUTH, bmps);
631
632 #if wxUSE_TOOLTIPS
633 bn->SetToolTip(_("Find northernmost cell"));
634 bw->SetToolTip(_("Find westernmost cell"));
635 bc->SetToolTip(_("Find center of mass"));
636 be->SetToolTip(_("Find easternmost cell"));
637 bs->SetToolTip(_("Find southernmost cell"));
638 #endif
639
640 // add buttons to sizers
641 sizer2->Add( bw, 0, wxCENTRE | wxWEST, 4 );
642 sizer2->Add( bc, 0, wxCENTRE);
643 sizer2->Add( be, 0, wxCENTRE | wxEAST, 4 );
644 sizer1->Add( bn, 0, wxCENTRE | wxNORTH, 4 );
645 sizer1->Add( sizer2 );
646 sizer1->Add( bs, 0, wxCENTRE | wxSOUTH, 4 );
647
648 // set the panel and miniframe size
649 panel->SetSizer(sizer1);
650
651 sizer1->Fit(panel);
652 SetClientSize(panel->GetSize());
653 wxSize sz = GetSize();
654 SetSizeHints(sz.x, sz.y, sz.x, sz.y);
655
656 // move it to a sensible position
657 wxRect parentRect = parent->GetRect();
658 wxSize childSize = GetSize();
659 int x = parentRect.GetX() +
660 parentRect.GetWidth();
661 int y = parentRect.GetY() +
662 (parentRect.GetHeight() - childSize.GetHeight()) / 4;
663 Move(x, y);
664
665 // done
666 Show(true);
667 }
668
669 void LifeNavigator::OnClose(wxCloseEvent& event)
670 {
671 // avoid if we can
672 if (event.CanVeto())
673 event.Veto();
674 else
675 Destroy();
676 }
677
678
679 // --------------------------------------------------------------------------
680 // LifeCanvas
681 // --------------------------------------------------------------------------
682
683 // canvas constructor
684 LifeCanvas::LifeCanvas(wxWindow *parent, Life *life, bool interactive)
685 : wxWindow(parent, wxID_ANY, wxDefaultPosition, wxSize(100, 100),
686 wxSUNKEN_BORDER|wxFULL_REPAINT_ON_RESIZE)
687 {
688 m_life = life;
689 m_interactive = interactive;
690 m_cellsize = 8;
691 m_status = MOUSE_NOACTION;
692 m_viewportX = 0;
693 m_viewportY = 0;
694 m_viewportH = 0;
695 m_viewportW = 0;
696
697 if (m_interactive)
698 SetCursor(*wxCROSS_CURSOR);
699
700 // reduce flicker if wxEVT_ERASE_BACKGROUND is not available
701 SetBackgroundColour(*wxWHITE);
702 }
703
704 LifeCanvas::~LifeCanvas()
705 {
706 delete m_life;
707 }
708
709 // recenter at the given position
710 void LifeCanvas::Recenter(wxInt32 i, wxInt32 j)
711 {
712 m_viewportX = i - m_viewportW / 2;
713 m_viewportY = j - m_viewportH / 2;
714
715 // redraw everything
716 Refresh(false);
717 }
718
719 // set the cell size and refresh display
720 void LifeCanvas::SetCellSize(int cellsize)
721 {
722 m_cellsize = cellsize;
723
724 // find current center
725 wxInt32 cx = m_viewportX + m_viewportW / 2;
726 wxInt32 cy = m_viewportY + m_viewportH / 2;
727
728 // get current canvas size and adjust viewport accordingly
729 int w, h;
730 GetClientSize(&w, &h);
731 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
732 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
733
734 // recenter
735 m_viewportX = cx - m_viewportW / 2;
736 m_viewportY = cy - m_viewportH / 2;
737
738 // adjust scrollbars
739 if (m_interactive)
740 {
741 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
742 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
743 m_thumbX = m_viewportW;
744 m_thumbY = m_viewportH;
745 }
746
747 Refresh(false);
748 }
749
750 // draw a cell
751 void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, bool alive)
752 {
753 wxClientDC dc(this);
754
755 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
756 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
757
758 dc.BeginDrawing();
759 DrawCell(i, j, dc);
760 dc.EndDrawing();
761 }
762
763 void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, wxDC &dc)
764 {
765 wxCoord x = CellToX(i);
766 wxCoord y = CellToY(j);
767
768 // if cellsize is 1 or 2, there will be no grid
769 switch (m_cellsize)
770 {
771 case 1:
772 dc.DrawPoint(x, y);
773 break;
774 case 2:
775 dc.DrawRectangle(x, y, 2, 2);
776 break;
777 default:
778 dc.DrawRectangle(x + 1, y + 1, m_cellsize - 1, m_cellsize - 1);
779 }
780 }
781
782 // draw all changed cells
783 void LifeCanvas::DrawChanged()
784 {
785 wxClientDC dc(this);
786
787 size_t ncells;
788 LifeCell *cells;
789 bool done = false;
790
791 m_life->BeginFind(m_viewportX,
792 m_viewportY,
793 m_viewportX + m_viewportW,
794 m_viewportY + m_viewportH,
795 true);
796
797 dc.BeginDrawing();
798
799 if (m_cellsize == 1)
800 {
801 dc.SetPen(*wxBLACK_PEN);
802 }
803 else
804 {
805 dc.SetPen(*wxTRANSPARENT_PEN);
806 dc.SetBrush(*wxBLACK_BRUSH);
807 }
808 dc.SetLogicalFunction(wxINVERT);
809
810 while (!done)
811 {
812 done = m_life->FindMore(&cells, &ncells);
813
814 for (size_t m = 0; m < ncells; m++)
815 DrawCell(cells[m].i, cells[m].j, dc);
816 }
817 dc.EndDrawing();
818 }
819
820 // event handlers
821 void LifeCanvas::OnPaint(wxPaintEvent& WXUNUSED(event))
822 {
823 wxPaintDC dc(this);
824 wxRect rect = GetUpdateRegion().GetBox();
825 wxCoord x, y, w, h;
826 wxInt32 i0, j0, i1, j1;
827
828 // find damaged area
829 x = rect.GetX();
830 y = rect.GetY();
831 w = rect.GetWidth();
832 h = rect.GetHeight();
833
834 i0 = XToCell(x);
835 j0 = YToCell(y);
836 i1 = XToCell(x + w - 1);
837 j1 = YToCell(y + h - 1);
838
839 size_t ncells;
840 LifeCell *cells;
841
842 m_life->BeginFind(i0, j0, i1, j1, false);
843 bool done = m_life->FindMore(&cells, &ncells);
844
845 // erase all damaged cells and draw the grid
846 dc.BeginDrawing();
847 dc.SetBrush(*wxWHITE_BRUSH);
848
849 if (m_cellsize <= 2)
850 {
851 // no grid
852 dc.SetPen(*wxWHITE_PEN);
853 dc.DrawRectangle(x, y, w, h);
854 }
855 else
856 {
857 x = CellToX(i0);
858 y = CellToY(j0);
859 w = CellToX(i1 + 1) - x + 1;
860 h = CellToY(j1 + 1) - y + 1;
861
862 dc.SetPen(*wxLIGHT_GREY_PEN);
863 for (wxInt32 yy = y; yy <= (y + h - m_cellsize); yy += m_cellsize)
864 dc.DrawRectangle(x, yy, w, m_cellsize + 1);
865 for (wxInt32 xx = x; xx <= (x + w - m_cellsize); xx += m_cellsize)
866 dc.DrawLine(xx, y, xx, y + h);
867 }
868
869 // draw all alive cells
870 dc.SetPen(*wxBLACK_PEN);
871 dc.SetBrush(*wxBLACK_BRUSH);
872
873 while (!done)
874 {
875 for (size_t m = 0; m < ncells; m++)
876 DrawCell(cells[m].i, cells[m].j, dc);
877
878 done = m_life->FindMore(&cells, &ncells);
879 }
880
881 // last set
882 for (size_t m = 0; m < ncells; m++)
883 DrawCell(cells[m].i, cells[m].j, dc);
884
885 dc.EndDrawing();
886 }
887
888 void LifeCanvas::OnMouse(wxMouseEvent& event)
889 {
890 if (!m_interactive)
891 return;
892
893 // which cell are we pointing at?
894 wxInt32 i = XToCell( event.GetX() );
895 wxInt32 j = YToCell( event.GetY() );
896
897 #if wxUSE_STATUSBAR
898 // set statusbar text
899 wxString msg;
900 msg.Printf(_("Cell: (%d, %d)"), i, j);
901 ((LifeFrame *) wxGetApp().GetTopWindow())->SetStatusText(msg, 1);
902 #endif // wxUSE_STATUSBAR
903
904 // NOTE that wxMouseEvent::LeftDown() and wxMouseEvent::LeftIsDown()
905 // have different semantics. The first one is used to signal that the
906 // button was just pressed (i.e., in "button down" events); the second
907 // one just describes the current status of the button, independently
908 // of the mouse event type. LeftIsDown is typically used in "mouse
909 // move" events, to test if the button is _still_ pressed.
910
911 // is the button down?
912 if (!event.LeftIsDown())
913 {
914 m_status = MOUSE_NOACTION;
915 return;
916 }
917
918 // was it pressed just now?
919 if (event.LeftDown())
920 {
921 // yes: start a new action and toggle this cell
922 m_status = (m_life->IsAlive(i, j)? MOUSE_ERASING : MOUSE_DRAWING);
923
924 m_mi = i;
925 m_mj = j;
926 m_life->SetCell(i, j, m_status == MOUSE_DRAWING);
927 DrawCell(i, j, m_status == MOUSE_DRAWING);
928 }
929 else if ((m_mi != i) || (m_mj != j))
930 {
931 // no: continue ongoing action
932 bool alive = (m_status == MOUSE_DRAWING);
933
934 // prepare DC and pen + brush to optimize drawing
935 wxClientDC dc(this);
936 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
937 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
938 dc.BeginDrawing();
939
940 // draw a line of cells using Bresenham's algorithm
941 wxInt32 d, ii, jj, di, ai, si, dj, aj, sj;
942 di = i - m_mi;
943 ai = abs(di) << 1;
944 si = (di < 0)? -1 : 1;
945 dj = j - m_mj;
946 aj = abs(dj) << 1;
947 sj = (dj < 0)? -1 : 1;
948
949 ii = m_mi;
950 jj = m_mj;
951
952 if (ai > aj)
953 {
954 // iterate over i
955 d = aj - (ai >> 1);
956
957 while (ii != i)
958 {
959 m_life->SetCell(ii, jj, alive);
960 DrawCell(ii, jj, dc);
961 if (d >= 0)
962 {
963 jj += sj;
964 d -= ai;
965 }
966 ii += si;
967 d += aj;
968 }
969 }
970 else
971 {
972 // iterate over j
973 d = ai - (aj >> 1);
974
975 while (jj != j)
976 {
977 m_life->SetCell(ii, jj, alive);
978 DrawCell(ii, jj, dc);
979 if (d >= 0)
980 {
981 ii += si;
982 d -= aj;
983 }
984 jj += sj;
985 d += ai;
986 }
987 }
988
989 // last cell
990 m_life->SetCell(ii, jj, alive);
991 DrawCell(ii, jj, dc);
992 m_mi = ii;
993 m_mj = jj;
994
995 dc.EndDrawing();
996 }
997
998 ((LifeFrame *) wxGetApp().GetTopWindow())->UpdateInfoText();
999 }
1000
1001 void LifeCanvas::OnSize(wxSizeEvent& event)
1002 {
1003 // find center
1004 wxInt32 cx = m_viewportX + m_viewportW / 2;
1005 wxInt32 cy = m_viewportY + m_viewportH / 2;
1006
1007 // get new size
1008 wxCoord w = event.GetSize().GetX();
1009 wxCoord h = event.GetSize().GetY();
1010 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
1011 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
1012
1013 // recenter
1014 m_viewportX = cx - m_viewportW / 2;
1015 m_viewportY = cy - m_viewportH / 2;
1016
1017 // scrollbars
1018 if (m_interactive)
1019 {
1020 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1021 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1022 m_thumbX = m_viewportW;
1023 m_thumbY = m_viewportH;
1024 }
1025
1026 // allow default processing
1027 event.Skip();
1028 }
1029
1030 void LifeCanvas::OnScroll(wxScrollWinEvent& event)
1031 {
1032 WXTYPE type = (WXTYPE)event.GetEventType();
1033 int pos = event.GetPosition();
1034 int orient = event.GetOrientation();
1035
1036 // calculate scroll increment
1037 int scrollinc = 0;
1038 if (type == wxEVT_SCROLLWIN_TOP)
1039 {
1040 if (orient == wxHORIZONTAL)
1041 scrollinc = -m_viewportW;
1042 else
1043 scrollinc = -m_viewportH;
1044 }
1045 else
1046 if (type == wxEVT_SCROLLWIN_BOTTOM)
1047 {
1048 if (orient == wxHORIZONTAL)
1049 scrollinc = m_viewportW;
1050 else
1051 scrollinc = m_viewportH;
1052 }
1053 else
1054 if (type == wxEVT_SCROLLWIN_LINEUP)
1055 {
1056 scrollinc = -1;
1057 }
1058 else
1059 if (type == wxEVT_SCROLLWIN_LINEDOWN)
1060 {
1061 scrollinc = +1;
1062 }
1063 else
1064 if (type == wxEVT_SCROLLWIN_PAGEUP)
1065 {
1066 scrollinc = -10;
1067 }
1068 else
1069 if (type == wxEVT_SCROLLWIN_PAGEDOWN)
1070 {
1071 scrollinc = +10;
1072 }
1073 else
1074 if (type == wxEVT_SCROLLWIN_THUMBTRACK)
1075 {
1076 if (orient == wxHORIZONTAL)
1077 {
1078 scrollinc = pos - m_thumbX;
1079 m_thumbX = pos;
1080 }
1081 else
1082 {
1083 scrollinc = pos - m_thumbY;
1084 m_thumbY = pos;
1085 }
1086 }
1087 else
1088 if (type == wxEVT_SCROLLWIN_THUMBRELEASE)
1089 {
1090 m_thumbX = m_viewportW;
1091 m_thumbY = m_viewportH;
1092 }
1093
1094 #if defined(__WXGTK__) || defined(__WXMOTIF__)
1095 // wxGTK and wxMotif update the thumb automatically (wxMSW doesn't);
1096 // so reset it back as we always want it to be in the same position.
1097 if (type != wxEVT_SCROLLWIN_THUMBTRACK)
1098 {
1099 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1100 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1101 }
1102 #endif
1103
1104 if (scrollinc == 0) return;
1105
1106 // scroll the window and adjust the viewport
1107 if (orient == wxHORIZONTAL)
1108 {
1109 m_viewportX += scrollinc;
1110 ScrollWindow( -m_cellsize * scrollinc, 0, (const wxRect *) NULL);
1111 }
1112 else
1113 {
1114 m_viewportY += scrollinc;
1115 ScrollWindow( 0, -m_cellsize * scrollinc, (const wxRect *) NULL);
1116 }
1117 }
1118
1119 void LifeCanvas::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
1120 {
1121 // do nothing. I just don't want the background to be erased, you know.
1122 }
1123
1124