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