allow testing wxSystemSettings::GetFont() return value
[wxWidgets.git] / samples / font / font.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: font.cpp
3 // Purpose: wxFont demo
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 30.09.99
7 // RCS-ID: $Id$
8 // Copyright: (c) 1999 Vadim Zeitlin
9 // Licence: wxWindows licence
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 // for all others, include the necessary headers (this file is usually all you
20 // need because it includes almost all standard wxWidgets headers
21 #ifndef WX_PRECOMP
22 #include "wx/wx.h"
23
24 #include "wx/log.h"
25 #endif
26
27 #include "wx/choicdlg.h"
28 #include "wx/fontdlg.h"
29 #include "wx/fontenum.h"
30 #include "wx/fontmap.h"
31 #include "wx/encconv.h"
32 #include "wx/splitter.h"
33 #include "wx/textfile.h"
34 #include "wx/settings.h"
35
36 #include "../sample.xpm"
37
38 #ifdef __WXMAC__
39 #undef wxFontDialog
40 #include "wx/osx/fontdlg.h"
41 #endif
42
43 // used as title for several dialog boxes
44 static const wxChar SAMPLE_TITLE[] = _T("wxWidgets Font Sample");
45
46 // ----------------------------------------------------------------------------
47 // private classes
48 // ----------------------------------------------------------------------------
49
50 // Define a new application type, each program should derive a class from wxApp
51 class MyApp : public wxApp
52 {
53 public:
54 // override base class virtuals
55 // ----------------------------
56
57 // this one is called on application startup and is a good place for the app
58 // initialization (doing it here and not in the ctor allows to have an error
59 // return: if OnInit() returns false, the application terminates)
60 virtual bool OnInit();
61 };
62
63 // MyCanvas is a canvas on which we show the font sample
64 class MyCanvas: public wxWindow
65 {
66 public:
67 MyCanvas( wxWindow *parent );
68 virtual ~MyCanvas(){};
69
70 // accessors for the frame
71 const wxFont& GetTextFont() const { return m_font; }
72 const wxColour& GetColour() const { return m_colour; }
73 void SetTextFont(const wxFont& font) { m_font = font; }
74 void SetColour(const wxColour& colour) { m_colour = colour; }
75
76 // event handlers
77 void OnPaint( wxPaintEvent &event );
78
79 private:
80 wxColour m_colour;
81 wxFont m_font;
82
83 DECLARE_EVENT_TABLE()
84 };
85
86 // Define a new frame type: this is going to be our main frame
87 class MyFrame : public wxFrame
88 {
89 public:
90 // ctor(s)
91 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
92
93 // accessors
94 MyCanvas *GetCanvas() const { return m_canvas; }
95
96 // event handlers (these functions should _not_ be virtual)
97 void OnQuit(wxCommandEvent& event);
98 void OnAbout(wxCommandEvent& event);
99
100 void OnIncFont(wxCommandEvent& WXUNUSED(event)) { DoResizeFont(+2); }
101 void OnDecFont(wxCommandEvent& WXUNUSED(event)) { DoResizeFont(-2); }
102
103 void OnBold(wxCommandEvent& event);
104 void OnItalic(wxCommandEvent& event);
105 void OnUnderline(wxCommandEvent& event);
106
107 void OnwxPointerFont(wxCommandEvent& event);
108 void OnwxSystemSettingsFont(wxCommandEvent& event);
109
110 void OnTestTextValue(wxCommandEvent& event);
111 void OnViewMsg(wxCommandEvent& event);
112 void OnSelectFont(wxCommandEvent& event);
113 void OnEnumerateFamiliesForEncoding(wxCommandEvent& event);
114 void OnEnumerateFamilies(wxCommandEvent& WXUNUSED(event))
115 { DoEnumerateFamilies(false); }
116 void OnEnumerateFixedFamilies(wxCommandEvent& WXUNUSED(event))
117 { DoEnumerateFamilies(true); }
118 void OnEnumerateEncodings(wxCommandEvent& event);
119
120 void OnSetNativeDesc(wxCommandEvent& event);
121 void OnSetNativeUserDesc(wxCommandEvent& event);
122 void OnSetFaceName(wxCommandEvent& event);
123 void OnSetEncoding(wxCommandEvent& event);
124
125 protected:
126 bool DoEnumerateFamilies(bool fixedWidthOnly,
127 wxFontEncoding encoding = wxFONTENCODING_SYSTEM,
128 bool silent = false);
129
130 void DoResizeFont(int diff);
131 void DoChangeFont(const wxFont& font, const wxColour& col = wxNullColour);
132
133 // ask the user to choose an encoding and return it or
134 // wxFONTENCODING_SYSTEM if the dialog was cancelled
135 wxFontEncoding GetEncodingFromUser();
136
137
138 size_t m_fontSize; // in points
139
140 wxTextCtrl *m_textctrl;
141 MyCanvas *m_canvas;
142
143 private:
144 // any class wishing to process wxWidgets events must use this macro
145 DECLARE_EVENT_TABLE()
146 };
147
148 // ----------------------------------------------------------------------------
149 // constants
150 // ----------------------------------------------------------------------------
151
152 // IDs for the controls and the menu commands
153 enum
154 {
155 // menu items
156 Font_Quit = wxID_EXIT,
157 Font_About = wxID_ABOUT,
158
159 Font_ViewMsg = wxID_HIGHEST+1,
160 Font_TestTextValue,
161
162 Font_IncSize,
163 Font_DecSize,
164 Font_Bold,
165 Font_Italic,
166 Font_Underlined,
167
168 // standard global wxFont objects:
169 Font_wxNORMAL_FONT,
170 Font_wxSMALL_FONT,
171 Font_wxITALIC_FONT,
172 Font_wxSWISS_FONT,
173 Font_Standard,
174
175 // wxSystemSettings::GetFont possible objects:
176 Font_wxSYS_OEM_FIXED_FONT,
177 Font_wxSYS_ANSI_FIXED_FONT,
178 Font_wxSYS_ANSI_VAR_FONT,
179 Font_wxSYS_SYSTEM_FONT,
180 Font_wxSYS_DEVICE_DEFAULT_FONT,
181 Font_wxSYS_DEFAULT_GUI_FONT,
182
183 Font_Choose = 100,
184 Font_EnumFamiliesForEncoding,
185 Font_EnumFamilies,
186 Font_EnumFixedFamilies,
187 Font_EnumEncodings,
188 Font_SetNativeDesc,
189 Font_SetNativeUserDesc,
190 Font_SetFaceName,
191 Font_SetEncoding,
192 Font_Max
193 };
194
195 // ----------------------------------------------------------------------------
196 // event tables and other macros for wxWidgets
197 // ----------------------------------------------------------------------------
198
199 // the event tables connect the wxWidgets events with the functions (event
200 // handlers) which process them. It can be also done at run-time, but for the
201 // simple menu events like this the static method is much simpler.
202 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
203 EVT_MENU(Font_Quit, MyFrame::OnQuit)
204 EVT_MENU(Font_TestTextValue, MyFrame::OnTestTextValue)
205 EVT_MENU(Font_ViewMsg, MyFrame::OnViewMsg)
206 EVT_MENU(Font_About, MyFrame::OnAbout)
207
208 EVT_MENU(Font_IncSize, MyFrame::OnIncFont)
209 EVT_MENU(Font_DecSize, MyFrame::OnDecFont)
210 EVT_MENU(Font_Bold, MyFrame::OnBold)
211 EVT_MENU(Font_Italic, MyFrame::OnItalic)
212 EVT_MENU(Font_Underlined, MyFrame::OnUnderline)
213
214 EVT_MENU(Font_wxNORMAL_FONT, MyFrame::OnwxPointerFont)
215 EVT_MENU(Font_wxSMALL_FONT, MyFrame::OnwxPointerFont)
216 EVT_MENU(Font_wxITALIC_FONT, MyFrame::OnwxPointerFont)
217 EVT_MENU(Font_wxSWISS_FONT, MyFrame::OnwxPointerFont)
218
219 EVT_MENU(Font_wxSYS_OEM_FIXED_FONT, MyFrame::OnwxSystemSettingsFont)
220 EVT_MENU(Font_wxSYS_ANSI_FIXED_FONT, MyFrame::OnwxSystemSettingsFont)
221 EVT_MENU(Font_wxSYS_ANSI_VAR_FONT, MyFrame::OnwxSystemSettingsFont)
222 EVT_MENU(Font_wxSYS_SYSTEM_FONT, MyFrame::OnwxSystemSettingsFont)
223 EVT_MENU(Font_wxSYS_DEVICE_DEFAULT_FONT, MyFrame::OnwxSystemSettingsFont)
224 EVT_MENU(Font_wxSYS_DEFAULT_GUI_FONT, MyFrame::OnwxSystemSettingsFont)
225
226 EVT_MENU(Font_SetNativeDesc, MyFrame::OnSetNativeDesc)
227 EVT_MENU(Font_SetNativeUserDesc, MyFrame::OnSetNativeUserDesc)
228 EVT_MENU(Font_SetFaceName, MyFrame::OnSetFaceName)
229 EVT_MENU(Font_SetEncoding, MyFrame::OnSetEncoding)
230
231 EVT_MENU(Font_Choose, MyFrame::OnSelectFont)
232 EVT_MENU(Font_EnumFamiliesForEncoding, MyFrame::OnEnumerateFamiliesForEncoding)
233 EVT_MENU(Font_EnumFamilies, MyFrame::OnEnumerateFamilies)
234 EVT_MENU(Font_EnumFixedFamilies, MyFrame::OnEnumerateFixedFamilies)
235 EVT_MENU(Font_EnumEncodings, MyFrame::OnEnumerateEncodings)
236 END_EVENT_TABLE()
237
238 // Create a new application object: this macro will allow wxWidgets to create
239 // the application object during program execution (it's better than using a
240 // static object for many reasons) and also declares the accessor function
241 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
242 // not wxApp)
243 IMPLEMENT_APP(MyApp)
244
245 // ============================================================================
246 // implementation
247 // ============================================================================
248
249 // ----------------------------------------------------------------------------
250 // the application class
251 // ----------------------------------------------------------------------------
252
253 // `Main program' equivalent: the program execution "starts" here
254 bool MyApp::OnInit()
255 {
256 if ( !wxApp::OnInit() )
257 return false;
258
259 // Create the main application window
260 MyFrame *frame = new MyFrame(wxT("Font wxWidgets demo"),
261 wxPoint(50, 50), wxSize(600, 400));
262
263 // Show it and tell the application that it's our main window
264 frame->Show(true);
265 SetTopWindow(frame);
266
267 // success: wxApp::OnRun() will be called which will enter the main message
268 // loop and the application will run. If we returned 'false' here, the
269 // application would exit immediately.
270 return true;
271 }
272
273 // ----------------------------------------------------------------------------
274 // main frame
275 // ----------------------------------------------------------------------------
276
277 // frame constructor
278 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
279 : wxFrame((wxFrame *)NULL, wxID_ANY, title, pos, size), m_textctrl(NULL)
280 {
281 m_fontSize = wxNORMAL_FONT->GetPointSize();
282
283 SetIcon(wxIcon(sample_xpm));
284
285 // create a menu bar
286 wxMenu *menuFile = new wxMenu;
287
288 menuFile->Append(Font_TestTextValue, wxT("&Test text value"),
289 wxT("Verify that getting and setting text value doesn't change it"));
290 menuFile->Append(Font_ViewMsg, wxT("&View...\tCtrl-V"),
291 wxT("View an email message file"));
292 menuFile->AppendSeparator();
293 menuFile->Append(Font_About, wxT("&About...\tCtrl-A"), wxT("Show about dialog"));
294 menuFile->AppendSeparator();
295 menuFile->Append(Font_Quit, wxT("E&xit\tAlt-X"), wxT("Quit this program"));
296
297 wxMenu *menuFont = new wxMenu;
298 menuFont->Append(Font_IncSize, wxT("&Increase font size by 2 points\tCtrl-I"));
299 menuFont->Append(Font_DecSize, wxT("&Decrease font size by 2 points\tCtrl-D"));
300 menuFont->AppendSeparator();
301 menuFont->AppendCheckItem(Font_Bold, wxT("&Bold\tCtrl-B"), wxT("Toggle bold state"));
302 menuFont->AppendCheckItem(Font_Italic, wxT("&Oblique\tCtrl-O"), wxT("Toggle italic state"));
303 menuFont->AppendCheckItem(Font_Underlined, wxT("&Underlined\tCtrl-U"),
304 wxT("Toggle underlined state"));
305
306 menuFont->AppendSeparator();
307 menuFont->Append(Font_SetNativeDesc,
308 wxT("Set native font &description\tShift-Ctrl-D"));
309 menuFont->Append(Font_SetNativeUserDesc,
310 wxT("Set &user font description\tShift-Ctrl-U"));
311 menuFont->Append(Font_SetFaceName, wxT("Check font face name"));
312 menuFont->Append(Font_SetEncoding, wxT("Set font &encoding\tShift-Ctrl-E"));
313
314 wxMenu *menuSelect = new wxMenu;
315 menuSelect->Append(Font_Choose, wxT("&Select font...\tCtrl-S"),
316 wxT("Select a standard font"));
317
318 wxMenu *menuStdFonts = new wxMenu;
319 menuStdFonts->Append(Font_wxNORMAL_FONT, wxT("wxNORMAL_FONT"), wxT("Normal font used by wxWidgets"));
320 menuStdFonts->Append(Font_wxSMALL_FONT, wxT("wxSMALL_FONT"), wxT("Small font used by wxWidgets"));
321 menuStdFonts->Append(Font_wxITALIC_FONT, wxT("wxITALIC_FONT"), wxT("Italic font used by wxWidgets"));
322 menuStdFonts->Append(Font_wxSWISS_FONT, wxT("wxSWISS_FONT"), wxT("Swiss font used by wxWidgets"));
323 menuStdFonts->AppendSeparator();
324 menuStdFonts->Append(Font_wxSYS_OEM_FIXED_FONT, wxT("wxSYS_OEM_FIXED_FONT"),
325 wxT("Original equipment manufacturer dependent fixed-pitch font."));
326 menuStdFonts->Append(Font_wxSYS_ANSI_FIXED_FONT, wxT("wxSYS_ANSI_FIXED_FONT"),
327 wxT("Windows fixed-pitch (monospaced) font. "));
328 menuStdFonts->Append(Font_wxSYS_ANSI_VAR_FONT, wxT("wxSYS_ANSI_VAR_FONT"),
329 wxT("Windows variable-pitch (proportional) font."));
330 menuStdFonts->Append(Font_wxSYS_SYSTEM_FONT, wxT("wxSYS_SYSTEM_FONT"),
331 wxT("System font."));
332 menuStdFonts->Append(Font_wxSYS_DEVICE_DEFAULT_FONT, wxT("wxSYS_DEVICE_DEFAULT_FONT"),
333 wxT("Device-dependent font."));
334 menuStdFonts->Append(Font_wxSYS_DEFAULT_GUI_FONT, wxT("wxSYS_DEFAULT_GUI_FONT"),
335 wxT("Default font for user interface objects such as menus and dialog boxes. "));
336 menuSelect->Append(Font_Standard, wxT("Standar&d fonts"), menuStdFonts);
337
338 menuSelect->AppendSeparator();
339 menuSelect->Append(Font_EnumFamilies, wxT("Enumerate font &families\tCtrl-F"));
340 menuSelect->Append(Font_EnumFixedFamilies,
341 wxT("Enumerate fi&xed font families\tCtrl-X"));
342 menuSelect->Append(Font_EnumEncodings,
343 wxT("Enumerate &encodings\tCtrl-E"));
344 menuSelect->Append(Font_EnumFamiliesForEncoding,
345 wxT("Find font for en&coding...\tCtrl-C"),
346 wxT("Find font families for given encoding"));
347
348 // now append the freshly created menu to the menu bar...
349 wxMenuBar *menuBar = new wxMenuBar;
350 menuBar->Append(menuFile, wxT("&File"));
351 menuBar->Append(menuFont, wxT("F&ont"));
352 menuBar->Append(menuSelect, wxT("&Select"));
353
354 // ... and attach this menu bar to the frame
355 SetMenuBar(menuBar);
356
357 wxSplitterWindow *splitter = new wxSplitterWindow(this);
358
359 m_textctrl = new wxTextCtrl(splitter, wxID_ANY,
360 wxT("Paste text here to see how it looks\nlike in the given font"),
361 wxDefaultPosition, wxDefaultSize,
362 wxTE_MULTILINE);
363
364 m_canvas = new MyCanvas(splitter);
365
366 splitter->SplitHorizontally(m_textctrl, m_canvas, 100);
367
368 #if wxUSE_STATUSBAR
369 // create a status bar just for fun (by default with 1 pane only)
370 CreateStatusBar();
371 SetStatusText(wxT("Welcome to wxWidgets font demo!"));
372 #endif // wxUSE_STATUSBAR
373 }
374
375 // --------------------------------------------------------
376
377 class MyEncodingEnumerator : public wxFontEnumerator
378 {
379 public:
380 MyEncodingEnumerator()
381 { m_n = 0; }
382
383 const wxString& GetText() const
384 { return m_text; }
385
386 protected:
387 virtual bool OnFontEncoding(const wxString& facename,
388 const wxString& encoding)
389 {
390 wxString text;
391 text.Printf(wxT("Encoding %u: %s (available in facename '%s')\n"),
392 (unsigned int) ++m_n, encoding.c_str(), facename.c_str());
393 m_text += text;
394 return true;
395 }
396
397 private:
398 size_t m_n;
399 wxString m_text;
400 };
401
402 void MyFrame::OnEnumerateEncodings(wxCommandEvent& WXUNUSED(event))
403 {
404 MyEncodingEnumerator fontEnumerator;
405
406 fontEnumerator.EnumerateEncodings();
407
408 wxLogMessage(wxT("Enumerating all available encodings:\n%s"),
409 fontEnumerator.GetText().c_str());
410 }
411
412 // -------------------------------------------------------------
413
414 class MyFontEnumerator : public wxFontEnumerator
415 {
416 public:
417 bool GotAny() const
418 { return !m_facenames.IsEmpty(); }
419
420 const wxArrayString& GetFacenames() const
421 { return m_facenames; }
422
423 protected:
424 virtual bool OnFacename(const wxString& facename)
425 {
426 m_facenames.Add(facename);
427 return true;
428 }
429
430 private:
431 wxArrayString m_facenames;
432 } fontEnumerator;
433
434 bool MyFrame::DoEnumerateFamilies(bool fixedWidthOnly,
435 wxFontEncoding encoding,
436 bool silent)
437 {
438 MyFontEnumerator fontEnumerator;
439
440 fontEnumerator.EnumerateFacenames(encoding, fixedWidthOnly);
441
442 if ( fontEnumerator.GotAny() )
443 {
444 int nFacenames = fontEnumerator.GetFacenames().GetCount();
445 if ( !silent )
446 {
447 wxLogStatus(this, wxT("Found %d %sfonts"),
448 nFacenames, fixedWidthOnly ? wxT("fixed width ") : wxT(""));
449 }
450
451 wxString facename;
452
453 if ( silent )
454 {
455 // choose the first
456 facename = fontEnumerator.GetFacenames().Item(0);
457 }
458 else
459 {
460 // let the user choose
461 wxString *facenames = new wxString[nFacenames];
462 int n;
463 for ( n = 0; n < nFacenames; n++ )
464 facenames[n] = fontEnumerator.GetFacenames().Item(n);
465
466 n = wxGetSingleChoiceIndex
467 (
468 wxT("Choose a facename"),
469 SAMPLE_TITLE,
470 nFacenames,
471 facenames,
472 this
473 );
474
475 if ( n != -1 )
476 facename = facenames[n];
477
478 delete [] facenames;
479 }
480
481 if ( !facename.empty() )
482 {
483 wxFont font(wxNORMAL_FONT->GetPointSize(),
484 wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
485 wxFONTWEIGHT_NORMAL, false, facename, encoding);
486
487 DoChangeFont(font);
488 }
489
490 return true;
491 }
492 else if ( !silent )
493 {
494 wxLogWarning(wxT("No such fonts found."));
495 }
496
497 return false;
498 }
499
500 void MyFrame::OnEnumerateFamiliesForEncoding(wxCommandEvent& WXUNUSED(event))
501 {
502 wxFontEncoding enc = GetEncodingFromUser();
503 if ( enc != wxFONTENCODING_SYSTEM )
504 {
505 DoEnumerateFamilies(false, enc);
506 }
507 }
508
509 void MyFrame::OnSetNativeDesc(wxCommandEvent& WXUNUSED(event))
510 {
511 wxString fontInfo = wxGetTextFromUser
512 (
513 wxT("Enter native font string"),
514 wxT("Input font description"),
515 m_canvas->GetTextFont().GetNativeFontInfoDesc(),
516 this
517 );
518 if ( fontInfo.empty() )
519 return; // user clicked "Cancel" - do nothing
520
521 wxFont font;
522 font.SetNativeFontInfo(fontInfo);
523 if ( !font.Ok() )
524 {
525 wxLogError(wxT("Font info string \"%s\" is invalid."),
526 fontInfo.c_str());
527 return;
528 }
529
530 DoChangeFont(font);
531 }
532
533 void MyFrame::OnSetFaceName(wxCommandEvent& WXUNUSED(event))
534 {
535 wxString facename = GetCanvas()->GetTextFont().GetFaceName();
536 wxString newFaceName = wxGetTextFromUser(
537 wxT("Here you can edit current font face name."),
538 wxT("Input font facename"), facename,
539 this);
540 if (newFaceName.IsEmpty())
541 return; // user clicked "Cancel" - do nothing
542
543 wxFont font(GetCanvas()->GetTextFont());
544 if (font.SetFaceName(newFaceName)) // change facename only
545 {
546 wxASSERT_MSG(font.Ok(), wxT("The font should now be valid"));
547 DoChangeFont(font);
548 }
549 else
550 {
551 wxASSERT_MSG(!font.Ok(), wxT("The font should now be invalid"));
552 wxMessageBox(wxT("There is no font with such face name..."),
553 wxT("Invalid face name"), wxOK|wxICON_ERROR, this);
554 }
555 }
556
557 void MyFrame::OnSetNativeUserDesc(wxCommandEvent& WXUNUSED(event))
558 {
559 wxString fontdesc = GetCanvas()->GetTextFont().GetNativeFontInfoUserDesc();
560 wxString fontUserInfo = wxGetTextFromUser(
561 wxT("Here you can edit current font description"),
562 wxT("Input font description"), fontdesc,
563 this);
564 if (fontUserInfo.IsEmpty())
565 return; // user clicked "Cancel" - do nothing
566
567 wxFont font;
568 if (font.SetNativeFontInfoUserDesc(fontUserInfo))
569 {
570 wxASSERT_MSG(font.Ok(), wxT("The font should now be valid"));
571 DoChangeFont(font);
572 }
573 else
574 {
575 wxASSERT_MSG(!font.Ok(), wxT("The font should now be invalid"));
576 wxMessageBox(wxT("Error trying to create a font with such description..."));
577 }
578 }
579
580 void MyFrame::OnSetEncoding(wxCommandEvent& WXUNUSED(event))
581 {
582 wxFontEncoding enc = GetEncodingFromUser();
583 if ( enc == wxFONTENCODING_SYSTEM )
584 return;
585
586 wxFont font = m_canvas->GetTextFont();
587 font.SetEncoding(enc);
588 DoChangeFont(font);
589 }
590
591 wxFontEncoding MyFrame::GetEncodingFromUser()
592 {
593 wxArrayString names;
594 wxArrayInt encodings;
595
596 const size_t count = wxFontMapper::GetSupportedEncodingsCount();
597 names.reserve(count);
598 encodings.reserve(count);
599
600 for ( size_t n = 0; n < count; n++ )
601 {
602 wxFontEncoding enc = wxFontMapper::GetEncoding(n);
603 encodings.push_back(enc);
604 names.push_back(wxFontMapper::GetEncodingName(enc));
605 }
606
607 int i = wxGetSingleChoiceIndex
608 (
609 wxT("Choose the encoding"),
610 SAMPLE_TITLE,
611 names,
612 this
613 );
614
615 return i == -1 ? wxFONTENCODING_SYSTEM : (wxFontEncoding)encodings[i];
616 }
617
618 void MyFrame::DoResizeFont(int diff)
619 {
620 wxFont font = m_canvas->GetTextFont();
621
622 font.SetPointSize(font.GetPointSize() + diff);
623 DoChangeFont(font);
624 }
625
626 void MyFrame::OnBold(wxCommandEvent& event)
627 {
628 wxFont font = m_canvas->GetTextFont();
629
630 font.SetWeight(event.IsChecked() ? wxFONTWEIGHT_BOLD : wxFONTWEIGHT_NORMAL);
631 DoChangeFont(font);
632 }
633
634 void MyFrame::OnItalic(wxCommandEvent& event)
635 {
636 wxFont font = m_canvas->GetTextFont();
637
638 font.SetStyle(event.IsChecked() ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL);
639 DoChangeFont(font);
640 }
641
642 void MyFrame::OnUnderline(wxCommandEvent& event)
643 {
644 wxFont font = m_canvas->GetTextFont();
645
646 font.SetUnderlined(event.IsChecked());
647 DoChangeFont(font);
648 }
649
650 void MyFrame::OnwxPointerFont(wxCommandEvent& event)
651 {
652 wxFont font;
653
654 switch ( event.GetId() )
655 {
656 case Font_wxNORMAL_FONT:
657 font = *wxNORMAL_FONT;
658 break;
659
660 case Font_wxSMALL_FONT:
661 font = *wxSMALL_FONT;
662 break;
663
664 case Font_wxITALIC_FONT:
665 font = *wxITALIC_FONT;
666 break;
667
668 case Font_wxSWISS_FONT:
669 font = *wxSWISS_FONT;
670 break;
671
672 default:
673 wxFAIL_MSG( wxT("unknown standard font") );
674 return;
675 }
676
677 DoChangeFont(font);
678 }
679
680 void MyFrame::OnwxSystemSettingsFont(wxCommandEvent& event)
681 {
682 wxFont font;
683
684 switch ( event.GetId() )
685 {
686 case Font_wxSYS_OEM_FIXED_FONT:
687 font = wxSystemSettings::GetFont(wxSYS_OEM_FIXED_FONT);
688 break;
689
690 case Font_wxSYS_ANSI_FIXED_FONT:
691 font = wxSystemSettings::GetFont(wxSYS_ANSI_FIXED_FONT);
692 break;
693
694 case Font_wxSYS_ANSI_VAR_FONT:
695 font = wxSystemSettings::GetFont(wxSYS_ANSI_VAR_FONT);
696 break;
697
698 case Font_wxSYS_SYSTEM_FONT:
699 font = wxSystemSettings::GetFont(wxSYS_SYSTEM_FONT);
700 break;
701
702 case Font_wxSYS_DEVICE_DEFAULT_FONT:
703 font = wxSystemSettings::GetFont(wxSYS_DEVICE_DEFAULT_FONT);
704 break;
705
706 case Font_wxSYS_DEFAULT_GUI_FONT:
707 font = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
708 break;
709
710 default:
711 wxFAIL_MSG( wxT("unknown standard font") );
712 return;
713 }
714
715 DoChangeFont(font);
716 }
717
718 void MyFrame::DoChangeFont(const wxFont& font, const wxColour& col)
719 {
720 m_canvas->SetTextFont(font);
721 if ( col.Ok() )
722 m_canvas->SetColour(col);
723 m_canvas->Refresh();
724
725 m_textctrl->SetFont(font);
726 if ( col.Ok() )
727 m_textctrl->SetForegroundColour(col);
728
729 // update the state of the bold/italic/underlined menu items
730 wxMenuBar *mbar = GetMenuBar();
731 if ( mbar )
732 {
733 mbar->Check(Font_Bold, font.GetWeight() == wxFONTWEIGHT_BOLD);
734 mbar->Check(Font_Italic, font.GetStyle() == wxFONTSTYLE_ITALIC);
735 mbar->Check(Font_Underlined, font.GetUnderlined());
736 }
737 }
738
739 void MyFrame::OnSelectFont(wxCommandEvent& WXUNUSED(event))
740 {
741 wxFontData data;
742 data.SetInitialFont(m_canvas->GetTextFont());
743 data.SetColour(m_canvas->GetColour());
744
745 wxFontDialog dialog(this, data);
746 if ( dialog.ShowModal() == wxID_OK )
747 {
748 wxFontData retData = dialog.GetFontData();
749 wxFont font = retData.GetChosenFont();
750 wxColour colour = retData.GetColour();
751
752 DoChangeFont(font, colour);
753 }
754 }
755
756 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
757 {
758 // true is to force the frame to close
759 Close(true);
760 }
761
762 void MyFrame::OnTestTextValue(wxCommandEvent& WXUNUSED(event))
763 {
764 wxString value = m_textctrl->GetValue();
765 m_textctrl->SetValue(value);
766 if ( m_textctrl->GetValue() != value )
767 {
768 wxLogError(wxT("Text value changed after getting and setting it"));
769 }
770 }
771
772 void MyFrame::OnViewMsg(wxCommandEvent& WXUNUSED(event))
773 {
774 #if wxUSE_FILEDLG
775 // first, choose the file
776 static wxString s_dir, s_file;
777 wxFileDialog dialog(this, wxT("Open an email message file"),
778 s_dir, s_file);
779 if ( dialog.ShowModal() != wxID_OK )
780 return;
781
782 // save for the next time
783 s_dir = dialog.GetDirectory();
784 s_file = dialog.GetFilename();
785
786 wxString filename = dialog.GetPath();
787
788 // load it and search for Content-Type header
789 wxTextFile file(filename);
790 if ( !file.Open() )
791 return;
792
793 wxString charset;
794
795 static const wxChar *prefix = wxT("Content-Type: text/plain; charset=");
796 const size_t len = wxStrlen(prefix);
797
798 size_t n, count = file.GetLineCount();
799 for ( n = 0; n < count; n++ )
800 {
801 wxString line = file[n];
802
803 if ( !line )
804 {
805 // if it is an email message, headers are over, no need to parse
806 // all the file
807 break;
808 }
809
810 if ( line.Left(len) == prefix )
811 {
812 // found!
813 const wxChar *pc = line.c_str() + len;
814 if ( *pc == wxT('"') )
815 pc++;
816
817 while ( *pc && *pc != wxT('"') )
818 {
819 charset += *pc++;
820 }
821
822 break;
823 }
824 }
825
826 if ( !charset )
827 {
828 wxLogError(wxT("The file '%s' doesn't contain charset information."),
829 filename.c_str());
830
831 return;
832 }
833
834 // ok, now get the corresponding encoding
835 wxFontEncoding fontenc = wxFontMapper::Get()->CharsetToEncoding(charset);
836 if ( fontenc == wxFONTENCODING_SYSTEM )
837 {
838 wxLogError(wxT("Charset '%s' is unsupported."), charset.c_str());
839 return;
840 }
841
842 m_textctrl->LoadFile(filename);
843
844 if ( fontenc == wxFONTENCODING_UTF8 ||
845 !wxFontMapper::Get()->IsEncodingAvailable(fontenc) )
846 {
847 // try to find some similar encoding:
848 wxFontEncoding encAlt;
849 if ( wxFontMapper::Get()->GetAltForEncoding(fontenc, &encAlt) )
850 {
851 wxEncodingConverter conv;
852
853 if (conv.Init(fontenc, encAlt))
854 {
855 fontenc = encAlt;
856 m_textctrl -> SetValue(conv.Convert(m_textctrl -> GetValue()));
857 }
858 else
859 {
860 wxLogWarning(wxT("Cannot convert from '%s' to '%s'."),
861 wxFontMapper::GetEncodingDescription(fontenc).c_str(),
862 wxFontMapper::GetEncodingDescription(encAlt).c_str());
863 }
864 }
865 else
866 wxLogWarning(wxT("No fonts for encoding '%s' on this system."),
867 wxFontMapper::GetEncodingDescription(fontenc).c_str());
868 }
869
870 // and now create the correct font
871 if ( !DoEnumerateFamilies(false, fontenc, true /* silent */) )
872 {
873 wxFont font(wxNORMAL_FONT->GetPointSize(),
874 wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
875 wxFONTWEIGHT_NORMAL, false /* !underlined */,
876 wxEmptyString /* facename */, fontenc);
877 if ( font.Ok() )
878 {
879 DoChangeFont(font);
880 }
881 else
882 {
883 wxLogWarning(wxT("No fonts for encoding '%s' on this system."),
884 wxFontMapper::GetEncodingDescription(fontenc).c_str());
885 }
886 }
887 #endif // wxUSE_FILEDLG
888 }
889
890 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
891 {
892 wxMessageBox(wxT("wxWidgets font sample\n")
893 wxT("(c) 1999-2006 Vadim Zeitlin"),
894 wxString(wxT("About ")) + SAMPLE_TITLE,
895 wxOK | wxICON_INFORMATION, this);
896 }
897
898 // ----------------------------------------------------------------------------
899 // MyCanvas
900 // ----------------------------------------------------------------------------
901
902 BEGIN_EVENT_TABLE(MyCanvas, wxWindow)
903 EVT_PAINT(MyCanvas::OnPaint)
904 END_EVENT_TABLE()
905
906 MyCanvas::MyCanvas( wxWindow *parent )
907 : wxWindow( parent, wxID_ANY ),
908 m_colour(*wxRED), m_font(*wxNORMAL_FONT)
909 {
910 }
911
912 void MyCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) )
913 {
914 wxPaintDC dc(this);
915 PrepareDC(dc);
916
917 // set background
918 dc.SetBackground(wxBrush(wxT("white"), wxSOLID));
919 dc.Clear();
920
921 // one text line height
922 wxCoord hLine = dc.GetCharHeight();
923
924 // the current text origin
925 wxCoord x = 5,
926 y = 5;
927
928 // output the font name/info
929 wxString fontInfo;
930 fontInfo.Printf(wxT("Font size is %d points, family: %s, encoding: %s"),
931 m_font.GetPointSize(),
932 m_font.GetFamilyString().c_str(),
933 wxFontMapper::
934 GetEncodingDescription(m_font.GetEncoding()).c_str());
935
936 dc.DrawText(fontInfo, x, y);
937 y += hLine;
938
939 fontInfo.Printf(wxT("Style: %s, weight: %s, fixed width: %s"),
940 m_font.GetStyleString().c_str(),
941 m_font.GetWeightString().c_str(),
942 m_font.IsFixedWidth() ? _T("yes") : _T("no"));
943
944 dc.DrawText(fontInfo, x, y);
945 y += hLine;
946
947 if ( m_font.Ok() )
948 {
949 const wxNativeFontInfo *info = m_font.GetNativeFontInfo();
950 if ( info )
951 {
952 wxString fontDesc = m_font.GetNativeFontInfoUserDesc();
953 fontInfo.Printf(wxT("Native font info: %s"), fontDesc.c_str());
954
955 dc.DrawText(fontInfo, x, y);
956 y += hLine;
957 }
958 }
959
960 y += hLine;
961
962 // prepare to draw the font
963 dc.SetFont(m_font);
964 dc.SetTextForeground(m_colour);
965
966 // the size of one cell (Normally biggest char + small margin)
967 wxCoord maxCharWidth, maxCharHeight;
968 dc.GetTextExtent(wxT("W"), &maxCharWidth, &maxCharHeight);
969 int w = maxCharWidth + 5,
970 h = maxCharHeight + 4;
971
972
973 // print all font symbols from 32 to 256 in 7 rows of 32 chars each
974 for ( int i = 0; i < 7; i++ )
975 {
976 for ( int j = 0; j < 32; j++ )
977 {
978 wxChar c = (wxChar)(32 * (i + 1) + j);
979
980 wxCoord charWidth, charHeight;
981 dc.GetTextExtent(c, &charWidth, &charHeight);
982 dc.DrawText
983 (
984 c,
985 x + w*j + (maxCharWidth - charWidth) / 2 + 1,
986 y + h*i + (maxCharHeight - charHeight) / 2
987 );
988 }
989 }
990
991 // draw the lines between them
992 dc.SetPen(wxPen(wxColour(_T("blue")), 1, wxSOLID));
993 int l;
994
995 // horizontal
996 for ( l = 0; l < 8; l++ )
997 {
998 int yl = y + h*l - 2;
999 dc.DrawLine(x - 2, yl, x + 32*w - 1, yl);
1000 }
1001
1002 // and vertical
1003 for ( l = 0; l < 33; l++ )
1004 {
1005 int xl = x + w*l - 2;
1006 dc.DrawLine(xl, y - 2, xl, y + 7*h - 1);
1007 }
1008 }