]> git.saurik.com Git - wxWidgets.git/blame - samples/font/font.cpp
more tests: OS/user info functions
[wxWidgets.git] / samples / font / font.cpp
CommitLineData
1ccd74da
VZ
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$
36f210c8 8// Copyright: (c) 1999 Vadim Zeitlin
1ccd74da
VZ
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
36f210c8 27#include <wx/choicdlg.h>
1ccd74da 28#include <wx/fontdlg.h>
ddc8c2e3 29#include <wx/fontenum.h>
3c1866e8 30#include <wx/fontmap.h>
7337790c 31#include <wx/encconv.h>
3c1866e8 32#include <wx/textfile.h>
1ccd74da
VZ
33
34// ----------------------------------------------------------------------------
35// private classes
36// ----------------------------------------------------------------------------
37
38// Define a new application type, each program should derive a class from wxApp
39class MyApp : public wxApp
40{
41public:
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
52class MyCanvas: public wxWindow
53{
54public:
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
67private:
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
75class MyFrame : public wxFrame
76{
77public:
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);
3c1866e8 87 void OnViewMsg(wxCommandEvent& event);
1ccd74da 88 void OnSelectFont(wxCommandEvent& event);
36f210c8 89 void OnEnumerateFamiliesForEncoding(wxCommandEvent& event);
ddc8c2e3
VZ
90 void OnEnumerateFamilies(wxCommandEvent& WXUNUSED(event))
91 { DoEnumerateFamilies(FALSE); }
92 void OnEnumerateFixedFamilies(wxCommandEvent& WXUNUSED(event))
93 { DoEnumerateFamilies(TRUE); }
d111a89a 94 void OnEnumerateEncodings(wxCommandEvent& event);
1ccd74da 95
36f210c8
VZ
96 void OnSize(wxSizeEvent& event);
97
1ccd74da 98protected:
7beba2fc
VZ
99 bool DoEnumerateFamilies(bool fixedWidthOnly,
100 wxFontEncoding encoding = wxFONTENCODING_SYSTEM,
101 bool silent = FALSE);
36f210c8 102
a1d58ddc
VZ
103 void DoChangeFont(const wxFont& font, const wxColour& col = wxNullColour);
104
36f210c8 105 void Resize(const wxSize& size, const wxFont& font = wxNullFont);
ddc8c2e3 106
36f210c8
VZ
107 wxTextCtrl *m_textctrl;
108 MyCanvas *m_canvas;
1ccd74da
VZ
109
110private:
111 // any class wishing to process wxWindows events must use this macro
112 DECLARE_EVENT_TABLE()
113};
114
1ccd74da
VZ
115// ----------------------------------------------------------------------------
116// constants
117// ----------------------------------------------------------------------------
118
119// IDs for the controls and the menu commands
120enum
121{
122 // menu items
123 Font_Quit = 1,
124 Font_About,
3c1866e8 125 Font_ViewMsg,
1ccd74da 126 Font_Choose = 100,
36f210c8 127 Font_EnumFamiliesForEncoding,
ddc8c2e3
VZ
128 Font_EnumFamilies,
129 Font_EnumFixedFamilies,
d111a89a 130 Font_EnumEncodings,
ddc8c2e3 131 Font_Max
1ccd74da
VZ
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.
141BEGIN_EVENT_TABLE(MyFrame, wxFrame)
142 EVT_MENU(Font_Quit, MyFrame::OnQuit)
143 EVT_MENU(Font_About, MyFrame::OnAbout)
3c1866e8 144 EVT_MENU(Font_ViewMsg, MyFrame::OnViewMsg)
1ccd74da 145 EVT_MENU(Font_Choose, MyFrame::OnSelectFont)
36f210c8 146 EVT_MENU(Font_EnumFamiliesForEncoding, MyFrame::OnEnumerateFamiliesForEncoding)
ddc8c2e3
VZ
147 EVT_MENU(Font_EnumFamilies, MyFrame::OnEnumerateFamilies)
148 EVT_MENU(Font_EnumFixedFamilies, MyFrame::OnEnumerateFixedFamilies)
d111a89a 149 EVT_MENU(Font_EnumEncodings, MyFrame::OnEnumerateEncodings)
36f210c8
VZ
150
151 EVT_SIZE(MyFrame::OnSize)
1ccd74da
VZ
152END_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)
159IMPLEMENT_APP(MyApp)
160
161// ============================================================================
162// implementation
163// ============================================================================
164
165// ----------------------------------------------------------------------------
166// the application class
167// ----------------------------------------------------------------------------
168
169// `Main program' equivalent: the program execution "starts" here
170bool MyApp::OnInit()
171{
172 // Create the main application window
ddc8c2e3 173 MyFrame *frame = new MyFrame("Font wxWindows demo",
1ccd74da
VZ
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
191MyFrame::MyFrame(const wxString& title, const wxPoint& pos, const wxSize& size)
a1d58ddc 192 : wxFrame((wxFrame *)NULL, -1, title, pos, size), m_textctrl(NULL)
1ccd74da 193{
1ccd74da
VZ
194 // create a menu bar
195 wxMenu *menuFile = new wxMenu;
196
3c1866e8
VZ
197 menuFile->Append(Font_ViewMsg, "&View...\tCtrl-V",
198 "View an email message file");
199 menuFile->AppendSeparator();
1ccd74da
VZ
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;
ddc8c2e3 205 menuFont->Append(Font_Choose, "&Select font...\tCtrl-S",
1ccd74da 206 "Select a standard font");
ddc8c2e3 207 menuFont->AppendSeparator();
d111a89a 208 menuFont->Append(Font_EnumFamilies, "Enumerate font &families\tCtrl-F");
ddc8c2e3 209 menuFont->Append(Font_EnumFixedFamilies,
d111a89a
VZ
210 "Enumerate f&ixed font families\tCtrl-I");
211 menuFont->Append(Font_EnumEncodings,
212 "Enumerate &encodings\tCtrl-E");
36f210c8
VZ
213 menuFont->Append(Font_EnumFamiliesForEncoding,
214 "Find font for en&coding...\tCtrl-C",
215 "Find font families for given encoding");
1ccd74da
VZ
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
36f210c8
VZ
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
1ccd74da
VZ
231 m_canvas = new MyCanvas(this);
232
233 // create a status bar just for fun (by default with 1 pane only)
a1d58ddc
VZ
234 CreateStatusBar();
235 SetStatusText("Welcome to wxWindows font demo!");
1ccd74da
VZ
236}
237
e680a378 238// --------------------------------------------------------
1ccd74da 239
e680a378 240class MyEncodingEnumerator : public wxFontEnumerator
d111a89a 241{
e680a378
RR
242public:
243 MyEncodingEnumerator()
244 { m_n = 0; }
d111a89a 245
e680a378
RR
246 const wxString& GetText() const
247 { return m_text; }
d111a89a 248
e680a378
RR
249protected:
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 }
d111a89a 259
e680a378
RR
260private:
261 size_t m_n;
262 wxString m_text;
263};
d111a89a 264
e680a378
RR
265void MyFrame::OnEnumerateEncodings(wxCommandEvent& WXUNUSED(event))
266{
267 MyEncodingEnumerator fontEnumerator;
d111a89a
VZ
268
269 fontEnumerator.EnumerateEncodings();
270
271 wxLogMessage("Enumerating all available encodings:\n%s",
272 fontEnumerator.GetText().c_str());
273}
1ccd74da 274
e680a378 275// -------------------------------------------------------------
36f210c8 276
e680a378
RR
277class MyFontEnumerator : public wxFontEnumerator
278{
279public:
280 bool GotAny() const
281 { return !m_facenames.IsEmpty(); }
d111a89a 282
e680a378
RR
283 const wxArrayString& GetFacenames() const
284 { return m_facenames; }
ddc8c2e3 285
e680a378
RR
286protected:
287 virtual bool OnFacename(const wxString& facename)
288 {
289 m_facenames.Add(facename);
290 return TRUE;
291 }
ddc8c2e3
VZ
292
293 private:
a1d58ddc 294 wxArrayString m_facenames;
e680a378
RR
295} fontEnumerator;
296
297bool MyFrame::DoEnumerateFamilies(bool fixedWidthOnly,
298 wxFontEncoding encoding,
299 bool silent)
300{
301 MyFontEnumerator fontEnumerator;
ddc8c2e3 302
3c1866e8 303 fontEnumerator.EnumerateFacenames(encoding, fixedWidthOnly);
d111a89a 304
36f210c8
VZ
305 if ( fontEnumerator.GotAny() )
306 {
ea9144a3
VZ
307 int nFacenames = fontEnumerator.GetFacenames().GetCount();
308 if ( !silent )
309 {
310 wxLogStatus(this, "Found %d %sfonts",
311 nFacenames, fixedWidthOnly ? "fixed width " : "");
312 }
a1d58ddc 313
ea9144a3 314 wxString facename;
7beba2fc 315 if ( silent )
ea9144a3
VZ
316 {
317 // choose the first
318 facename = fontEnumerator.GetFacenames().Item(0);
319 }
7beba2fc 320 else
ea9144a3
VZ
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
7beba2fc
VZ
328 n = wxGetSingleChoiceIndex("Choose a facename", "Font demo",
329 nFacenames, facenames, this);
ea9144a3
VZ
330
331 if ( n != -1 )
332 facename = facenames[n];
333
334 delete [] facenames;
335 }
336
337 if ( !facename.IsEmpty() )
a1d58ddc 338 {
ea9144a3
VZ
339 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
340 wxFONTWEIGHT_NORMAL, FALSE, facename, encoding);
a1d58ddc
VZ
341
342 DoChangeFont(font);
343 }
344
7beba2fc 345 return TRUE;
36f210c8 346 }
7beba2fc 347 else if ( !silent )
36f210c8
VZ
348 {
349 wxLogWarning("No such fonts found.");
350 }
7beba2fc
VZ
351
352 return FALSE;
ddc8c2e3
VZ
353}
354
36f210c8 355void MyFrame::OnEnumerateFamiliesForEncoding(wxCommandEvent& WXUNUSED(event))
1ccd74da 356{
36f210c8
VZ
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",
a1d58ddc
VZ
384 WXSIZEOF(encodingNames),
385 (char **)encodingNames,
36f210c8
VZ
386 this);
387
388 if ( n != -1 )
389 {
390 DoEnumerateFamilies(FALSE, encodings[n]);
391 }
1ccd74da
VZ
392}
393
a1d58ddc
VZ
394void 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
1ccd74da
VZ
408void 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();
36f210c8
VZ
418 wxFont font = retData.GetChosenFont();
419 wxColour colour = retData.GetColour();
420
a1d58ddc 421 DoChangeFont(font, colour);
1ccd74da
VZ
422 }
423}
424
425void MyFrame::OnQuit(wxCommandEvent& WXUNUSED(event))
426{
427 // TRUE is to force the frame to close
428 Close(TRUE);
429}
430
3c1866e8
VZ
431void 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
7beba2fc 493 wxFontEncoding fontenc = wxTheFontMapper->CharsetToEncoding(charset);
3c1866e8
VZ
494 if ( fontenc == wxFONTENCODING_SYSTEM )
495 {
496 wxLogError("Charset '%s' is unsupported.", charset.c_str());
497 return;
498 }
499
7337790c
VS
500 m_textctrl->LoadFile(filename);
501
502 if (!wxTheFontMapper->IsEncodingAvailable(fontenc))
503 {
504 // try to find some similar encoding:
3e2dd3db
VZ
505 wxFontEncoding encAlt;
506 if ( wxTheFontMapper->GetAltForEncoding(fontenc, &encAlt) )
7337790c
VS
507 {
508 wxEncodingConverter conv;
509
3e2dd3db 510 if (conv.Init(fontenc, encAlt))
7337790c 511 {
3e2dd3db 512 fontenc = encAlt;
7337790c
VS
513 m_textctrl -> SetValue(conv.Convert(m_textctrl -> GetValue()));
514 }
515 else
3e2dd3db 516 {
7337790c
VS
517 wxLogWarning("Cannot convert from '%s' to '%s'.",
518 wxFontMapper::GetEncodingDescription(fontenc).c_str(),
3e2dd3db
VZ
519 wxFontMapper::GetEncodingDescription(encAlt).c_str());
520 }
7337790c
VS
521 }
522 else
523 wxLogWarning("No fonts for encoding '%s' on this system.",
524 wxFontMapper::GetEncodingDescription(fontenc).c_str());
525 }
526
3c1866e8 527 // and now create the correct font
7beba2fc
VZ
528 if ( !DoEnumerateFamilies(FALSE, fontenc, TRUE /* silent */) )
529 {
ea9144a3 530 wxFont font(12, wxFONTFAMILY_DEFAULT, wxFONTSTYLE_NORMAL,
7beba2fc
VZ
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 }
3c1866e8
VZ
543}
544
1ccd74da
VZ
545void MyFrame::OnAbout(wxCommandEvent& WXUNUSED(event))
546{
36f210c8
VZ
547 wxMessageBox("wxWindows font demo\n"
548 "(c) 1999 Vadim Zeitlin",
549 "About Font",
1ccd74da
VZ
550 wxOK | wxICON_INFORMATION, this);
551}
552
36f210c8
VZ
553void MyFrame::OnSize(wxSizeEvent& event)
554{
555 wxSize size = event.GetSize();
556
557 Resize(size);
717a57c2
VZ
558
559 event.Skip();
36f210c8
VZ
560}
561
562void MyFrame::Resize(const wxSize& size, const wxFont& font)
563{
a1d58ddc
VZ
564 if ( !m_textctrl )
565 return;
566
36f210c8
VZ
567 wxCoord h;
568 if ( font.Ok() )
569 {
570 wxClientDC dc(this);
571 dc.SetFont(font);
572
3c1866e8 573 h = 10*(dc.GetCharHeight() + 1);
36f210c8
VZ
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}
1ccd74da
VZ
583
584// ----------------------------------------------------------------------------
585// MyCanvas
586// ----------------------------------------------------------------------------
587
588BEGIN_EVENT_TABLE(MyCanvas, wxWindow)
589 EVT_PAINT(MyCanvas::OnPaint)
590END_EVENT_TABLE()
591
592MyCanvas::MyCanvas( wxWindow *parent )
11c7d5b6
VZ
593 : wxWindow( parent, -1 ),
594 m_colour(*wxRED), m_font(*wxNORMAL_FONT)
1ccd74da 595{
1ccd74da
VZ
596}
597
598MyCanvas::~MyCanvas()
599{
600}
601
602void 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,
36f210c8 630 y = 2*h;
1ccd74da
VZ
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}