]> git.saurik.com Git - wxWidgets.git/blob - demos/life/life.cpp
Added a parameter 'failOnDataTypeUnsupported' to getDbInfo (that defaults to TRUE...
[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 wxWindows, 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 wxWindows
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, -1, -1, (wxObject *)0, 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 // 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, wxID_ANY);
282 wxPanel *panel2 = new wxPanel(this, wxID_ANY);
283
284 // canvas
285 m_canvas = new LifeCanvas(panel1, m_life);
286
287 // info panel
288 m_text = new wxStaticText(panel2, wxID_ANY,
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, wxID_ANY), 0, wxGROW );
308 sizer1->Add( m_canvas, 1, wxGROW | wxALL, 2 );
309 sizer1->Add( new wxStaticLine(panel1, wxID_ANY), 0, wxGROW );
310 panel1->SetSizer( sizer1 );
311 sizer1->Fit( panel1 );
312
313 sizer2->Add( m_text, 0, wxGROW | wxTOP, 4 );
314 sizer2->Add( slider, 0, wxCENTRE | wxALL, 4 );
315
316 panel2->SetSizer( sizer2 );
317 sizer2->Fit( panel2 );
318
319 sizer3->Add( panel1, 1, wxGROW );
320 sizer3->Add( panel2, 0, wxGROW );
321 SetSizer( sizer3 );
322 sizer3->Fit( this );
323
324 // set minimum frame size
325 sizer3->SetSizeHints( this );
326
327 // navigator frame
328 m_navigator = new LifeNavigator(this);
329 }
330
331 LifeFrame::~LifeFrame()
332 {
333 delete m_timer;
334 }
335
336 void LifeFrame::UpdateInfoText()
337 {
338 wxString msg;
339
340 msg.Printf(_(" Generation: %u (T: %u ms), Population: %u "),
341 m_tics,
342 m_topspeed? 0 : m_interval,
343 m_life->GetNumCells());
344 m_text->SetLabel(msg);
345 }
346
347 // Enable or disable tools and menu entries according to the current
348 // state. See also wxEVT_UPDATE_UI events for a slightly different
349 // way to do this.
350 void LifeFrame::UpdateUI()
351 {
352 // start / stop
353 GetToolBar()->EnableTool(ID_START, !m_running);
354 GetToolBar()->EnableTool(ID_STOP, m_running);
355 GetMenuBar()->Enable(ID_START, !m_running);
356 GetMenuBar()->Enable(ID_STEP, !m_running);
357 GetMenuBar()->Enable(ID_STOP, m_running);
358 GetMenuBar()->Enable(ID_TOPSPEED, !m_topspeed);
359
360 // zooming
361 int cellsize = m_canvas->GetCellSize();
362 GetToolBar()->EnableTool(ID_ZOOMIN, cellsize < 32);
363 GetToolBar()->EnableTool(ID_ZOOMOUT, cellsize > 1);
364 GetMenuBar()->Enable(ID_ZOOMIN, cellsize < 32);
365 GetMenuBar()->Enable(ID_ZOOMOUT, cellsize > 1);
366 }
367
368 // Event handlers -----------------------------------------------------------
369
370 // OnMenu handles all events which don't have their own event handler
371 void LifeFrame::OnMenu(wxCommandEvent& event)
372 {
373 switch (event.GetId())
374 {
375 case wxID_NEW:
376 {
377 // stop if it was running
378 OnStop();
379 m_life->Clear();
380 m_canvas->Recenter(0, 0);
381 m_tics = 0;
382 UpdateInfoText();
383 break;
384 }
385 case wxID_ABOUT:
386 {
387 LifeAboutDialog dialog(this);
388 dialog.ShowModal();
389 break;
390 }
391 case wxID_EXIT:
392 {
393 // true is to force the frame to close
394 Close(true);
395 break;
396 }
397 case ID_SHOWNAV:
398 {
399 bool checked = GetMenuBar()->GetMenu(1)->IsChecked(ID_SHOWNAV);
400 m_navigator->Show(checked);
401 break;
402 }
403 case ID_INFO:
404 {
405 wxString desc = m_life->GetDescription();
406
407 if ( desc.IsEmpty() )
408 desc = _("Not available");
409
410 // should we make the description editable here?
411 wxMessageBox(desc, _("Description"), wxOK | wxICON_INFORMATION);
412
413 break;
414 }
415 case ID_START : OnStart(); break;
416 case ID_STEP : OnStep(); break;
417 case ID_STOP : OnStop(); break;
418 case ID_TOPSPEED:
419 {
420 m_running = true;
421 m_topspeed = true;
422 UpdateUI();
423 while (m_running && m_topspeed)
424 {
425 OnStep();
426 wxYield();
427 }
428 break;
429 }
430 }
431 }
432
433 void LifeFrame::OnOpen(wxCommandEvent& WXUNUSED(event))
434 {
435 wxFileDialog filedlg(this,
436 _("Choose a file to open"),
437 wxEmptyString,
438 wxEmptyString,
439 _("Life patterns (*.lif)|*.lif|All files (*.*)|*.*"),
440 wxOPEN | wxFILE_MUST_EXIST);
441
442 if (filedlg.ShowModal() == wxID_OK)
443 {
444 wxFileInputStream stream(filedlg.GetPath());
445 LifeReader reader(stream);
446
447 // the reader handles errors itself, no need to do anything here
448 if (reader.IsOk())
449 {
450 // stop if running and put the pattern
451 OnStop();
452 m_life->Clear();
453 m_life->SetPattern(reader.GetPattern());
454
455 // recenter canvas
456 m_canvas->Recenter(0, 0);
457 m_tics = 0;
458 UpdateInfoText();
459 }
460 }
461 }
462
463 void LifeFrame::OnSamples(wxCommandEvent& WXUNUSED(event))
464 {
465 // stop if it was running
466 OnStop();
467
468 // dialog box
469 LifeSamplesDialog dialog(this);
470
471 if (dialog.ShowModal() == wxID_OK)
472 {
473 const LifePattern pattern = dialog.GetPattern();
474
475 // put the pattern
476 m_life->Clear();
477 m_life->SetPattern(pattern);
478
479 // recenter canvas
480 m_canvas->Recenter(0, 0);
481 m_tics = 0;
482 UpdateInfoText();
483 }
484 }
485
486 void LifeFrame::OnZoom(wxCommandEvent& event)
487 {
488 int cellsize = m_canvas->GetCellSize();
489
490 if ((event.GetId() == ID_ZOOMIN) && cellsize < 32)
491 {
492 m_canvas->SetCellSize(cellsize * 2);
493 UpdateUI();
494 }
495 else if ((event.GetId() == ID_ZOOMOUT) && cellsize > 1)
496 {
497 m_canvas->SetCellSize(cellsize / 2);
498 UpdateUI();
499 }
500 }
501
502 void LifeFrame::OnNavigate(wxCommandEvent& event)
503 {
504 LifeCell c;
505
506 switch (event.GetId())
507 {
508 case ID_NORTH: c = m_life->FindNorth(); break;
509 case ID_SOUTH: c = m_life->FindSouth(); break;
510 case ID_WEST: c = m_life->FindWest(); break;
511 case ID_EAST: c = m_life->FindEast(); break;
512 case ID_CENTER: c = m_life->FindCenter(); break;
513 default :
514 wxFAIL;
515 // Fall through!
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, wxID_ANY,
589 _("Navigation"),
590 wxDefaultPosition,
591 wxDefaultSize,
592 wxCAPTION | wxSIMPLE_BORDER)
593 {
594 wxPanel *panel = new wxPanel(this, wxID_ANY);
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
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, wxID_ANY, wxDefaultPosition, 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& WXUNUSED(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
832 m_life->BeginFind(i0, j0, i1, j1, false);
833 bool done = m_life->FindMore(&cells, &ncells);
834
835 // erase all damaged cells and draw the grid
836 dc.BeginDrawing();
837 dc.SetBrush(*wxWHITE_BRUSH);
838
839 if (m_cellsize <= 2)
840 {
841 // no grid
842 dc.SetPen(*wxWHITE_PEN);
843 dc.DrawRectangle(x, y, w, h);
844 }
845 else
846 {
847 x = CellToX(i0);
848 y = CellToY(j0);
849 w = CellToX(i1 + 1) - x + 1;
850 h = CellToY(j1 + 1) - y + 1;
851
852 dc.SetPen(*wxLIGHT_GREY_PEN);
853 for (wxInt32 yy = y; yy <= (y + h - m_cellsize); yy += m_cellsize)
854 dc.DrawRectangle(x, yy, w, m_cellsize + 1);
855 for (wxInt32 xx = x; xx <= (x + w - m_cellsize); xx += m_cellsize)
856 dc.DrawLine(xx, y, xx, y + h);
857 }
858
859 // draw all alive cells
860 dc.SetPen(*wxBLACK_PEN);
861 dc.SetBrush(*wxBLACK_BRUSH);
862
863 while (!done)
864 {
865 for (size_t m = 0; m < ncells; m++)
866 DrawCell(cells[m].i, cells[m].j, dc);
867
868 done = m_life->FindMore(&cells, &ncells);
869 }
870
871 // last set
872 for (size_t m = 0; m < ncells; m++)
873 DrawCell(cells[m].i, cells[m].j, dc);
874
875 dc.EndDrawing();
876 }
877
878 void LifeCanvas::OnMouse(wxMouseEvent& event)
879 {
880 if (!m_interactive)
881 return;
882
883 // which cell are we pointing at?
884 wxInt32 i = XToCell( event.GetX() );
885 wxInt32 j = YToCell( event.GetY() );
886
887 // set statusbar text
888 wxString msg;
889 msg.Printf(_("Cell: (%d, %d)"), i, j);
890 ((LifeFrame *) wxGetApp().GetTopWindow())->SetStatusText(msg, 1);
891
892 // NOTE that wxMouseEvent::LeftDown() and wxMouseEvent::LeftIsDown()
893 // have different semantics. The first one is used to signal that the
894 // button was just pressed (i.e., in "button down" events); the second
895 // one just describes the current status of the button, independently
896 // of the mouse event type. LeftIsDown is typically used in "mouse
897 // move" events, to test if the button is _still_ pressed.
898
899 // is the button down?
900 if (!event.LeftIsDown())
901 {
902 m_status = MOUSE_NOACTION;
903 return;
904 }
905
906 // was it pressed just now?
907 if (event.LeftDown())
908 {
909 // yes: start a new action and toggle this cell
910 m_status = (m_life->IsAlive(i, j)? MOUSE_ERASING : MOUSE_DRAWING);
911
912 m_mi = i;
913 m_mj = j;
914 m_life->SetCell(i, j, m_status == MOUSE_DRAWING);
915 DrawCell(i, j, m_status == MOUSE_DRAWING);
916 }
917 else if ((m_mi != i) || (m_mj != j))
918 {
919 // no: continue ongoing action
920 bool alive = (m_status == MOUSE_DRAWING);
921
922 // prepare DC and pen + brush to optimize drawing
923 wxClientDC dc(this);
924 dc.SetPen(alive? *wxBLACK_PEN : *wxWHITE_PEN);
925 dc.SetBrush(alive? *wxBLACK_BRUSH : *wxWHITE_BRUSH);
926 dc.BeginDrawing();
927
928 // draw a line of cells using Bresenham's algorithm
929 wxInt32 d, ii, jj, di, ai, si, dj, aj, sj;
930 di = i - m_mi;
931 ai = abs(di) << 1;
932 si = (di < 0)? -1 : 1;
933 dj = j - m_mj;
934 aj = abs(dj) << 1;
935 sj = (dj < 0)? -1 : 1;
936
937 ii = m_mi;
938 jj = m_mj;
939
940 if (ai > aj)
941 {
942 // iterate over i
943 d = aj - (ai >> 1);
944
945 while (ii != i)
946 {
947 m_life->SetCell(ii, jj, alive);
948 DrawCell(ii, jj, dc);
949 if (d >= 0)
950 {
951 jj += sj;
952 d -= ai;
953 }
954 ii += si;
955 d += aj;
956 }
957 }
958 else
959 {
960 // iterate over j
961 d = ai - (aj >> 1);
962
963 while (jj != j)
964 {
965 m_life->SetCell(ii, jj, alive);
966 DrawCell(ii, jj, dc);
967 if (d >= 0)
968 {
969 ii += si;
970 d -= aj;
971 }
972 jj += sj;
973 d += ai;
974 }
975 }
976
977 // last cell
978 m_life->SetCell(ii, jj, alive);
979 DrawCell(ii, jj, dc);
980 m_mi = ii;
981 m_mj = jj;
982
983 dc.EndDrawing();
984 }
985
986 ((LifeFrame *) wxGetApp().GetTopWindow())->UpdateInfoText();
987 }
988
989 void LifeCanvas::OnSize(wxSizeEvent& event)
990 {
991 // find center
992 wxInt32 cx = m_viewportX + m_viewportW / 2;
993 wxInt32 cy = m_viewportY + m_viewportH / 2;
994
995 // get new size
996 wxCoord w = event.GetSize().GetX();
997 wxCoord h = event.GetSize().GetY();
998 m_viewportW = (w + m_cellsize - 1) / m_cellsize;
999 m_viewportH = (h + m_cellsize - 1) / m_cellsize;
1000
1001 // recenter
1002 m_viewportX = cx - m_viewportW / 2;
1003 m_viewportY = cy - m_viewportH / 2;
1004
1005 // scrollbars
1006 if (m_interactive)
1007 {
1008 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1009 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1010 m_thumbX = m_viewportW;
1011 m_thumbY = m_viewportH;
1012 }
1013
1014 // allow default processing
1015 event.Skip();
1016 }
1017
1018 void LifeCanvas::OnScroll(wxScrollWinEvent& event)
1019 {
1020 WXTYPE type = event.GetEventType();
1021 int pos = event.GetPosition();
1022 int orient = event.GetOrientation();
1023
1024 // calculate scroll increment
1025 int scrollinc = 0;
1026 if (type == wxEVT_SCROLLWIN_TOP)
1027 {
1028 if (orient == wxHORIZONTAL)
1029 scrollinc = -m_viewportW;
1030 else
1031 scrollinc = -m_viewportH;
1032 }
1033 else
1034 if (type == wxEVT_SCROLLWIN_BOTTOM)
1035 {
1036 if (orient == wxHORIZONTAL)
1037 scrollinc = m_viewportW;
1038 else
1039 scrollinc = m_viewportH;
1040 }
1041 else
1042 if (type == wxEVT_SCROLLWIN_LINEUP)
1043 {
1044 scrollinc = -1;
1045 }
1046 else
1047 if (type == wxEVT_SCROLLWIN_LINEDOWN)
1048 {
1049 scrollinc = +1;
1050 }
1051 else
1052 if (type == wxEVT_SCROLLWIN_PAGEUP)
1053 {
1054 scrollinc = -10;
1055 }
1056 else
1057 if (type == wxEVT_SCROLLWIN_PAGEDOWN)
1058 {
1059 scrollinc = +10;
1060 }
1061 else
1062 if (type == wxEVT_SCROLLWIN_THUMBTRACK)
1063 {
1064 if (orient == wxHORIZONTAL)
1065 {
1066 scrollinc = pos - m_thumbX;
1067 m_thumbX = pos;
1068 }
1069 else
1070 {
1071 scrollinc = pos - m_thumbY;
1072 m_thumbY = pos;
1073 }
1074 }
1075 else
1076 if (type == wxEVT_SCROLLWIN_THUMBRELEASE)
1077 {
1078 m_thumbX = m_viewportW;
1079 m_thumbY = m_viewportH;
1080 }
1081
1082 #if defined(__WXGTK__) || defined(__WXMOTIF__)
1083 // wxGTK and wxMotif update the thumb automatically (wxMSW doesn't);
1084 // so reset it back as we always want it to be in the same position.
1085 if (type != wxEVT_SCROLLWIN_THUMBTRACK)
1086 {
1087 SetScrollbar(wxHORIZONTAL, m_viewportW, m_viewportW, 3 * m_viewportW);
1088 SetScrollbar(wxVERTICAL, m_viewportH, m_viewportH, 3 * m_viewportH);
1089 }
1090 #endif
1091
1092 if (scrollinc == 0) return;
1093
1094 // scroll the window and adjust the viewport
1095 if (orient == wxHORIZONTAL)
1096 {
1097 m_viewportX += scrollinc;
1098 ScrollWindow( -m_cellsize * scrollinc, 0, (const wxRect *) NULL);
1099 }
1100 else
1101 {
1102 m_viewportY += scrollinc;
1103 ScrollWindow( 0, -m_cellsize * scrollinc, (const wxRect *) NULL);
1104 }
1105 }
1106
1107 void LifeCanvas::OnEraseBackground(wxEraseEvent& WXUNUSED(event))
1108 {
1109 // do nothing. I just don't want the background to be erased, you know.
1110 }
1111
1112