Applied patch [ 804322 ] Fixes for the "life" demo
[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(_T(""), wxMENU_TEAROFF);
198 wxMenu *menuView = new wxMenu(_T(""), wxMENU_TEAROFF);
199 wxMenu *menuGame = new wxMenu(_T(""), 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()->Enable(ID_START, !m_running);
359 GetMenuBar()->Enable(ID_STEP, !m_running);
360 GetMenuBar()->Enable(ID_STOP, m_running);
361 GetMenuBar()->Enable(ID_TOPSPEED, !m_topspeed);
362
363 // zooming
364 int cellsize = m_canvas->GetCellSize();
365 GetToolBar()->EnableTool(ID_ZOOMIN, cellsize < 32);
366 GetToolBar()->EnableTool(ID_ZOOMOUT, cellsize > 1);
367 GetMenuBar()->Enable(ID_ZOOMIN, cellsize < 32);
368 GetMenuBar()->Enable(ID_ZOOMOUT, cellsize > 1);
369 }
370
371 // Event handlers -----------------------------------------------------------
372
373 // OnMenu handles all events which don't have their own event handler
374 void LifeFrame::OnMenu(wxCommandEvent& event)
375 {
376 switch (event.GetId())
377 {
378 case ID_NEW:
379 {
380 // stop if it was running
381 OnStop();
382 m_life->Clear();
383 m_canvas->Recenter(0, 0);
384 m_tics = 0;
385 UpdateInfoText();
386 break;
387 }
388 case ID_ABOUT:
389 {
390 LifeAboutDialog dialog(this);
391 dialog.ShowModal();
392 break;
393 }
394 case ID_EXIT:
395 {
396 // TRUE is to force the frame to close
397 Close(TRUE);
398 break;
399 }
400 case ID_SHOWNAV :
401 {
402 bool checked = GetMenuBar()->GetMenu(1)->IsChecked(ID_SHOWNAV);
403 m_navigator->Show(checked);
404 break;
405 }
406 case ID_INFO:
407 {
408 wxString desc = m_life->GetDescription();
409
410 if ( desc.IsEmpty() )
411 desc = _("Not available");
412
413 // should we make the description editable here?
414 wxMessageBox(desc, _("Description"), wxOK | wxICON_INFORMATION);
415
416 break;
417 }
418 case ID_START : OnStart(); break;
419 case ID_STEP : OnStep(); break;
420 case ID_STOP : OnStop(); break;
421 case ID_TOPSPEED:
422 {
423 m_running = TRUE;
424 m_topspeed = TRUE;
425 UpdateUI();
426 while (m_running && m_topspeed)
427 {
428 OnStep();
429 wxYield();
430 }
431 break;
432 }
433 }
434 }
435
436 void LifeFrame::OnOpen(wxCommandEvent& WXUNUSED(event))
437 {
438 wxFileDialog filedlg(this,
439 _("Choose a file to open"),
440 _(""),
441 _(""),
442 _("Life patterns (*.lif)|*.lif|All files (*.*)|*.*"),
443 wxOPEN | wxFILE_MUST_EXIST);
444
445 if (filedlg.ShowModal() == wxID_OK)
446 {
447 wxFileInputStream stream(filedlg.GetPath());
448 LifeReader reader(stream);
449
450 // the reader handles errors itself, no need to do anything here
451 if (reader.IsOk())
452 {
453 // stop if running and put the pattern
454 OnStop();
455 m_life->Clear();
456 m_life->SetPattern(reader.GetPattern());
457
458 // recenter canvas
459 m_canvas->Recenter(0, 0);
460 m_tics = 0;
461 UpdateInfoText();
462 }
463 }
464 }
465
466 void LifeFrame::OnSamples(wxCommandEvent& WXUNUSED(event))
467 {
468 // stop if it was running
469 OnStop();
470
471 // dialog box
472 LifeSamplesDialog dialog(this);
473
474 if (dialog.ShowModal() == wxID_OK)
475 {
476 const LifePattern pattern = dialog.GetPattern();
477
478 // put the pattern
479 m_life->Clear();
480 m_life->SetPattern(pattern);
481
482 // recenter canvas
483 m_canvas->Recenter(0, 0);
484 m_tics = 0;
485 UpdateInfoText();
486 }
487 }
488
489 void LifeFrame::OnZoom(wxCommandEvent& event)
490 {
491 int cellsize = m_canvas->GetCellSize();
492
493 if ((event.GetId() == ID_ZOOMIN) && cellsize < 32)
494 {
495 m_canvas->SetCellSize(cellsize * 2);
496 UpdateUI();
497 }
498 else if ((event.GetId() == ID_ZOOMOUT) && cellsize > 1)
499 {
500 m_canvas->SetCellSize(cellsize / 2);
501 UpdateUI();
502 }
503 }
504
505 void LifeFrame::OnNavigate(wxCommandEvent& event)
506 {
507 LifeCell c;
508
509 switch (event.GetId())
510 {
511 case ID_NORTH: c = m_life->FindNorth(); break;
512 case ID_SOUTH: c = m_life->FindSouth(); break;
513 case ID_WEST: c = m_life->FindWest(); break;
514 case ID_EAST: c = m_life->FindEast(); break;
515 case ID_CENTER: c = m_life->FindCenter(); break;
516 case ID_ORIGIN: c.i = c.j = 0; break;
517 }
518
519 m_canvas->Recenter(c.i, c.j);
520 }
521
522 void LifeFrame::OnSlider(wxScrollEvent& event)
523 {
524 m_interval = event.GetPosition() * 100;
525
526 if (m_running)
527 {
528 OnStop();
529 OnStart();
530 }
531
532 UpdateInfoText();
533 }
534
535 void LifeFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
536 {
537 OnStep();
538 }
539
540 void LifeFrame::OnClose(wxCloseEvent& WXUNUSED(event))
541 {
542 // Stop if it was running; this is absolutely needed because
543 // the frame won't be actually destroyed until there are no
544 // more pending events, and this in turn won't ever happen
545 // if the timer is running faster than the window can redraw.
546 OnStop();
547 Destroy();
548 }
549
550 void LifeFrame::OnStart()
551 {
552 if (!m_running)
553 {
554 m_timer->Start(m_interval);
555 m_running = TRUE;
556 UpdateUI();
557 }
558 }
559
560 void LifeFrame::OnStop()
561 {
562 if (m_running)
563 {
564 m_timer->Stop();
565 m_running = FALSE;
566 m_topspeed = FALSE;
567 UpdateUI();
568 }
569 }
570
571 void LifeFrame::OnStep()
572 {
573 if (m_life->NextTic())
574 m_tics++;
575 else
576 OnStop();
577
578 m_canvas->DrawChanged();
579 UpdateInfoText();
580 }
581
582
583 // --------------------------------------------------------------------------
584 // LifeNavigator miniframe
585 // --------------------------------------------------------------------------
586
587 LifeNavigator::LifeNavigator(wxWindow *parent)
588 : wxMiniFrame(parent, -1,
589 _("Navigation"),
590 wxDefaultPosition,
591 wxDefaultSize,
592 wxCAPTION | wxSIMPLE_BORDER)
593 {
594 wxPanel *panel = new wxPanel(this, -1);
595 wxBoxSizer *sizer1 = new wxBoxSizer(wxVERTICAL);
596 wxBoxSizer *sizer2 = new wxBoxSizer(wxHORIZONTAL);
597
598 // create bitmaps and masks for the buttons
599 wxBitmap
600 bmpn = wxBITMAP(north),
601 bmpw = wxBITMAP(west),
602 bmpc = wxBITMAP(center),
603 bmpe = wxBITMAP(east),
604 bmps = wxBITMAP(south);
605
606 #if !defined(__WXGTK__) && !defined(__WXMOTIF__) && !defined(__WXMAC__)
607 bmpn.SetMask(new wxMask(bmpn, *wxLIGHT_GREY));
608 bmpw.SetMask(new wxMask(bmpw, *wxLIGHT_GREY));
609 bmpc.SetMask(new wxMask(bmpc, *wxLIGHT_GREY));
610 bmpe.SetMask(new wxMask(bmpe, *wxLIGHT_GREY));
611 bmps.SetMask(new wxMask(bmps, *wxLIGHT_GREY));
612 #endif
613
614 // create the buttons and attach tooltips to them
615 wxBitmapButton
616 *bn = new wxBitmapButton(panel, ID_NORTH, bmpn),
617 *bw = new wxBitmapButton(panel, ID_WEST , bmpw),
618 *bc = new wxBitmapButton(panel, ID_CENTER, bmpc),
619 *be = new wxBitmapButton(panel, ID_EAST , bmpe),
620 *bs = new wxBitmapButton(panel, ID_SOUTH, bmps);
621
622 #if wxUSE_TOOLTIPS
623 bn->SetToolTip(_("Find northernmost cell"));
624 bw->SetToolTip(_("Find westernmost cell"));
625 bc->SetToolTip(_("Find center of mass"));
626 be->SetToolTip(_("Find easternmost cell"));
627 bs->SetToolTip(_("Find southernmost cell"));
628 #endif
629
630 // add buttons to sizers
631 sizer2->Add( bw, 0, wxCENTRE | wxWEST, 4 );
632 sizer2->Add( bc, 0, wxCENTRE);
633 sizer2->Add( be, 0, wxCENTRE | wxEAST, 4 );
634 sizer1->Add( bn, 0, wxCENTRE | wxNORTH, 4 );
635 sizer1->Add( sizer2 );
636 sizer1->Add( bs, 0, wxCENTRE | wxSOUTH, 4 );
637
638 // set the panel and miniframe size
639 panel->SetSizer(sizer1);
640 panel->SetAutoLayout(TRUE);
641
642 sizer1->Fit(panel);
643 SetClientSize(panel->GetSize());
644 wxSize sz = GetSize();
645 SetSizeHints(sz.x, sz.y, sz.x, sz.y);
646
647 // move it to a sensible position
648 wxRect parentRect = parent->GetRect();
649 wxSize childSize = GetSize();
650 int x = parentRect.GetX() +
651 parentRect.GetWidth();
652 int y = parentRect.GetY() +
653 (parentRect.GetHeight() - childSize.GetHeight()) / 4;
654 Move(x, y);
655
656 // done
657 Show(TRUE);
658 }
659
660 void LifeNavigator::OnClose(wxCloseEvent& event)
661 {
662 // avoid if we can
663 if (event.CanVeto())
664 event.Veto();
665 else
666 Destroy();
667 }
668
669
670 // --------------------------------------------------------------------------
671 // LifeCanvas
672 // --------------------------------------------------------------------------
673
674 // canvas constructor
675 LifeCanvas::LifeCanvas(wxWindow *parent, Life *life, bool interactive)
676 : wxWindow(parent, -1, wxPoint(0, 0), wxSize(100, 100),
677 wxSUNKEN_BORDER)
678 {
679 m_life = life;
680 m_interactive = interactive;
681 m_cellsize = 8;
682 m_status = MOUSE_NOACTION;
683 m_viewportX = 0;
684 m_viewportY = 0;
685 m_viewportH = 0;
686 m_viewportW = 0;
687
688 if (m_interactive)
689 SetCursor(*wxCROSS_CURSOR);
690
691 // reduce flicker if wxEVT_ERASE_BACKGROUND is not available
692 SetBackgroundColour(*wxWHITE);
693 }
694
695 LifeCanvas::~LifeCanvas()
696 {
697 delete m_life;
698 }
699
700 // recenter at the given position
701 void LifeCanvas::Recenter(wxInt32 i, wxInt32 j)
702 {
703 m_viewportX = i - m_viewportW / 2;
704 m_viewportY = j - m_viewportH / 2;
705
706 // redraw everything
707 Refresh(FALSE);
708 }
709
710 // set the cell size and refresh display
711 void LifeCanvas::SetCellSize(int cellsize)
712 {
713 m_cellsize = cellsize;
714
715 // find current center
716 wxInt32 cx = m_viewportX + m_viewportW / 2;
717 wxInt32 cy = m_viewportY + m_viewportH / 2;
718
719 // get current canvas size and adjust viewport accordingly
720 int w, h;
721 GetClientSize(&w, &h);
722 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
723 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
724
725 // recenter
726 m_viewportX = cx - m_viewportW / 2;
727 m_viewportY = cy - m_viewportH / 2;
728
729 // adjust scrollbars
730 if (m_interactive)
731 {
732 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
733 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
734 m_thumbX = m_viewportW;
735 m_thumbY = m_viewportH;
736 }
737
738 Refresh(FALSE);
739 }
740
741 // draw a cell
742 void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, bool alive)
743 {
744 wxClientDC dc(this);
745
746 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
747 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
748
749 dc.BeginDrawing();
750 DrawCell(i, j, dc);
751 dc.EndDrawing();
752 }
753
754 void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, wxDC &dc)
755 {
756 wxCoord x = CellToX(i);
757 wxCoord y = CellToY(j);
758
759 // if cellsize is 1 or 2, there will be no grid
760 switch (m_cellsize)
761 {
762 case 1:
763 dc.DrawPoint(x, y);
764 break;
765 case 2:
766 dc.DrawRectangle(x, y, 2, 2);
767 break;
768 default:
769 dc.DrawRectangle(x + 1, y + 1, m_cellsize - 1, m_cellsize - 1);
770 }
771 }
772
773 // draw all changed cells
774 void LifeCanvas::DrawChanged()
775 {
776 wxClientDC dc(this);
777
778 size_t ncells;
779 LifeCell *cells;
780 bool done = FALSE;
781
782 m_life->BeginFind(m_viewportX,
783 m_viewportY,
784 m_viewportX + m_viewportW,
785 m_viewportY + m_viewportH,
786 TRUE);
787
788 dc.BeginDrawing();
789
790 if (m_cellsize == 1)
791 {
792 dc.SetPen(*wxBLACK_PEN);
793 }
794 else
795 {
796 dc.SetPen(*wxTRANSPARENT_PEN);
797 dc.SetBrush(*wxBLACK_BRUSH);
798 }
799 dc.SetLogicalFunction(wxINVERT);
800
801 while (!done)
802 {
803 done = m_life->FindMore(&cells, &ncells);
804
805 for (size_t m = 0; m < ncells; m++)
806 DrawCell(cells[m].i, cells[m].j, dc);
807 }
808 dc.EndDrawing();
809 }
810
811 // event handlers
812 void LifeCanvas::OnPaint(wxPaintEvent& event)
813 {
814 wxPaintDC dc(this);
815 wxRect rect = GetUpdateRegion().GetBox();
816 wxCoord x, y, w, h;
817 wxInt32 i0, j0, i1, j1;
818
819 // find damaged area
820 x = rect.GetX();
821 y = rect.GetY();
822 w = rect.GetWidth();
823 h = rect.GetHeight();
824
825 i0 = XToCell(x);
826 j0 = YToCell(y);
827 i1 = XToCell(x + w - 1);
828 j1 = YToCell(y + h - 1);
829
830 size_t ncells;
831 LifeCell *cells;
832 bool done = FALSE;
833
834 m_life->BeginFind(i0, j0, i1, j1, FALSE);
835 done = m_life->FindMore(&cells, &ncells);
836
837 // erase all damaged cells and draw the grid
838 dc.BeginDrawing();
839 dc.SetBrush(*wxWHITE_BRUSH);
840
841 if (m_cellsize <= 2)
842 {
843 // no grid
844 dc.SetPen(*wxWHITE_PEN);
845 dc.DrawRectangle(x, y, w, h);
846 }
847 else
848 {
849 x = CellToX(i0);
850 y = CellToY(j0);
851 w = CellToX(i1 + 1) - x + 1;
852 h = CellToY(j1 + 1) - y + 1;
853
854 dc.SetPen(*wxLIGHT_GREY_PEN);
855 for (wxInt32 yy = y; yy <= (y + h - m_cellsize); yy += m_cellsize)
856 dc.DrawRectangle(x, yy, w, m_cellsize + 1);
857 for (wxInt32 xx = x; xx <= (x + w - m_cellsize); xx += m_cellsize)
858 dc.DrawLine(xx, y, xx, y + h);
859 }
860
861 // draw all alive cells
862 dc.SetPen(*wxBLACK_PEN);
863 dc.SetBrush(*wxBLACK_BRUSH);
864
865 while (!done)
866 {
867 for (size_t m = 0; m < ncells; m++)
868 DrawCell(cells[m].i, cells[m].j, dc);
869
870 done = m_life->FindMore(&cells, &ncells);
871 }
872
873 // last set
874 for (size_t m = 0; m < ncells; m++)
875 DrawCell(cells[m].i, cells[m].j, dc);
876
877 dc.EndDrawing();
878 }
879
880 void LifeCanvas::OnMouse(wxMouseEvent& event)
881 {
882 if (!m_interactive)
883 return;
884
885 // which cell are we pointing at?
886 wxInt32 i = XToCell( event.GetX() );
887 wxInt32 j = YToCell( event.GetY() );
888
889 // set statusbar text
890 wxString msg;
891 msg.Printf(_("Cell: (%d, %d)"), i, j);
892 ((LifeFrame *) wxGetApp().GetTopWindow())->SetStatusText(msg, 1);
893
894 // NOTE that wxMouseEvent::LeftDown() and wxMouseEvent::LeftIsDown()
895 // have different semantics. The first one is used to signal that the
896 // button was just pressed (i.e., in "button down" events); the second
897 // one just describes the current status of the button, independently
898 // of the mouse event type. LeftIsDown is typically used in "mouse
899 // move" events, to test if the button is _still_ pressed.
900
901 // is the button down?
902 if (!event.LeftIsDown())
903 {
904 m_status = MOUSE_NOACTION;
905 return;
906 }
907
908 // was it pressed just now?
909 if (event.LeftDown())
910 {
911 // yes: start a new action and toggle this cell
912 m_status = (m_life->IsAlive(i, j)? MOUSE_ERASING : MOUSE_DRAWING);
913
914 m_mi = i;
915 m_mj = j;
916 m_life->SetCell(i, j, m_status == MOUSE_DRAWING);
917 DrawCell(i, j, m_status == MOUSE_DRAWING);
918 }
919 else if ((m_mi != i) || (m_mj != j))
920 {
921 // no: continue ongoing action
922 bool alive = (m_status == MOUSE_DRAWING);
923
924 // prepare DC and pen + brush to optimize drawing
925 wxClientDC dc(this);
926 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
927 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
928 dc.BeginDrawing();
929
930 // draw a line of cells using Bresenham's algorithm
931 wxInt32 d, ii, jj, di, ai, si, dj, aj, sj;
932 di = i - m_mi;
933 ai = abs(di) << 1;
934 si = (di < 0)? -1 : 1;
935 dj = j - m_mj;
936 aj = abs(dj) << 1;
937 sj = (dj < 0)? -1 : 1;
938
939 ii = m_mi;
940 jj = m_mj;
941
942 if (ai > aj)
943 {
944 // iterate over i
945 d = aj - (ai >> 1);
946
947 while (ii != i)
948 {
949 m_life->SetCell(ii, jj, alive);
950 DrawCell(ii, jj, dc);
951 if (d >= 0)
952 {
953 jj += sj;
954 d -= ai;
955 }
956 ii += si;
957 d += aj;
958 }
959 }
960 else
961 {
962 // iterate over j
963 d = ai - (aj >> 1);
964
965 while (jj != j)
966 {
967 m_life->SetCell(ii, jj, alive);
968 DrawCell(ii, jj, dc);
969 if (d >= 0)
970 {
971 ii += si;
972 d -= aj;
973 }
974 jj += sj;
975 d += ai;
976 }
977 }
978
979 // last cell
980 m_life->SetCell(ii, jj, alive);
981 DrawCell(ii, jj, dc);
982 m_mi = ii;
983 m_mj = jj;
984
985 dc.EndDrawing();
986 }
987
988 ((LifeFrame *) wxGetApp().GetTopWindow())->UpdateInfoText();
989 }
990
991 void LifeCanvas::OnSize(wxSizeEvent& event)
992 {
993 // find center
994 wxInt32 cx = m_viewportX + m_viewportW / 2;
995 wxInt32 cy = m_viewportY + m_viewportH / 2;
996
997 // get new size
998 wxCoord w = event.GetSize().GetX();
999 wxCoord h = event.GetSize().GetY();
1000 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
1001 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
1002
1003 // recenter
1004 m_viewportX = cx - m_viewportW / 2;
1005 m_viewportY = cy - m_viewportH / 2;
1006
1007 // scrollbars
1008 if (m_interactive)
1009 {
1010 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1011 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1012 m_thumbX = m_viewportW;
1013 m_thumbY = m_viewportH;
1014 }
1015
1016 // allow default processing
1017 event.Skip();
1018 }
1019
1020 void LifeCanvas::OnScroll(wxScrollWinEvent& event)
1021 {
1022 WXTYPE type = event.GetEventType();
1023 int pos = event.GetPosition();
1024 int orient = event.GetOrientation();
1025
1026 // calculate scroll increment
1027 int scrollinc = 0;
1028 if (type == wxEVT_SCROLLWIN_TOP)
1029 {
1030 if (orient == wxHORIZONTAL)
1031 scrollinc = -m_viewportW;
1032 else
1033 scrollinc = -m_viewportH;
1034 }
1035 else
1036 if (type == wxEVT_SCROLLWIN_BOTTOM)
1037 {
1038 if (orient == wxHORIZONTAL)
1039 scrollinc = m_viewportW;
1040 else
1041 scrollinc = m_viewportH;
1042 }
1043 else
1044 if (type == wxEVT_SCROLLWIN_LINEUP)
1045 {
1046 scrollinc = -1;
1047 }
1048 else
1049 if (type == wxEVT_SCROLLWIN_LINEDOWN)
1050 {
1051 scrollinc = +1;
1052 }
1053 else
1054 if (type == wxEVT_SCROLLWIN_PAGEUP)
1055 {
1056 scrollinc = -10;
1057 }
1058 else
1059 if (type == wxEVT_SCROLLWIN_PAGEDOWN)
1060 {
1061 scrollinc = +10;
1062 }
1063 else
1064 if (type == wxEVT_SCROLLWIN_THUMBTRACK)
1065 {
1066 if (orient == wxHORIZONTAL)
1067 {
1068 scrollinc = pos - m_thumbX;
1069 m_thumbX = pos;
1070 }
1071 else
1072 {
1073 scrollinc = pos - m_thumbY;
1074 m_thumbY = pos;
1075 }
1076 }
1077 else
1078 if (type == wxEVT_SCROLLWIN_THUMBRELEASE)
1079 {
1080 m_thumbX = m_viewportW;
1081 m_thumbY = m_viewportH;
1082 }
1083
1084 #if defined(__WXGTK__) || defined(__WXMOTIF__)
1085 // wxGTK and wxMotif update the thumb automatically (wxMSW doesn't);
1086 // so reset it back as we always want it to be in the same position.
1087 if (type != wxEVT_SCROLLWIN_THUMBTRACK)
1088 {
1089 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1090 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1091 }
1092 #endif
1093
1094 if (scrollinc == 0) return;
1095
1096 // scroll the window and adjust the viewport
1097 if (orient == wxHORIZONTAL)
1098 {
1099 m_viewportX += scrollinc;
1100 ScrollWindow( -m_cellsize * scrollinc, 0, (const wxRect *) NULL);
1101 }
1102 else
1103 {
1104 m_viewportY += scrollinc;
1105 ScrollWindow( 0, -m_cellsize * scrollinc, (const wxRect *) NULL);
1106 }
1107 }
1108
1109 void LifeCanvas::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
1110 {
1111 // do nothing. I just don't want the background to be erased, you know.
1112 }
1113
1114