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