added a menu item to disable a control
[wxWidgets.git] / samples / widgets / widgets.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Program: wxWidgets Widgets Sample
3 // Name: widgets.cpp
4 // Purpose: Sample showing most of the simple wxWidgets widgets
5 // Author: Vadim Zeitlin
6 // Created: 27.03.01
7 // Id: $Id$
8 // Copyright: (c) 2001 Vadim Zeitlin
9 // License: wxWindows license
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // for compilers that support precompilation, includes "wx/wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 // for all others, include the necessary headers
28 #ifndef WX_PRECOMP
29 #include "wx/app.h"
30 #include "wx/log.h"
31 #include "wx/frame.h"
32 #include "wx/menu.h"
33
34 #include "wx/button.h"
35 #include "wx/checkbox.h"
36 #include "wx/listbox.h"
37 #include "wx/statbox.h"
38 #include "wx/stattext.h"
39 #include "wx/textctrl.h"
40 #endif
41
42 #include "wx/sysopt.h"
43 #include "wx/bookctrl.h"
44 #include "wx/sizer.h"
45 #include "wx/colordlg.h"
46 #include "wx/fontdlg.h"
47 #include "wx/textdlg.h"
48
49 #include "widgets.h"
50
51 // ----------------------------------------------------------------------------
52 // constants
53 // ----------------------------------------------------------------------------
54
55 // control ids
56 enum
57 {
58 Widgets_ClearLog = 100,
59 Widgets_Quit,
60 #if wxUSE_TOOLTIPS
61 Widgets_SetTooltip,
62 #endif // wxUSE_TOOLTIPS
63 Widgets_SetFgColour,
64 Widgets_SetBgColour,
65 Widgets_SetFont,
66 Widgets_Enable
67 };
68
69 // ----------------------------------------------------------------------------
70 // our classes
71 // ----------------------------------------------------------------------------
72
73 // Define a new application type, each program should derive a class from wxApp
74 class WidgetsApp : public wxApp
75 {
76 public:
77 // override base class virtuals
78 // ----------------------------
79
80 // this one is called on application startup and is a good place for the app
81 // initialization (doing it here and not in the ctor allows to have an error
82 // return: if OnInit() returns false, the application terminates)
83 virtual bool OnInit();
84 };
85
86 // Define a new frame type: this is going to be our main frame
87 class WidgetsFrame : public wxFrame
88 {
89 public:
90 // ctor(s) and dtor
91 WidgetsFrame(const wxString& title);
92 virtual ~WidgetsFrame();
93
94 protected:
95 // event handlers
96 #if USE_LOG
97 void OnButtonClearLog(wxCommandEvent& event);
98 #endif // USE_LOG
99 void OnExit(wxCommandEvent& event);
100
101 #if wxUSE_MENUS
102 #if wxUSE_TOOLTIPS
103 void OnSetTooltip(wxCommandEvent& event);
104 #endif // wxUSE_TOOLTIPS
105 void OnSetFgCol(wxCommandEvent& event);
106 void OnSetBgCol(wxCommandEvent& event);
107 void OnSetFont(wxCommandEvent& event);
108 void OnEnable(wxCommandEvent& event);
109 #endif // wxUSE_MENUS
110
111 // initialize the book: add all pages to it
112 void InitBook();
113
114 private:
115 // the panel containing everything
116 wxPanel *m_panel;
117
118 #if USE_LOG
119 // the listbox for logging messages
120 wxListBox *m_lboxLog;
121
122 // the log target we use to redirect messages to the listbox
123 wxLog *m_logTarget;
124 #endif // USE_LOG
125
126 // the book containing the test pages
127 wxBookCtrl *m_book;
128
129 // and the image list for it
130 wxImageList *m_imaglist;
131
132 #if wxUSE_MENUS
133 // last chosen fg/bg colours and font
134 wxColour m_colFg,
135 m_colBg;
136 wxFont m_font;
137 #endif // wxUSE_MENUS
138
139 // any class wishing to process wxWidgets events must use this macro
140 DECLARE_EVENT_TABLE()
141 };
142
143 #if USE_LOG
144 // A log target which just redirects the messages to a listbox
145 class LboxLogger : public wxLog
146 {
147 public:
148 LboxLogger(wxListBox *lbox, wxLog *logOld)
149 {
150 m_lbox = lbox;
151 //m_lbox->Disable(); -- looks ugly under MSW
152 m_logOld = logOld;
153 }
154
155 virtual ~LboxLogger()
156 {
157 wxLog::SetActiveTarget(m_logOld);
158 }
159
160 private:
161 // implement sink functions
162 virtual void DoLog(wxLogLevel level, const wxChar *szString, time_t t)
163 {
164 // don't put trace messages into listbox or we can get into infinite
165 // recursion
166 if ( level == wxLOG_Trace )
167 {
168 if ( m_logOld )
169 {
170 // cast is needed to call protected method
171 ((LboxLogger *)m_logOld)->DoLog(level, szString, t);
172 }
173 }
174 else
175 {
176 wxLog::DoLog(level, szString, t);
177 }
178 }
179
180 virtual void DoLogString(const wxChar *szString, time_t WXUNUSED(t))
181 {
182 wxString msg;
183 TimeStamp(&msg);
184 msg += szString;
185
186 #ifdef __WXUNIVERSAL__
187 m_lbox->AppendAndEnsureVisible(msg);
188 #else // other ports don't have this method yet
189 m_lbox->Append(msg);
190 m_lbox->SetFirstItem(m_lbox->GetCount() - 1);
191 #endif
192 }
193
194 // the control we use
195 wxListBox *m_lbox;
196
197 // the old log target
198 wxLog *m_logOld;
199 };
200 #endif // USE_LOG
201
202 // array of pages
203 WX_DEFINE_ARRAY_PTR(WidgetsPage *, ArrayWidgetsPage);
204
205 // ----------------------------------------------------------------------------
206 // misc macros
207 // ----------------------------------------------------------------------------
208
209 IMPLEMENT_APP(WidgetsApp)
210
211 // ----------------------------------------------------------------------------
212 // event tables
213 // ----------------------------------------------------------------------------
214
215 BEGIN_EVENT_TABLE(WidgetsFrame, wxFrame)
216 #if USE_LOG
217 EVT_BUTTON(Widgets_ClearLog, WidgetsFrame::OnButtonClearLog)
218 #endif // USE_LOG
219 EVT_BUTTON(Widgets_Quit, WidgetsFrame::OnExit)
220
221 #if wxUSE_TOOLTIPS
222 EVT_MENU(Widgets_SetTooltip, WidgetsFrame::OnSetTooltip)
223 #endif // wxUSE_TOOLTIPS
224
225 EVT_MENU(Widgets_SetFgColour, WidgetsFrame::OnSetFgCol)
226 EVT_MENU(Widgets_SetBgColour, WidgetsFrame::OnSetBgCol)
227 EVT_MENU(Widgets_SetFont, WidgetsFrame::OnSetFont)
228 EVT_MENU(Widgets_Enable, WidgetsFrame::OnEnable)
229
230 EVT_MENU(wxID_EXIT, WidgetsFrame::OnExit)
231 END_EVENT_TABLE()
232
233 // ============================================================================
234 // implementation
235 // ============================================================================
236
237 // ----------------------------------------------------------------------------
238 // app class
239 // ----------------------------------------------------------------------------
240
241 bool WidgetsApp::OnInit()
242 {
243 if ( !wxApp::OnInit() )
244 return false;
245
246 // the reason for having these ifdef's is that I often run two copies of
247 // this sample side by side and it is useful to see which one is which
248 wxString title;
249 #if defined(__WXUNIVERSAL__)
250 title = _T("wxUniv/");
251 #endif
252
253 #if defined(__WXMSW__)
254 title += _T("wxMSW");
255 #elif defined(__WXGTK__)
256 title += _T("wxGTK");
257 #elif defined(__WXMAC__)
258 title += _T("wxMAC");
259 #elif defined(__WXMOTIF__)
260 title += _T("wxMOTIF");
261 #else
262 title += _T("wxWidgets");
263 #endif
264
265 wxFrame *frame = new WidgetsFrame(title + _T(" widgets demo"));
266 frame->Show();
267
268 //wxLog::AddTraceMask(_T("listbox"));
269 //wxLog::AddTraceMask(_T("scrollbar"));
270 //wxLog::AddTraceMask(_T("focus"));
271
272 return true;
273 }
274
275 // ----------------------------------------------------------------------------
276 // WidgetsFrame construction
277 // ----------------------------------------------------------------------------
278
279 WidgetsFrame::WidgetsFrame(const wxString& title)
280 : wxFrame(NULL, wxID_ANY, title,
281 wxPoint(0, 50), wxDefaultSize,
282 wxDEFAULT_FRAME_STYLE |
283 wxNO_FULL_REPAINT_ON_RESIZE |
284 wxCLIP_CHILDREN |
285 wxTAB_TRAVERSAL)
286 {
287 // init everything
288 #if USE_LOG
289 m_lboxLog = (wxListBox *)NULL;
290 m_logTarget = (wxLog *)NULL;
291 #endif // USE_LOG
292 m_book = (wxBookCtrl *)NULL;
293 m_imaglist = (wxImageList *)NULL;
294
295 #if wxUSE_MENUS
296 // create the menubar
297 wxMenuBar *mbar = new wxMenuBar;
298 wxMenu *menuWidget = new wxMenu;
299 #if wxUSE_TOOLTIPS
300 menuWidget->Append(Widgets_SetTooltip, _T("Set &tooltip...\tCtrl-T"));
301 menuWidget->AppendSeparator();
302 #endif // wxUSE_TOOLTIPS
303 menuWidget->Append(Widgets_SetFgColour, _T("Set &foreground...\tCtrl-F"));
304 menuWidget->Append(Widgets_SetBgColour, _T("Set &background...\tCtrl-B"));
305 menuWidget->Append(Widgets_SetFont, _T("Set f&ont...\tCtrl-O"));
306 menuWidget->AppendCheckItem(Widgets_Enable, _T("&Enable/disable\tCtrl-E"));
307 menuWidget->AppendSeparator();
308 menuWidget->Append(wxID_EXIT, _T("&Quit\tCtrl-Q"));
309 mbar->Append(menuWidget, _T("&Widget"));
310 SetMenuBar(mbar);
311
312 mbar->Check(Widgets_Enable, true);
313 #endif // wxUSE_MENUS
314
315 // create controls
316 m_panel = new wxPanel(this, wxID_ANY,
317 wxDefaultPosition, wxDefaultSize, wxCLIP_CHILDREN);
318
319 wxSizer *sizerTop = new wxBoxSizer(wxVERTICAL);
320
321 // we have 2 panes: book with pages demonstrating the controls in the
322 // upper one and the log window with some buttons in the lower
323
324 int style = wxNO_FULL_REPAINT_ON_RESIZE|wxCLIP_CHILDREN|wxBC_DEFAULT;
325 // Uncomment to suppress page theme (draw in solid colour)
326 //style |= wxNB_NOPAGETHEME;
327
328 m_book = new wxBookCtrl(m_panel, wxID_ANY, wxDefaultPosition,
329 wxDefaultSize, style);
330 InitBook();
331
332 #ifndef __SMARTPHONE__
333 // the lower one only has the log listbox and a button to clear it
334 #if USE_LOG
335 wxSizer *sizerDown = new wxStaticBoxSizer(
336 new wxStaticBox( m_panel, wxID_ANY, _T("&Log window") ),
337 wxVERTICAL);
338
339 m_lboxLog = new wxListBox(m_panel, wxID_ANY);
340 sizerDown->Add(m_lboxLog, 1, wxGROW | wxALL, 5);
341 sizerDown->SetMinSize(100, 150);
342 #else
343 wxSizer *sizerDown = new wxBoxSizer(wxVERTICAL);
344 #endif // USE_LOG
345
346 wxBoxSizer *sizerBtns = new wxBoxSizer(wxHORIZONTAL);
347 wxButton *btn;
348 #if USE_LOG
349 btn = new wxButton(m_panel, Widgets_ClearLog, _T("Clear &log"));
350 sizerBtns->Add(btn);
351 sizerBtns->Add(10, 0); // spacer
352 #endif // USE_LOG
353 btn = new wxButton(m_panel, Widgets_Quit, _T("E&xit"));
354 sizerBtns->Add(btn);
355 sizerDown->Add(sizerBtns, 0, wxALL | wxALIGN_RIGHT, 5);
356
357 // put everything together
358 sizerTop->Add(m_book, 1, wxGROW | (wxALL & ~(wxTOP | wxBOTTOM)), 10);
359 sizerTop->Add(0, 5, 0, wxGROW); // spacer in between
360 sizerTop->Add(sizerDown, 0, wxGROW | (wxALL & ~wxTOP), 10);
361
362 #else // !__SMARTPHONE__/__SMARTPHONE__
363
364 sizerTop->Add(m_book, 1, wxGROW | wxALL );
365
366 #endif // __SMARTPHONE__
367
368 m_panel->SetSizer(sizerTop);
369
370 sizerTop->Fit(this);
371 sizerTop->SetSizeHints(this);
372
373 #if USE_LOG && !defined(__WXCOCOA__)
374 // wxCocoa's listbox is too flakey to use for logging right now
375 // now that everything is created we can redirect the log messages to the
376 // listbox
377 m_logTarget = new LboxLogger(m_lboxLog, wxLog::GetActiveTarget());
378 wxLog::SetActiveTarget(m_logTarget);
379 #endif
380 }
381
382 void WidgetsFrame::InitBook()
383 {
384 m_imaglist = new wxImageList(32, 32);
385
386 ArrayWidgetsPage pages;
387 wxArrayString labels;
388
389 // we need to first create all pages and only then add them to the book
390 // as we need the image list first
391 WidgetsPageInfo *info = WidgetsPage::ms_widgetPages;
392 while ( info )
393 {
394 WidgetsPage *page = (*info->GetCtor())(m_book, m_imaglist);
395 pages.Add(page);
396
397 labels.Add(info->GetLabel());
398
399 info = info->GetNext();
400 }
401
402 m_book->SetImageList(m_imaglist);
403
404 // now do add them
405 size_t count = pages.GetCount();
406 for ( size_t n = 0; n < count; n++ )
407 {
408 m_book->AddPage(
409 pages[n],
410 labels[n],
411 false, // don't select
412 n // image id
413 );
414
415 /*
416 wxColour colour = m_book->MSWGetBgColourForChild(pages[n]);
417 pages[n]->SetBackgroundColour(colour);
418 */
419 }
420 }
421
422 WidgetsFrame::~WidgetsFrame()
423 {
424 #if USE_LOG
425 delete m_logTarget;
426 #endif // USE_LOG
427 delete m_imaglist;
428 }
429
430 // ----------------------------------------------------------------------------
431 // WidgetsFrame event handlers
432 // ----------------------------------------------------------------------------
433
434 void WidgetsFrame::OnExit(wxCommandEvent& WXUNUSED(event))
435 {
436 Close();
437 }
438
439 #if USE_LOG
440 void WidgetsFrame::OnButtonClearLog(wxCommandEvent& WXUNUSED(event))
441 {
442 m_lboxLog->Clear();
443 }
444 #endif // USE_LOG
445
446 #if wxUSE_MENUS
447
448 #if wxUSE_TOOLTIPS
449
450 void WidgetsFrame::OnSetTooltip(wxCommandEvent& WXUNUSED(event))
451 {
452 static wxString s_tip = _T("This is a tooltip");
453
454 wxString s = wxGetTextFromUser
455 (
456 _T("Tooltip text: "),
457 _T("Widgets sample"),
458 s_tip,
459 this
460 );
461
462 if ( s.empty() )
463 return;
464
465 WidgetsPage *page = wxStaticCast(m_book->GetCurrentPage(), WidgetsPage);
466 page->GetWidget()->SetToolTip(s_tip = s);
467
468 wxControl *ctrl2 = page->GetWidget2();
469 if ( ctrl2 )
470 ctrl2->SetToolTip(s);
471 }
472
473 #endif // wxUSE_TOOLTIPS
474
475 void WidgetsFrame::OnSetFgCol(wxCommandEvent& WXUNUSED(event))
476 {
477 #if wxUSE_COLOURDLG
478 // allow for debugging the default colour the first time this is called
479 WidgetsPage *page = wxStaticCast(m_book->GetCurrentPage(), WidgetsPage);
480 if (!m_colFg.Ok())
481 m_colFg = page->GetForegroundColour();
482
483 wxColour col = wxGetColourFromUser(this, m_colFg);
484 if ( !col.Ok() )
485 return;
486
487 m_colFg = col;
488
489 page->GetWidget()->SetForegroundColour(m_colFg);
490 page->GetWidget()->Refresh();
491
492 wxControl *ctrl2 = page->GetWidget2();
493 if ( ctrl2 )
494 {
495 ctrl2->SetForegroundColour(m_colFg);
496 ctrl2->Refresh();
497 }
498 #else
499 wxLogMessage(_T("Colour selection dialog not available in current build."));
500 #endif
501 }
502
503 void WidgetsFrame::OnSetBgCol(wxCommandEvent& WXUNUSED(event))
504 {
505 #if wxUSE_COLOURDLG
506 WidgetsPage *page = wxStaticCast(m_book->GetCurrentPage(), WidgetsPage);
507 if ( !m_colBg.Ok() )
508 m_colBg = page->GetBackgroundColour();
509
510 wxColour col = wxGetColourFromUser(this, m_colBg);
511 if ( !col.Ok() )
512 return;
513
514 m_colBg = col;
515
516 page->GetWidget()->SetBackgroundColour(m_colBg);
517 page->GetWidget()->Refresh();
518
519 wxControl *ctrl2 = page->GetWidget2();
520 if ( ctrl2 )
521 {
522 ctrl2->SetBackgroundColour(m_colFg);
523 ctrl2->Refresh();
524 }
525 #else
526 wxLogMessage(_T("Colour selection dialog not available in current build."));
527 #endif
528 }
529
530 void WidgetsFrame::OnSetFont(wxCommandEvent& WXUNUSED(event))
531 {
532 #if wxUSE_FONTDLG
533 WidgetsPage *page = wxStaticCast(m_book->GetCurrentPage(), WidgetsPage);
534 if (!m_font.Ok())
535 m_font = page->GetFont();
536
537 wxFont font = wxGetFontFromUser(this, m_font);
538 if ( !font.Ok() )
539 return;
540
541 m_font = font;
542
543 page->GetWidget()->SetFont(m_font);
544 page->GetWidget()->Refresh();
545
546 wxControl *ctrl2 = page->GetWidget2();
547 if ( ctrl2 )
548 {
549 ctrl2->SetFont(m_font);
550 ctrl2->Refresh();
551 }
552 #else
553 wxLogMessage(_T("Font selection dialog not available in current build."));
554 #endif
555 }
556
557 void WidgetsFrame::OnEnable(wxCommandEvent& event)
558 {
559 WidgetsPage *page = wxStaticCast(m_book->GetCurrentPage(), WidgetsPage);
560 page->GetWidget()->Enable(event.IsChecked());
561 }
562
563 #endif // wxUSE_MENUS
564
565 // ----------------------------------------------------------------------------
566 // WidgetsPageInfo
567 // ----------------------------------------------------------------------------
568
569 WidgetsPageInfo *WidgetsPage::ms_widgetPages = NULL;
570
571 WidgetsPageInfo::WidgetsPageInfo(Constructor ctor, const wxChar *label)
572 : m_label(label)
573 {
574 m_ctor = ctor;
575
576 m_next = NULL;
577
578 // dummy sorting: add and immediately sort on list according to label
579
580 if(WidgetsPage::ms_widgetPages)
581 {
582 WidgetsPageInfo *node_prev = WidgetsPage::ms_widgetPages;
583 if(wxStrcmp(label,node_prev->GetLabel().c_str())<0)
584 {
585 // add as first
586 m_next = node_prev;
587 WidgetsPage::ms_widgetPages = this;
588 }
589 else
590 {
591 WidgetsPageInfo *node_next;
592 do
593 {
594 node_next = node_prev->GetNext();
595 if(node_next)
596 {
597 // add if between two
598 if(wxStrcmp(label,node_next->GetLabel().c_str())<0)
599 {
600 node_prev->SetNext(this);
601 m_next = node_next;
602 // force to break loop
603 node_next = NULL;
604 }
605 }
606 else
607 {
608 // add as last
609 node_prev->SetNext(this);
610 m_next = node_next;
611 }
612 node_prev = node_next;
613 }while(node_next);
614 }
615 }
616 else
617 {
618 // add when first
619
620 WidgetsPage::ms_widgetPages = this;
621
622 }
623
624 }
625
626 // ----------------------------------------------------------------------------
627 // WidgetsPage
628 // ----------------------------------------------------------------------------
629
630 WidgetsPage::WidgetsPage(wxBookCtrl *book)
631 : wxPanel(book, wxID_ANY,
632 wxDefaultPosition, wxDefaultSize,
633 wxNO_FULL_REPAINT_ON_RESIZE |
634 wxCLIP_CHILDREN |
635 wxTAB_TRAVERSAL)
636 {
637 }
638
639 wxSizer *WidgetsPage::CreateSizerWithText(wxControl *control,
640 wxWindowID id,
641 wxTextCtrl **ppText)
642 {
643 wxSizer *sizerRow = new wxBoxSizer(wxHORIZONTAL);
644 wxTextCtrl *text = new wxTextCtrl(this, id, wxEmptyString,
645 wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER);
646
647 sizerRow->Add(control, 0, wxRIGHT | wxALIGN_CENTRE_VERTICAL, 5);
648 sizerRow->Add(text, 1, wxLEFT | wxALIGN_CENTRE_VERTICAL, 5);
649
650 if ( ppText )
651 *ppText = text;
652
653 return sizerRow;
654 }
655
656 // create a sizer containing a label and a text ctrl
657 wxSizer *WidgetsPage::CreateSizerWithTextAndLabel(const wxString& label,
658 wxWindowID id,
659 wxTextCtrl **ppText)
660 {
661 return CreateSizerWithText(new wxStaticText(this, wxID_ANY, label),
662 id, ppText);
663 }
664
665 // create a sizer containing a button and a text ctrl
666 wxSizer *WidgetsPage::CreateSizerWithTextAndButton(wxWindowID idBtn,
667 const wxString& label,
668 wxWindowID id,
669 wxTextCtrl **ppText)
670 {
671 return CreateSizerWithText(new wxButton(this, idBtn, label), id, ppText);
672 }
673
674 wxCheckBox *WidgetsPage::CreateCheckBoxAndAddToSizer(wxSizer *sizer,
675 const wxString& label,
676 wxWindowID id)
677 {
678 wxCheckBox *checkbox = new wxCheckBox(this, id, label);
679 sizer->Add(checkbox, 0, wxLEFT | wxRIGHT, 5);
680 sizer->Add(0, 2, 0, wxGROW); // spacer
681
682 return checkbox;
683 }
684