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