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