]> git.saurik.com Git - wxWidgets.git/blob - samples/scroll/scroll.cpp
1bec08436a3c29920185a0b15f11fea9cf136290
[wxWidgets.git] / samples / scroll / scroll.cpp
1 /*
2 * Program: scroll
3 *
4 * Author: Robert Roebling
5 *
6 * Copyright: (C) 1998, Robert Roebling
7 * 2002, Ron Lee
8 * 2003, Matt Gregory
9 *
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( -1, ( 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( -1, 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 )
410 {
411 SetBackgroundColour( wxT("GREEN") );
412
413 // Set the rate we'd like for scrolling.
414
415 SetScrollRate( 5, 5 );
416
417 // Populate a sizer with a 'resizing' button and some
418 // other static decoration
419
420 wxFlexGridSizer *innersizer = new wxFlexGridSizer( 2, 2 );
421
422 m_button = new wxButton( this,
423 ID_RESIZEBUTTON,
424 _T("Press me"),
425 wxDefaultPosition,
426 SMALL_BUTTON );
427
428 // We need to do this here, because wxADJUST_MINSIZE below
429 // will cause the initial size to be ignored for Best/Min size.
430 // It would be nice to fix the sizers to handle this a little
431 // more cleanly.
432
433 m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() );
434
435 innersizer->Add( m_button,
436 0,
437 wxALIGN_CENTER | wxALL | wxADJUST_MINSIZE,
438 20 );
439
440 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("This is just") ),
441 0,
442 wxALIGN_CENTER );
443
444 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("some decoration") ),
445 0,
446 wxALIGN_CENTER );
447
448 innersizer->Add( new wxStaticText( this, wxID_ANY, _T("for you to scroll...") ),
449 0,
450 wxALIGN_CENTER );
451
452 // Then use the sizer to set the scrolled region size.
453
454 SetSizer( innersizer );
455 }
456
457 void MyAutoScrollWindow::OnResizeClick( wxCommandEvent &WXUNUSED( event ) )
458 {
459 // Arbitrarily resize the button to change the minimum size of
460 // the (scrolled) sizer.
461
462 if( m_button->GetSize() == SMALL_BUTTON )
463 m_button->SetSizeHints( LARGE_BUTTON.GetWidth(), LARGE_BUTTON.GetHeight() );
464 else
465 m_button->SetSizeHints( SMALL_BUTTON.GetWidth(), SMALL_BUTTON.GetHeight() );
466
467 // Force update layout and scrollbars, since nothing we do here
468 // necessarily generates a size event which would do it for us.
469
470 FitInside();
471 }
472
473 // ----------------------------------------------------------------------------
474 // MyFrame
475 // ----------------------------------------------------------------------------
476
477 const long ID_QUIT = wxNewId();
478 const long ID_ABOUT = wxNewId();
479 const long ID_DELETE_ALL = wxNewId();
480 const long ID_INSERT_NEW = wxNewId();
481
482 IMPLEMENT_DYNAMIC_CLASS( MyFrame, wxFrame )
483
484 BEGIN_EVENT_TABLE(MyFrame,wxFrame)
485 EVT_MENU (ID_DELETE_ALL, MyFrame::OnDeleteAll)
486 EVT_MENU (ID_INSERT_NEW, MyFrame::OnInsertNew)
487 EVT_MENU (ID_ABOUT, MyFrame::OnAbout)
488 EVT_MENU (ID_QUIT, MyFrame::OnQuit)
489 END_EVENT_TABLE()
490
491 MyFrame::MyFrame()
492 : wxFrame( (wxFrame *)NULL, wxID_ANY, _T("wxScrolledWindow sample"),
493 wxPoint(20,20), wxSize(800,500) )
494 {
495 wxMenu *file_menu = new wxMenu();
496 file_menu->Append( ID_DELETE_ALL, _T("Delete all"));
497 file_menu->Append( ID_INSERT_NEW, _T("Insert new"));
498 file_menu->Append( ID_ABOUT, _T("&About.."));
499 file_menu->Append( ID_QUIT, _T("E&xit\tAlt-X"));
500
501 wxMenuBar *menu_bar = new wxMenuBar();
502 menu_bar->Append(file_menu, _T("&File"));
503
504 SetMenuBar( menu_bar );
505
506 #if wxUSE_STATUSBAR
507 CreateStatusBar(2);
508 int widths[] = { -1, 100 };
509 SetStatusWidths( 2, widths );
510 #endif // wxUSE_STATUSBAR
511
512 wxBoxSizer *topsizer = new wxBoxSizer( wxHORIZONTAL );
513 // subsizer splits topsizer down the middle
514 wxBoxSizer *subsizer = new wxBoxSizer( wxVERTICAL );
515
516 // Setting an explicit size here is superfluous, it will be overridden
517 // by the sizer in any case.
518 m_canvas = new MyCanvas( this, wxID_ANY, wxPoint(0,0), wxSize(100,100) );
519
520 // This is done with ScrollRate/VirtualSize in MyCanvas ctor now,
521 // both should produce identical results.
522 //m_canvas->SetScrollbars( 10, 10, 50, 100 );
523
524 subsizer->Add( m_canvas, 1, wxEXPAND );
525 subsizer->Add( new MyAutoScrollWindow( this ), 1, wxEXPAND );
526
527 wxSizer *sizerBtm = new wxBoxSizer(wxHORIZONTAL);
528 sizerBtm->Add( new MyScrolledWindowDumb(this), 1, wxEXPAND );
529 sizerBtm->Add( new MyScrolledWindowSmart(this), 1, wxEXPAND );
530 subsizer->Add( sizerBtm, 1, wxEXPAND );
531
532 topsizer->Add( subsizer, 1, wxEXPAND );
533 topsizer->Add( new MyAutoTimedScrollingWindow( this ), 1, wxEXPAND );
534
535 SetSizer( topsizer );
536 }
537
538 void MyFrame::OnDeleteAll( wxCommandEvent &WXUNUSED(event) )
539 {
540 m_canvas->DestroyChildren();
541 }
542
543 void MyFrame::OnInsertNew( wxCommandEvent &WXUNUSED(event) )
544 {
545 (void)new wxButton( m_canvas, wxID_ANY, _T("Hello"), wxPoint(100,100) );
546 }
547
548 void MyFrame::OnQuit( wxCommandEvent &WXUNUSED(event) )
549 {
550 Close( true );
551 }
552
553 void MyFrame::OnAbout( wxCommandEvent &WXUNUSED(event) )
554 {
555 (void)wxMessageBox( _T("wxScroll demo\n")
556 _T("Robert Roebling (c) 1998\n")
557 _T("Autoscrolling examples\n")
558 _T("Ron Lee (c) 2002\n")
559 _T("Auto-timed-scrolling example\n")
560 _T("Matt Gregory (c) 2003\n"),
561 _T("About wxScroll Demo"),
562 wxICON_INFORMATION | wxOK );
563 }
564
565 //-----------------------------------------------------------------------------
566 // MyApp
567 //-----------------------------------------------------------------------------
568
569 bool MyApp::OnInit()
570 {
571 wxFrame *frame = new MyFrame();
572 frame->Show( true );
573
574 return true;
575 }
576
577 // ----------------------------------------------------------------------------
578 // MyScrolledWindowXXX
579 // ----------------------------------------------------------------------------
580
581 void MyScrolledWindowDumb::OnDraw(wxDC& dc)
582 {
583 // this is useful to see which lines are redrawn
584 static size_t s_redrawCount = 0;
585 dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE);
586
587 wxCoord y = 0;
588 for ( size_t line = 0; line < m_nLines; line++ )
589 {
590 wxCoord yPhys;
591 CalcScrolledPosition(0, y, NULL, &yPhys);
592
593 dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"),
594 line, y, yPhys), 0, y);
595 y += m_hLine;
596 }
597 }
598
599 void MyScrolledWindowSmart::OnDraw(wxDC& dc)
600 {
601 // this is useful to see which lines are redrawn
602 static size_t s_redrawCount = 0;
603 dc.SetTextForeground(s_redrawCount++ % 2 ? *wxRED : *wxBLUE);
604
605 // update region is always in device coords, translate to logical ones
606 wxRect rectUpdate = GetUpdateRegion().GetBox();
607 CalcUnscrolledPosition(rectUpdate.x, rectUpdate.y,
608 &rectUpdate.x, &rectUpdate.y);
609
610 size_t lineFrom = rectUpdate.y / m_hLine,
611 lineTo = rectUpdate.GetBottom() / m_hLine;
612
613 if ( lineTo > m_nLines - 1)
614 lineTo = m_nLines - 1;
615
616 wxCoord y = lineFrom*m_hLine;
617 for ( size_t line = lineFrom; line <= lineTo; line++ )
618 {
619 wxCoord yPhys;
620 CalcScrolledPosition(0, y, NULL, &yPhys);
621
622 dc.DrawText(wxString::Format(_T("Line %u (logical %d, physical %d)"),
623 line, y, yPhys), 0, y);
624 y += m_hLine;
625 }
626 }
627
628 // ----------------------------------------------------------------------------
629 // MyAutoTimedScrollingWindow
630 // ----------------------------------------------------------------------------
631
632 BEGIN_EVENT_TABLE(MyAutoTimedScrollingWindow, wxScrolledWindow)
633 EVT_LEFT_DOWN(MyAutoTimedScrollingWindow::OnMouseLeftDown)
634 EVT_LEFT_UP(MyAutoTimedScrollingWindow::OnMouseLeftUp)
635 EVT_MOTION(MyAutoTimedScrollingWindow::OnMouseMove)
636 EVT_SCROLLWIN(MyAutoTimedScrollingWindow::OnScroll)
637 END_EVENT_TABLE()
638
639 MyAutoTimedScrollingWindow::MyAutoTimedScrollingWindow(wxWindow* parent)
640 : wxScrolledWindow(parent, -1, wxDefaultPosition, wxDefaultSize
641 //, wxSUNKEN_BORDER) // can't seem to do it this way
642 , wxVSCROLL | wxHSCROLL | wxSUNKEN_BORDER)
643 , m_selStart(-1, -1), m_cursor(-1, -1)
644 , m_font(9, wxFONTFAMILY_TELETYPE, wxFONTSTYLE_NORMAL
645 , wxFONTWEIGHT_NORMAL)
646 {
647 wxClientDC dc(this);
648 // query dc for text size
649 dc.SetFont(m_font);
650 dc.GetTextExtent(wxString(_T("A")), &m_fontW, &m_fontH);
651 // set up the virtual window
652 SetScrollbars(m_fontW, m_fontH, sm_lineLen, sm_lineCnt);
653 }
654
655 wxRect MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars
656 (wxRect updRect) const
657 {
658 wxPoint pos(updRect.GetPosition());
659 pos = DeviceCoordsToGraphicalChars(pos);
660 updRect.x = pos.x;
661 updRect.y = pos.y;
662 updRect.width /= m_fontW;
663 updRect.height /= m_fontH;
664 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
665 // so an off-by-one correction is needed
666 ++updRect.width; // kludge
667 ++updRect.height; // kludge
668 return updRect;
669 }
670
671 wxPoint MyAutoTimedScrollingWindow::DeviceCoordsToGraphicalChars
672 (wxPoint pos) const
673 {
674 pos.x /= m_fontW;
675 pos.y /= m_fontH;
676 int vX, vY;
677 GetViewStart(&vX, &vY);
678 pos.x += vX;
679 pos.y += vY;
680 return pos;
681 }
682
683 wxPoint MyAutoTimedScrollingWindow::GraphicalCharToDeviceCoords
684 (wxPoint pos) const
685 {
686 int vX, vY;
687 GetViewStart(&vX, &vY);
688 pos.x -= vX;
689 pos.y -= vY;
690 pos.x *= m_fontW;
691 pos.y *= m_fontH;
692 return pos;
693 }
694
695 wxRect MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars
696 (wxRect updRect) const
697 {
698 wxPoint pos(updRect.GetPosition());
699 pos = LogicalCoordsToGraphicalChars(pos);
700 updRect.x = pos.x;
701 updRect.y = pos.y;
702 updRect.width /= m_fontW;
703 updRect.height /= m_fontH;
704 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
705 // so an off-by-one correction is needed
706 ++updRect.width; // kludge
707 ++updRect.height; // kludge
708 return updRect;
709 }
710
711 wxPoint MyAutoTimedScrollingWindow::LogicalCoordsToGraphicalChars
712 (wxPoint pos) const
713 {
714 pos.x /= m_fontW;
715 pos.y /= m_fontH;
716 return pos;
717 }
718
719 wxPoint MyAutoTimedScrollingWindow::GraphicalCharToLogicalCoords
720 (wxPoint pos) const
721 {
722 pos.x *= m_fontW;
723 pos.y *= m_fontH;
724 return pos;
725 }
726
727 void MyAutoTimedScrollingWindow::MyRefresh()
728 {
729 static wxPoint lastSelStart(-1, -1), lastCursor(-1, -1);
730 // refresh last selected area (to deselect previously selected text)
731 wxRect lastUpdRect(
732 GraphicalCharToDeviceCoords(lastSelStart),
733 GraphicalCharToDeviceCoords(lastCursor)
734 );
735 // off-by-one corrections, necessary because it's not possible to know
736 // when to round up until rect is normalized by lastUpdRect constructor
737 lastUpdRect.width += m_fontW; // kludge
738 lastUpdRect.height += m_fontH; // kludge
739 // refresh currently selected (to select previously unselected text)
740 wxRect updRect(
741 GraphicalCharToDeviceCoords(m_selStart),
742 GraphicalCharToDeviceCoords(m_cursor)
743 );
744 // off-by-one corrections
745 updRect.width += m_fontW; // kludge
746 updRect.height += m_fontH; // kludge
747 // find necessary refresh areas
748 wxCoord rx = lastUpdRect.x;
749 wxCoord ry = lastUpdRect.y;
750 wxCoord rw = updRect.x - lastUpdRect.x;
751 wxCoord rh = lastUpdRect.height;
752 if (rw && rh) {
753 RefreshRect(DCNormalize(rx, ry, rw, rh));
754 }
755 rx = updRect.x;
756 ry = updRect.y + updRect.height;
757 rw= updRect.width;
758 rh = (lastUpdRect.y + lastUpdRect.height) - (updRect.y + updRect.height);
759 if (rw && rh) {
760 RefreshRect(DCNormalize(rx, ry, rw, rh));
761 }
762 rx = updRect.x + updRect.width;
763 ry = lastUpdRect.y;
764 rw = (lastUpdRect.x + lastUpdRect.width) - (updRect.x + updRect.width);
765 rh = lastUpdRect.height;
766 if (rw && rh) {
767 RefreshRect(DCNormalize(rx, ry, rw, rh));
768 }
769 rx = updRect.x;
770 ry = lastUpdRect.y;
771 rw = updRect.width;
772 rh = updRect.y - lastUpdRect.y;
773 if (rw && rh) {
774 RefreshRect(DCNormalize(rx, ry, rw, rh));
775 }
776 // update last
777 lastSelStart = m_selStart;
778 lastCursor = m_cursor;
779 }
780
781 bool MyAutoTimedScrollingWindow::IsSelected(int chX, int chY) const
782 {
783 if (IsInside(chX, m_selStart.x, m_cursor.x)
784 && IsInside(chY, m_selStart.y, m_cursor.y)) {
785 return TRUE;
786 }
787 return FALSE;
788 }
789
790 bool MyAutoTimedScrollingWindow::IsInside(int k, int bound1, int bound2)
791 {
792 if ((k >= bound1 && k <= bound2) || (k >= bound2 && k <= bound1)) {
793 return TRUE;
794 }
795 return FALSE;
796 }
797
798 wxRect MyAutoTimedScrollingWindow::DCNormalize(wxCoord x, wxCoord y
799 , wxCoord w, wxCoord h)
800 {
801 // this is needed to get rid of the graphical remnants from the selection
802 // I think it's because DrawRectangle() excludes a pixel in either direction
803 const int kludge = 1;
804 // make (x, y) the top-left corner
805 if (w < 0) {
806 w = -w + kludge;
807 x -= w;
808 } else {
809 x -= kludge;
810 w += kludge;
811 }
812 if (h < 0) {
813 h = -h + kludge;
814 y -= h;
815 } else {
816 y -= kludge;
817 h += kludge;
818 }
819 return wxRect(x, y, w, h);
820 }
821
822 void MyAutoTimedScrollingWindow::OnDraw(wxDC& dc)
823 {
824 dc.SetFont(m_font);
825 wxBrush normBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOW)
826 , wxSOLID);
827 wxBrush selBrush(wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHT)
828 , wxSOLID);
829 dc.SetPen(*wxTRANSPARENT_PEN);
830 // draw the characters
831 // 1. for each update region
832 for (wxRegionIterator upd(GetUpdateRegion()); upd; ++upd) {
833 wxRect updRect = upd.GetRect();
834 wxRect updRectInGChars(DeviceCoordsToGraphicalChars(updRect));
835 // 2. for each row of chars in the update region
836 for (int chY = updRectInGChars.y
837 ; chY <= updRectInGChars.y + updRectInGChars.height; ++chY) {
838 // 3. for each character in the row
839 for (int chX = updRectInGChars.x
840 ; chX <= updRectInGChars.x + updRectInGChars.width
841 ; ++chX) {
842 // 4. set up dc
843 if (IsSelected(chX, chY)) {
844 dc.SetBrush(selBrush);
845 dc.SetTextForeground( wxSystemSettings::GetColour
846 (wxSYS_COLOUR_HIGHLIGHTTEXT));
847 } else {
848 dc.SetBrush(normBrush);
849 dc.SetTextForeground( wxSystemSettings::GetColour
850 (wxSYS_COLOUR_WINDOWTEXT));
851 }
852 // 5. find position info
853 wxPoint charPos = GraphicalCharToLogicalCoords(wxPoint
854 (chX, chY));
855 // 6. draw!
856 dc.DrawRectangle(charPos.x, charPos.y, m_fontW, m_fontH);
857 if (chY < sm_lineCnt && chX < sm_lineLen) {
858 int charIndex = chY * sm_lineLen + chX;
859 dc.DrawText(wxString(sm_testData[charIndex])
860 , charPos.x, charPos.y);
861 }
862 }
863 }
864 }
865 }
866
867 void MyAutoTimedScrollingWindow::OnMouseLeftDown(wxMouseEvent& event)
868 {
869 // initial press of mouse button sets the beginning of the selection
870 m_selStart = DeviceCoordsToGraphicalChars(event.GetPosition());
871 // set the cursor to the same position
872 m_cursor = m_selStart;
873 // draw/erase selection
874 MyRefresh();
875 }
876
877 void MyAutoTimedScrollingWindow::OnMouseLeftUp(wxMouseEvent& WXUNUSED(event))
878 {
879 // this test is necessary
880 if (HasCapture()) {
881 // uncapture mouse
882 ReleaseMouse();
883 }
884 }
885
886 void MyAutoTimedScrollingWindow::OnMouseMove(wxMouseEvent& event)
887 {
888 // if user is dragging
889 if (event.Dragging() && event.LeftIsDown()) {
890 // set the new cursor position
891 m_cursor = DeviceCoordsToGraphicalChars(event.GetPosition());
892 // draw/erase selection
893 MyRefresh();
894 // capture mouse to activate auto-scrolling
895 if (!HasCapture()) {
896 CaptureMouse();
897 }
898 }
899 }
900
901 void MyAutoTimedScrollingWindow::OnScroll(wxScrollWinEvent& event)
902 {
903 // need to move the cursor when autoscrolling
904 // FIXME: the cursor also moves when the scrollbar arrows are clicked
905 if (HasCapture()) {
906 if (event.GetOrientation() == wxHORIZONTAL) {
907 if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) {
908 --m_cursor.x;
909 } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) {
910 ++m_cursor.x;
911 }
912 } else if (event.GetOrientation() == wxVERTICAL) {
913 if (event.GetEventType() == wxEVT_SCROLLWIN_LINEUP) {
914 --m_cursor.y;
915 } else if (event.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN) {
916 ++m_cursor.y;
917 }
918 }
919 }
920 MyRefresh();
921 event.Skip();
922 }
923
924 const int MyAutoTimedScrollingWindow::sm_lineCnt = 125;
925 const int MyAutoTimedScrollingWindow::sm_lineLen = 79;
926 const wxChar* MyAutoTimedScrollingWindow::sm_testData = _T("\
927 162 Cult of the genius out of vanity.\97 Because we think well of ourselves, but \
928 nonetheless never suppose ourselves capable of producing a painting like one of\
929 Raphael's or a dramatic scene like one of Shakespeare's, we convince ourselves \
930 that the capacity to do so is quite extraordinarily marvelous, a wholly \
931 uncommon accident, or, if we are still religiously inclined, a mercy from on \
932 high. Thus our vanity, our self-love, promotes the cult of the genius: for only\
933 if we think of him as being very remote from us, as a miraculum, does he not \
934 aggrieve us (even Goethe, who was without envy, called Shakespeare his star of \
935 the most distant heights [\"William! Stern der schönsten Ferne\": from Goethe's, \
936 \"Between Two Worlds\"]; in regard to which one might recall the lines: \"the \
937 stars, these we do not desire\" [from Goethe's, \"Comfort in Tears\"]). But, aside\
938 from these suggestions of our vanity, the activity of the genius seems in no \
939 way fundamentally different from the activity of the inventor of machines, the \
940 scholar of astronomy or history, the master of tactics. All these activities \
941 are explicable if one pictures to oneself people whose thinking is active in \
942 one direction, who employ everything as material, who always zealously observe \
943 their own inner life and that of others, who perceive everywhere models and \
944 incentives, who never tire of combining together the means available to them. \
945 Genius too does nothing except learn first how to lay bricks then how to build,\
946 except continually seek for material and continually form itself around it. \
947 Every activity of man is amazingly complicated, not only that of the genius: \
948 but none is a \"miracle.\"\97 Whence, then, the belief that genius exists only in \
949 the artist, orator and philosopher? that only they have \"intuition\"? (Whereby \
950 they are supposed to possess a kind of miraculous eyeglass with which they can \
951 see directly into \"the essence of the thing\"!) It is clear that people speak of\
952 ") _T("\
953 genius only where the effects of the great intellect are most pleasant to them \
954 and where they have no desire to feel envious. To call someone \"divine\" means: \
955 \"here there is no need for us to compete.\" Then, everything finished and \
956 complete is regarded with admiration, everything still becoming is undervalued.\
957 But no one can see in the work of the artist how it has become; that is its \
958 advantage, for wherever one can see the act of becoming one grows somewhat \
959 cool. The finished and perfect art of representation repulses all thinking as \
960 to how it has become; it tyrannizes as present completeness and perfection. \
961 That is why the masters of the art of representation count above all as gifted \
962 with genius and why men of science do not. In reality, this evaluation of the \
963 former and undervaluation of the latter is only a piece of childishness in the \
964 realm of reason. \
965 \
966 \
967 163 The serious workman.\97 Do not talk about giftedness, inborn talents! One can\
968 name great men of all kinds who were very little gifted. The acquired \
969 greatness, became \"geniuses\" (as we put it), through qualities the lack of \
970 which no one who knew what they were would boast of: they all possessed that \
971 seriousness of the efficient workman which first learns to construct the parts \
972 properly before it ventures to fashion a great whole; they allowed themselves \
973 time for it, because they took more pleasure in making the little, secondary \
974 things well than in the effect of a dazzling whole. the recipe for becoming a \
975 good novelist, for example, is easy to give, but to carry it out presupposes \
976 qualities one is accustomed to overlook when one says \"I do not have enough \
977 talent.\" One has only to make a hundred or so sketches for novels, none longer \
978 ") _T("\
979 than two pages but of such distinctness that every word in them is necessary; \
980 one should write down anecdotes each day until one has learned how to give them\
981 the most pregnant and effective form; one should be tireless in collecting and \
982 describing human types and characters; one should above all relate things to \
983 others and listen to others relate, keeping one's eyes and ears open for the \
984 effect produced on those present, one should travel like a landscape painter or\
985 costume designer; one should excerpt for oneself out of the individual sciences\
986 everything that will produce an artistic effect when it is well described, one \
987 should, finally, reflect on the motives of human actions, disdain no signpost \
988 to instruction about them and be a collector of these things by day and night. \
989 One should continue in this many-sided exercise some ten years: what is then \
990 created in the workshop, however, will be fit to go out into the world.\97 What, \
991 however, do most people do? They begin, not with the parts, but with the whole.\
992 Perhaps they chance to strike a right note, excite attention and from then on \
993 strike worse and worse notes, for good, natural reasons.\97 Sometimes, when the \
994 character and intellect needed to formulate such a life-plan are lacking, fate \
995 and need take their place and lead the future master step by step through all \
996 the stipulations of his trade. \
997 \
998 \
999 164 Peril and profit in the cult of the genius.\97 The belief in great, superior,\
1000 fruitful spirits is not necessarily, yet nonetheless is very frequently \
1001 associated with that religious or semi-religious superstition that these \
1002 spirits are of supra-human origin and possess certain miraculous abilities by \
1003 virtue of which they acquire their knowledge by quite other means than the rest\
1004 ") _T("\
1005 of mankind. One ascribes to them, it seems, a direct view of the nature of the \
1006 world, as it were a hole in the cloak of appearance, and believes that, by \
1007 virtue of this miraculous seer's vision, they are able to communicate something\
1008 conclusive and decisive about man and the world without the toil and \
1009 rigorousness required by science. As long as there continue to be those who \
1010 believe in the miraculous in the domain of knowledge one can perhaps concede \
1011 that these people themselves derive some benefit from their belief, inasmuch as\
1012 through their unconditional subjection to the great spirits they create for \
1013 their own spirit during its time of development the finest form of discipline \
1014 and schooling. On the other hand, it is at least questionable whether the \
1015 superstitious belief in genius, in its privileges and special abilities, is of \
1016 benefit to the genius himself if it takes root in him. It is in any event a \
1017 dangerous sign when a man is assailed by awe of himself, whether it be the \
1018 celebrated Caesar's awe of Caesar or the awe of one's own genius now under \
1019 consideration; when the sacrificial incense which is properly rendered only to \
1020 a god penetrates the brain of the genius, so that his head begins to swim and \
1021 he comes to regard himself as something supra-human. The consequences that \
1022 slowly result are: the feeling of irresponsibility, of exceptional rights, the \
1023 belief that he confers a favor by his mere presence, insane rage when anyone \
1024 attempts even to compare him with others, let alone to rate him beneath them, \
1025 or to draw attention to lapses in his work. Because he ceases to practice \
1026 criticism of himself, at last one pinion after the other falls out of his \
1027 plumage: that superstitious eats at the roots of his powers and perhaps even \
1028 turns him into a hypocrite after his powers have fled from him. For the great \
1029 spirits themselves it is therefore probably more beneficial if they acquire an \
1030 ") _T("\
1031 insight into the nature and origin of their powers, if they grasp, that is to \
1032 say, what purely human qualities have come together in them and what fortunate \
1033 circumstances attended them: in the first place undiminished energy, resolute \
1034 application to individual goals, great personal courage, then the good fortune \
1035 to receive an upbringing which offered in the early years the finest teachers, \
1036 models and methods. To be sure, when their goal is the production of the \
1037 greatest possible effect, unclarity with regard to oneself and that \
1038 semi-insanity superadded to it has always achieved much; for what has been \
1039 admired and envied at all times has been that power in them by virtue of which \
1040 they render men will-less and sweep them away into the delusion that the \
1041 leaders they are following are supra-natural. Indeed, it elevates and inspires \
1042 men to believe that someone is in possession of supra-natural powers: to this \
1043 extent Plato was right to say [Plato: Phaedrus, 244a] that madness has brought \
1044 the greatest of blessings upon mankind.\97 In rare individual cases this portion \
1045 of madness may, indeed, actually have been the means by which such a nature, \
1046 excessive in all directions, was held firmly together: in the life of \
1047 individuals, too, illusions that are in themselves poisons often play the role \
1048 of healers; yet, in the end, in the case of every \"genius\" who believes in his \
1049 own divinity the poison shows itself to the same degree as his \"genius\" grows \
1050 old: one may recall, for example, the case of Napoleon, whose nature certainly \
1051 grew into the mighty unity that sets him apart from all men of modern times \
1052 precisely through his belief in himself and his star and through the contempt \
1053 for men that flowed from it; until in the end, however, this same belief went \
1054 over into an almost insane fatalism, robbed him of his acuteness and swiftness \
1055 of perception, and became the cause of his destruction. \
1056 ");
1057