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