small tests added here and there
[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
240 class MyEncodingEnumerator : public wxFontEnumerator
241 {
242 public:
243 MyEncodingEnumerator()
244 { m_n = 0; }
245
246 const wxString& GetText() const
247 { 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 return TRUE;
258 }
259
260 private:
261 size_t m_n;
262 wxString m_text;
263 };
264
265 void MyFrame::OnEnumerateEncodings(wxCommandEvent& WXUNUSED(event))
266 {
267 MyEncodingEnumerator fontEnumerator;
268
269 fontEnumerator.EnumerateEncodings();
270
271 wxLogMessage("Enumerating all available encodings:\n%s",
272 fontEnumerator.GetText().c_str());
273 }
274
275 // -------------------------------------------------------------
276
277 class MyFontEnumerator : public wxFontEnumerator
278 {
279 public:
280 bool GotAny() const
281 { return !m_facenames.IsEmpty(); }
282
283 const wxArrayString& GetFacenames() const
284 { return m_facenames; }
285
286 protected:
287 virtual bool OnFacename(const wxString& facename)
288 {
289 m_facenames.Add(facename);
290 return TRUE;
291 }
292
293 private:
294 wxArrayString m_facenames;
295 } fontEnumerator;
296
297 bool MyFrame::DoEnumerateFamilies(bool fixedWidthOnly,
298 wxFontEncoding encoding,
299 bool silent)
300 {
301 MyFontEnumerator fontEnumerator;
302
303 fontEnumerator.EnumerateFacenames(encoding, fixedWidthOnly);
304
305 if ( fontEnumerator.GotAny() )
306 {
307 int nFacenames = fontEnumerator.GetFacenames().GetCount();
308 if ( !silent )
309 {
310 wxLogStatus(this, "Found %d %sfonts",
311 nFacenames, fixedWidthOnly ? "fixed width " : "");
312 }
313
314 wxString facename;
315 if ( silent )
316 {
317 // choose the first
318 facename = fontEnumerator.GetFacenames().Item(0);
319 }
320 else
321 {
322 // let the user choose
323 wxString *facenames = new wxString[nFacenames];
324 int n;
325 for ( n = 0; n < nFacenames; n++ )
326 facenames[n] = fontEnumerator.GetFacenames().Item(n);
327
328 n = wxGetSingleChoiceIndex("Choose a facename", "Font demo",
329 nFacenames, facenames, this);
330
331 if ( n != -1 )
332 facename = facenames[n];
333
334 delete [] facenames;
335 }
336
337 if ( !facename.IsEmpty() )
338 {
339 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
340 wxFONTWEIGHT_NORMAL, FALSE, facename, encoding);
341
342 DoChangeFont(font);
343 }
344
345 return TRUE;
346 }
347 else if ( !silent )
348 {
349 wxLogWarning("No such fonts found.");
350 }
351
352 return FALSE;
353 }
354
355 void MyFrame::OnEnumerateFamiliesForEncoding(wxCommandEvent& WXUNUSED(event))
356 {
357 static wxFontEncoding encodings[] =
358 {
359 wxFONTENCODING_ISO8859_1,
360 wxFONTENCODING_ISO8859_2,
361 wxFONTENCODING_ISO8859_5,
362 wxFONTENCODING_ISO8859_7,
363 wxFONTENCODING_ISO8859_15,
364 wxFONTENCODING_KOI8,
365 wxFONTENCODING_CP1250,
366 wxFONTENCODING_CP1251,
367 wxFONTENCODING_CP1252,
368 };
369
370 static const char *encodingNames[] =
371 {
372 "West European (Latin 1)",
373 "Central European (Latin 2)",
374 "Cyrillic (Latin 5)",
375 "Greek (Latin 7)",
376 "West European new (Latin 0)",
377 "KOI8-R",
378 "Windows Latin 2",
379 "Windows Cyrillic",
380 "Windows Latin 1",
381 };
382
383 int n = wxGetSingleChoiceIndex("Choose an encoding", "Font demo",
384 WXSIZEOF(encodingNames),
385 (char **)encodingNames,
386 this);
387
388 if ( n != -1 )
389 {
390 DoEnumerateFamilies(FALSE, encodings[n]);
391 }
392 }
393
394 void MyFrame::DoChangeFont(const wxFont& font, const wxColour& col)
395 {
396 Resize(GetSize(), font);
397
398 m_canvas->SetTextFont(font);
399 if ( col.Ok() )
400 m_canvas->SetColour(col);
401 m_canvas->Refresh();
402
403 m_textctrl->SetFont(font);
404 if ( col.Ok() )
405 m_textctrl->SetForegroundColour(col);
406 }
407
408 void MyFrame::OnSelectFont(wxCommandEvent& WXUNUSED(event))
409 {
410 wxFontData data;
411 data.SetInitialFont(m_canvas->GetTextFont());
412 data.SetColour(m_canvas->GetColour());
413
414 wxFontDialog dialog(this, &data);
415 if ( dialog.ShowModal() == wxID_OK )
416 {
417 wxFontData retData = dialog.GetFontData();
418 wxFont font = retData.GetChosenFont();
419 wxColour colour = retData.GetColour();
420
421 DoChangeFont(font, colour);
422 }
423 }
424
425 void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
426 {
427 // TRUE is to force the frame to close
428 Close(TRUE);
429 }
430
431 void MyFrame::OnViewMsg(wxCommandEvent& WXUNUSED(event))
432 {
433 // first, choose the file
434 static wxString s_dir, s_file;
435 wxFileDialog dialog(this, "Open an email message file",
436 s_dir, s_file);
437 if ( dialog.ShowModal() != wxID_OK )
438 return;
439
440 // save for the next time
441 s_dir = dialog.GetDirectory();
442 s_file = dialog.GetFilename();
443
444 wxString filename = dialog.GetPath();
445
446 // load it and search for Content-Type header
447 wxTextFile file(filename);
448 if ( !file.Open() )
449 return;
450
451 wxString charset;
452
453 static const char *prefix = "Content-Type: text/plain; charset=";
454 const size_t len = strlen(prefix);
455
456 size_t n, count = file.GetLineCount();
457 for ( n = 0; n < count; n++ )
458 {
459 wxString line = file[n];
460
461 if ( !line )
462 {
463 // if it is an email message, headers are over, no need to parse
464 // all the file
465 break;
466 }
467
468 if ( line.Left(len) == prefix )
469 {
470 // found!
471 const char *pc = line.c_str() + len;
472 if ( *pc == '"' )
473 pc++;
474
475 while ( *pc && *pc != '"' )
476 {
477 charset += *pc++;
478 }
479
480 break;
481 }
482 }
483
484 if ( !charset )
485 {
486 wxLogError("The file '%s' doesn't contain charset information.",
487 filename.c_str());
488
489 return;
490 }
491
492 // ok, now get the corresponding encoding
493 wxFontEncoding fontenc = wxTheFontMapper->CharsetToEncoding(charset);
494 if ( fontenc == wxFONTENCODING_SYSTEM )
495 {
496 wxLogError("Charset '%s' is unsupported.", charset.c_str());
497 return;
498 }
499
500 m_textctrl->LoadFile(filename);
501
502 if (!wxTheFontMapper->IsEncodingAvailable(fontenc))
503 {
504 // try to find some similar encoding:
505 wxFontEncoding encAlt;
506 if ( wxTheFontMapper->GetAltForEncoding(fontenc, &encAlt) )
507 {
508 wxEncodingConverter conv;
509
510 if (conv.Init(fontenc, encAlt))
511 {
512 fontenc = encAlt;
513 m_textctrl -> SetValue(conv.Convert(m_textctrl -> GetValue()));
514 }
515 else
516 {
517 wxLogWarning("Cannot convert from '%s' to '%s'.",
518 wxFontMapper::GetEncodingDescription(fontenc).c_str(),
519 wxFontMapper::GetEncodingDescription(encAlt).c_str());
520 }
521 }
522 else
523 wxLogWarning("No fonts for encoding '%s' on this system.",
524 wxFontMapper::GetEncodingDescription(fontenc).c_str());
525 }
526
527 // and now create the correct font
528 if ( !DoEnumerateFamilies(FALSE, fontenc, TRUE /* silent */) )
529 {
530 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
531 wxFONTWEIGHT_NORMAL, FALSE /* !underlined */,
532 wxEmptyString /* facename */, fontenc);
533 if ( font.Ok() )
534 {
535 DoChangeFont(font);
536 }
537 else
538 {
539 wxLogWarning("No fonts for encoding '%s' on this system.",
540 wxFontMapper::GetEncodingDescription(fontenc).c_str());
541 }
542 }
543 }
544
545 void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
546 {
547 wxMessageBox("wxWindows font demo\n"
548 "(c) 1999 Vadim Zeitlin",
549 "About Font",
550 wxOK | wxICON_INFORMATION, this);
551 }
552
553 void MyFrame::OnSize(wxSizeEvent& event)
554 {
555 wxSize size = event.GetSize();
556
557 Resize(size);
558
559 event.Skip();
560 }
561
562 void MyFrame::Resize(const wxSize& size, const wxFont& font)
563 {
564 if ( !m_textctrl )
565 return;
566
567 wxCoord h;
568 if ( font.Ok() )
569 {
570 wxClientDC dc(this);
571 dc.SetFont(font);
572
573 h = 10*(dc.GetCharHeight() + 1);
574 }
575 else
576 {
577 h = m_textctrl->GetSize().y;
578 }
579
580 m_textctrl->SetSize(0, 0, size.x, h);
581 m_canvas->SetSize(0, h, size.x, size.y - h);
582 }
583
584 // ----------------------------------------------------------------------------
585 // MyCanvas
586 // ----------------------------------------------------------------------------
587
588 BEGIN_EVENT_TABLE(MyCanvas, wxWindow)
589 EVT_PAINT(MyCanvas::OnPaint)
590 END_EVENT_TABLE()
591
592 MyCanvas::MyCanvas( wxWindow *parent )
593 : wxWindow( parent, -1 ),
594 m_colour(*wxRED), m_font(*wxNORMAL_FONT)
595 {
596 }
597
598 MyCanvas::~MyCanvas()
599 {
600 }
601
602 void MyCanvas::OnPaint( wxPaintEvent &WXUNUSED(event) )
603 {
604 wxPaintDC dc(this);
605 PrepareDC(dc);
606
607 // set background
608 dc.SetBackground(wxBrush("white", wxSOLID));
609 dc.Clear();
610
611 // output the font name/info
612 wxString fontInfo;
613 fontInfo.Printf("Font family is '%s', style '%s', weight '%s'",
614 m_font.GetFamilyString().c_str(),
615 m_font.GetStyleString().c_str(),
616 m_font.GetWeightString().c_str());
617
618 dc.DrawText(fontInfo, 5, 5);
619
620 // prepare to draw the font
621 dc.SetFont(m_font);
622 dc.SetTextForeground(m_colour);
623
624 // the size of one cell (char + small margin)
625 int w = dc.GetCharWidth() + 5,
626 h = dc.GetCharHeight() + 4;
627
628 // the origin for our table
629 int x = 5,
630 y = 2*h;
631
632 // print all font symbols from 32 to 256 in 7 rows of 32 chars each
633 for ( int i = 1; i < 8; i++ )
634 {
635 for ( int j = 0; j < 32; j++ )
636 {
637 dc.DrawText(char(32*i + j), x + w*j, y + h*i);
638 }
639 }
640
641 // draw the lines between them
642 dc.SetPen(wxPen(wxColour("blue"), 1, wxSOLID));
643 int l;
644
645 // horizontal
646 y += h;
647 for ( l = 0; l < 8; l++ )
648 {
649 int yl = y + h*l - 2;
650 dc.DrawLine(x - 2, yl, x + 32*w - 2, yl);
651 }
652
653 // and vertical
654 for ( l = 0; l < 33; l++ )
655 {
656 int xl = x + w*l - 2;
657 dc.DrawLine(xl, y, xl, y + 7*h - 2);
658 }
659 }