add the wxFont(const wxSize& pixelSize, ...) ctor to all ports; add some wxCHECK_MSGs...
[wxWidgets.git] / src / common / fontcmn.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/common/fontcmn.cpp
3 // Purpose: implementation of wxFontBase methods
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 20.09.99
7 // RCS-ID: $Id$
8 // Copyright: (c) wxWidgets team
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // declarations
14 // ============================================================================
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // For compilers that support precompilation, includes "wx.h".
21 #include "wx/wxprec.h"
22
23 #ifdef __BORLANDC__
24 #pragma hdrstop
25 #endif
26
27 #include "wx/font.h"
28
29 #ifndef WX_PRECOMP
30 #include "wx/dc.h"
31 #include "wx/intl.h"
32 #include "wx/dcscreen.h"
33 #include "wx/log.h"
34 #include "wx/gdicmn.h"
35 #endif // WX_PRECOMP
36
37 #if defined(__WXMSW__)
38 #include "wx/msw/private.h" // includes windows.h for LOGFONT
39 #include "wx/msw/winundef.h"
40 #endif
41
42 #include "wx/fontutil.h" // for wxNativeFontInfo
43 #include "wx/fontmap.h"
44 #include "wx/fontenum.h"
45
46 #include "wx/tokenzr.h"
47
48 // ============================================================================
49 // implementation
50 // ============================================================================
51
52 // ----------------------------------------------------------------------------
53 // helper functions
54 // ----------------------------------------------------------------------------
55
56 static inline int flags2Style(int flags)
57 {
58 return flags & wxFONTFLAG_ITALIC
59 ? wxFONTSTYLE_ITALIC
60 : flags & wxFONTFLAG_SLANT
61 ? wxFONTSTYLE_SLANT
62 : wxFONTSTYLE_NORMAL;
63 }
64
65 static inline int flags2Weight(int flags)
66 {
67 return flags & wxFONTFLAG_LIGHT
68 ? wxFONTWEIGHT_LIGHT
69 : flags & wxFONTFLAG_BOLD
70 ? wxFONTWEIGHT_BOLD
71 : wxFONTWEIGHT_NORMAL;
72 }
73
74 static inline bool flags2Underlined(int flags)
75 {
76 return (flags & wxFONTFLAG_UNDERLINED) != 0;
77 }
78
79 // ----------------------------------------------------------------------------
80 // wxFontBase
81 // ----------------------------------------------------------------------------
82
83 wxFontEncoding wxFontBase::ms_encodingDefault = wxFONTENCODING_SYSTEM;
84
85 /* static */
86 void wxFontBase::SetDefaultEncoding(wxFontEncoding encoding)
87 {
88 // GetDefaultEncoding() should return something != wxFONTENCODING_DEFAULT
89 // and, besides, using this value here doesn't make any sense
90 wxCHECK_RET( encoding != wxFONTENCODING_DEFAULT,
91 _T("can't set default encoding to wxFONTENCODING_DEFAULT") );
92
93 ms_encodingDefault = encoding;
94 }
95
96 wxFontBase::~wxFontBase()
97 {
98 // this destructor is required for Darwin
99 }
100
101 /* static */
102 wxFont *wxFontBase::New(int size,
103 wxFontFamily family,
104 wxFontStyle style,
105 wxFontWeight weight,
106 bool underlined,
107 const wxString& face,
108 wxFontEncoding encoding)
109 {
110 return new wxFont(size, family, style, weight, underlined, face, encoding);
111 }
112
113 /* static */
114 wxFont *wxFontBase::New(const wxSize& pixelSize,
115 wxFontFamily family,
116 wxFontStyle style,
117 wxFontWeight weight,
118 bool underlined,
119 const wxString& face,
120 wxFontEncoding encoding)
121 {
122 return new wxFont(pixelSize, family, style, weight, underlined,
123 face, encoding);
124 }
125
126 /* static */
127 wxFont *wxFontBase::New(int pointSize,
128 wxFontFamily family,
129 int flags,
130 const wxString& face,
131 wxFontEncoding encoding)
132 {
133 return New(pointSize, family, flags2Style(flags), flags2Weight(flags),
134 flags2Underlined(flags), face, encoding);
135 }
136
137 /* static */
138 wxFont *wxFontBase::New(const wxSize& pixelSize,
139 wxFontFamily family,
140 int flags,
141 const wxString& face,
142 wxFontEncoding encoding)
143 {
144 return New(pixelSize, family, flags2Style(flags), flags2Weight(flags),
145 flags2Underlined(flags), face, encoding);
146 }
147
148 /* static */
149 wxFont *wxFontBase::New(const wxNativeFontInfo& info)
150 {
151 return new wxFont(info);
152 }
153
154 /* static */
155 wxFont *wxFontBase::New(const wxString& strNativeFontDesc)
156 {
157 wxNativeFontInfo fontInfo;
158 if ( !fontInfo.FromString(strNativeFontDesc) )
159 return new wxFont(*wxNORMAL_FONT);
160
161 return New(fontInfo);
162 }
163
164 bool wxFontBase::IsFixedWidth() const
165 {
166 return GetFamily() == wxFONTFAMILY_TELETYPE;
167 }
168
169 wxSize wxFontBase::GetPixelSize() const
170 {
171 wxScreenDC dc;
172 dc.SetFont(*(wxFont *)this);
173 return wxSize(dc.GetCharWidth(), dc.GetCharHeight());
174 }
175
176 bool wxFontBase::IsUsingSizeInPixels() const
177 {
178 return false;
179 }
180
181 void wxFontBase::SetPixelSize( const wxSize& pixelSize )
182 {
183 wxCHECK_RET( pixelSize.GetWidth() >= 0 && pixelSize.GetHeight() > 0,
184 "Negative values for the pixel size or zero pixel height are not allowed" );
185
186 wxScreenDC dc;
187
188 // NOTE: this algorithm for adjusting the font size is used by all
189 // implementations of wxFont except under wxMSW and wxGTK where
190 // native support to font creation using pixel-size is provided.
191
192 int largestGood = 0;
193 int smallestBad = 0;
194
195 bool initialGoodFound = false;
196 bool initialBadFound = false;
197
198 // NB: this assignment was separated from the variable definition
199 // in order to fix a gcc v3.3.3 compiler crash
200 int currentSize = GetPointSize();
201 while (currentSize > 0)
202 {
203 dc.SetFont(*static_cast<wxFont*>(this));
204
205 // if currentSize (in points) results in a font that is smaller
206 // than required by pixelSize it is considered a good size
207 // NOTE: the pixel size width may be zero
208 if (dc.GetCharHeight() <= pixelSize.GetHeight() &&
209 (pixelSize.GetWidth() == 0 ||
210 dc.GetCharWidth() <= pixelSize.GetWidth()))
211 {
212 largestGood = currentSize;
213 initialGoodFound = true;
214 }
215 else
216 {
217 smallestBad = currentSize;
218 initialBadFound = true;
219 }
220 if (!initialGoodFound)
221 {
222 currentSize /= 2;
223 }
224 else if (!initialBadFound)
225 {
226 currentSize *= 2;
227 }
228 else
229 {
230 int distance = smallestBad - largestGood;
231 if (distance == 1)
232 break;
233
234 currentSize = largestGood + distance / 2;
235 }
236
237 SetPointSize(currentSize);
238 }
239
240 if (currentSize != largestGood)
241 SetPointSize(largestGood);
242 }
243
244 void wxFontBase::DoSetNativeFontInfo(const wxNativeFontInfo& info)
245 {
246 #ifdef wxNO_NATIVE_FONTINFO
247 SetPointSize(info.pointSize);
248 SetFamily(info.family);
249 SetStyle(info.style);
250 SetWeight(info.weight);
251 SetUnderlined(info.underlined);
252 SetFaceName(info.faceName);
253 SetEncoding(info.encoding);
254 #else
255 (void)info;
256 #endif
257 }
258
259 wxString wxFontBase::GetNativeFontInfoDesc() const
260 {
261 wxString fontDesc;
262 const wxNativeFontInfo *fontInfo = GetNativeFontInfo();
263 if ( fontInfo )
264 {
265 fontDesc = fontInfo->ToString();
266 wxASSERT_MSG(!fontDesc.empty(), wxT("This should be a non-empty string!"));
267 }
268 else
269 {
270 wxFAIL_MSG(wxT("Derived class should have created the wxNativeFontInfo!"));
271 }
272
273 return fontDesc;
274 }
275
276 wxString wxFontBase::GetNativeFontInfoUserDesc() const
277 {
278 wxString fontDesc;
279 const wxNativeFontInfo *fontInfo = GetNativeFontInfo();
280 if ( fontInfo )
281 {
282 fontDesc = fontInfo->ToUserString();
283 wxASSERT_MSG(!fontDesc.empty(), wxT("This should be a non-empty string!"));
284 }
285 else
286 {
287 wxFAIL_MSG(wxT("Derived class should have created the wxNativeFontInfo!"));
288 }
289
290 return fontDesc;
291 }
292
293 bool wxFontBase::SetNativeFontInfo(const wxString& info)
294 {
295 wxNativeFontInfo fontInfo;
296 if ( !info.empty() && fontInfo.FromString(info) )
297 {
298 SetNativeFontInfo(fontInfo);
299 return true;
300 }
301
302 return false;
303 }
304
305 bool wxFontBase::SetNativeFontInfoUserDesc(const wxString& info)
306 {
307 wxNativeFontInfo fontInfo;
308 if ( !info.empty() && fontInfo.FromUserString(info) )
309 {
310 SetNativeFontInfo(fontInfo);
311 return true;
312 }
313
314 return false;
315 }
316
317 bool wxFontBase::operator==(const wxFont& font) const
318 {
319 // either it is the same font, i.e. they share the same common data or they
320 // have different ref datas but still describe the same font
321 return IsSameAs(font) ||
322 (
323 Ok() == font.Ok() &&
324 GetPointSize() == font.GetPointSize() &&
325 // in wxGTK1 GetPixelSize() calls GetInternalFont() which uses
326 // operator==() resulting in infinite recursion so we can't use it
327 // in that port
328 #if !defined(__WXGTK__) || defined(__WXGTK20__)
329 GetPixelSize() == font.GetPixelSize() &&
330 #endif
331 GetFamily() == font.GetFamily() &&
332 GetStyle() == font.GetStyle() &&
333 GetWeight() == font.GetWeight() &&
334 GetUnderlined() == font.GetUnderlined() &&
335 GetFaceName().IsSameAs(font.GetFaceName(), false) &&
336 GetEncoding() == font.GetEncoding()
337 );
338 }
339
340 wxString wxFontBase::GetFamilyString() const
341 {
342 wxCHECK_MSG( Ok(), wxT("wxDEFAULT"), wxT("invalid font") );
343
344 switch ( GetFamily() )
345 {
346 case wxDECORATIVE: return wxT("wxDECORATIVE");
347 case wxROMAN: return wxT("wxROMAN");
348 case wxSCRIPT: return wxT("wxSCRIPT");
349 case wxSWISS: return wxT("wxSWISS");
350 case wxMODERN: return wxT("wxMODERN");
351 case wxTELETYPE: return wxT("wxTELETYPE");
352 default: return wxT("wxDEFAULT");
353 }
354 }
355
356 wxString wxFontBase::GetStyleString() const
357 {
358 wxCHECK_MSG( Ok(), wxT("wxDEFAULT"), wxT("invalid font") );
359
360 switch ( GetStyle() )
361 {
362 case wxNORMAL: return wxT("wxNORMAL");
363 case wxSLANT: return wxT("wxSLANT");
364 case wxITALIC: return wxT("wxITALIC");
365 default: return wxT("wxDEFAULT");
366 }
367 }
368
369 wxString wxFontBase::GetWeightString() const
370 {
371 wxCHECK_MSG( Ok(), wxT("wxDEFAULT"), wxT("invalid font") );
372
373 switch ( GetWeight() )
374 {
375 case wxNORMAL: return wxT("wxNORMAL");
376 case wxBOLD: return wxT("wxBOLD");
377 case wxLIGHT: return wxT("wxLIGHT");
378 default: return wxT("wxDEFAULT");
379 }
380 }
381
382 bool wxFontBase::SetFaceName(const wxString& facename)
383 {
384 #if wxUSE_FONTENUM
385 if (!wxFontEnumerator::IsValidFacename(facename))
386 {
387 UnRef(); // make Ok() return false
388 return false;
389 }
390 #else // !wxUSE_FONTENUM
391 wxUnusedVar(facename);
392 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
393
394 return true;
395 }
396
397
398 // ----------------------------------------------------------------------------
399 // wxNativeFontInfo
400 // ----------------------------------------------------------------------------
401
402 // Up to now, there are no native implementations of this function:
403 void wxNativeFontInfo::SetFaceName(const wxArrayString& facenames)
404 {
405 #if wxUSE_FONTENUM
406 for (size_t i=0; i < facenames.GetCount(); i++)
407 {
408 if (wxFontEnumerator::IsValidFacename(facenames[i]))
409 {
410 SetFaceName(facenames[i]);
411 return;
412 }
413 }
414
415 // set the first valid facename we can find on this system
416 wxString validfacename = wxFontEnumerator::GetFacenames().Item(0);
417 wxLogTrace(wxT("font"), wxT("Falling back to '%s'"), validfacename.c_str());
418 SetFaceName(validfacename);
419 #else // !wxUSE_FONTENUM
420 SetFaceName(facenames[0]);
421 #endif // wxUSE_FONTENUM/!wxUSE_FONTENUM
422 }
423
424
425 #ifdef wxNO_NATIVE_FONTINFO
426
427 // These are the generic forms of FromString()/ToString.
428 //
429 // convert to/from the string representation: format is
430 // version;pointsize;family;style;weight;underlined;facename;encoding
431
432 bool wxNativeFontInfo::FromString(const wxString& s)
433 {
434 long l;
435
436 wxStringTokenizer tokenizer(s, _T(";"));
437
438 wxString token = tokenizer.GetNextToken();
439 //
440 // Ignore the version for now
441 //
442
443 token = tokenizer.GetNextToken();
444 if ( !token.ToLong(&l) )
445 return false;
446 pointSize = (int)l;
447
448 token = tokenizer.GetNextToken();
449 if ( !token.ToLong(&l) )
450 return false;
451 family = (wxFontFamily)l;
452
453 token = tokenizer.GetNextToken();
454 if ( !token.ToLong(&l) )
455 return false;
456 style = (wxFontStyle)l;
457
458 token = tokenizer.GetNextToken();
459 if ( !token.ToLong(&l) )
460 return false;
461 weight = (wxFontWeight)l;
462
463 token = tokenizer.GetNextToken();
464 if ( !token.ToLong(&l) )
465 return false;
466 underlined = l != 0;
467
468 faceName = tokenizer.GetNextToken();
469
470 #ifndef __WXMAC__
471 if( !faceName )
472 return false;
473 #endif
474
475 token = tokenizer.GetNextToken();
476 if ( !token.ToLong(&l) )
477 return false;
478 encoding = (wxFontEncoding)l;
479
480 return true;
481 }
482
483 wxString wxNativeFontInfo::ToString() const
484 {
485 wxString s;
486
487 s.Printf(_T("%d;%d;%d;%d;%d;%d;%s;%d"),
488 0, // version
489 pointSize,
490 family,
491 (int)style,
492 (int)weight,
493 underlined,
494 faceName.GetData(),
495 (int)encoding);
496
497 return s;
498 }
499
500 void wxNativeFontInfo::Init()
501 {
502 pointSize = 0;
503 family = wxFONTFAMILY_DEFAULT;
504 style = wxFONTSTYLE_NORMAL;
505 weight = wxFONTWEIGHT_NORMAL;
506 underlined = false;
507 faceName.clear();
508 encoding = wxFONTENCODING_DEFAULT;
509 }
510
511 int wxNativeFontInfo::GetPointSize() const
512 {
513 return pointSize;
514 }
515
516 wxFontStyle wxNativeFontInfo::GetStyle() const
517 {
518 return style;
519 }
520
521 wxFontWeight wxNativeFontInfo::GetWeight() const
522 {
523 return weight;
524 }
525
526 bool wxNativeFontInfo::GetUnderlined() const
527 {
528 return underlined;
529 }
530
531 wxString wxNativeFontInfo::GetFaceName() const
532 {
533 return faceName;
534 }
535
536 wxFontFamily wxNativeFontInfo::GetFamily() const
537 {
538 return family;
539 }
540
541 wxFontEncoding wxNativeFontInfo::GetEncoding() const
542 {
543 return encoding;
544 }
545
546 void wxNativeFontInfo::SetPointSize(int pointsize)
547 {
548 pointSize = pointsize;
549 }
550
551 void wxNativeFontInfo::SetStyle(wxFontStyle style_)
552 {
553 style = style_;
554 }
555
556 void wxNativeFontInfo::SetWeight(wxFontWeight weight_)
557 {
558 weight = weight_;
559 }
560
561 void wxNativeFontInfo::SetUnderlined(bool underlined_)
562 {
563 underlined = underlined_;
564 }
565
566 bool wxNativeFontInfo::SetFaceName(const wxString& facename_)
567 {
568 faceName = facename_;
569 return true;
570 }
571
572 void wxNativeFontInfo::SetFamily(wxFontFamily family_)
573 {
574 family = family_;
575 }
576
577 void wxNativeFontInfo::SetEncoding(wxFontEncoding encoding_)
578 {
579 encoding = encoding_;
580 }
581
582 #endif // generic wxNativeFontInfo implementation
583
584 // conversion to/from user-readable string: this is used in the generic
585 // versions and under MSW as well because there is no standard font description
586 // format there anyhow (but there is a well-defined standard for X11 fonts used
587 // by wxGTK and wxMotif)
588
589 #if defined(wxNO_NATIVE_FONTINFO) || defined(__WXMSW__) || defined (__WXPM__)
590
591 wxString wxNativeFontInfo::ToUserString() const
592 {
593 wxString desc;
594
595 // first put the adjectives, if any - this is English-centric, of course,
596 // but what else can we do?
597 if ( GetUnderlined() )
598 {
599 desc << _("underlined");
600 }
601
602 switch ( GetWeight() )
603 {
604 default:
605 wxFAIL_MSG( _T("unknown font weight") );
606 // fall through
607
608 case wxFONTWEIGHT_NORMAL:
609 break;
610
611 case wxFONTWEIGHT_LIGHT:
612 desc << _(" light");
613 break;
614
615 case wxFONTWEIGHT_BOLD:
616 desc << _(" bold");
617 break;
618 }
619
620 switch ( GetStyle() )
621 {
622 default:
623 wxFAIL_MSG( _T("unknown font style") );
624 // fall through
625
626 case wxFONTSTYLE_NORMAL:
627 break;
628
629 // we don't distinguish between the two for now anyhow...
630 case wxFONTSTYLE_ITALIC:
631 case wxFONTSTYLE_SLANT:
632 desc << _(" italic");
633 break;
634 }
635
636 wxString face = GetFaceName();
637 if ( !face.empty() )
638 {
639 desc << _T(' ') << face;
640 }
641
642 int size = GetPointSize();
643 if ( size != wxNORMAL_FONT->GetPointSize() )
644 {
645 desc << _T(' ') << size;
646 }
647
648 #if wxUSE_FONTMAP
649 wxFontEncoding enc = GetEncoding();
650 if ( enc != wxFONTENCODING_DEFAULT && enc != wxFONTENCODING_SYSTEM )
651 {
652 desc << _T(' ') << wxFontMapper::GetEncodingName(enc);
653 }
654 #endif // wxUSE_FONTMAP
655
656 return desc.Strip(wxString::both).MakeLower();
657 }
658
659 bool wxNativeFontInfo::FromUserString(const wxString& s)
660 {
661 // reset to the default state
662 Init();
663
664 // parse a more or less free form string
665 //
666 // TODO: we should handle at least the quoted facenames
667 wxStringTokenizer tokenizer(s, _T(";, "), wxTOKEN_STRTOK);
668
669 wxString face;
670 unsigned long size;
671 bool weightfound = false, pointsizefound = false;
672 #if wxUSE_FONTMAP
673 bool encodingfound = false;
674 #endif
675
676 while ( tokenizer.HasMoreTokens() )
677 {
678 wxString token = tokenizer.GetNextToken();
679
680 // normalize it
681 token.Trim(true).Trim(false).MakeLower();
682
683 // look for the known tokens
684 if ( token == _T("underlined") || token == _("underlined") )
685 {
686 SetUnderlined(true);
687 }
688 else if ( token == _T("light") || token == _("light") )
689 {
690 SetWeight(wxFONTWEIGHT_LIGHT);
691 weightfound = true;
692 }
693 else if ( token == _T("bold") || token == _("bold") )
694 {
695 SetWeight(wxFONTWEIGHT_BOLD);
696 weightfound = true;
697 }
698 else if ( token == _T("italic") || token == _("italic") )
699 {
700 SetStyle(wxFONTSTYLE_ITALIC);
701 }
702 else if ( token.ToULong(&size) )
703 {
704 SetPointSize(size);
705 pointsizefound = true;
706 }
707 else
708 {
709 #if wxUSE_FONTMAP
710 // try to interpret this as an encoding
711 wxFontEncoding encoding = wxFontMapper::Get()->CharsetToEncoding(token, false);
712 if ( encoding != wxFONTENCODING_DEFAULT &&
713 encoding != wxFONTENCODING_SYSTEM ) // returned when the recognition failed
714 {
715 SetEncoding(encoding);
716 encodingfound = true;
717 }
718 else
719 {
720 #endif // wxUSE_FONTMAP
721
722 // assume it is the face name
723 if ( !face.empty() )
724 {
725 face += _T(' ');
726 }
727
728 face += token;
729
730 // skip the code which resets face below
731 continue;
732
733 #if wxUSE_FONTMAP
734 }
735 #endif // wxUSE_FONTMAP
736 }
737
738 // if we had had the facename, we shouldn't continue appending tokens
739 // to it (i.e. "foo bold bar" shouldn't result in the facename "foo
740 // bar")
741 if ( !face.empty() )
742 {
743 // NB: the check on the facename is implemented in wxFontBase::SetFaceName
744 // and not in wxNativeFontInfo::SetFaceName thus we need to explicitely
745 // call here wxFontEnumerator::IsValidFacename
746 if (
747 #if wxUSE_FONTENUM
748 !wxFontEnumerator::IsValidFacename(face) ||
749 #endif // wxUSE_FONTENUM
750 !SetFaceName(face) )
751 {
752 SetFaceName(wxNORMAL_FONT->GetFaceName());
753 }
754
755 face.clear();
756 }
757 }
758
759 // we might not have flushed it inside the loop
760 if ( !face.empty() )
761 {
762 // NB: the check on the facename is implemented in wxFontBase::SetFaceName
763 // and not in wxNativeFontInfo::SetFaceName thus we need to explicitely
764 // call here wxFontEnumerator::IsValidFacename
765 if (
766 #if wxUSE_FONTENUM
767 !wxFontEnumerator::IsValidFacename(face) ||
768 #endif // wxUSE_FONTENUM
769 !SetFaceName(face) )
770 {
771 SetFaceName(wxNORMAL_FONT->GetFaceName());
772 }
773 }
774
775 // set point size to default value if size was not given
776 if ( !pointsizefound )
777 SetPointSize(wxNORMAL_FONT->GetPointSize());
778
779 // set font weight to default value if weight was not given
780 if ( !weightfound )
781 SetWeight(wxFONTWEIGHT_NORMAL);
782
783 #if wxUSE_FONTMAP
784 // set font encoding to default value if encoding was not given
785 if ( !encodingfound )
786 SetEncoding(wxFONTENCODING_SYSTEM);
787 #endif // wxUSE_FONTMAP
788
789 return true;
790 }
791
792 #endif // generic or wxMSW or wxOS2
793
794
795 // wxFont <-> wxString utilities, used by wxConfig
796 wxString wxToString(const wxFontBase& font)
797 {
798 return font.IsOk() ? font.GetNativeFontInfoDesc()
799 : wxString();
800 }
801
802 bool wxFromString(const wxString& str, wxFontBase *font)
803 {
804 wxCHECK_MSG( font, false, _T("NULL output parameter") );
805
806 if ( str.empty() )
807 {
808 *font = wxNullFont;
809 return true;
810 }
811
812 return font->SetNativeFontInfo(str);
813 }
814
815