1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxScrolledWindow sample
4 // Author: Robert Roebling
6 // Copyright: (C) 1998 Robert Roebling, 2002 Ron Lee, 2003 Matt Gregory
7 // (C) 2008 Vadim Zeitlin
8 // Licence: wxWindows license
9 /////////////////////////////////////////////////////////////////////////////
11 #include "wx/wxprec.h"
23 #include "wx/tglbtn.h"
25 // ----------------------------------------------------------------------------
27 // ----------------------------------------------------------------------------
29 // MySimpleCanvas: a scrolled window which draws a simple rectangle
30 class MySimpleCanvas
: public wxScrolledWindow
35 // these numbers are not multiple of 10 (our scroll step) to test for
36 // the absence of rounding errors (e.g. we should have one more page
37 // than WIDTH/10 to show the right side of the rectangle)
42 MySimpleCanvas(wxWindow
*parent
)
43 : wxScrolledWindow(parent
, wxID_ANY
)
45 SetScrollRate( 10, 10 );
46 SetVirtualSize( WIDTH
, HEIGHT
);
47 SetBackgroundColour( *wxWHITE
);
49 Connect(wxEVT_PAINT
, wxPaintEventHandler(MySimpleCanvas
::OnPaint
));
53 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
57 // this call is vital: it adjusts the dc to account for the current
61 dc
.SetPen( *wxRED_PEN
);
62 dc
.SetBrush( *wxTRANSPARENT_BRUSH
);
63 dc
.DrawRectangle( 0, 0, WIDTH
, HEIGHT
);
68 // MySimpleFrame: a frame which contains a MySimpleCanvas
69 class MySimpleFrame
: public wxFrame
72 MySimpleFrame(wxWindow
*parent
)
73 : wxFrame(parent
, wxID_ANY
, "MySimpleCanvas")
75 new MySimpleCanvas(this);
77 // ensure that we have scrollbars initially
78 SetClientSize(MySimpleCanvas
::WIDTH
/2, MySimpleCanvas
::HEIGHT
/2);
84 // ----------------------------------------------------------------------
85 // a more complex example
86 // ----------------------------------------------------------------------
89 class MyCanvas
: public wxScrolledWindow
92 MyCanvas(wxWindow
*parent
);
95 void OnPaint(wxPaintEvent
& event
);
96 void OnQueryPosition(wxCommandEvent
& event
);
97 void OnAddButton(wxCommandEvent
& event
);
98 void OnDeleteButton(wxCommandEvent
& event
);
99 void OnMoveButton(wxCommandEvent
& event
);
100 void OnScrollWin(wxCommandEvent
& event
);
101 void OnMouseRightDown(wxMouseEvent
& event
);
102 void OnMouseWheel(wxMouseEvent
& event
);
106 DECLARE_EVENT_TABLE()
109 class MyCanvasFrame
: public wxFrame
112 MyCanvasFrame(wxWindow
*parent
)
113 : wxFrame(parent
, wxID_ANY
, "MyCanvas")
115 m_canvas
= new MyCanvas(this);
117 wxMenu
*menuFile
= new wxMenu();
118 menuFile
->Append(wxID_DELETE
, "&Delete all");
119 menuFile
->Append(wxID_NEW
, "Insert &new");
121 wxMenuBar
*mbar
= new wxMenuBar();
122 mbar
->Append(menuFile
, "&File");
125 Connect(wxID_DELETE
, wxEVT_COMMAND_MENU_SELECTED
,
126 wxCommandEventHandler(MyCanvasFrame
::OnDeleteAll
));
127 Connect(wxID_NEW
, wxEVT_COMMAND_MENU_SELECTED
,
128 wxCommandEventHandler(MyCanvasFrame
::OnInsertNew
));
134 void OnDeleteAll(wxCommandEvent
& WXUNUSED(event
))
136 m_canvas
->DestroyChildren();
139 void OnInsertNew(wxCommandEvent
& WXUNUSED(event
))
141 (void)new wxButton(m_canvas
, wxID_ANY
, "Hello", wxPoint(100,100));
147 // ----------------------------------------------------------------------------
148 // example using sizers with wxScrolledWindow
149 // ----------------------------------------------------------------------------
151 const wxSize
SMALL_BUTTON( 100, 50 );
152 const wxSize
LARGE_BUTTON( 300, 200 );
154 class MySizerScrolledWindow
: public wxScrolledWindow
157 MySizerScrolledWindow(wxWindow
*parent
);
160 // this button can be clicked to change its own size in the handler below,
161 // the window size will be automatically adjusted to fit the button
164 void OnResizeClick(wxCommandEvent
& event
);
167 class MySizerFrame
: public wxFrame
170 MySizerFrame(wxWindow
*parent
)
171 : wxFrame(parent
, wxID_ANY
, "MySizerScrolledWindow")
173 new MySizerScrolledWindow(this);
175 // ensure that the scrollbars appear when the button becomes large
176 SetClientSize(LARGE_BUTTON
/2);
181 // ----------------------------------------------------------------------------
182 // example showing scrolling only part of the window
183 // ----------------------------------------------------------------------------
185 // this window consists of an empty space in its corner, column labels window
186 // along its top, row labels window along its left hand side and a canvas in
187 // the remaining space
189 class MySubColLabels
: public wxWindow
192 MySubColLabels(wxScrolledWindow
*parent
)
193 : wxWindow(parent
, wxID_ANY
)
197 Connect(wxEVT_PAINT
, wxPaintEventHandler(MySubColLabels
::OnPaint
));
201 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
205 // This is wrong.. it will translate both x and y if the
206 // window is scrolled, the label windows are active in one
207 // direction only. Do the action below instead -- RL.
208 //m_owner->PrepareDC( dc );
210 int xScrollUnits
, xOrigin
;
212 m_owner
->GetViewStart( &xOrigin
, 0 );
213 m_owner
->GetScrollPixelsPerUnit( &xScrollUnits
, 0 );
214 dc
.SetDeviceOrigin( -xOrigin
* xScrollUnits
, 0 );
216 dc
.DrawText("Column 1", 5, 5);
217 dc
.DrawText("Column 2", 105, 5);
218 dc
.DrawText("Column 3", 205, 5);
221 wxScrolledWindow
*m_owner
;
224 class MySubRowLabels
: public wxWindow
227 MySubRowLabels(wxScrolledWindow
*parent
)
228 : wxWindow(parent
, wxID_ANY
)
232 Connect(wxEVT_PAINT
, wxPaintEventHandler(MySubRowLabels
::OnPaint
));
236 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
240 // This is wrong.. it will translate both x and y if the
241 // window is scrolled, the label windows are active in one
242 // direction only. Do the action below instead -- RL.
243 //m_owner->PrepareDC( dc );
245 int yScrollUnits
, yOrigin
;
247 m_owner
->GetViewStart( 0, &yOrigin
);
248 m_owner
->GetScrollPixelsPerUnit( 0, &yScrollUnits
);
249 dc
.SetDeviceOrigin( 0, -yOrigin
* yScrollUnits
);
251 dc
.DrawText("Row 1", 5, 5);
252 dc
.DrawText("Row 2", 5, 30);
253 dc
.DrawText("Row 3", 5, 55);
254 dc
.DrawText("Row 4", 5, 80);
255 dc
.DrawText("Row 5", 5, 105);
256 dc
.DrawText("Row 6", 5, 130);
259 wxScrolledWindow
*m_owner
;
262 class MySubCanvas
: public wxPanel
265 MySubCanvas(wxScrolledWindow
*parent
, wxWindow
*cols
, wxWindow
*rows
)
266 : wxPanel(parent
, wxID_ANY
)
272 (void)new wxButton(this, wxID_ANY
, "Hallo I",
273 wxPoint(0,50), wxSize(100,25) );
274 (void)new wxButton(this, wxID_ANY
, "Hallo II",
275 wxPoint(200,50), wxSize(100,25) );
277 (void)new wxTextCtrl(this, wxID_ANY
, "Text I",
278 wxPoint(0,100), wxSize(100,25) );
279 (void)new wxTextCtrl(this, wxID_ANY
, "Text II",
280 wxPoint(200,100), wxSize(100,25) );
282 (void)new wxComboBox(this, wxID_ANY
, "ComboBox I",
283 wxPoint(0,150), wxSize(100,25));
284 (void)new wxComboBox(this, wxID_ANY
, "ComboBox II",
285 wxPoint(200,150), wxSize(100,25));
287 SetBackgroundColour("WHEAT");
289 Connect(wxEVT_PAINT
, wxPaintEventHandler(MySubCanvas
::OnPaint
));
292 // override the base class function so that when this window is scrolled,
293 // the labels are scrolled in sync
294 virtual void ScrollWindow(int dx
, int dy
, const wxRect
*rect
)
296 wxPanel
::ScrollWindow( dx
, dy
, rect
);
297 m_colLabels
->ScrollWindow( dx
, 0, rect
);
298 m_rowLabels
->ScrollWindow( 0, dy
, rect
);
302 void OnPaint(wxPaintEvent
& WXUNUSED(event
))
304 wxPaintDC
dc( this );
305 m_owner
->PrepareDC( dc
);
307 dc
.SetPen( *wxBLACK_PEN
);
309 // OK, let's assume we are a grid control and we have two
310 // grid cells. Here in OnPaint we want to know which cell
311 // to redraw so that we prevent redrawing cells that don't
312 // need to get redrawn. We have one cell at (0,0) and one
313 // more at (200,0), both having a size of (100,25).
315 // We can query how much the window has been scrolled
316 // by calling CalcUnscrolledPosition()
320 m_owner
->CalcUnscrolledPosition( scroll_x
, scroll_y
, &scroll_x
, &scroll_y
);
322 // We also need to know the size of the window to see which
323 // cells are completely hidden and not get redrawn
327 GetClientSize( &size_x
, &size_y
);
329 // First cell: (0,0)(100,25)
331 if ((0+100-scroll_x
> 0) && (0+25-scroll_y
> 0) &&
332 (0-scroll_x
< size_x
) && (0-scroll_y
< size_y
))
334 // Has the region on screen been exposed?
335 if (IsExposed(0,0,100,25))
337 dc
.DrawRectangle( 0, 0, 100, 25 );
338 dc
.DrawText("First Cell", 5, 5);
343 // Second cell: (0,200)(100,25)
345 if ((200+100-scroll_x
> 0) && (0+25-scroll_y
> 0) &&
346 (200-scroll_x
< size_x
) && (0-scroll_y
< size_y
))
348 // Has the region on screen been exposed?
349 if (IsExposed(200,0,100,25))
351 dc
.DrawRectangle( 200, 0, 100, 25 );
352 dc
.DrawText("Second Cell", 205, 5);
357 wxScrolledWindow
*m_owner
;
358 wxWindow
*m_colLabels
,
362 class MySubScrolledWindow
: public wxScrolledWindow
371 MySubScrolledWindow(wxWindow
*parent
)
372 : wxScrolledWindow(parent
, wxID_ANY
)
374 // create the children
375 MySubColLabels
*cols
= new MySubColLabels(this);
376 MySubRowLabels
*rows
= new MySubRowLabels(this);
378 m_canvas
= new MySubCanvas(this, cols
, rows
);
381 wxFlexGridSizer
*sizer
= new wxFlexGridSizer(2, 2, 10, 10);
382 sizer
->Add(CORNER_WIDTH
, CORNER_HEIGHT
); // just a spacer
383 sizer
->Add(cols
, wxSizerFlags().Expand());
384 sizer
->Add(rows
, wxSizerFlags().Expand());
385 sizer
->Add(m_canvas
, wxSizerFlags().Expand());
386 sizer
->AddGrowableRow(1);
387 sizer
->AddGrowableCol(1);
390 // this is the key call: it means that only m_canvas will be scrolled
391 // and not this window itself
392 SetTargetWindow(m_canvas
);
394 SetScrollbars(10, 10, 50, 50);
396 Connect(wxEVT_SIZE
, wxSizeEventHandler(MySubScrolledWindow
::OnSize
));
400 // scrolled windows which use scroll target different from the window
401 // itself must override this virtual method
402 virtual wxSize
GetSizeAvailableForScrollTarget(const wxSize
& size
)
404 // decrease the total size by the size of the non-scrollable parts
405 // above/to the left of the canvas
406 wxSize
sizeCanvas(size
);
413 void OnSize(wxSizeEvent
& WXUNUSED(event
))
415 // We need to override OnSize so that our scrolled
416 // window a) does call Layout() to use sizers for
417 // positioning the controls but b) does not query
418 // the sizer for their size and use that for setting
419 // the scrollable area as set that ourselves by
420 // calling SetScrollbar() further down.
427 MySubCanvas
*m_canvas
;
430 class MySubFrame
: public wxFrame
433 MySubFrame(wxWindow
*parent
)
434 : wxFrame(parent
, wxID_ANY
, "MySubScrolledWindow")
436 new MySubScrolledWindow(this);
442 // ----------------------------------------------------------------------------
443 // more simple examples of wxScrolledWindow usage
444 // ----------------------------------------------------------------------------
446 // base class for both of them
447 class MyScrolledWindowBase
: public wxScrolledWindow
450 MyScrolledWindowBase(wxWindow
*parent
)
451 : wxScrolledWindow(parent
, wxID_ANY
,
452 wxDefaultPosition
, wxDefaultSize
,
460 dc
.GetTextExtent("Line 17", NULL
, &m_hLine
);
463 // this scrolled window can be synchronized with another one: if this
464 // function is called with a non-NULL pointer, the given window will be
465 // scrolled to the same position as this one
466 void SyncWith(MyScrolledWindowBase
*win
)
473 virtual void ScrollWindow(int dx
, int dy
, const wxRect
*rect
= NULL
)
475 wxScrolledWindow
::ScrollWindow(dx
, dy
, rect
);
481 // the height of one line on screen
484 // the number of lines we draw
488 bool WasScrolledFirst() const { return m_inDoSync
; }
490 void DoSyncIfNecessary()
492 if ( m_winSync
&& !m_winSync
->WasScrolledFirst() )
497 GetViewStart(&x
, &y
);
499 m_winSync
->Scroll(x
, y
);
505 // the window to synchronize with this one or NULL
506 MyScrolledWindowBase
*m_winSync
;
508 // the flag preventing infinite recursion which would otherwise happen if
509 // one window synchronized the other one which in turn synchronized this
514 // this class does "stupid" redrawing - it redraws everything each time
515 // and sets the scrollbar extent directly.
517 class MyScrolledWindowDumb
: public MyScrolledWindowBase
520 MyScrolledWindowDumb(wxWindow
*parent
) : MyScrolledWindowBase(parent
)
523 SetScrollbars(0, m_hLine
, 0, m_nLines
+ 1, 0, 0, true /* no refresh */);
526 virtual void OnDraw(wxDC
& dc
);
529 // this class does "smart" redrawing - only redraws the lines which must be
530 // redrawn and sets the scroll rate and virtual size to affect the
533 // Note that this class should produce identical results to the one above.
535 class MyScrolledWindowSmart
: public MyScrolledWindowBase
538 MyScrolledWindowSmart(wxWindow
*parent
) : MyScrolledWindowBase(parent
)
541 SetScrollRate( 0, m_hLine
);
542 SetVirtualSize( wxDefaultCoord
, ( m_nLines
+ 1 ) * m_hLine
);
545 virtual void OnDraw(wxDC
& dc
);
548 // ----------------------------------------------------------------------------
549 // implements a text viewer with simple block selection to test auto-scrolling
551 // ----------------------------------------------------------------------------
553 class MyAutoScrollingWindow
: public wxScrolledWindow
556 MyAutoScrollingWindow( wxWindow
* parent
);
557 wxRect
DeviceCoordsToGraphicalChars(wxRect updRect
) const;
558 wxPoint
DeviceCoordsToGraphicalChars(wxPoint pos
) const;
559 wxPoint
GraphicalCharToDeviceCoords(wxPoint pos
) const;
560 wxRect
LogicalCoordsToGraphicalChars(wxRect updRect
) const;
561 wxPoint
LogicalCoordsToGraphicalChars(wxPoint pos
) const;
562 wxPoint
GraphicalCharToLogicalCoords(wxPoint pos
) const;
564 bool IsSelected(int chX
, int chY
) const;
565 static bool IsInside(int k
, int bound1
, int bound2
);
566 static wxRect
DCNormalize(int x
, int y
, int w
, int h
);
570 void OnDraw(wxDC
& dc
);
571 void OnMouseLeftDown(wxMouseEvent
& event
);
572 void OnMouseLeftUp(wxMouseEvent
& event
);
573 void OnMouseMove(wxMouseEvent
& event
);
574 void OnMouseCaptureLost(wxMouseCaptureLostEvent
& event
);
575 void OnScroll(wxScrollWinEvent
& event
);
577 // test data variables
578 static const char* sm_testData
;
579 static const int sm_lineCnt
; // line count
580 static const int sm_lineLen
; // line length in characters
581 // sizes for graphical data
582 int m_fontH
, m_fontW
;
583 // selection tracking
584 wxPoint m_selStart
; // beginning of blockwise selection
585 wxPoint m_cursor
; // end of blockwise selection (mouse position)
591 DECLARE_EVENT_TABLE()
594 class MyAutoFrame
: public wxFrame
597 MyAutoFrame(wxWindow
*parent
)
598 : wxFrame(parent
, wxID_ANY
, "MyAutoScrollingWindow")
600 new MyAutoScrollingWindow(this);
607 // ----------------------------------------------------------------------------
608 // MyFrame: the main application frame showing all the classes above
609 // ----------------------------------------------------------------------------
611 class MyFrame
: public wxFrame
617 void OnAbout(wxCommandEvent
& event
);
618 void OnQuit(wxCommandEvent
& event
);
620 void OnTestSimple(wxCommandEvent
& WXUNUSED(event
)) { new MySimpleFrame(this); }
621 void OnTestCanvas(wxCommandEvent
& WXUNUSED(event
)) { new MyCanvasFrame(this); }
622 void OnTestSizer(wxCommandEvent
& WXUNUSED(event
)) { new MySizerFrame(this); }
623 void OnTestSub(wxCommandEvent
& WXUNUSED(event
)) { new MySubFrame(this); }
624 void OnTestAuto(wxCommandEvent
& WXUNUSED(event
)) { new MyAutoFrame(this); }
626 void OnToggleSync(wxCommandEvent
& event
);
628 MyScrolledWindowBase
*m_win1
,
631 DECLARE_EVENT_TABLE()
634 // ----------------------------------------------------------------------------
636 // ----------------------------------------------------------------------------
638 class MyApp
: public wxApp
641 virtual bool OnInit();
645 // ============================================================================
647 // ============================================================================
649 // ----------------------------------------------------------------------------
651 // ----------------------------------------------------------------------------
653 const wxWindowID ID_ADDBUTTON
= wxWindow
::NewControlId();
654 const wxWindowID ID_DELBUTTON
= wxWindow
::NewControlId();
655 const wxWindowID ID_MOVEBUTTON
= wxWindow
::NewControlId();
656 const wxWindowID ID_SCROLLWIN
= wxWindow
::NewControlId();
657 const wxWindowID ID_QUERYPOS
= wxWindow
::NewControlId();
659 const wxWindowID ID_NEWBUTTON
= wxWindow
::NewControlId();
661 BEGIN_EVENT_TABLE(MyCanvas
, wxScrolledWindow
)
662 EVT_PAINT( MyCanvas
::OnPaint
)
663 EVT_RIGHT_DOWN( MyCanvas
::OnMouseRightDown
)
664 EVT_MOUSEWHEEL( MyCanvas
::OnMouseWheel
)
665 EVT_BUTTON( ID_QUERYPOS
, MyCanvas
::OnQueryPosition
)
666 EVT_BUTTON( ID_ADDBUTTON
, MyCanvas
::OnAddButton
)
667 EVT_BUTTON( ID_DELBUTTON
, MyCanvas
::OnDeleteButton
)
668 EVT_BUTTON( ID_MOVEBUTTON
, MyCanvas
::OnMoveButton
)
669 EVT_BUTTON( ID_SCROLLWIN
, MyCanvas
::OnScrollWin
)
672 MyCanvas
::MyCanvas(wxWindow
*parent
)
673 : wxScrolledWindow(parent
, wxID_ANY
,
674 wxDefaultPosition
, wxDefaultSize
,
675 wxSUNKEN_BORDER
| wxTAB_TRAVERSAL
)
677 // you can use either a single SetScrollbars() call or these 2 functions,
678 // usually using them is better because you normally won't need to change
679 // the scroll rate in the future and the sizer can be used to update the
680 // virtual size automatically
681 SetScrollRate( 10, 10 );
682 SetVirtualSize( 500, 1000 );
684 (void) new wxButton( this, ID_ADDBUTTON
, "add button", wxPoint(10,10) );
685 (void) new wxButton( this, ID_DELBUTTON
, "del button", wxPoint(10,40) );
686 (void) new wxButton( this, ID_MOVEBUTTON
, "move button", wxPoint(150,10) );
687 (void) new wxButton( this, ID_SCROLLWIN
, "scroll win", wxPoint(250,10) );
689 wxPanel
*test
= new wxPanel( this, wxID_ANY
,
690 wxPoint(10, 110), wxSize(130,50),
691 wxSIMPLE_BORDER
| wxTAB_TRAVERSAL
);
692 test
->SetBackgroundColour( "WHEAT" );
694 SetBackgroundColour( "BLUE" );
697 void MyCanvas
::OnMouseRightDown( wxMouseEvent
&event
)
699 wxPoint
pt( event
.GetPosition() );
701 CalcUnscrolledPosition( pt
.x
, pt
.y
, &x
, &y
);
702 wxLogMessage("Mouse down event at: %d %d, scrolled: %d %d",
706 void MyCanvas
::OnMouseWheel( wxMouseEvent
&event
)
708 wxPoint
pt( event
.GetPosition() );
710 CalcUnscrolledPosition( pt
.x
, pt
.y
, &x
, &y
);
711 wxLogMessage( "Mouse wheel event at: %d %d, scrolled: %d %d\n"
712 "Rotation: %d, delta = %d",
714 event
.GetWheelRotation(), event
.GetWheelDelta() );
719 void MyCanvas
::OnPaint( wxPaintEvent
&WXUNUSED(event
) )
721 wxPaintDC
dc( this );
724 dc
.DrawText( "Press right mouse button to test calculations!", 160, 50 );
726 dc
.DrawText( "Some text", 140, 140 );
728 dc
.DrawRectangle( 100, 160, 200, 200 );
731 void MyCanvas
::OnQueryPosition( wxCommandEvent
&WXUNUSED(event
) )
733 wxPoint
pt( m_button
->GetPosition() );
734 wxLogMessage( "Position of \"Query position\" is %d %d", pt
.x
, pt
.y
);
735 pt
= ClientToScreen( pt
);
736 wxLogMessage("Position of \"Query position\" on screen is %d %d",
740 void MyCanvas
::OnAddButton( wxCommandEvent
&WXUNUSED(event
) )
742 wxLogMessage( "Inserting button at position 10,70..." );
743 wxButton
*button
= new wxButton( this, ID_NEWBUTTON
, "new button",
744 wxPoint(10,70), wxSize(80,25) );
745 wxPoint
pt( button
->GetPosition() );
746 wxLogMessage( "-> Position after inserting %d %d", pt
.x
, pt
.y
);
749 void MyCanvas
::OnDeleteButton( wxCommandEvent
&WXUNUSED(event
) )
751 wxLogMessage( "Deleting button inserted with \"Add button\"..." );
752 wxWindow
*win
= FindWindow( ID_NEWBUTTON
);
756 wxLogMessage( "-> No window with id = ID_NEWBUTTON found." );
759 void MyCanvas
::OnMoveButton( wxCommandEvent
&event
)
761 wxLogMessage( "Moving button 10 pixels downward.." );
762 wxWindow
*win
= FindWindow( event
.GetId() );
763 wxPoint
pt( win
->GetPosition() );
764 wxLogMessage( "-> Position before move is %d %d", pt
.x
, pt
.y
);
765 win
->Move( wxDefaultCoord
, pt
.y
+ 10 );
766 pt
= win
->GetPosition();
767 wxLogMessage( "-> Position after move is %d %d", pt
.x
, pt
.y
);
770 void MyCanvas
::OnScrollWin( wxCommandEvent
&WXUNUSED(event
) )
772 wxLogMessage("Scrolling 2 units up.\n"
773 "The white square and the controls should move equally!");
775 GetViewStart( &x
, &y
);
776 Scroll( wxDefaultCoord
, y
+2 );
779 // ----------------------------------------------------------------------------
780 // MySizerScrolledWindow
781 // ----------------------------------------------------------------------------
783 MySizerScrolledWindow
::MySizerScrolledWindow(wxWindow
*parent
)
784 : wxScrolledWindow(parent
)
786 SetBackgroundColour( "GREEN" );
788 // Set the rate we'd like for scrolling.
790 SetScrollRate( 5, 5 );
792 // Populate a sizer with a 'resizing' button and some other static
795 wxFlexGridSizer
*sizer
= new wxFlexGridSizer(2);
797 m_button
= new wxButton( this, wxID_RESIZE_FRAME
, "Press me",
798 wxDefaultPosition
, SMALL_BUTTON
);
800 sizer
->Add(m_button
, wxSizerFlags().Centre().Border(20));
801 sizer
->Add(new wxStaticText(this, wxID_ANY
, "This is just"),
802 wxSizerFlags().Centre());
803 sizer
->Add(new wxStaticText(this, wxID_ANY
, "some decoration"),
804 wxSizerFlags().Centre());
805 sizer
->Add(new wxStaticText(this, wxID_ANY
, "for you to scroll..."),
806 wxSizerFlags().Centre());
808 // Then use the sizer to set the scrolled region size.
812 Connect(wxID_RESIZE_FRAME
, wxEVT_COMMAND_BUTTON_CLICKED
,
813 wxCommandEventHandler(MySizerScrolledWindow
::OnResizeClick
));
816 void MySizerScrolledWindow
::OnResizeClick(wxCommandEvent
&WXUNUSED(event
))
818 // Arbitrarily resize the button to change the minimum size of
819 // the (scrolled) sizer.
821 if ( m_button
->GetSize() == SMALL_BUTTON
)
822 m_button
->SetSizeHints(LARGE_BUTTON
);
824 m_button
->SetSizeHints(SMALL_BUTTON
);
826 // Force update layout and scrollbars, since nothing we do here
827 // necessarily generates a size event which would do it for us.
831 // ----------------------------------------------------------------------------
833 // ----------------------------------------------------------------------------
835 const wxWindowID Scroll_Test_Simple
= wxWindow
::NewControlId();
836 const wxWindowID Scroll_Test_Canvas
= wxWindow
::NewControlId();
837 const wxWindowID Scroll_Test_Sizers
= wxWindow
::NewControlId();
838 const wxWindowID Scroll_Test_Sub
= wxWindow
::NewControlId();
839 const wxWindowID Scroll_Test_Auto
= wxWindow
::NewControlId();
841 const wxWindowID Scroll_TglBtn_Sync
= wxWindow
::NewControlId();
843 BEGIN_EVENT_TABLE(MyFrame
,wxFrame
)
844 EVT_MENU(wxID_ABOUT
, MyFrame
::OnAbout
)
845 EVT_MENU(wxID_EXIT
, MyFrame
::OnQuit
)
847 EVT_MENU(Scroll_Test_Simple
, MyFrame
::OnTestSimple
)
848 EVT_MENU(Scroll_Test_Canvas
, MyFrame
::OnTestCanvas
)
849 EVT_MENU(Scroll_Test_Sizers
, MyFrame
::OnTestSizer
)
850 EVT_MENU(Scroll_Test_Sub
, MyFrame
::OnTestSub
)
851 EVT_MENU(Scroll_Test_Auto
, MyFrame
::OnTestAuto
)
853 EVT_TOGGLEBUTTON(Scroll_TglBtn_Sync
, MyFrame
::OnToggleSync
)
857 : wxFrame(NULL
, wxID_ANY
, "wxWidgets scroll sample")
859 wxMenu
*menuFile
= new wxMenu
;
860 menuFile
->Append(wxID_ABOUT
, "&About..");
861 menuFile
->AppendSeparator();
862 menuFile
->Append(wxID_EXIT
, "E&xit\tAlt-X");
864 wxMenu
*menuTest
= new wxMenu
;
865 menuTest
->Append(Scroll_Test_Simple
, "&Simple scroll window\tF1",
866 "Simplest possible scrolled window test.");
867 menuTest
->Append(Scroll_Test_Canvas
, "Scrolled window with &children\tF2",
868 "Scrolled window with controls on it.");
869 menuTest
->Append(Scroll_Test_Sizers
, "Scrolled window with si&zer\tF3",
870 "Scrolled window with children managed by sizer.");
871 menuTest
->Append(Scroll_Test_Sub
, "Scrolled s&ub-window\tF4",
872 "Window only part of which is scrolled.");
873 menuTest
->Append(Scroll_Test_Auto
, "&Auto-scrolled window\tF5",
874 "Window which scrolls when the mouse is held pressed "
877 wxMenuBar
*mbar
= new wxMenuBar
;
878 mbar
->Append(menuFile
, "&File");
879 mbar
->Append(menuTest
, "&Test");
884 const wxSizerFlags
flagsExpand(wxSizerFlags(1).Expand());
886 wxSizer
*topsizer
= new wxBoxSizer(wxVERTICAL
);
887 topsizer
->Add(new wxStaticText(this, wxID_ANY
,
888 "The windows below should behave in the same way, even though\n"
889 "they're implemented quite differently, see the code for details.\n"
891 "The lines redrawn during odd/even repaint iterations are drawn in\n"
892 "red/blue colour to allow seeing immediately how much is repainted,\n"
893 "don't be surprised by this."),
894 wxSizerFlags().Centre().Border());
896 m_win1
= new MyScrolledWindowDumb(this);
897 m_win2
= new MyScrolledWindowSmart(this);
899 wxSizer
*sizerScrollWin
= new wxBoxSizer(wxHORIZONTAL
);
900 sizerScrollWin
->Add(m_win1
, flagsExpand
);
901 sizerScrollWin
->Add(m_win2
, flagsExpand
);
902 topsizer
->Add(sizerScrollWin
, flagsExpand
);
904 wxSizer
*sizerBtns
= new wxBoxSizer(wxHORIZONTAL
);
905 sizerBtns
->Add(new wxToggleButton(this, Scroll_TglBtn_Sync
, "&Synchronize"));
906 topsizer
->Add(sizerBtns
, wxSizerFlags().Centre().Border());
914 void MyFrame
::OnToggleSync(wxCommandEvent
& event
)
916 if ( event
.IsChecked() )
918 m_win1
->SyncWith(m_win2
);
919 m_win2
->SyncWith(m_win1
);
923 m_win1
->SyncWith(NULL
);
924 m_win2
->SyncWith(NULL
);
928 void MyFrame
::OnQuit(wxCommandEvent
&WXUNUSED(event
))
933 void MyFrame
::OnAbout( wxCommandEvent
&WXUNUSED(event
) )
935 (void)wxMessageBox( "wxScrolledWindow sample\n"
937 "Robert Roebling (c) 1998\n"
938 "Vadim Zeitlin (c) 2008\n"
939 "Autoscrolling examples\n"
941 "Auto-timed-scrolling example\n"
942 "Matt Gregory (c) 2003\n",
943 "About wxWidgets scroll sample",
944 wxICON_INFORMATION
| wxOK
);
947 // ----------------------------------------------------------------------------
949 // ----------------------------------------------------------------------------
955 if ( !wxApp
::OnInit() )
963 // ----------------------------------------------------------------------------
964 // MyScrolledWindowXXX
965 // ----------------------------------------------------------------------------
967 void MyScrolledWindowDumb
::OnDraw(wxDC
& dc
)
969 // this is useful to see which lines are redrawn
970 static size_t s_redrawCount
= 0;
971 dc
.SetTextForeground(s_redrawCount
++ % 2 ?
*wxRED
: *wxBLUE
);
974 for ( size_t line
= 0; line
< m_nLines
; line
++ )
977 CalcScrolledPosition(0, y
, NULL
, &yPhys
);
979 dc
.DrawText(wxString
::Format("Line %u (logical %d, physical %d)",
980 unsigned(line
), y
, yPhys
), 0, y
);
985 void MyScrolledWindowSmart
::OnDraw(wxDC
& dc
)
987 // this is useful to see which lines are redrawn
988 static size_t s_redrawCount
= 0;
989 dc
.SetTextForeground(s_redrawCount
++ % 2 ?
*wxRED
: *wxBLUE
);
991 // update region is always in device coords, translate to logical ones
992 wxRect rectUpdate
= GetUpdateRegion().GetBox();
993 CalcUnscrolledPosition(rectUpdate
.x
, rectUpdate
.y
,
994 &rectUpdate
.x
, &rectUpdate
.y
);
996 size_t lineFrom
= rectUpdate
.y
/ m_hLine
,
997 lineTo
= rectUpdate
.GetBottom() / m_hLine
;
999 if ( lineTo
> m_nLines
- 1)
1000 lineTo
= m_nLines
- 1;
1002 int y
= lineFrom
*m_hLine
;
1003 for ( size_t line
= lineFrom
; line
<= lineTo
; line
++ )
1006 CalcScrolledPosition(0, y
, NULL
, &yPhys
);
1008 dc
.DrawText(wxString
::Format("Line %u (logical %d, physical %d)",
1009 unsigned(line
), y
, yPhys
), 0, y
);
1014 // ----------------------------------------------------------------------------
1015 // MyAutoScrollingWindow
1016 // ----------------------------------------------------------------------------
1018 BEGIN_EVENT_TABLE(MyAutoScrollingWindow
, wxScrolledWindow
)
1019 EVT_LEFT_DOWN(MyAutoScrollingWindow
::OnMouseLeftDown
)
1020 EVT_LEFT_UP(MyAutoScrollingWindow
::OnMouseLeftUp
)
1021 EVT_MOTION(MyAutoScrollingWindow
::OnMouseMove
)
1022 EVT_MOUSE_CAPTURE_LOST(MyAutoScrollingWindow
::OnMouseCaptureLost
)
1023 EVT_SCROLLWIN(MyAutoScrollingWindow
::OnScroll
)
1026 MyAutoScrollingWindow
::MyAutoScrollingWindow(wxWindow
* parent
)
1027 : wxScrolledWindow(parent
, wxID_ANY
, wxDefaultPosition
, wxDefaultSize
,
1028 wxVSCROLL
| wxHSCROLL
| wxSUNKEN_BORDER
),
1031 m_font(9, wxFONTFAMILY_TELETYPE
, wxFONTSTYLE_NORMAL
, wxFONTWEIGHT_NORMAL
)
1033 wxClientDC
dc(this);
1034 // query dc for text size
1036 dc
.GetTextExtent(wxString("A"), &m_fontW
, &m_fontH
);
1037 // set up the virtual window
1038 SetScrollbars(m_fontW
, m_fontH
, sm_lineLen
, sm_lineCnt
);
1042 MyAutoScrollingWindow
::DeviceCoordsToGraphicalChars(wxRect updRect
) const
1044 wxPoint
pos(updRect
.GetPosition());
1045 pos
= DeviceCoordsToGraphicalChars(pos
);
1048 updRect
.width
/= m_fontW
;
1049 updRect
.height
/= m_fontH
;
1050 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
1051 // so an off-by-one correction is needed
1052 ++updRect
.width
; // kludge
1053 ++updRect
.height
; // kludge
1058 MyAutoScrollingWindow
::DeviceCoordsToGraphicalChars(wxPoint pos
) const
1063 GetViewStart(&vX
, &vY
);
1070 MyAutoScrollingWindow
::GraphicalCharToDeviceCoords(wxPoint pos
) const
1073 GetViewStart(&vX
, &vY
);
1082 MyAutoScrollingWindow
::LogicalCoordsToGraphicalChars(wxRect updRect
) const
1084 wxPoint
pos(updRect
.GetPosition());
1085 pos
= LogicalCoordsToGraphicalChars(pos
);
1088 updRect
.width
/= m_fontW
;
1089 updRect
.height
/= m_fontH
;
1090 // the *CoordsToGraphicalChars() funcs round down to upper-left corner,
1091 // so an off-by-one correction is needed
1092 ++updRect
.width
; // kludge
1093 ++updRect
.height
; // kludge
1098 MyAutoScrollingWindow
::LogicalCoordsToGraphicalChars(wxPoint pos
) const
1106 MyAutoScrollingWindow
::GraphicalCharToLogicalCoords(wxPoint pos
) const
1113 void MyAutoScrollingWindow
::MyRefresh()
1115 static wxPoint
lastSelStart(-1, -1), lastCursor(-1, -1);
1116 // refresh last selected area (to deselect previously selected text)
1118 GraphicalCharToDeviceCoords(lastSelStart
),
1119 GraphicalCharToDeviceCoords(lastCursor
)
1121 // off-by-one corrections, necessary because it's not possible to know
1122 // when to round up until rect is normalized by lastUpdRect constructor
1123 lastUpdRect
.width
+= m_fontW
; // kludge
1124 lastUpdRect
.height
+= m_fontH
; // kludge
1125 // refresh currently selected (to select previously unselected text)
1127 GraphicalCharToDeviceCoords(m_selStart
),
1128 GraphicalCharToDeviceCoords(m_cursor
)
1130 // off-by-one corrections
1131 updRect
.width
+= m_fontW
; // kludge
1132 updRect
.height
+= m_fontH
; // kludge
1133 // find necessary refresh areas
1134 int rx
= lastUpdRect
.x
;
1135 int ry
= lastUpdRect
.y
;
1136 int rw
= updRect
.x
- lastUpdRect
.x
;
1137 int rh
= lastUpdRect
.height
;
1139 RefreshRect(DCNormalize(rx
, ry
, rw
, rh
));
1142 ry
= updRect
.y
+ updRect
.height
;
1144 rh
= (lastUpdRect
.y
+ lastUpdRect
.height
) - (updRect
.y
+ updRect
.height
);
1146 RefreshRect(DCNormalize(rx
, ry
, rw
, rh
));
1148 rx
= updRect
.x
+ updRect
.width
;
1150 rw
= (lastUpdRect
.x
+ lastUpdRect
.width
) - (updRect
.x
+ updRect
.width
);
1151 rh
= lastUpdRect
.height
;
1153 RefreshRect(DCNormalize(rx
, ry
, rw
, rh
));
1158 rh
= updRect
.y
- lastUpdRect
.y
;
1160 RefreshRect(DCNormalize(rx
, ry
, rw
, rh
));
1163 lastSelStart
= m_selStart
;
1164 lastCursor
= m_cursor
;
1167 bool MyAutoScrollingWindow
::IsSelected(int chX
, int chY
) const
1169 if (IsInside(chX
, m_selStart
.x
, m_cursor
.x
)
1170 && IsInside(chY
, m_selStart
.y
, m_cursor
.y
)) {
1176 bool MyAutoScrollingWindow
::IsInside(int k
, int bound1
, int bound2
)
1178 if ((k
>= bound1
&& k
<= bound2
) || (k
>= bound2
&& k
<= bound1
)) {
1185 MyAutoScrollingWindow
::DCNormalize(int x
, int y
, int w
, int h
)
1187 // this is needed to get rid of the graphical remnants from the selection
1188 // I think it's because DrawRectangle() excludes a pixel in either direction
1189 const int kludge
= 1;
1190 // make (x, y) the top-left corner
1205 return wxRect(x
, y
, w
, h
);
1208 void MyAutoScrollingWindow
::OnDraw(wxDC
& dc
)
1211 wxBrush
normBrush(wxSystemSettings
::GetColour(wxSYS_COLOUR_WINDOW
)
1213 wxBrush
selBrush(wxSystemSettings
::GetColour(wxSYS_COLOUR_HIGHLIGHT
)
1215 dc
.SetPen(*wxTRANSPARENT_PEN
);
1216 const wxString str
= sm_testData
;
1217 size_t strLength
= str
.length();
1218 wxString
::const_iterator str_i
;
1220 // draw the characters
1221 // 1. for each update region
1222 for (wxRegionIterator
upd(GetUpdateRegion()); upd
; ++upd
) {
1223 wxRect updRect
= upd
.GetRect();
1224 wxRect
updRectInGChars(DeviceCoordsToGraphicalChars(updRect
));
1225 // 2. for each row of chars in the update region
1226 for (int chY
= updRectInGChars
.y
1227 ; chY
<= updRectInGChars
.y
+ updRectInGChars
.height
; ++chY
) {
1228 // 3. for each character in the row
1229 bool isFirstX
= true;
1230 for (int chX
= updRectInGChars
.x
1231 ; chX
<= updRectInGChars
.x
+ updRectInGChars
.width
1234 if (IsSelected(chX
, chY
)) {
1235 dc
.SetBrush(selBrush
);
1236 dc
.SetTextForeground( wxSystemSettings
::GetColour
1237 (wxSYS_COLOUR_HIGHLIGHTTEXT
));
1239 dc
.SetBrush(normBrush
);
1240 dc
.SetTextForeground( wxSystemSettings
::GetColour
1241 (wxSYS_COLOUR_WINDOWTEXT
));
1243 // 5. find position info
1244 wxPoint charPos
= GraphicalCharToLogicalCoords(wxPoint
1247 dc
.DrawRectangle(charPos
.x
, charPos
.y
, m_fontW
, m_fontH
);
1248 size_t charIndex
= chY
* sm_lineLen
+ chX
;
1249 if (chY
< sm_lineCnt
&&
1251 charIndex
< strLength
)
1255 str_i
= str
.begin() + charIndex
;
1258 dc
.DrawText(*str_i
, charPos
.x
, charPos
.y
);
1266 void MyAutoScrollingWindow
::OnMouseLeftDown(wxMouseEvent
& event
)
1268 // initial press of mouse button sets the beginning of the selection
1269 m_selStart
= DeviceCoordsToGraphicalChars(event
.GetPosition());
1270 // set the cursor to the same position
1271 m_cursor
= m_selStart
;
1272 // draw/erase selection
1276 void MyAutoScrollingWindow
::OnMouseLeftUp(wxMouseEvent
& WXUNUSED(event
))
1278 // this test is necessary
1285 void MyAutoScrollingWindow
::OnMouseMove(wxMouseEvent
& event
)
1287 // if user is dragging
1288 if (event
.Dragging() && event
.LeftIsDown()) {
1289 // set the new cursor position
1290 m_cursor
= DeviceCoordsToGraphicalChars(event
.GetPosition());
1291 // draw/erase selection
1293 // capture mouse to activate auto-scrolling
1294 if (!HasCapture()) {
1301 MyAutoScrollingWindow
::OnMouseCaptureLost(wxMouseCaptureLostEvent
&
1304 // we only capture mouse for timed scrolling, so nothing is needed here
1305 // other than making sure to not call event.Skip()
1308 void MyAutoScrollingWindow
::OnScroll(wxScrollWinEvent
& event
)
1310 // need to move the cursor when autoscrolling
1311 // FIXME: the cursor also moves when the scrollbar arrows are clicked
1313 if (event
.GetOrientation() == wxHORIZONTAL
) {
1314 if (event
.GetEventType() == wxEVT_SCROLLWIN_LINEUP
) {
1316 } else if (event
.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN
) {
1319 } else if (event
.GetOrientation() == wxVERTICAL
) {
1320 if (event
.GetEventType() == wxEVT_SCROLLWIN_LINEUP
) {
1322 } else if (event
.GetEventType() == wxEVT_SCROLLWIN_LINEDOWN
) {
1331 const int MyAutoScrollingWindow
::sm_lineCnt
= 125;
1332 const int MyAutoScrollingWindow
::sm_lineLen
= 79;
1333 const char *MyAutoScrollingWindow
::sm_testData
=
1334 "162 Cult of the genius out of vanity. Because we think well of ourselves, but "
1335 "nonetheless never suppose ourselves capable of producing a painting like one of "
1336 "Raphael's or a dramatic scene like one of Shakespeare's, we convince ourselves "
1337 "that the capacity to do so is quite extraordinarily marvelous, a wholly "
1338 "uncommon accident, or, if we are still religiously inclined, a mercy from on "
1339 "high. Thus our vanity, our self-love, promotes the cult of the genius: for only "
1340 "if we think of him as being very remote from us, as a miraculum, does he not "
1341 "aggrieve us (even Goethe, who was without envy, called Shakespeare his star of "
1342 "the most distant heights [\"William! Stern der schonsten Ferne\": from Goethe's, "
1343 "\"Between Two Worlds\"]; in regard to which one might recall the lines: \"the "
1344 "stars, these we do not desire\" [from Goethe's, \"Comfort in Tears\"]). But, aside "
1345 "from these suggestions of our vanity, the activity of the genius seems in no "
1346 "way fundamentally different from the activity of the inventor of machines, the "
1347 "scholar of astronomy or history, the master of tactics. All these activities "
1348 "are explicable if one pictures to oneself people whose thinking is active in "
1349 "one direction, who employ everything as material, who always zealously observe "
1350 "their own inner life and that of others, who perceive everywhere models and "
1351 "incentives, who never tire of combining together the means available to them. "
1352 "Genius too does nothing except learn first how to lay bricks then how to build, "
1353 "except continually seek for material and continually form itself around it. "
1354 "Every activity of man is amazingly complicated, not only that of the genius: "
1355 "but none is a \"miracle.\" Whence, then, the belief that genius exists only in "
1356 "the artist, orator and philosopher? that only they have \"intuition\"? (Whereby "
1357 "they are supposed to possess a kind of miraculous eyeglass with which they can "
1358 "see directly into \"the essence of the thing\"!) It is clear that people speak of "
1359 "genius only where the effects of the great intellect are most pleasant to them "
1360 "and where they have no desire to feel envious. To call someone \"divine\" means: "
1361 "\"here there is no need for us to compete.\" Then, everything finished and "
1362 "complete is regarded with admiration, everything still becoming is undervalued. "
1363 "But no one can see in the work of the artist how it has become; that is its "
1364 "advantage, for wherever one can see the act of becoming one grows somewhat "
1365 "cool. The finished and perfect art of representation repulses all thinking as "
1366 "to how it has become; it tyrannizes as present completeness and perfection. "
1367 "That is why the masters of the art of representation count above all as gifted "
1368 "with genius and why men of science do not. In reality, this evaluation of the "
1369 "former and undervaluation of the latter is only a piece of childishness in the "
1372 "163 The serious workman. Do not talk about giftedness, inborn talents! One can "
1373 "name great men of all kinds who were very little gifted. The acquired "
1374 "greatness, became \"geniuses\" (as we put it), through qualities the lack of "
1375 "which no one who knew what they were would boast of: they all possessed that "
1376 "seriousness of the efficient workman which first learns to construct the parts "
1377 "properly before it ventures to fashion a great whole; they allowed themselves "
1378 "time for it, because they took more pleasure in making the little, secondary "
1379 "things well than in the effect of a dazzling whole. the recipe for becoming a "
1380 "good novelist, for example, is easy to give, but to carry it out presupposes "
1381 "qualities one is accustomed to overlook when one says \"I do not have enough "
1382 "talent.\" One has only to make a hundred or so sketches for novels, none longer "
1383 "than two pages but of such distinctness that every word in them is necessary; "
1384 "one should write down anecdotes each day until one has learned how to give them "
1385 "the most pregnant and effective form; one should be tireless in collecting and "
1386 "describing human types and characters; one should above all relate things to "
1387 "others and listen to others relate, keeping one's eyes and ears open for the "
1388 "effect produced on those present, one should travel like a landscape painter or "
1389 "costume designer; one should excerpt for oneself out of the individual sciences "
1390 "everything that will produce an artistic effect when it is well described, one "
1391 "should, finally, reflect on the motives of human actions, disdain no signpost "
1392 "to instruction about them and be a collector of these things by day and night. "
1393 "One should continue in this many-sided exercise some ten years: what is then "
1394 "created in the workshop, however, will be fit to go out into the world. What, "
1395 "however, do most people do? They begin, not with the parts, but with the whole. "
1396 "Perhaps they chance to strike a right note, excite attention and from then on "
1397 "strike worse and worse notes, for good, natural reasons. Sometimes, when the "
1398 "character and intellect needed to formulate such a life-plan are lacking, fate "
1399 "and need take their place and lead the future master step by step through all "
1400 "the stipulations of his trade. "
1402 "164 Peril and profit in the cult of the genius. The belief in great, superior, "
1403 "fruitful spirits is not necessarily, yet nonetheless is very frequently "
1404 "associated with that religious or semi-religious superstition that these "
1405 "spirits are of supra-human origin and possess certain miraculous abilities by "
1406 "virtue of which they acquire their knowledge by quite other means than the rest "
1407 "of mankind. One ascribes to them, it seems, a direct view of the nature of the "
1408 "world, as it were a hole in the cloak of appearance, and believes that, by "
1409 "virtue of this miraculous seer's vision, they are able to communicate something "
1410 "conclusive and decisive about man and the world without the toil and "
1411 "rigorousness required by science. As long as there continue to be those who "
1412 "believe in the miraculous in the domain of knowledge one can perhaps concede "
1413 "that these people themselves derive some benefit from their belief, inasmuch as "
1414 "through their unconditional subjection to the great spirits they create for "
1415 "their own spirit during its time of development the finest form of discipline "
1416 "and schooling. On the other hand, it is at least questionable whether the "
1417 "superstitious belief in genius, in its privileges and special abilities, is of "
1418 "benefit to the genius himself if it takes root in him. It is in any event a "
1419 "dangerous sign when a man is assailed by awe of himself, whether it be the "
1420 "celebrated Caesar's awe of Caesar or the awe of one's own genius now under "
1421 "consideration; when the sacrificial incense which is properly rendered only to "
1422 "a god penetrates the brain of the genius, so that his head begins to swim and "
1423 "he comes to regard himself as something supra-human. The consequences that "
1424 "slowly result are: the feeling of irresponsibility, of exceptional rights, the "
1425 "belief that he confers a favor by his mere presence, insane rage when anyone "
1426 "attempts even to compare him with others, let alone to rate him beneath them, "
1427 "or to draw attention to lapses in his work. Because he ceases to practice "
1428 "criticism of himself, at last one pinion after the other falls out of his "
1429 "plumage: that superstitious eats at the roots of his powers and perhaps even "
1430 "turns him into a hypocrite after his powers have fled from him. For the great "
1431 "spirits themselves it is therefore probably more beneficial if they acquire an "
1432 "insight into the nature and origin of their powers, if they grasp, that is to "
1433 "say, what purely human qualities have come together in them and what fortunate "
1434 "circumstances attended them: in the first place undiminished energy, resolute "
1435 "application to individual goals, great personal courage, then the good fortune "
1436 "to receive an upbringing which offered in the early years the finest teachers, "
1437 "models and methods. To be sure, when their goal is the production of the "
1438 "greatest possible effect, unclarity with regard to oneself and that "
1439 "semi-insanity superadded to it has always achieved much; for what has been "
1440 "admired and envied at all times has been that power in them by virtue of which "
1441 "they render men will-less and sweep them away into the delusion that the "
1442 "leaders they are following are supra-natural. Indeed, it elevates and inspires "
1443 "men to believe that someone is in possession of supra-natural powers: to this "
1444 "extent Plato was right to say [Plato: Phaedrus, 244a] that madness has brought "
1445 "the greatest of blessings upon mankind. In rare individual cases this portion "
1446 "of madness may, indeed, actually have been the means by which such a nature, "
1447 "excessive in all directions, was held firmly together: in the life of "
1448 "individuals, too, illusions that are in themselves poisons often play the role "
1449 "of healers; yet, in the end, in the case of every \"genius\" who believes in his "
1450 "own divinity the poison shows itself to the same degree as his \"genius\" grows "
1451 "old: one may recall, for example, the case of Napoleon, whose nature certainly "
1452 "grew into the mighty unity that sets him apart from all men of modern times "
1453 "precisely through his belief in himself and his star and through the contempt "
1454 "for men that flowed from it; until in the end, however, this same belief went "
1455 "over into an almost insane fatalism, robbed him of his acuteness and swiftness "
1456 "of perception, and became the cause of his destruction.";