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