]> git.saurik.com Git - wxWidgets.git/blob - samples/scroll/scroll.cpp
Artwork replacement (c) Julian Smart
[wxWidgets.git] / samples / scroll / scroll.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: scroll.cpp
3 // Purpose: wxScrolledWindow sample
4 // Author: Robert Roebling
5 // Modified by:
6 // Created:
7 // RCS-ID: $Id$
8 // Copyright: (C) 1998 Robert Roebling, 2002 Ron Lee, 2003 Matt Gregory
9 // Licence: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // For compilers that support precompilation, includes "wx/wx.h".
13 #include "wx/wxprec.h"
14
15 #ifdef __BORLANDC__
16 #pragma hdrstop
17 #endif
18
19 #ifndef WX_PRECOMP
20 #include "wx/wx.h"
21 #endif
22
23 #include "wx/image.h"
24 #include "wx/listctrl.h"
25 #include "wx/sizer.h"
26 #include "wx/log.h"
27
28
29 // derived classes
30
31 class MyFrame;
32 class MyApp;
33
34 // MyCanvas
35
36 class MyCanvas: public wxScrolledWindow
37 {
38 public:
39 MyCanvas() {}
40 MyCanvas( wxWindow *parent, wxWindowID, const wxPoint &pos, const wxSize &size );
41 ~MyCanvas(){};
42 void OnPaint( wxPaintEvent &event );
43 void OnQueryPosition( wxCommandEvent &event );
44 void OnAddButton( wxCommandEvent &event );
45 void OnDeleteButton( wxCommandEvent &event );
46 void OnMoveButton( wxCommandEvent &event );
47 void OnScrollWin( wxCommandEvent &event );
48 void OnMouseDown( wxMouseEvent &event );
49
50 wxButton *m_button;
51
52 DECLARE_DYNAMIC_CLASS(MyCanvas)
53 DECLARE_EVENT_TABLE()
54 };
55
56
57 // ----------------------------------------------------------------------------
58 // Autoscrolling example.
59 // ----------------------------------------------------------------------------
60
61 // this class uses the 'virtual' size attribute along with an internal
62 // sizer to automatically set up scrollbars as needed
63
64 class MyAutoScrollWindow : public wxScrolledWindow
65 {
66 private:
67
68 wxButton *m_button;
69
70 public:
71
72 MyAutoScrollWindow( wxWindow *parent );
73
74 void OnResizeClick( wxCommandEvent &WXUNUSED( event ) );
75
76 DECLARE_EVENT_TABLE()
77 };
78
79
80 // ----------------------------------------------------------------------------
81 // MyScrolledWindow classes: examples of wxScrolledWindow usage
82 // ----------------------------------------------------------------------------
83
84 // base class for both of them
85 class MyScrolledWindowBase : public wxScrolledWindow
86 {
87 public:
88 MyScrolledWindowBase(wxWindow *parent)
89 : wxScrolledWindow(parent)
90 , m_nLines( 100 )
91 {
92 wxClientDC dc(this);
93 dc.GetTextExtent(_T("Line 17"), NULL, &m_hLine);
94 }
95
96 protected:
97 // the height of one line on screen
98 wxCoord m_hLine;
99
100 // the number of lines we draw
101 size_t m_nLines;
102 };
103
104 // this class does "stupid" redrawing - it redraws everything each time
105 // and sets the scrollbar extent directly.
106
107 class MyScrolledWindowDumb : public MyScrolledWindowBase
108 {
109 public:
110 MyScrolledWindowDumb(wxWindow *parent) : MyScrolledWindowBase(parent)
111 {
112 // no horz scrolling
113 SetScrollbars(0, m_hLine, 0, m_nLines + 1, 0, 0, true /* no refresh */);
114 }
115
116 virtual void OnDraw(wxDC& dc);
117 };
118
119 // this class does "smart" redrawing - only redraws the lines which must be
120 // redrawn and sets the scroll rate and virtual size to affect the
121 // scrollbars.
122 //
123 // Note that this class should produce identical results to the one above.
124
125 class MyScrolledWindowSmart : public MyScrolledWindowBase
126 {
127 public:
128 MyScrolledWindowSmart(wxWindow *parent) : MyScrolledWindowBase(parent)
129 {
130 // no horz scrolling
131 SetScrollRate( 0, m_hLine );
132 SetVirtualSize( wxDefaultCoord, ( m_nLines + 1 ) * m_hLine );
133 }
134
135 virtual void OnDraw(wxDC& dc);
136 };
137
138 // ----------------------------------------------------------------------------
139 // MyAutoTimedScrollingWindow: implements a text viewer with simple blocksize
140 // selection to test auto-scrolling functionality
141 // ----------------------------------------------------------------------------
142
143 class MyAutoTimedScrollingWindow : public wxScrolledWindow
144 {
145 protected: // member data
146 // test data variables
147 static const wxChar* sm_testData;
148 static const int sm_lineCnt; // line count
149 static const int sm_lineLen; // line length in characters
150 // sizes for graphical data
151 wxCoord m_fontH, m_fontW;
152 // selection tracking
153 wxPoint m_selStart; // beginning of blockwise selection
154 wxPoint m_cursor; // end of blockwise selection (mouse position)
155
156 protected: // gui stuff
157 wxFont m_font;
158
159 public: // interface
160 MyAutoTimedScrollingWindow( wxWindow* parent );
161 wxRect DeviceCoordsToGraphicalChars(wxRect updRect) const;
162 wxPoint DeviceCoordsToGraphicalChars(wxPoint pos) const;
163 wxPoint GraphicalCharToDeviceCoords(wxPoint pos) const;
164 wxRect LogicalCoordsToGraphicalChars(wxRect updRect) const;
165 wxPoint LogicalCoordsToGraphicalChars(wxPoint pos) const;
166 wxPoint GraphicalCharToLogicalCoords(wxPoint pos) const;
167 void MyRefresh();
168 bool IsSelected(int chX, int chY) const;
169 static bool IsInside(int k, int bound1, int bound2);
170 static wxRect DCNormalize(wxCoord x, wxCoord y, wxCoord w, wxCoord h);
171
172 protected: // event stuff
173 DECLARE_EVENT_TABLE()
174 void OnDraw(wxDC& dc);
175 void OnMouseLeftDown(wxMouseEvent& event);
176 void OnMouseLeftUp(wxMouseEvent& event);
177 void OnMouseMove(wxMouseEvent& event);
178 void OnScroll(wxScrollWinEvent& event);
179 };
180
181 // ----------------------------------------------------------------------------
182 // MyFrame
183 // ----------------------------------------------------------------------------
184
185 class MyFrame: public wxFrame
186 {
187 public:
188 MyFrame();
189
190 void OnAbout( wxCommandEvent &event );
191 void OnQuit( wxCommandEvent &event );
192 void OnDeleteAll( wxCommandEvent &event );
193 void OnInsertNew( wxCommandEvent &event );
194
195 MyCanvas *m_canvas;
196 wxTextCtrl *m_log;
197
198 DECLARE_DYNAMIC_CLASS(MyFrame)
199 DECLARE_EVENT_TABLE()
200 };
201
202 // ----------------------------------------------------------------------------
203 // MyApp
204 // ----------------------------------------------------------------------------
205
206 class MyApp: public wxApp
207 {
208 public:
209 virtual bool OnInit();
210 };
211
212
213 // ----------------------------------------------------------------------------
214 // main program
215 // ----------------------------------------------------------------------------
216
217 IMPLEMENT_APP(MyApp)
218
219 // ids
220
221 const long ID_ADDBUTTON = wxNewId();
222 const long ID_DELBUTTON = wxNewId();
223 const long ID_MOVEBUTTON = wxNewId();
224 const long ID_SCROLLWIN = wxNewId();
225 const long ID_QUERYPOS = wxNewId();
226
227 const long ID_NEWBUTTON = wxNewId();
228
229 // ----------------------------------------------------------------------------
230 // MyCanvas
231 // ----------------------------------------------------------------------------
232
233 IMPLEMENT_DYNAMIC_CLASS(MyCanvas, wxScrolledWindow)
234
235 BEGIN_EVENT_TABLE(MyCanvas, wxScrolledWindow)
236 EVT_PAINT( MyCanvas::OnPaint)
237 EVT_MOUSE_EVENTS( MyCanvas::OnMouseDown)
238 EVT_BUTTON( ID_QUERYPOS, MyCanvas::OnQueryPosition)
239 EVT_BUTTON( ID_ADDBUTTON, MyCanvas::OnAddButton)
240 EVT_BUTTON( ID_DELBUTTON, MyCanvas::OnDeleteButton)
241 EVT_BUTTON( ID_MOVEBUTTON, MyCanvas::OnMoveButton)
242 EVT_BUTTON( ID_SCROLLWIN, MyCanvas::OnScrollWin)
243 END_EVENT_TABLE()
244
245 MyCanvas::MyCanvas( wxWindow *parent, wxWindowID id,
246 const wxPoint &pos, const wxSize &size )
247 : wxScrolledWindow( parent, id, pos, size, wxSUNKEN_BORDER | wxTAB_TRAVERSAL, _T("test canvas") )
248 {
249 SetScrollRate( 10, 10 );
250 SetVirtualSize( 500, 1000 );
251
252 (void) new wxButton( this, ID_ADDBUTTON, _T("add button"), wxPoint(10,10) );
253 (void) new wxButton( this, ID_DELBUTTON, _T("del button"), wxPoint(10,40) );
254 (void) new wxButton( this, ID_MOVEBUTTON, _T("move button"), wxPoint(150,10) );
255 (void) new wxButton( this, ID_SCROLLWIN, _T("scroll win"), wxPoint(250,10) );
256
257 #if 0
258
259 wxString choices[] =
260 {
261 "This",
262 "is one of my",
263 "really",
264 "wonderful",
265 "examples."
266 };
267
268 m_button = new wxButton( this, ID_QUERYPOS, "Query position", wxPoint(10,110) );
269
270 (void) new wxTextCtrl( this, wxID_ANY, "wxTextCtrl", wxPoint(10,150), wxSize(80,wxDefaultCoord) );
271
272 (void) new wxRadioButton( this, wxID_ANY, "Disable", wxPoint(10,190) );
273
274 (void) new wxComboBox( this, wxID_ANY, "This", wxPoint(10,230), wxDefaultSize, 5, choices );
275
276 (void) new wxRadioBox( this, wxID_ANY, "This", wxPoint(10,310), wxDefaultSize, 5, choices, 2, wxRA_SPECIFY_COLS );
277
278 (void) new wxRadioBox( this, wxID_ANY, "This", wxPoint(10,440), wxDefaultSize, 5, choices, 2, wxRA_SPECIFY_ROWS );
279
280 wxListCtrl *m_listCtrl = new wxListCtrl(
281 this, wxID_ANY, wxPoint(200, 110), wxSize(180, 120),
282 wxLC_REPORT | wxSIMPLE_BORDER | wxLC_SINGLE_SEL );
283
284 m_listCtrl->InsertColumn(0, "First", wxLIST_FORMAT_LEFT, 90);
285 m_listCtrl->InsertColumn(1, "Last", wxLIST_FORMAT_LEFT, 90);
286
287 for ( int i=0; i < 30; i++)
288 {
289 char buf[20];
290 sprintf(buf, "Item %d", i);
291 m_listCtrl->InsertItem(i, buf);
292 }
293 m_listCtrl->SetItemState( 3, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
294
295 (void) new wxListBox( this, wxID_ANY, wxPoint(260,280), wxSize(120,120), 5, choices, wxLB_ALWAYS_SB );
296
297 #endif
298
299 wxPanel *test = new wxPanel( this, wxID_ANY, wxPoint(10, 110), wxSize(130,50), wxSIMPLE_BORDER | wxTAB_TRAVERSAL );
300 test->SetBackgroundColour( wxT("WHEAT") );
301
302 #if 0
303
304 wxButton *test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) );
305
306 test = new wxPanel( this, wxID_ANY, wxPoint(160, 530), wxSize(130,120), wxSUNKEN_BORDER | wxTAB_TRAVERSAL );
307 test->SetBackgroundColour( wxT("WHEAT") );
308 test->SetCursor( wxCursor( wxCURSOR_NO_ENTRY ) );
309 test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) );
310 test2->SetCursor( wxCursor( wxCURSOR_PENCIL ) );
311
312 test = new wxPanel( this, wxID_ANY, wxPoint(310, 530), wxSize(130,120), wxRAISED_BORDER | wxTAB_TRAVERSAL );
313 test->SetBackgroundColour( wxT("WHEAT") );
314 test->SetCursor( wxCursor( wxCURSOR_PENCIL ) );
315 test2 = new wxButton( test, wxID_ANY, "Hallo", wxPoint(10,10) );
316 test2->SetCursor( wxCursor( wxCURSOR_NO_ENTRY ) );
317
318 #endif
319
320 SetBackgroundColour( wxT("BLUE") );
321
322 SetCursor( wxCursor( wxCURSOR_IBEAM ) );
323 }
324
325 void MyCanvas::OnMouseDown( wxMouseEvent &event )
326 {
327 if (event.LeftDown())
328 {
329 wxPoint pt( event.GetPosition() );
330 int x,y;
331 CalcUnscrolledPosition( pt.x, pt.y, &x, &y );
332 wxLogMessage( wxT("Mouse down event at: %d %d, scrolled: %d %d"), pt.x, pt.y, x, y );
333
334 if ( !event.LeftIsDown() )
335 wxLogMessage( wxT("Error: LeftIsDown() should be true if for LeftDown()") );
336 }
337 }
338
339 void MyCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) )
340 {
341 wxPaintDC dc( this );
342 PrepareDC( dc );
343
344 dc.DrawText( _T("Press mouse button to test calculations!"), 160, 50 );
345
346 dc.DrawText( _T("Some text"), 140, 140 );
347
348 dc.DrawRectangle( 100, 160, 200, 200 );
349 }
350
351 void MyCanvas::OnQueryPosition( wxCommandEvent &WXUNUSED(event) )
352 {
353 wxPoint pt( m_button->GetPosition() );
354 wxLogMessage( wxT("Position of \"Query position\" is %d %d"), pt.x, pt.y );
355 pt = ClientToScreen( pt );
356 wxLogMessage( wxT("Position of \"Query position\" on screen is %d %d"), pt.x, pt.y );
357 }
358
359 void MyCanvas::OnAddButton( wxCommandEvent &WXUNUSED(event) )
360 {
361 wxLogMessage( wxT("Inserting button at position 10,70...") );
362 wxButton *button = new wxButton( this, ID_NEWBUTTON, wxT("new button"), wxPoint(10,70), wxSize(80,25) );
363 wxPoint pt( button->GetPosition() );
364 wxLogMessage( wxT("-> Position after inserting %d %d"), pt.x, pt.y );
365 }
366
367 void MyCanvas::OnDeleteButton( wxCommandEvent &WXUNUSED(event) )
368 {
369 wxLogMessage( wxT("Deleting button inserted with \"Add button\"...") );
370 wxWindow *win = FindWindow( ID_NEWBUTTON );
371 if (win)
372 win->Destroy();
373 else
374 wxLogMessage( wxT("-> No window with id = ID_NEWBUTTON found.") );
375 }
376
377 void MyCanvas::OnMoveButton( wxCommandEvent &event )
378 {
379 wxLogMessage( wxT("Moving button 10 pixels downward..") );
380 wxWindow *win = FindWindow( event.GetId() );
381 wxPoint pt( win->GetPosition() );
382 wxLogMessage( wxT("-> Position before move is %d %d"), pt.x, pt.y );
383 win->Move( wxDefaultCoord, pt.y + 10 );
384 pt = win->GetPosition();
385 wxLogMessage( wxT("-> Position after move is %d %d"), pt.x, pt.y );
386 }
387
388 void MyCanvas::OnScrollWin( wxCommandEvent &WXUNUSED(event) )
389 {
390 wxLogMessage( wxT("Scrolling 2 units up.\nThe white square and the controls should move equally!") );
391 int x,y;
392 GetViewStart( &x, &y );
393 Scroll( wxDefaultCoord, y+2 );
394 }
395
396 // ----------------------------------------------------------------------------
397 // MyAutoScrollWindow
398 // ----------------------------------------------------------------------------
399
400 const long ID_RESIZEBUTTON = wxNewId();
401 const wxSize SMALL_BUTTON( 100, 50 );
402 const wxSize LARGE_BUTTON( 300, 100 );
403
404 BEGIN_EVENT_TABLE( MyAutoScrollWindow, wxScrolledWindow)
405 EVT_BUTTON( ID_RESIZEBUTTON, MyAutoScrollWindow::OnResizeClick)
406 END_EVENT_TABLE()
407
408 MyAutoScrollWindow::MyAutoScrollWindow( wxWindow *parent )
409 : wxScrolledWindow( parent, -1, wxDefaultPosition, wxDefaultSize,
410 wxSUNKEN_BORDER|wxScrolledWindowStyle )
411 {
412 SetBackgroundColour( wxT("GREEN") );
413
414 // Set the rate we'd like for scrolling.
415
416 SetScrollRate( 5, 5 );
417
418 // Populate a sizer with a 'resizing' button and some
419 // other static decoration
420
421 wxFlexGridSizer *innersizer = new wxFlexGridSizer( 2, 2 );
422
423 m_button = new wxButton( this,
424 ID_RESIZEBUTTON,
425 _T("Press me"),
426 wxDefaultPosition,
427 SMALL_BUTTON );
428
429 // We need to do this here, because wxADJUST_MINSIZE below
430 // will cause the initial size to be ignored for Best/Min size.
431 // It would be nice to fix the sizers to handle this a little
432 // more cleanly.
433
434 m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() );
435
436 innersizer->Add( m_button,
437 0,
438 wxALIGN_CENTER | wxALL | wxADJUST_MINSIZE,
439 20 );
440
441 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("This is just") ),
442 0,
443 wxALIGN_CENTER );
444
445 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("some decoration") ),
446 0,
447 wxALIGN_CENTER );
448
449 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("for you to scroll...") ),
450 0,
451 wxALIGN_CENTER );
452
453 // Then use the sizer to set the scrolled region size.
454
455 SetSizer( innersizer );
456 }
457
458 void MyAutoScrollWindow::OnResizeClick( wxCommandEvent &WXUNUSED( event ) )
459 {
460 // Arbitrarily resize the button to change the minimum size of
461 // the (scrolled) sizer.
462
463 if( m_button->GetSize() == SMALL_BUTTON )
464 m_button->SetSizeHints( LARGE_BUTTON.GetWidth(), LARGE_BUTTON.GetHeight() );
465 else
466 m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() );
467
468 // Force update layout and scrollbars, since nothing we do here
469 // necessarily generates a size event which would do it for us.
470
471 FitInside();
472 }
473
474 // ----------------------------------------------------------------------------
475 // MyFrame
476 // ----------------------------------------------------------------------------
477
478 const long ID_QUIT = wxNewId();
479 const long ID_ABOUT = wxNewId();
480 const long ID_DELETE_ALL = wxNewId();
481 const long ID_INSERT_NEW = wxNewId();
482
483 IMPLEMENT_DYNAMIC_CLASS( MyFrame, wxFrame )
484
485 BEGIN_EVENT_TABLE(MyFrame,wxFrame)
486 EVT_MENU (ID_DELETE_ALL, MyFrame::OnDeleteAll)
487 EVT_MENU (ID_INSERT_NEW, MyFrame::OnInsertNew)
488 EVT_MENU (ID_ABOUT, MyFrame::OnAbout)
489 EVT_MENU (ID_QUIT, MyFrame::OnQuit)
490 END_EVENT_TABLE()
491
492 MyFrame::MyFrame()
493 : wxFrame( (wxFrame *)NULL, wxID_ANY, _T("wxScrolledWindow sample"),
494 wxPoint(20,20), wxSize(800,500) )
495 {
496 wxMenu *file_menu = new wxMenu();
497 file_menu->Append( ID_DELETE_ALL, _T("Delete all"));
498 file_menu->Append( ID_INSERT_NEW, _T("Insert new"));
499 file_menu->Append( ID_ABOUT, _T("&About.."));
500 file_menu->Append( ID_QUIT, _T("E&xit\tAlt-X"));
501
502 wxMenuBar *menu_bar = new wxMenuBar();
503 menu_bar->Append(file_menu, _T("&File"));
504
505 SetMenuBar( menu_bar );
506
507 #if wxUSE_STATUSBAR
508 CreateStatusBar(2);
509 int widths[] = { -1, 100 };
510 SetStatusWidths( 2, widths );
511 #endif // wxUSE_STATUSBAR
512
513 wxBoxSizer *topsizer = new wxBoxSizer( wxHORIZONTAL );
514 // subsizer splits topsizer down the middle
515 wxBoxSizer *subsizer = new wxBoxSizer( wxVERTICAL );
516
517 // Setting an explicit size here is superfluous, it will be overridden
518 // by the sizer in any case.
519 m_canvas = new MyCanvas( this, wxID_ANY, wxPoint(0,0), wxSize(100,100) );
520
521 // This is done with ScrollRate/VirtualSize in MyCanvas ctor now,
522 // both should produce identical results.
523 //m_canvas->SetScrollbars( 10, 10, 50, 100 );
524
525 subsizer->Add( m_canvas, 1, wxEXPAND );
526 subsizer->Add( new MyAutoScrollWindow( this ), 1, wxEXPAND );
527
528 wxSizer *sizerBtm = new wxBoxSizer(wxHORIZONTAL);
529 sizerBtm->Add( new MyScrolledWindowDumb(this), 1, wxEXPAND );
530 sizerBtm->Add( new MyScrolledWindowSmart(this), 1, wxEXPAND );
531 subsizer->Add( sizerBtm, 1, wxEXPAND );
532
533 topsizer->Add( subsizer, 1, wxEXPAND );
534 topsizer->Add( new MyAutoTimedScrollingWindow( this ), 1, wxEXPAND );
535
536 SetSizer( topsizer );
537 }
538
539 void MyFrame::OnDeleteAll( wxCommandEvent &WXUNUSED(event) )
540 {
541 m_canvas->DestroyChildren();
542 }
543
544 void MyFrame::OnInsertNew( wxCommandEvent &WXUNUSED(event) )
545 {
546 (void)new wxButton( m_canvas, wxID_ANY, _T("Hello"), wxPoint(100,100) );
547 }
548
549 void MyFrame::OnQuit( wxCommandEvent &WXUNUSED(event) )
550 {
551 Close( true );
552 }
553
554 void MyFrame::OnAbout( wxCommandEvent &WXUNUSED(event) )
555 {
556 (void)wxMessageBox( _T("wxScroll demo\n")
557 _T("Robert Roebling (c) 1998\n")
558 _T("Autoscrolling examples\n")
559 _T("Ron Lee (c) 2002\n")
560 _T("Auto-timed-scrolling example\n")
561 _T("Matt Gregory (c) 2003\n"),
562 _T("About wxScroll Demo"),
563 wxICON_INFORMATION | wxOK );
564 }
565
566 //-----------------------------------------------------------------------------
567 // MyApp
568 //-----------------------------------------------------------------------------
569
570 bool MyApp::OnInit()
571 {
572 wxFrame *frame = new MyFrame();
573 frame->Show( true );
574
575 return true;
576 }
577
578 // ----------------------------------------------------------------------------
579 // MyScrolledWindowXXX
580 // ----------------------------------------------------------------------------
581
582 void MyScrolledWindowDumb::OnDraw(wxDC& dc)
583 {
584 // this is useful to see which lines are redrawn
585 static size_t s_redrawCount = 0;
586 dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE);
587
588 wxCoord y = 0;
589 for ( size_t line = 0; line < m_nLines; line++ )
590 {
591 wxCoord yPhys;
592 CalcScrolledPosition(0, y, NULL, &yPhys);
593
594 dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"),
595 line, y, yPhys), 0, y);
596 y += m_hLine;
597 }
598 }
599
600 void MyScrolledWindowSmart::OnDraw(wxDC& dc)
601 {
602 // this is useful to see which lines are redrawn
603 static size_t s_redrawCount = 0;
604 dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE);
605
606 // update region is always in device coords, translate to logical ones
607 wxRect rectUpdate = GetUpdateRegion().GetBox();
608 CalcUnscrolledPosition(rectUpdate.x, rectUpdate.y,
609 &rectUpdate.x, &rectUpdate.y);
610
611 size_t lineFrom = rectUpdate.y / m_hLine,
612 lineTo = rectUpdate.GetBottom() / m_hLine;
613
614 if ( lineTo > m_nLines - 1)
615 lineTo = m_nLines - 1;
616
617 wxCoord y = lineFrom*m_hLine;
618 for ( size_t line = lineFrom; line <= lineTo; line++ )
619 {
620 wxCoord yPhys;
621 CalcScrolledPosition(0, y, NULL, &yPhys);
622
623 dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"),
624 line, y, yPhys), 0, y);
625 y += m_hLine;
626 }
627 }
628
629 // ----------------------------------------------------------------------------
630 // MyAutoTimedScrollingWindow
631 // ----------------------------------------------------------------------------
632
633 BEGIN_EVENT_TABLE(MyAutoTimedScrollingWindow, wxScrolledWindow)
634 EVT_LEFT_DOWN(MyAutoTimedScrollingWindow::OnMouseLeftDown)
635 EVT_LEFT_UP(MyAutoTimedScrollingWindow::OnMouseLeftUp)
636 EVT_MOTION(MyAutoTimedScrollingWindow::OnMouseMove)
637 EVT_SCROLLWIN(MyAutoTimedScrollingWindow::OnScroll)
638 END_EVENT_TABLE()
639
640 MyAutoTimedScrollingWindow::MyAutoTimedScrollingWindow(wxWindow* parent)
641 : wxScrolledWindow(parent, wxID_ANY, wxDefaultPosition, wxDefaultSize
642 //, wxSUNKEN_BORDER) // can't seem to do it this way
643 , wxVSCROLL | wxHSCROLL | wxSUNKEN_BORDER)
644 , m_selStart(-1, -1), m_cursor(-1, -1)
645 , m_font(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL
646 , wxFONTWEIGHT_NORMAL)
647 {
648 wxClientDC dc(this);
649 // query dc for text size
650 dc.SetFont(m_font);
651 dc.GetTextExtent(wxString(_T("A")), &m_fontW, &m_fontH);
652 // set up the virtual window
653 SetScrollbars(m_fontW, m_fontH, sm_lineLen, sm_lineCnt);
654 }
655
656 wxRect MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars
657 (wxRect updRect) const
658 {
659 wxPoint pos(updRect.GetPosition());
660 pos = DeviceCoordsToGraphicalChars(pos);
661 updRect.x = pos.x;
662 updRect.y = pos.y;
663 updRect.width /= m_fontW;
664 updRect.height /= m_fontH;
665 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
666 // so an off-by-one correction is needed
667 ++updRect.width; // kludge
668 ++updRect.height; // kludge
669 return updRect;
670 }
671
672 wxPoint MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars
673 (wxPoint pos) const
674 {
675 pos.x /= m_fontW;
676 pos.y /= m_fontH;
677 int vX, vY;
678 GetViewStart(&vX, &vY);
679 pos.x += vX;
680 pos.y += vY;
681 return pos;
682 }
683
684 wxPoint MyAutoTimedScrollingWindow::GraphicalCharToDeviceCoords
685 (wxPoint pos) const
686 {
687 int vX, vY;
688 GetViewStart(&vX, &vY);
689 pos.x -= vX;
690 pos.y -= vY;
691 pos.x *= m_fontW;
692 pos.y *= m_fontH;
693 return pos;
694 }
695
696 wxRect MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars
697 (wxRect updRect) const
698 {
699 wxPoint pos(updRect.GetPosition());
700 pos = LogicalCoordsToGraphicalChars(pos);
701 updRect.x = pos.x;
702 updRect.y = pos.y;
703 updRect.width /= m_fontW;
704 updRect.height /= m_fontH;
705 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
706 // so an off-by-one correction is needed
707 ++updRect.width; // kludge
708 ++updRect.height; // kludge
709 return updRect;
710 }
711
712 wxPoint MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars
713 (wxPoint pos) const
714 {
715 pos.x /= m_fontW;
716 pos.y /= m_fontH;
717 return pos;
718 }
719
720 wxPoint MyAutoTimedScrollingWindow::GraphicalCharToLogicalCoords
721 (wxPoint pos) const
722 {
723 pos.x *= m_fontW;
724 pos.y *= m_fontH;
725 return pos;
726 }
727
728 void MyAutoTimedScrollingWindow::MyRefresh()
729 {
730 static wxPoint lastSelStart(-1, -1), lastCursor(-1, -1);
731 // refresh last selected area (to deselect previously selected text)
732 wxRect lastUpdRect(
733 GraphicalCharToDeviceCoords(lastSelStart),
734 GraphicalCharToDeviceCoords(lastCursor)
735 );
736 // off-by-one corrections, necessary because it's not possible to know
737 // when to round up until rect is normalized by lastUpdRect constructor
738 lastUpdRect.width += m_fontW; // kludge
739 lastUpdRect.height += m_fontH; // kludge
740 // refresh currently selected (to select previously unselected text)
741 wxRect updRect(
742 GraphicalCharToDeviceCoords(m_selStart),
743 GraphicalCharToDeviceCoords(m_cursor)
744 );
745 // off-by-one corrections
746 updRect.width += m_fontW; // kludge
747 updRect.height += m_fontH; // kludge
748 // find necessary refresh areas
749 wxCoord rx = lastUpdRect.x;
750 wxCoord ry = lastUpdRect.y;
751 wxCoord rw = updRect.x - lastUpdRect.x;
752 wxCoord rh = lastUpdRect.height;
753 if (rw && rh) {
754 RefreshRect(DCNormalize(rx, ry, rw, rh));
755 }
756 rx = updRect.x;
757 ry = updRect.y + updRect.height;
758 rw= updRect.width;
759 rh = (lastUpdRect.y + lastUpdRect.height) - (updRect.y + updRect.height);
760 if (rw && rh) {
761 RefreshRect(DCNormalize(rx, ry, rw, rh));
762 }
763 rx = updRect.x + updRect.width;
764 ry = lastUpdRect.y;
765 rw = (lastUpdRect.x + lastUpdRect.width) - (updRect.x + updRect.width);
766 rh = lastUpdRect.height;
767 if (rw && rh) {
768 RefreshRect(DCNormalize(rx, ry, rw, rh));
769 }
770 rx = updRect.x;
771 ry = lastUpdRect.y;
772 rw = updRect.width;
773 rh = updRect.y - lastUpdRect.y;
774 if (rw && rh) {
775 RefreshRect(DCNormalize(rx, ry, rw, rh));
776 }
777 // update last
778 lastSelStart = m_selStart;
779 lastCursor = m_cursor;
780 }
781
782 bool MyAutoTimedScrollingWindow::IsSelected(int chX, int chY) const
783 {
784 if (IsInside(chX, m_selStart.x, m_cursor.x)
785 && IsInside(chY, m_selStart.y, m_cursor.y)) {
786 return true;
787 }
788 return false;
789 }
790
791 bool MyAutoTimedScrollingWindow::IsInside(int k, int bound1, int bound2)
792 {
793 if ((k >= bound1 && k <= bound2) || (k >= bound2 && k <= bound1)) {
794 return true;
795 }
796 return false;
797 }
798
799 wxRect MyAutoTimedScrollingWindow::DCNormalize(wxCoord x, wxCoord y
800 , wxCoord w, wxCoord h)
801 {
802 // this is needed to get rid of the graphical remnants from the selection
803 // I think it's because DrawRectangle() excludes a pixel in either direction
804 const int kludge = 1;
805 // make (x, y) the top-left corner
806 if (w < 0) {
807 w = -w + kludge;
808 x -= w;
809 } else {
810 x -= kludge;
811 w += kludge;
812 }
813 if (h < 0) {
814 h = -h + kludge;
815 y -= h;
816 } else {
817 y -= kludge;
818 h += kludge;
819 }
820 return wxRect(x, y, w, h);
821 }
822
823 void MyAutoTimedScrollingWindow::OnDraw(wxDC& dc)
824 {
825 dc.SetFont(m_font);
826 wxBrush normBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)
827 , wxSOLID);
828 wxBrush selBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)
829 , wxSOLID);
830 dc.SetPen(*wxTRANSPARENT_PEN);
831 wxString str = sm_testData;
832
833 // draw the characters
834 // 1. for each update region
835 for (wxRegionIterator upd(GetUpdateRegion()); upd; ++upd) {
836 wxRect updRect = upd.GetRect();
837 wxRect updRectInGChars(DeviceCoordsToGraphicalChars(updRect));
838 // 2. for each row of chars in the update region
839 for (int chY = updRectInGChars.y
840 ; chY <= updRectInGChars.y + updRectInGChars.height; ++chY) {
841 // 3. for each character in the row
842 for (int chX = updRectInGChars.x
843 ; chX <= updRectInGChars.x + updRectInGChars.width
844 ; ++chX) {
845 // 4. set up dc
846 if (IsSelected(chX, chY)) {
847 dc.SetBrush(selBrush);
848 dc.SetTextForeground( wxSystemSettings::GetColour
849 (wxSYS_COLOUR_HIGHLIGHTTEXT));
850 } else {
851 dc.SetBrush(normBrush);
852 dc.SetTextForeground( wxSystemSettings::GetColour
853 (wxSYS_COLOUR_WINDOWTEXT));
854 }
855 // 5. find position info
856 wxPoint charPos = GraphicalCharToLogicalCoords(wxPoint
857 (chX, chY));
858 // 6. draw!
859 dc.DrawRectangle(charPos.x, charPos.y, m_fontW, m_fontH);
860 size_t charIndex = chY * sm_lineLen + chX;
861 if (chY < sm_lineCnt &&
862 chX < sm_lineLen &&
863 charIndex < str.Length())
864 {
865 dc.DrawText(str.Mid(charIndex,1),
866 charPos.x, charPos.y);
867 }
868 }
869 }
870 }
871 }
872
873 void MyAutoTimedScrollingWindow::OnMouseLeftDown(wxMouseEvent& event)
874 {
875 // initial press of mouse button sets the beginning of the selection
876 m_selStart = DeviceCoordsToGraphicalChars(event.GetPosition());
877 // set the cursor to the same position
878 m_cursor = m_selStart;
879 // draw/erase selection
880 MyRefresh();
881 }
882
883 void MyAutoTimedScrollingWindow::OnMouseLeftUp(wxMouseEvent& WXUNUSED(event))
884 {
885 // this test is necessary
886 if (HasCapture()) {
887 // uncapture mouse
888 ReleaseMouse();
889 }
890 }
891
892 void MyAutoTimedScrollingWindow::OnMouseMove(wxMouseEvent& event)
893 {
894 // if user is dragging
895 if (event.Dragging() && event.LeftIsDown()) {
896 // set the new cursor position
897 m_cursor = DeviceCoordsToGraphicalChars(event.GetPosition());
898 // draw/erase selection
899 MyRefresh();
900 // capture mouse to activate auto-scrolling
901 if (!HasCapture()) {
902 CaptureMouse();
903 }
904 }
905 }
906
907 void MyAutoTimedScrollingWindow::OnScroll(wxScrollWinEvent& event)
908 {
909 // need to move the cursor when autoscrolling
910 // FIXME: the cursor also moves when the scrollbar arrows are clicked
911 if (HasCapture()) {
912 if (event.GetOrientation() == wxHORIZONTAL) {
913 if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) {
914 --m_cursor.x;
915 } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) {
916 ++m_cursor.x;
917 }
918 } else if (event.GetOrientation() == wxVERTICAL) {
919 if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) {
920 --m_cursor.y;
921 } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) {
922 ++m_cursor.y;
923 }
924 }
925 }
926 MyRefresh();
927 event.Skip();
928 }
929
930 const int MyAutoTimedScrollingWindow::sm_lineCnt = 125;
931 const int MyAutoTimedScrollingWindow::sm_lineLen = 79;
932 const wxChar* MyAutoTimedScrollingWindow::sm_testData =
933 _T("162 Cult of the genius out of vanity.\97 Because we think well of ourselves, but ")
934 _T("nonetheless never suppose ourselves capable of producing a painting like one of ")
935 _T("Raphael's or a dramatic scene like one of Shakespeare's, we convince ourselves ")
936 _T("that the capacity to do so is quite extraordinarily marvelous, a wholly ")
937 _T("uncommon accident, or, if we are still religiously inclined, a mercy from on ")
938 _T("high. Thus our vanity, our self-love, promotes the cult of the genius: for only ")
939 _T("if we think of him as being very remote from us, as a miraculum, does he not ")
940 _T("aggrieve us (even Goethe, who was without envy, called Shakespeare his star of ")
941 _T("the most distant heights [\"William! Stern der schönsten Ferne\": from Goethe's, ")
942 _T("\"Between Two Worlds\"]; in regard to which one might recall the lines: \"the ")
943 _T("stars, these we do not desire\" [from Goethe's, \"Comfort in Tears\"]). But, aside ")
944 _T("from these suggestions of our vanity, the activity of the genius seems in no ")
945 _T("way fundamentally different from the activity of the inventor of machines, the ")
946 _T("scholar of astronomy or history, the master of tactics. All these activities ")
947 _T("are explicable if one pictures to oneself people whose thinking is active in ")
948 _T("one direction, who employ everything as material, who always zealously observe ")
949 _T("their own inner life and that of others, who perceive everywhere models and ")
950 _T("incentives, who never tire of combining together the means available to them. ")
951 _T("Genius too does nothing except learn first how to lay bricks then how to build, ")
952 _T("except continually seek for material and continually form itself around it. ")
953 _T("Every activity of man is amazingly complicated, not only that of the genius: ")
954 _T("but none is a \"miracle.\"\97 Whence, then, the belief that genius exists only in ")
955 _T("the artist, orator and philosopher? that only they have \"intuition\"? (Whereby ")
956 _T("they are supposed to possess a kind of miraculous eyeglass with which they can ")
957 _T("see directly into \"the essence of the thing\"!) It is clear that people speak of ")
958 _T("genius only where the effects of the great intellect are most pleasant to them ")
959 _T("and where they have no desire to feel envious. To call someone \"divine\" means: ")
960 _T("\"here there is no need for us to compete.\" Then, everything finished and ")
961 _T("complete is regarded with admiration, everything still becoming is undervalued. ")
962 _T("But no one can see in the work of the artist how it has become; that is its ")
963 _T("advantage, for wherever one can see the act of becoming one grows somewhat ")
964 _T("cool. The finished and perfect art of representation repulses all thinking as ")
965 _T("to how it has become; it tyrannizes as present completeness and perfection. ")
966 _T("That is why the masters of the art of representation count above all as gifted ")
967 _T("with genius and why men of science do not. In reality, this evaluation of the ")
968 _T("former and undervaluation of the latter is only a piece of childishness in the ")
969 _T("realm of reason. ")
970 _T("\n\n")
971 _T("163 The serious workman.\97 Do not talk about giftedness, inborn talents! One can ")
972 _T("name great men of all kinds who were very little gifted. The acquired ")
973 _T("greatness, became \"geniuses\" (as we put it), through qualities the lack of ")
974 _T("which no one who knew what they were would boast of: they all possessed that ")
975 _T("seriousness of the efficient workman which first learns to construct the parts ")
976 _T("properly before it ventures to fashion a great whole; they allowed themselves ")
977 _T("time for it, because they took more pleasure in making the little, secondary ")
978 _T("things well than in the effect of a dazzling whole. the recipe for becoming a ")
979 _T("good novelist, for example, is easy to give, but to carry it out presupposes ")
980 _T("qualities one is accustomed to overlook when one says \"I do not have enough ")
981 _T("talent.\" One has only to make a hundred or so sketches for novels, none longer ")
982 _T("than two pages but of such distinctness that every word in them is necessary; ")
983 _T("one should write down anecdotes each day until one has learned how to give them ")
984 _T("the most pregnant and effective form; one should be tireless in collecting and ")
985 _T("describing human types and characters; one should above all relate things to ")
986 _T("others and listen to others relate, keeping one's eyes and ears open for the ")
987 _T("effect produced on those present, one should travel like a landscape painter or ")
988 _T("costume designer; one should excerpt for oneself out of the individual sciences ")
989 _T("everything that will produce an artistic effect when it is well described, one ")
990 _T("should, finally, reflect on the motives of human actions, disdain no signpost ")
991 _T("to instruction about them and be a collector of these things by day and night. ")
992 _T("One should continue in this many-sided exercise some ten years: what is then ")
993 _T("created in the workshop, however, will be fit to go out into the world.\97 What, ")
994 _T("however, do most people do? They begin, not with the parts, but with the whole. ")
995 _T("Perhaps they chance to strike a right note, excite attention and from then on ")
996 _T("strike worse and worse notes, for good, natural reasons.\97 Sometimes, when the ")
997 _T("character and intellect needed to formulate such a life-plan are lacking, fate ")
998 _T("and need take their place and lead the future master step by step through all ")
999 _T("the stipulations of his trade. ")
1000 _T("\n\n")
1001 _T("164 Peril and profit in the cult of the genius.\97 The belief in great, superior, ")
1002 _T("fruitful spirits is not necessarily, yet nonetheless is very frequently ")
1003 _T("associated with that religious or semi-religious superstition that these ")
1004 _T("spirits are of supra-human origin and possess certain miraculous abilities by ")
1005 _T("virtue of which they acquire their knowledge by quite other means than the rest ")
1006 _T("of mankind. One ascribes to them, it seems, a direct view of the nature of the ")
1007 _T("world, as it were a hole in the cloak of appearance, and believes that, by ")
1008 _T("virtue of this miraculous seer's vision, they are able to communicate something ")
1009 _T("conclusive and decisive about man and the world without the toil and ")
1010 _T("rigorousness required by science. As long as there continue to be those who ")
1011 _T("believe in the miraculous in the domain of knowledge one can perhaps concede ")
1012 _T("that these people themselves derive some benefit from their belief, inasmuch as ")
1013 _T("through their unconditional subjection to the great spirits they create for ")
1014 _T("their own spirit during its time of development the finest form of discipline ")
1015 _T("and schooling. On the other hand, it is at least questionable whether the ")
1016 _T("superstitious belief in genius, in its privileges and special abilities, is of ")
1017 _T("benefit to the genius himself if it takes root in him. It is in any event a ")
1018 _T("dangerous sign when a man is assailed by awe of himself, whether it be the ")
1019 _T("celebrated Caesar's awe of Caesar or the awe of one's own genius now under ")
1020 _T("consideration; when the sacrificial incense which is properly rendered only to ")
1021 _T("a god penetrates the brain of the genius, so that his head begins to swim and ")
1022 _T("he comes to regard himself as something supra-human. The consequences that ")
1023 _T("slowly result are: the feeling of irresponsibility, of exceptional rights, the ")
1024 _T("belief that he confers a favor by his mere presence, insane rage when anyone ")
1025 _T("attempts even to compare him with others, let alone to rate him beneath them, ")
1026 _T("or to draw attention to lapses in his work. Because he ceases to practice ")
1027 _T("criticism of himself, at last one pinion after the other falls out of his ")
1028 _T("plumage: that superstitious eats at the roots of his powers and perhaps even ")
1029 _T("turns him into a hypocrite after his powers have fled from him. For the great ")
1030 _T("spirits themselves it is therefore probably more beneficial if they acquire an ")
1031 _T("insight into the nature and origin of their powers, if they grasp, that is to ")
1032 _T("say, what purely human qualities have come together in them and what fortunate ")
1033 _T("circumstances attended them: in the first place undiminished energy, resolute ")
1034 _T("application to individual goals, great personal courage, then the good fortune ")
1035 _T("to receive an upbringing which offered in the early years the finest teachers, ")
1036 _T("models and methods. To be sure, when their goal is the production of the ")
1037 _T("greatest possible effect, unclarity with regard to oneself and that ")
1038 _T("semi-insanity superadded to it has always achieved much; for what has been ")
1039 _T("admired and envied at all times has been that power in them by virtue of which ")
1040 _T("they render men will-less and sweep them away into the delusion that the ")
1041 _T("leaders they are following are supra-natural. Indeed, it elevates and inspires ")
1042 _T("men to believe that someone is in possession of supra-natural powers: to this ")
1043 _T("extent Plato was right to say [Plato: Phaedrus, 244a] that madness has brought ")
1044 _T("the greatest of blessings upon mankind.\97 In rare individual cases this portion ")
1045 _T("of madness may, indeed, actually have been the means by which such a nature, ")
1046 _T("excessive in all directions, was held firmly together: in the life of ")
1047 _T("individuals, too, illusions that are in themselves poisons often play the role ")
1048 _T("of healers; yet, in the end, in the case of every \"genius\" who believes in his ")
1049 _T("own divinity the poison shows itself to the same degree as his \"genius\" grows ")
1050 _T("old: one may recall, for example, the case of Napoleon, whose nature certainly ")
1051 _T("grew into the mighty unity that sets him apart from all men of modern times ")
1052 _T("precisely through his belief in himself and his star and through the contempt ")
1053 _T("for men that flowed from it; until in the end, however, this same belief went ")
1054 _T("over into an almost insane fatalism, robbed him of his acuteness and swiftness ")
1055 _T("of perception, and became the cause of his destruction.");