]> git.saurik.com Git - wxWidgets.git/blame_incremental - demos/life/life.cpp
show the resize cursor when the mouse is above the grip and not only when it's just...
[wxWidgets.git] / demos / life / life.cpp
... / ...
CommitLineData
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
70enum
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
109BEGIN_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)
132END_EVENT_TABLE()
133
134BEGIN_EVENT_TABLE(LifeNavigator, wxMiniFrame)
135 EVT_CLOSE ( LifeNavigator::OnClose)
136END_EVENT_TABLE()
137
138BEGIN_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)
147END_EVENT_TABLE()
148
149
150// Create a new application object
151IMPLEMENT_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
168bool 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
191LifeFrame::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
334LifeFrame::~LifeFrame()
335{
336 delete m_timer;
337}
338
339void 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.
353void 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
373void 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
435void 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
465void 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
488void 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
504void 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
521void 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
534void LifeFrame::OnTimer(wxTimerEvent& WXUNUSED(event))
535{
536 OnStep();
537}
538
539void 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
549void LifeFrame::OnStart()
550{
551 if (!m_running)
552 {
553 m_timer->Start(m_interval);
554 m_running = TRUE;
555 UpdateUI();
556 }
557}
558
559void 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
570void 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
586LifeNavigator::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 miniframe size
638 panel->SetSizer(sizer1);
639 panel->SetAutoLayout(TRUE);
640 sizer1->Fit(this);
641 sizer1->SetSizeHints(this);
642
643 // move it to a sensible position
644 wxRect parentRect = parent->GetRect();
645 wxSize childSize = GetSize();
646 int x = parentRect.GetX() +
647 parentRect.GetWidth();
648 int y = parentRect.GetY() +
649 (parentRect.GetHeight() - childSize.GetHeight()) / 4;
650 Move(x, y);
651
652 // done
653 Show(TRUE);
654}
655
656void LifeNavigator::OnClose(wxCloseEvent& event)
657{
658 // avoid if we can
659 if (event.CanVeto())
660 event.Veto();
661 else
662 Destroy();
663}
664
665
666// --------------------------------------------------------------------------
667// LifeCanvas
668// --------------------------------------------------------------------------
669
670// canvas constructor
671LifeCanvas::LifeCanvas(wxWindow *parent, Life *life, bool interactive)
672 : wxWindow(parent, -1, wxPoint(0, 0), wxSize(100, 100),
673 wxSUNKEN_BORDER)
674{
675 m_life = life;
676 m_interactive = interactive;
677 m_cellsize = 8;
678 m_status = MOUSE_NOACTION;
679 m_viewportX = 0;
680 m_viewportY = 0;
681 m_viewportH = 0;
682 m_viewportW = 0;
683
684 if (m_interactive)
685 SetCursor(*wxCROSS_CURSOR);
686
687 // reduce flicker if wxEVT_ERASE_BACKGROUND is not available
688 SetBackgroundColour(*wxWHITE);
689}
690
691LifeCanvas::~LifeCanvas()
692{
693 delete m_life;
694}
695
696// recenter at the given position
697void LifeCanvas::Recenter(wxInt32 i, wxInt32 j)
698{
699 m_viewportX = i - m_viewportW / 2;
700 m_viewportY = j - m_viewportH / 2;
701
702 // redraw everything
703 Refresh(FALSE);
704}
705
706// set the cell size and refresh display
707void LifeCanvas::SetCellSize(int cellsize)
708{
709 m_cellsize = cellsize;
710
711 // find current center
712 wxInt32 cx = m_viewportX + m_viewportW / 2;
713 wxInt32 cy = m_viewportY + m_viewportH / 2;
714
715 // get current canvas size and adjust viewport accordingly
716 int w, h;
717 GetClientSize(&w, &h);
718 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
719 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
720
721 // recenter
722 m_viewportX = cx - m_viewportW / 2;
723 m_viewportY = cy - m_viewportH / 2;
724
725 // adjust scrollbars
726 if (m_interactive)
727 {
728 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
729 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
730 m_thumbX = m_viewportW;
731 m_thumbY = m_viewportH;
732 }
733
734 Refresh(FALSE);
735}
736
737// draw a cell
738void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, bool alive)
739{
740 wxClientDC dc(this);
741
742 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
743 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
744
745 dc.BeginDrawing();
746 DrawCell(i, j, dc);
747 dc.EndDrawing();
748}
749
750void LifeCanvas::DrawCell(wxInt32 i, wxInt32 j, wxDC &dc)
751{
752 wxCoord x = CellToX(i);
753 wxCoord y = CellToY(j);
754
755 // if cellsize is 1 or 2, there will be no grid
756 switch (m_cellsize)
757 {
758 case 1:
759 dc.DrawPoint(x, y);
760 break;
761 case 2:
762 dc.DrawRectangle(x, y, 2, 2);
763 break;
764 default:
765 dc.DrawRectangle(x + 1, y + 1, m_cellsize - 1, m_cellsize - 1);
766 }
767}
768
769// draw all changed cells
770void LifeCanvas::DrawChanged()
771{
772 wxClientDC dc(this);
773
774 size_t ncells;
775 LifeCell *cells;
776 bool done = FALSE;
777
778 m_life->BeginFind(m_viewportX,
779 m_viewportY,
780 m_viewportX + m_viewportW,
781 m_viewportY + m_viewportH,
782 TRUE);
783
784 dc.BeginDrawing();
785
786 if (m_cellsize == 1)
787 {
788 dc.SetPen(*wxBLACK_PEN);
789 }
790 else
791 {
792 dc.SetPen(*wxTRANSPARENT_PEN);
793 dc.SetBrush(*wxBLACK_BRUSH);
794 }
795 dc.SetLogicalFunction(wxINVERT);
796
797 while (!done)
798 {
799 done = m_life->FindMore(&cells, &ncells);
800
801 for (size_t m = 0; m < ncells; m++)
802 DrawCell(cells[m].i, cells[m].j, dc);
803 }
804 dc.EndDrawing();
805}
806
807// event handlers
808void LifeCanvas::OnPaint(wxPaintEvent& event)
809{
810 wxPaintDC dc(this);
811 wxRect rect = GetUpdateRegion().GetBox();
812 wxCoord x, y, w, h;
813 wxInt32 i0, j0, i1, j1;
814
815 // find damaged area
816 x = rect.GetX();
817 y = rect.GetY();
818 w = rect.GetWidth();
819 h = rect.GetHeight();
820
821 i0 = XToCell(x);
822 j0 = YToCell(y);
823 i1 = XToCell(x + w - 1);
824 j1 = YToCell(y + h - 1);
825
826 size_t ncells;
827 LifeCell *cells;
828 bool done = FALSE;
829
830 m_life->BeginFind(i0, j0, i1, j1, FALSE);
831 done = m_life->FindMore(&cells, &ncells);
832
833 // erase all damaged cells and draw the grid
834 dc.BeginDrawing();
835 dc.SetBrush(*wxWHITE_BRUSH);
836
837 if (m_cellsize <= 2)
838 {
839 // no grid
840 dc.SetPen(*wxWHITE_PEN);
841 dc.DrawRectangle(x, y, w, h);
842 }
843 else
844 {
845 x = CellToX(i0);
846 y = CellToY(j0);
847 w = CellToX(i1 + 1) - x + 1;
848 h = CellToY(j1 + 1) - y + 1;
849
850 dc.SetPen(*wxLIGHT_GREY_PEN);
851 for (wxInt32 yy = y; yy <= (y + h - m_cellsize); yy += m_cellsize)
852 dc.DrawRectangle(x, yy, w, m_cellsize + 1);
853 for (wxInt32 xx = x; xx <= (x + w - m_cellsize); xx += m_cellsize)
854 dc.DrawLine(xx, y, xx, y + h);
855 }
856
857 // draw all alive cells
858 dc.SetPen(*wxBLACK_PEN);
859 dc.SetBrush(*wxBLACK_BRUSH);
860
861 while (!done)
862 {
863 for (size_t m = 0; m < ncells; m++)
864 DrawCell(cells[m].i, cells[m].j, dc);
865
866 done = m_life->FindMore(&cells, &ncells);
867 }
868
869 // last set
870 for (size_t m = 0; m < ncells; m++)
871 DrawCell(cells[m].i, cells[m].j, dc);
872
873 dc.EndDrawing();
874}
875
876void LifeCanvas::OnMouse(wxMouseEvent& event)
877{
878 if (!m_interactive)
879 return;
880
881 // which cell are we pointing at?
882 wxInt32 i = XToCell( event.GetX() );
883 wxInt32 j = YToCell( event.GetY() );
884
885 // set statusbar text
886 wxString msg;
887 msg.Printf(_("Cell: (%d, %d)"), i, j);
888 ((LifeFrame *) wxGetApp().GetTopWindow())->SetStatusText(msg, 1);
889
890 // NOTE that wxMouseEvent::LeftDown() and wxMouseEvent::LeftIsDown()
891 // have different semantics. The first one is used to signal that the
892 // button was just pressed (i.e., in "button down" events); the second
893 // one just describes the current status of the button, independently
894 // of the mouse event type. LeftIsDown is typically used in "mouse
895 // move" events, to test if the button is _still_ pressed.
896
897 // is the button down?
898 if (!event.LeftIsDown())
899 {
900 m_status = MOUSE_NOACTION;
901 return;
902 }
903
904 // was it pressed just now?
905 if (event.LeftDown())
906 {
907 // yes: start a new action and toggle this cell
908 m_status = (m_life->IsAlive(i, j)? MOUSE_ERASING : MOUSE_DRAWING);
909
910 m_mi = i;
911 m_mj = j;
912 m_life->SetCell(i, j, m_status == MOUSE_DRAWING);
913 DrawCell(i, j, m_status == MOUSE_DRAWING);
914 }
915 else if ((m_mi != i) || (m_mj != j))
916 {
917 // no: continue ongoing action
918 bool alive = (m_status == MOUSE_DRAWING);
919
920 // prepare DC and pen + brush to optimize drawing
921 wxClientDC dc(this);
922 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
923 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
924 dc.BeginDrawing();
925
926 // draw a line of cells using Bresenham's algorithm
927 wxInt32 d, ii, jj, di, ai, si, dj, aj, sj;
928 di = i - m_mi;
929 ai = abs(di) << 1;
930 si = (di < 0)? -1 : 1;
931 dj = j - m_mj;
932 aj = abs(dj) << 1;
933 sj = (dj < 0)? -1 : 1;
934
935 ii = m_mi;
936 jj = m_mj;
937
938 if (ai > aj)
939 {
940 // iterate over i
941 d = aj - (ai >> 1);
942
943 while (ii != i)
944 {
945 m_life->SetCell(ii, jj, alive);
946 DrawCell(ii, jj, dc);
947 if (d >= 0)
948 {
949 jj += sj;
950 d -= ai;
951 }
952 ii += si;
953 d += aj;
954 }
955 }
956 else
957 {
958 // iterate over j
959 d = ai - (aj >> 1);
960
961 while (jj != j)
962 {
963 m_life->SetCell(ii, jj, alive);
964 DrawCell(ii, jj, dc);
965 if (d >= 0)
966 {
967 ii += si;
968 d -= aj;
969 }
970 jj += sj;
971 d += ai;
972 }
973 }
974
975 // last cell
976 m_life->SetCell(ii, jj, alive);
977 DrawCell(ii, jj, dc);
978 m_mi = ii;
979 m_mj = jj;
980
981 dc.EndDrawing();
982 }
983
984 ((LifeFrame *) wxGetApp().GetTopWindow())->UpdateInfoText();
985}
986
987void LifeCanvas::OnSize(wxSizeEvent& event)
988{
989 // find center
990 wxInt32 cx = m_viewportX + m_viewportW / 2;
991 wxInt32 cy = m_viewportY + m_viewportH / 2;
992
993 // get new size
994 wxCoord w = event.GetSize().GetX();
995 wxCoord h = event.GetSize().GetY();
996 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
997 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
998
999 // recenter
1000 m_viewportX = cx - m_viewportW / 2;
1001 m_viewportY = cy - m_viewportH / 2;
1002
1003 // scrollbars
1004 if (m_interactive)
1005 {
1006 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1007 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1008 m_thumbX = m_viewportW;
1009 m_thumbY = m_viewportH;
1010 }
1011
1012 // allow default processing
1013 event.Skip();
1014}
1015
1016void LifeCanvas::OnScroll(wxScrollWinEvent& event)
1017{
1018 WXTYPE type = event.GetEventType();
1019 int pos = event.GetPosition();
1020 int orient = event.GetOrientation();
1021
1022 // calculate scroll increment
1023 int scrollinc = 0;
1024 if (type == wxEVT_SCROLLWIN_TOP)
1025 {
1026 if (orient == wxHORIZONTAL)
1027 scrollinc = -m_viewportW;
1028 else
1029 scrollinc = -m_viewportH;
1030 }
1031 else
1032 if (type == wxEVT_SCROLLWIN_BOTTOM)
1033 {
1034 if (orient == wxHORIZONTAL)
1035 scrollinc = m_viewportW;
1036 else
1037 scrollinc = m_viewportH;
1038 }
1039 else
1040 if (type == wxEVT_SCROLLWIN_LINEUP)
1041 {
1042 scrollinc = -1;
1043 }
1044 else
1045 if (type == wxEVT_SCROLLWIN_LINEDOWN)
1046 {
1047 scrollinc = +1;
1048 }
1049 else
1050 if (type == wxEVT_SCROLLWIN_PAGEUP)
1051 {
1052 scrollinc = -10;
1053 }
1054 else
1055 if (type == wxEVT_SCROLLWIN_PAGEDOWN)
1056 {
1057 scrollinc = -10;
1058 }
1059 else
1060 if (type == wxEVT_SCROLLWIN_THUMBTRACK)
1061 {
1062 if (orient == wxHORIZONTAL)
1063 {
1064 scrollinc = pos - m_thumbX;
1065 m_thumbX = pos;
1066 }
1067 else
1068 {
1069 scrollinc = pos - m_thumbY;
1070 m_thumbY = pos;
1071 }
1072 }
1073 else
1074 if (type == wxEVT_SCROLLWIN_THUMBRELEASE)
1075 {
1076 m_thumbX = m_viewportW;
1077 m_thumbY = m_viewportH;
1078 }
1079
1080#if defined(__WXGTK__) || defined(__WXMOTIF__)
1081 // wxGTK and wxMotif update the thumb automatically (wxMSW doesn't);
1082 // so reset it back as we always want it to be in the same position.
1083 if (type != wxEVT_SCROLLWIN_THUMBTRACK)
1084 {
1085 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1086 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1087 }
1088#endif
1089
1090 if (scrollinc == 0) return;
1091
1092 // scroll the window and adjust the viewport
1093 if (orient == wxHORIZONTAL)
1094 {
1095 m_viewportX += scrollinc;
1096 ScrollWindow( -m_cellsize * scrollinc, 0, (const wxRect *) NULL);
1097 }
1098 else
1099 {
1100 m_viewportY += scrollinc;
1101 ScrollWindow( 0, -m_cellsize * scrollinc, (const wxRect *) NULL);
1102 }
1103}
1104
1105void LifeCanvas::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
1106{
1107 // do nothing. I just don't want the background to be erased, you know.
1108}
1109
1110