added demo of wxEncodingConverter
[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< wxWindows 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/textfile.h>
33
34 // ----------------------------------------------------------------------------
35 // private classes
36 // ----------------------------------------------------------------------------
37
38 // Define a new application type, each program should derive a class from wxApp
39 class MyApp : public wxApp
40 {
41 public:
42 // override base class virtuals
43 // ----------------------------
44
45 // this one is called on application startup and is a good place for the app
46 // initialization (doing it here and not in the ctor allows to have an error
47 // return: if OnInit() returns false, the application terminates)
48 virtual bool OnInit();
49 };
50
51 // MyCanvas is a canvas on which we show the font sample
52 class MyCanvas: public wxWindow
53 {
54 public:
55 MyCanvas( wxWindow *parent );
56 ~MyCanvas();
57
58 // accessors for the frame
59 const wxFont& GetTextFont() const { return m_font; }
60 const wxColour& GetColour() const { return m_colour; }
61 void SetTextFont(const wxFont& font) { m_font = font; }
62 void SetColour(const wxColour& colour) { m_colour = colour; }
63
64 // event handlers
65 void OnPaint( wxPaintEvent &event );
66
67 private:
68 wxColour m_colour;
69 wxFont m_font;
70
71 DECLARE_EVENT_TABLE()
72 };
73
74 // Define a new frame type: this is going to be our main frame
75 class MyFrame : public wxFrame
76 {
77 public:
78 // ctor(s)
79 MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size);
80
81 // accessors
82 MyCanvas *GetCanvas() const { return m_canvas; }
83
84 // event handlers (these functions should _not_ be virtual)
85 void OnQuit(wxCommandEvent& event);
86 void OnAbout(wxCommandEvent& event);
87 void OnViewMsg(wxCommandEvent& event);
88 void OnSelectFont(wxCommandEvent& event);
89 void OnEnumerateFamiliesForEncoding(wxCommandEvent& event);
90 void OnEnumerateFamilies(wxCommandEvent& WXUNUSED(event))
91 { DoEnumerateFamilies(FALSE); }
92 void OnEnumerateFixedFamilies(wxCommandEvent& WXUNUSED(event))
93 { DoEnumerateFamilies(TRUE); }
94 void OnEnumerateEncodings(wxCommandEvent& event);
95
96 void OnSize(wxSizeEvent& event);
97
98 protected:
99 bool DoEnumerateFamilies(bool fixedWidthOnly,
100 wxFontEncoding encoding = wxFONTENCODING_SYSTEM,
101 bool silent = FALSE);
102
103 void DoChangeFont(const wxFont& font, const wxColour& col = wxNullColour);
104
105 void Resize(const wxSize& size, const wxFont& font = wxNullFont);
106
107 wxTextCtrl *m_textctrl;
108 MyCanvas *m_canvas;
109
110 private:
111 // any class wishing to process wxWindows events must use this macro
112 DECLARE_EVENT_TABLE()
113 };
114
115 // ----------------------------------------------------------------------------
116 // constants
117 // ----------------------------------------------------------------------------
118
119 // IDs for the controls and the menu commands
120 enum
121 {
122 // menu items
123 Font_Quit = 1,
124 Font_About,
125 Font_ViewMsg,
126 Font_Choose = 100,
127 Font_EnumFamiliesForEncoding,
128 Font_EnumFamilies,
129 Font_EnumFixedFamilies,
130 Font_EnumEncodings,
131 Font_Max
132 };
133
134 // ----------------------------------------------------------------------------
135 // event tables and other macros for wxWindows
136 // ----------------------------------------------------------------------------
137
138 // the event tables connect the wxWindows events with the functions (event
139 // handlers) which process them. It can be also done at run-time, but for the
140 // simple menu events like this the static method is much simpler.
141 BEGIN_EVENT_TABLE(MyFrame, wxFrame)
142 EVT_MENU(Font_Quit, MyFrame::OnQuit)
143 EVT_MENU(Font_About, MyFrame::OnAbout)
144 EVT_MENU(Font_ViewMsg, MyFrame::OnViewMsg)
145 EVT_MENU(Font_Choose, MyFrame::OnSelectFont)
146 EVT_MENU(Font_EnumFamiliesForEncoding, MyFrame::OnEnumerateFamiliesForEncoding)
147 EVT_MENU(Font_EnumFamilies, MyFrame::OnEnumerateFamilies)
148 EVT_MENU(Font_EnumFixedFamilies, MyFrame::OnEnumerateFixedFamilies)
149 EVT_MENU(Font_EnumEncodings, MyFrame::OnEnumerateEncodings)
150
151 EVT_SIZE(MyFrame::OnSize)
152 END_EVENT_TABLE()
153
154 // Create a new application object: this macro will allow wxWindows to create
155 // the application object during program execution (it's better than using a
156 // static object for many reasons) and also declares the accessor function
157 // wxGetApp() which will return the reference of the right type (i.e. MyApp and
158 // not wxApp)
159 IMPLEMENT_APP(MyApp)
160
161 // ============================================================================
162 // implementation
163 // ============================================================================
164
165 // ----------------------------------------------------------------------------
166 // the application class
167 // ----------------------------------------------------------------------------
168
169 // `Main program' equivalent: the program execution "starts" here
170 bool MyApp::OnInit()
171 {
172 // Create the main application window
173 MyFrame *frame = new MyFrame("Font wxWindows demo",
174 wxPoint(50, 50), wxSize(450, 340));
175
176 // Show it and tell the application that it's our main window
177 frame->Show(TRUE);
178 SetTopWindow(frame);
179
180 // success: wxApp::OnRun() will be called which will enter the main message
181 // loop and the application will run. If we returned FALSE here, the
182 // application would exit immediately.
183 return TRUE;
184 }
185
186 // ----------------------------------------------------------------------------
187 // main frame
188 // ----------------------------------------------------------------------------
189
190 // frame constructor
191 MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
192 : wxFrame((wxFrame *)NULL, -1, title, pos, size), m_textctrl(NULL)
193 {
194 // create a menu bar
195 wxMenu *menuFile = new wxMenu;
196
197 menuFile->Append(Font_ViewMsg, "&View...\tCtrl-V",
198 "View an email message file");
199 menuFile->AppendSeparator();
200 menuFile->Append(Font_About, "&About...\tCtrl-A", "Show about dialog");
201 menuFile->AppendSeparator();
202 menuFile->Append(Font_Quit, "E&xit\tAlt-X", "Quit this program");
203
204 wxMenu *menuFont = new wxMenu;
205 menuFont->Append(Font_Choose, "&Select font...\tCtrl-S",
206 "Select a standard font");
207 menuFont->AppendSeparator();
208 menuFont->Append(Font_EnumFamilies, "Enumerate font &families\tCtrl-F");
209 menuFont->Append(Font_EnumFixedFamilies,
210 "Enumerate f&ixed font families\tCtrl-I");
211 menuFont->Append(Font_EnumEncodings,
212 "Enumerate &encodings\tCtrl-E");
213 menuFont->Append(Font_EnumFamiliesForEncoding,
214 "Find font for en&coding...\tCtrl-C",
215 "Find font families for given encoding");
216
217 // now append the freshly created menu to the menu bar...
218 wxMenuBar *menuBar = new wxMenuBar;
219 menuBar->Append(menuFile, "&File");
220 menuBar->Append(menuFont, "F&ont");
221
222 // ... and attach this menu bar to the frame
223 SetMenuBar(menuBar);
224
225 m_textctrl = new wxTextCtrl(this, -1,
226 "Paste text here to see how it looks\n"
227 "like in the given font",
228 wxDefaultPosition, wxDefaultSize,
229 wxTE_MULTILINE);
230
231 m_canvas = new MyCanvas(this);
232
233 // create a status bar just for fun (by default with 1 pane only)
234 CreateStatusBar();
235 SetStatusText("Welcome to wxWindows font demo!");
236 }
237
238
239 // event handlers
240 void MyFrame::OnEnumerateEncodings(wxCommandEvent& WXUNUSED(event))
241 {
242 class MyEncodingEnumerator : public wxFontEnumerator
243 {
244 public:
245 MyEncodingEnumerator() { m_n = 0; }
246
247 const wxString& GetText() const { return m_text; }
248
249 protected:
250 virtual bool OnFontEncoding(const wxString& facename,
251 const wxString& encoding)
252 {
253 wxString text;
254 text.Printf("Encoding %d: %s (available in facename '%s')\n",
255 ++m_n, encoding.c_str(), facename.c_str());
256 m_text += text;
257
258 return TRUE;
259 }
260
261 private:
262 size_t m_n;
263
264 wxString m_text;
265 } fontEnumerator;
266
267 fontEnumerator.EnumerateEncodings();
268
269 wxLogMessage("Enumerating all available encodings:\n%s",
270 fontEnumerator.GetText().c_str());
271 }
272
273 bool MyFrame::DoEnumerateFamilies(bool fixedWidthOnly,
274 wxFontEncoding encoding,
275 bool silent)
276 {
277 class MyFontEnumerator : public wxFontEnumerator
278 {
279 public:
280 bool GotAny() const { return !m_facenames.IsEmpty(); }
281
282 const wxArrayString& GetFacenames() const { return m_facenames; }
283
284 protected:
285 virtual bool OnFacename(const wxString& facename)
286 {
287 m_facenames.Add(facename);
288
289 return TRUE;
290 }
291
292 private:
293 wxArrayString m_facenames;
294 } fontEnumerator;
295
296 fontEnumerator.EnumerateFacenames(encoding, fixedWidthOnly);
297
298 if ( fontEnumerator.GotAny() )
299 {
300 int nFacenames = fontEnumerator.GetFacenames().GetCount();
301 if ( !silent )
302 {
303 wxLogStatus(this, "Found %d %sfonts",
304 nFacenames, fixedWidthOnly ? "fixed width " : "");
305 }
306
307 wxString facename;
308 if ( silent )
309 {
310 // choose the first
311 facename = fontEnumerator.GetFacenames().Item(0);
312 }
313 else
314 {
315 // let the user choose
316 wxString *facenames = new wxString[nFacenames];
317 int n;
318 for ( n = 0; n < nFacenames; n++ )
319 facenames[n] = fontEnumerator.GetFacenames().Item(n);
320
321 n = wxGetSingleChoiceIndex("Choose a facename", "Font demo",
322 nFacenames, facenames, this);
323
324 if ( n != -1 )
325 facename = facenames[n];
326
327 delete [] facenames;
328 }
329
330 if ( !facename.IsEmpty() )
331 {
332 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
333 wxFONTWEIGHT_NORMAL, FALSE, facename, encoding);
334
335 DoChangeFont(font);
336 }
337
338 return TRUE;
339 }
340 else if ( !silent )
341 {
342 wxLogWarning("No such fonts found.");
343 }
344
345 return FALSE;
346 }
347
348 void MyFrame::OnEnumerateFamiliesForEncoding(wxCommandEvent& WXUNUSED(event))
349 {
350 static wxFontEncoding encodings[] =
351 {
352 wxFONTENCODING_ISO8859_1,
353 wxFONTENCODING_ISO8859_2,
354 wxFONTENCODING_ISO8859_5,
355 wxFONTENCODING_ISO8859_7,
356 wxFONTENCODING_ISO8859_15,
357 wxFONTENCODING_KOI8,
358 wxFONTENCODING_CP1250,
359 wxFONTENCODING_CP1251,
360 wxFONTENCODING_CP1252,
361 };
362
363 static const char *encodingNames[] =
364 {
365 "West European (Latin 1)",
366 "Central European (Latin 2)",
367 "Cyrillic (Latin 5)",
368 "Greek (Latin 7)",
369 "West European new (Latin 0)",
370 "KOI8-R",
371 "Windows Latin 2",
372 "Windows Cyrillic",
373 "Windows Latin 1",
374 };
375
376 int n = wxGetSingleChoiceIndex("Choose an encoding", "Font demo",
377 WXSIZEOF(encodingNames),
378 (char **)encodingNames,
379 this);
380
381 if ( n != -1 )
382 {
383 DoEnumerateFamilies(FALSE, encodings[n]);
384 }
385 }
386
387 void MyFrame::DoChangeFont(const wxFont& font, const wxColour& col)
388 {
389 Resize(GetSize(), font);
390
391 m_canvas->SetTextFont(font);
392 if ( col.Ok() )
393 m_canvas->SetColour(col);
394 m_canvas->Refresh();
395
396 m_textctrl->SetFont(font);
397 if ( col.Ok() )
398 m_textctrl->SetForegroundColour(col);
399 }
400
401 void MyFrame::OnSelectFont(wxCommandEvent& WXUNUSED(event))
402 {
403 wxFontData data;
404 data.SetInitialFont(m_canvas->GetTextFont());
405 data.SetColour(m_canvas->GetColour());
406
407 wxFontDialog dialog(this, &data);
408 if ( dialog.ShowModal() == wxID_OK )
409 {
410 wxFontData retData = dialog.GetFontData();
411 wxFont font = retData.GetChosenFont();
412 wxColour colour = retData.GetColour();
413
414 DoChangeFont(font, colour);
415 }
416 }
417
418 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
419 {
420 // TRUE is to force the frame to close
421 Close(TRUE);
422 }
423
424 void MyFrame::OnViewMsg(wxCommandEvent& WXUNUSED(event))
425 {
426 // first, choose the file
427 static wxString s_dir, s_file;
428 wxFileDialog dialog(this, "Open an email message file",
429 s_dir, s_file);
430 if ( dialog.ShowModal() != wxID_OK )
431 return;
432
433 // save for the next time
434 s_dir = dialog.GetDirectory();
435 s_file = dialog.GetFilename();
436
437 wxString filename = dialog.GetPath();
438
439 // load it and search for Content-Type header
440 wxTextFile file(filename);
441 if ( !file.Open() )
442 return;
443
444 wxString charset;
445
446 static const char *prefix = "Content-Type: text/plain; charset=";
447 const size_t len = strlen(prefix);
448
449 size_t n, count = file.GetLineCount();
450 for ( n = 0; n < count; n++ )
451 {
452 wxString line = file[n];
453
454 if ( !line )
455 {
456 // if it is an email message, headers are over, no need to parse
457 // all the file
458 break;
459 }
460
461 if ( line.Left(len) == prefix )
462 {
463 // found!
464 const char *pc = line.c_str() + len;
465 if ( *pc == '"' )
466 pc++;
467
468 while ( *pc && *pc != '"' )
469 {
470 charset += *pc++;
471 }
472
473 break;
474 }
475 }
476
477 if ( !charset )
478 {
479 wxLogError("The file '%s' doesn't contain charset information.",
480 filename.c_str());
481
482 return;
483 }
484
485 // ok, now get the corresponding encoding
486 wxFontEncoding fontenc = wxTheFontMapper->CharsetToEncoding(charset);
487 if ( fontenc == wxFONTENCODING_SYSTEM )
488 {
489 wxLogError("Charset '%s' is unsupported.", charset.c_str());
490 return;
491 }
492
493 m_textctrl->LoadFile(filename);
494
495 if (!wxTheFontMapper->IsEncodingAvailable(fontenc))
496 {
497 // try to find some similar encoding:
498 wxFontEncoding enc2;
499 if (wxTheFontMapper->GetAltForEncoding(fontenc, &enc2,
500 wxEmptyString /*facename*/, FALSE /*interactive*/))
501 {
502 wxEncodingConverter conv;
503
504 if (conv.Init(fontenc, enc2))
505 {
506 fontenc = enc2;
507 m_textctrl -> SetValue(conv.Convert(m_textctrl -> GetValue()));
508 }
509 else
510 wxLogWarning("Cannot convert from '%s' to '%s'.",
511 wxFontMapper::GetEncodingDescription(fontenc).c_str(),
512 wxFontMapper::GetEncodingDescription(enc2).c_str());
513 }
514 else
515 wxLogWarning("No fonts for encoding '%s' on this system.",
516 wxFontMapper::GetEncodingDescription(fontenc).c_str());
517 }
518
519 // and now create the correct font
520 if ( !DoEnumerateFamilies(FALSE, fontenc, TRUE /* silent */) )
521 {
522 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
523 wxFONTWEIGHT_NORMAL, FALSE /* !underlined */,
524 wxEmptyString /* facename */, fontenc);
525 if ( font.Ok() )
526 {
527 DoChangeFont(font);
528 }
529 else
530 {
531 wxLogWarning("No fonts for encoding '%s' on this system.",
532 wxFontMapper::GetEncodingDescription(fontenc).c_str());
533 }
534 }
535 }
536
537 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
538 {
539 wxMessageBox("wxWindows font demo\n"
540 "(c) 1999 Vadim Zeitlin",
541 "About Font",
542 wxOK | wxICON_INFORMATION, this);
543 }
544
545 void MyFrame::OnSize(wxSizeEvent& event)
546 {
547 wxSize size = event.GetSize();
548
549 Resize(size);
550
551 event.Skip();
552 }
553
554 void MyFrame::Resize(const wxSize& size, const wxFont& font)
555 {
556 if ( !m_textctrl )
557 return;
558
559 wxCoord h;
560 if ( font.Ok() )
561 {
562 wxClientDC dc(this);
563 dc.SetFont(font);
564
565 h = 10*(dc.GetCharHeight() + 1);
566 }
567 else
568 {
569 h = m_textctrl->GetSize().y;
570 }
571
572 m_textctrl->SetSize(0, 0, size.x, h);
573 m_canvas->SetSize(0, h, size.x, size.y - h);
574 }
575
576 // ----------------------------------------------------------------------------
577 // MyCanvas
578 // ----------------------------------------------------------------------------
579
580 BEGIN_EVENT_TABLE(MyCanvas, wxWindow)
581 EVT_PAINT(MyCanvas::OnPaint)
582 END_EVENT_TABLE()
583
584 MyCanvas::MyCanvas( wxWindow *parent )
585 : wxWindow( parent, -1 ),
586 m_colour(*wxRED), m_font(*wxNORMAL_FONT)
587 {
588 }
589
590 MyCanvas::~MyCanvas()
591 {
592 }
593
594 void MyCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) )
595 {
596 wxPaintDC dc(this);
597 PrepareDC(dc);
598
599 // set background
600 dc.SetBackground(wxBrush("white", wxSOLID));
601 dc.Clear();
602
603 // output the font name/info
604 wxString fontInfo;
605 fontInfo.Printf("Font family is '%s', style '%s', weight '%s'",
606 m_font.GetFamilyString().c_str(),
607 m_font.GetStyleString().c_str(),
608 m_font.GetWeightString().c_str());
609
610 dc.DrawText(fontInfo, 5, 5);
611
612 // prepare to draw the font
613 dc.SetFont(m_font);
614 dc.SetTextForeground(m_colour);
615
616 // the size of one cell (char + small margin)
617 int w = dc.GetCharWidth() + 5,
618 h = dc.GetCharHeight() + 4;
619
620 // the origin for our table
621 int x = 5,
622 y = 2*h;
623
624 // print all font symbols from 32 to 256 in 7 rows of 32 chars each
625 for ( int i = 1; i < 8; i++ )
626 {
627 for ( int j = 0; j < 32; j++ )
628 {
629 dc.DrawText(char(32*i + j), x + w*j, y + h*i);
630 }
631 }
632
633 // draw the lines between them
634 dc.SetPen(wxPen(wxColour("blue"), 1, wxSOLID));
635 int l;
636
637 // horizontal
638 y += h;
639 for ( l = 0; l < 8; l++ )
640 {
641 int yl = y + h*l - 2;
642 dc.DrawLine(x - 2, yl, x + 32*w - 2, yl);
643 }
644
645 // and vertical
646 for ( l = 0; l < 33; l++ )
647 {
648 int xl = x + w*l - 2;
649 dc.DrawLine(xl, y, xl, y + 7*h - 2);
650 }
651 }