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