clamp the point size of the font to a reaosnable range (second part of patch 1481722)
[wxWidgets.git] / src / unix / fontutil.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/fontutil.cpp
3 // Purpose: Font helper functions for X11 (GDK/X)
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 05.11.99
7 // RCS-ID: $Id$
8 // Copyright: (c) Vadim Zeitlin
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 #ifndef WX_PRECOMP
28 #include "wx/font.h" // wxFont enums
29 #include "wx/encinfo.h"
30 #include "wx/hash.h"
31 #include "wx/utils.h" // for wxGetDisplay()
32 #endif // PCH
33
34 #include "wx/fontutil.h"
35 #include "wx/fontmap.h"
36 #include "wx/tokenzr.h"
37 #include "wx/module.h"
38
39 #if wxUSE_PANGO
40
41 #include "pango/pango.h"
42
43 #ifdef __WXGTK20__
44 #include "wx/gtk/private.h"
45 extern GtkWidget *wxGetRootWindow();
46 #else
47 #include "wx/x11/private.h"
48 #endif
49
50 // ----------------------------------------------------------------------------
51 // wxNativeFontInfo
52 // ----------------------------------------------------------------------------
53
54 void wxNativeFontInfo::Init()
55 {
56 description = NULL;
57 }
58
59 void
60 wxNativeFontInfo::Init(const wxNativeFontInfo& info)
61 {
62 if (info.description)
63 description = pango_font_description_copy(info.description);
64 else
65 description = NULL;
66 }
67
68 void wxNativeFontInfo::Free()
69 {
70 if (description)
71 pango_font_description_free(description);
72 }
73
74 int wxNativeFontInfo::GetPointSize() const
75 {
76 return pango_font_description_get_size( description ) / PANGO_SCALE;
77 }
78
79 wxFontStyle wxNativeFontInfo::GetStyle() const
80 {
81 wxFontStyle m_style = wxFONTSTYLE_NORMAL;
82
83 switch (pango_font_description_get_style( description ))
84 {
85 case PANGO_STYLE_NORMAL:
86 m_style = wxFONTSTYLE_NORMAL;
87 break;
88 case PANGO_STYLE_ITALIC:
89 m_style = wxFONTSTYLE_ITALIC;
90 break;
91 case PANGO_STYLE_OBLIQUE:
92 m_style = wxFONTSTYLE_SLANT;
93 break;
94 }
95
96 return m_style;
97 }
98
99 wxFontWeight wxNativeFontInfo::GetWeight() const
100 {
101 #if 0
102 // We seem to currently initialize only by string.
103 // In that case PANGO_FONT_MASK_WEIGHT is always set.
104 if (!(pango_font_description_get_set_fields(description) & PANGO_FONT_MASK_WEIGHT))
105 return wxFONTWEIGHT_NORMAL;
106 #endif
107
108 PangoWeight pango_weight = pango_font_description_get_weight( description );
109
110 // Until the API can be changed the following ranges of weight values are used:
111 // wxFONTWEIGHT_LIGHT: 100 .. 349 - range of 250
112 // wxFONTWEIGHT_NORMAL: 350 .. 599 - range of 250
113 // wxFONTWEIGHT_BOLD: 600 .. 900 - range of 301 (600 is "semibold" already)
114
115 if (pango_weight >= 600)
116 return wxFONTWEIGHT_BOLD;
117
118 if (pango_weight < 350)
119 return wxFONTWEIGHT_LIGHT;
120
121 return wxFONTWEIGHT_NORMAL;
122 }
123
124 bool wxNativeFontInfo::GetUnderlined() const
125 {
126 return false;
127 }
128
129 wxString wxNativeFontInfo::GetFaceName() const
130 {
131 wxString tmp = wxGTK_CONV_BACK( pango_font_description_get_family( description ) );
132
133 return tmp;
134 }
135
136 wxFontFamily wxNativeFontInfo::GetFamily() const
137 {
138 wxFontFamily ret = wxFONTFAMILY_DEFAULT;
139 // note: not passing -1 as the 2nd parameter to g_ascii_strdown to work
140 // around a bug in the 64-bit glib shipped with solaris 10, -1 causes it
141 // to try to allocate 2^32 bytes.
142 const char *family_name = pango_font_description_get_family( description );
143 char *family_text = g_ascii_strdown( family_name, family_name ? strlen( family_name ) : 0 );
144 // Check for some common fonts, to salvage what we can from the current win32 centric wxFont API:
145 if (strncmp( family_text, "monospace", 9 ) == 0)
146 ret = wxFONTFAMILY_TELETYPE; // begins with "Monospace"
147 else if (strncmp( family_text, "courier", 7 ) == 0)
148 ret = wxFONTFAMILY_TELETYPE; // begins with "Courier"
149 #if defined(__WXGTK24__) || defined(HAVE_PANGO_FONT_FAMILY_IS_MONOSPACE)
150 else
151 #ifdef __WXGTK24__
152 if (!gtk_check_version(2,4,0))
153 #endif
154 {
155 PangoFontFamily **families;
156 PangoFontFamily *family = NULL;
157 int n_families;
158 pango_context_list_families(
159 #ifdef __WXGTK20__
160 gtk_widget_get_pango_context( wxGetRootWindow() ),
161 #else
162 wxTheApp->GetPangoContext(),
163 #endif
164 &families, &n_families);
165
166 for (int i = 0;i < n_families;++i)
167 {
168 if (g_ascii_strcasecmp(pango_font_family_get_name( families[i] ), pango_font_description_get_family( description )) == 0 )
169 {
170 family = families[i];
171 break;
172 }
173 }
174
175 g_free(families);
176
177 // Some gtk+ systems might query for a non-existing font from wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT)
178 // on initialization, don't assert until wxSystemSettings::GetFont is checked for this - MR
179 // wxASSERT_MSG( family, wxT("wxNativeFontInfo::GetFamily() - No appropriate PangoFontFamily found for ::description") );
180
181 //BCI: Cache the wxFontFamily inside the class. Validate cache with
182 //BCI: g_ascii_strcasecmp(pango_font_description_get_family(description), pango_font_family_get_name(family)) == 0
183
184 if (family != NULL && pango_font_family_is_monospace( family ))
185 ret = wxFONTFAMILY_TELETYPE; // is deemed a monospace font by pango
186 }
187 #endif // gtk24 || HAVE_PANGO_FONT_FAMILY_IS_MONOSPACE
188
189 if (ret == wxFONTFAMILY_DEFAULT)
190 {
191 if (strstr( family_text, "sans" ) != NULL) // checked before serif, so that "* Sans Serif" fonts are detected correctly
192 ret = wxFONTFAMILY_SWISS; // contains "Sans"
193 else if (strstr( family_text, "serif" ) != NULL)
194 ret = wxFONTFAMILY_ROMAN; // contains "Serif"
195 else if (strncmp( family_text, "times", 5 ) == 0)
196 ret = wxFONTFAMILY_ROMAN; // begins with "Times"
197 else if (strncmp( family_text, "old", 3 ) == 0)
198 ret = wxFONTFAMILY_DECORATIVE; // Begins with "Old" - "Old English", "Old Town"
199 }
200
201 free(family_text);
202 return ret;
203 }
204
205 wxFontEncoding wxNativeFontInfo::GetEncoding() const
206 {
207 return wxFONTENCODING_SYSTEM;
208 }
209
210
211 void wxNativeFontInfo::SetPointSize(int pointsize)
212 {
213 pango_font_description_set_size( description, pointsize * PANGO_SCALE );
214 }
215
216 void wxNativeFontInfo::SetStyle(wxFontStyle style)
217 {
218 switch (style)
219 {
220 case wxFONTSTYLE_ITALIC:
221 pango_font_description_set_style( description, PANGO_STYLE_ITALIC );
222 break;
223 case wxFONTSTYLE_SLANT:
224 pango_font_description_set_style( description, PANGO_STYLE_OBLIQUE );
225 break;
226 default:
227 wxFAIL_MSG( _T("unknown font style") );
228 // fall through
229 case wxFONTSTYLE_NORMAL:
230 pango_font_description_set_style( description, PANGO_STYLE_NORMAL );
231 break;
232 }
233 }
234
235 void wxNativeFontInfo::SetWeight(wxFontWeight weight)
236 {
237 switch (weight)
238 {
239 case wxFONTWEIGHT_BOLD:
240 pango_font_description_set_weight(description, PANGO_WEIGHT_BOLD);
241 break;
242 case wxFONTWEIGHT_LIGHT:
243 pango_font_description_set_weight(description, PANGO_WEIGHT_LIGHT);
244 break;
245 default:
246 wxFAIL_MSG( _T("unknown font weight") );
247 // fall through
248 case wxFONTWEIGHT_NORMAL:
249 pango_font_description_set_weight(description, PANGO_WEIGHT_NORMAL);
250 }
251 }
252
253 void wxNativeFontInfo::SetUnderlined(bool WXUNUSED(underlined))
254 {
255 wxFAIL_MSG( _T("not implemented") );
256 }
257
258 void wxNativeFontInfo::SetFaceName(const wxString& facename)
259 {
260 pango_font_description_set_family(description, wxGTK_CONV_SYS(facename));
261 }
262
263 void wxNativeFontInfo::SetFamily(wxFontFamily WXUNUSED(family))
264 {
265 wxFAIL_MSG( _T("not implemented") );
266 }
267
268 void wxNativeFontInfo::SetEncoding(wxFontEncoding WXUNUSED(encoding))
269 {
270 wxFAIL_MSG( _T("not implemented") );
271 }
272
273
274
275 bool wxNativeFontInfo::FromString(const wxString& s)
276 {
277 if (description)
278 pango_font_description_free( description );
279
280 // there is a bug in at least pango <= 1.13 which makes it (or its backends)
281 // segfault for very big point sizes and for negative point sizes.
282 // To workaround that bug for pango <= 1.13
283 // (see http://bugzilla.gnome.org/show_bug.cgi?id=340229)
284 // we do the check on the size here using same (arbitrary) limits used by
285 // pango > 1.13. Note that the segfault could happen also for pointsize
286 // smaller than this limit !!
287 wxString str(s);
288 const size_t pos = str.find_last_of(_T(" "));
289 double size;
290 if ( pos != wxString::npos && wxString(str, pos + 1).ToDouble(&size) )
291 {
292 wxString sizeStr;
293 if ( size < 1 )
294 sizeStr = _T("1");
295 else if ( n >= 1E6 )
296 sizeStr = _T("1E6");
297
298 if ( !sizeStr.empty() )
299 {
300 // replace the old size with the adjusted one
301 str = wxString(s, 0, pos) + sizeStr;
302 }
303 }
304
305 description = pango_font_description_from_string( wxGTK_CONV_SYS( str ) );
306
307 return true;
308 }
309
310 wxString wxNativeFontInfo::ToString() const
311 {
312 char *str = pango_font_description_to_string( description );
313 wxString tmp = wxGTK_CONV_BACK( str );
314 g_free( str );
315
316 return tmp;
317 }
318
319 bool wxNativeFontInfo::FromUserString(const wxString& s)
320 {
321 return FromString( s );
322 }
323
324 wxString wxNativeFontInfo::ToUserString() const
325 {
326 return ToString();
327 }
328
329 // ----------------------------------------------------------------------------
330 // wxNativeEncodingInfo
331 // ----------------------------------------------------------------------------
332
333 bool wxNativeEncodingInfo::FromString(const wxString& WXUNUSED(s))
334 {
335 return false;
336 }
337
338 wxString wxNativeEncodingInfo::ToString() const
339 {
340 return wxEmptyString;
341 }
342
343 bool wxTestFontEncoding(const wxNativeEncodingInfo& WXUNUSED(info))
344 {
345 return true;
346 }
347
348 bool wxGetNativeFontEncoding(wxFontEncoding encoding,
349 wxNativeEncodingInfo *info)
350 {
351 // all encodings are available in GTK+ 2 because we translate text in any
352 // encoding to UTF-8 internally anyhow
353 info->facename.clear();
354 info->encoding = encoding;
355
356 return true;
357 }
358
359 #else // GTK+ 1.x
360
361 #ifdef __X__
362 #ifdef __VMS__
363 #pragma message disable nosimpint
364 #endif
365
366 #include <X11/Xlib.h>
367
368 #ifdef __VMS__
369 #pragma message enable nosimpint
370 #endif
371
372 #elif defined(__WXGTK__)
373 // we have to declare struct tm to avoid problems with first forward
374 // declaring it in C code (glib.h included from gdk.h does it) and then
375 // defining it when time.h is included from the headers below - this is
376 // known not to work at least with Sun CC 6.01
377 #include <time.h>
378
379 #include <gdk/gdk.h>
380 #endif
381
382
383 // ----------------------------------------------------------------------------
384 // private data
385 // ----------------------------------------------------------------------------
386
387 static wxHashTable *g_fontHash = (wxHashTable*) NULL;
388
389 // ----------------------------------------------------------------------------
390 // private functions
391 // ----------------------------------------------------------------------------
392
393 // define the functions to create and destroy native fonts for this toolkit
394 #ifdef __X__
395 wxNativeFont wxLoadFont(const wxString& fontSpec)
396 {
397 return XLoadQueryFont((Display *)wxGetDisplay(), fontSpec);
398 }
399
400 inline void wxFreeFont(wxNativeFont font)
401 {
402 XFreeFont((Display *)wxGetDisplay(), (XFontStruct *)font);
403 }
404 #elif defined(__WXGTK__)
405 wxNativeFont wxLoadFont(const wxString& fontSpec)
406 {
407 // VZ: we should use gdk_fontset_load() instead of gdk_font_load()
408 // here to be able to display Japanese fonts correctly (at least
409 // this is what people report) but unfortunately doing it results
410 // in tons of warnings when using GTK with "normal" European
411 // languages and so we can't always do it and I don't know enough
412 // to determine when should this be done... (FIXME)
413 return gdk_font_load( wxConvertWX2MB(fontSpec) );
414 }
415
416 inline void wxFreeFont(wxNativeFont font)
417 {
418 gdk_font_unref(font);
419 }
420 #else
421 #error "Unknown GUI toolkit"
422 #endif
423
424 static bool wxTestFontSpec(const wxString& fontspec);
425
426 static wxNativeFont wxLoadQueryFont(int pointSize,
427 int family,
428 int style,
429 int weight,
430 bool underlined,
431 const wxString& facename,
432 const wxString& xregistry,
433 const wxString& xencoding,
434 wxString* xFontName);
435
436 // ============================================================================
437 // implementation
438 // ============================================================================
439
440 // ----------------------------------------------------------------------------
441 // wxNativeEncodingInfo
442 // ----------------------------------------------------------------------------
443
444 // convert to/from the string representation: format is
445 // encodingid;registry;encoding[;facename]
446 bool wxNativeEncodingInfo::FromString(const wxString& s)
447 {
448 // use ";", not "-" because it may be part of encoding name
449 wxStringTokenizer tokenizer(s, _T(";"));
450
451 wxString encid = tokenizer.GetNextToken();
452 long enc;
453 if ( !encid.ToLong(&enc) )
454 return false;
455 encoding = (wxFontEncoding)enc;
456
457 xregistry = tokenizer.GetNextToken();
458 if ( !xregistry )
459 return false;
460
461 xencoding = tokenizer.GetNextToken();
462 if ( !xencoding )
463 return false;
464
465 // ok even if empty
466 facename = tokenizer.GetNextToken();
467
468 return true;
469 }
470
471 wxString wxNativeEncodingInfo::ToString() const
472 {
473 wxString s;
474 s << (long)encoding << _T(';') << xregistry << _T(';') << xencoding;
475 if ( !facename.empty() )
476 {
477 s << _T(';') << facename;
478 }
479
480 return s;
481 }
482
483 // ----------------------------------------------------------------------------
484 // wxNativeFontInfo
485 // ----------------------------------------------------------------------------
486
487 void wxNativeFontInfo::Init()
488 {
489 m_isDefault = true;
490 }
491
492 bool wxNativeFontInfo::FromString(const wxString& s)
493 {
494 wxStringTokenizer tokenizer(s, _T(";"));
495
496 // check the version
497 wxString token = tokenizer.GetNextToken();
498 if ( token != _T('0') )
499 return false;
500
501 xFontName = tokenizer.GetNextToken();
502
503 // this should be the end
504 if ( tokenizer.HasMoreTokens() )
505 return false;
506
507 return FromXFontName(xFontName);
508 }
509
510 wxString wxNativeFontInfo::ToString() const
511 {
512 // 0 is the version
513 return wxString::Format(_T("%d;%s"), 0, GetXFontName().c_str());
514 }
515
516 bool wxNativeFontInfo::FromUserString(const wxString& s)
517 {
518 return FromXFontName(s);
519 }
520
521 wxString wxNativeFontInfo::ToUserString() const
522 {
523 return GetXFontName();
524 }
525
526 bool wxNativeFontInfo::HasElements() const
527 {
528 // we suppose that the foundry is never empty, so if it is it means that we
529 // had never parsed the XLFD
530 return !fontElements[0].empty();
531 }
532
533 wxString wxNativeFontInfo::GetXFontComponent(wxXLFDField field) const
534 {
535 wxCHECK_MSG( field < wxXLFD_MAX, wxEmptyString, _T("invalid XLFD field") );
536
537 if ( !HasElements() )
538 {
539 // const_cast
540 if ( !((wxNativeFontInfo *)this)->FromXFontName(xFontName) )
541 return wxEmptyString;
542 }
543
544 return fontElements[field];
545 }
546
547 bool wxNativeFontInfo::FromXFontName(const wxString& fontname)
548 {
549 // TODO: we should be able to handle the font aliases here, but how?
550 wxStringTokenizer tokenizer(fontname, _T("-"));
551
552 // skip the leading, usually empty field (font name registry)
553 if ( !tokenizer.HasMoreTokens() )
554 return false;
555
556 (void)tokenizer.GetNextToken();
557
558 for ( size_t n = 0; n < WXSIZEOF(fontElements); n++ )
559 {
560 if ( !tokenizer.HasMoreTokens() )
561 {
562 // not enough elements in the XLFD - or maybe an alias
563 return false;
564 }
565
566 wxString field = tokenizer.GetNextToken();
567 if ( !field.empty() && field != _T('*') )
568 {
569 // we're really initialized now
570 m_isDefault = false;
571 }
572
573 fontElements[n] = field;
574 }
575
576 // this should be all
577 if ( tokenizer.HasMoreTokens() )
578 return false;
579
580 return true;
581 }
582
583 wxString wxNativeFontInfo::GetXFontName() const
584 {
585 if ( xFontName.empty() )
586 {
587 for ( size_t n = 0; n < WXSIZEOF(fontElements); n++ )
588 {
589 // replace the non specified elements with '*' except for the
590 // additional style which is usually just omitted
591 wxString elt = fontElements[n];
592 if ( elt.empty() && n != wxXLFD_ADDSTYLE )
593 {
594 elt = _T('*');
595 }
596
597 // const_cast
598 ((wxNativeFontInfo *)this)->xFontName << _T('-') << elt;
599 }
600 }
601
602 return xFontName;
603 }
604
605 void
606 wxNativeFontInfo::SetXFontComponent(wxXLFDField field, const wxString& value)
607 {
608 wxCHECK_RET( field < wxXLFD_MAX, _T("invalid XLFD field") );
609
610 // this class should be initialized with a valid font spec first and only
611 // then the fields may be modified!
612 wxASSERT_MSG( !IsDefault(), _T("can't modify an uninitialized XLFD") );
613
614 if ( !HasElements() )
615 {
616 // const_cast
617 if ( !((wxNativeFontInfo *)this)->FromXFontName(xFontName) )
618 {
619 wxFAIL_MSG( _T("can't set font element for invalid XLFD") );
620
621 return;
622 }
623 }
624
625 fontElements[field] = value;
626
627 // invalidate the XFLD, it doesn't correspond to the font elements any more
628 xFontName.clear();
629 }
630
631 void wxNativeFontInfo::SetXFontName(const wxString& xFontName_)
632 {
633 // invalidate the font elements, GetXFontComponent() will reparse the XLFD
634 fontElements[0].clear();
635
636 xFontName = xFontName_;
637
638 m_isDefault = false;
639 }
640
641 int wxNativeFontInfo::GetPointSize() const
642 {
643 const wxString s = GetXFontComponent(wxXLFD_POINTSIZE);
644
645 // return -1 to indicate that the size is unknown
646 long l;
647 return s.ToLong(&l) ? l : -1;
648 }
649
650 wxFontStyle wxNativeFontInfo::GetStyle() const
651 {
652 const wxString s = GetXFontComponent(wxXLFD_SLANT);
653
654 if ( s.length() != 1 )
655 {
656 // it is really unknown but we don't have any way to return it from
657 // here
658 return wxFONTSTYLE_NORMAL;
659 }
660
661 switch ( s[0] )
662 {
663 default:
664 // again, unknown but consider normal by default
665
666 case _T('r'):
667 return wxFONTSTYLE_NORMAL;
668
669 case _T('i'):
670 return wxFONTSTYLE_ITALIC;
671
672 case _T('o'):
673 return wxFONTSTYLE_SLANT;
674 }
675 }
676
677 wxFontWeight wxNativeFontInfo::GetWeight() const
678 {
679 const wxString s = GetXFontComponent(wxXLFD_WEIGHT).MakeLower();
680 if ( s.find(_T("bold")) != wxString::npos || s == _T("black") )
681 return wxFONTWEIGHT_BOLD;
682 else if ( s == _T("light") )
683 return wxFONTWEIGHT_LIGHT;
684
685 return wxFONTWEIGHT_NORMAL;
686 }
687
688 bool wxNativeFontInfo::GetUnderlined() const
689 {
690 // X fonts are never underlined
691 return false;
692 }
693
694 wxString wxNativeFontInfo::GetFaceName() const
695 {
696 // wxWidgets facename probably more accurately corresponds to X family
697 return GetXFontComponent(wxXLFD_FAMILY);
698 }
699
700 wxFontFamily wxNativeFontInfo::GetFamily() const
701 {
702 // and wxWidgets family -- to X foundry, but we have to translate it to
703 // wxFontFamily somehow...
704 wxFAIL_MSG(_T("not implemented")); // GetXFontComponent(wxXLFD_FOUNDRY);
705
706 return wxFONTFAMILY_DEFAULT;
707 }
708
709 wxFontEncoding wxNativeFontInfo::GetEncoding() const
710 {
711 // we already have the code for this but need to refactor it first
712 wxFAIL_MSG( _T("not implemented") );
713
714 return wxFONTENCODING_MAX;
715 }
716
717 void wxNativeFontInfo::SetPointSize(int pointsize)
718 {
719 SetXFontComponent(wxXLFD_POINTSIZE, wxString::Format(_T("%d"), pointsize));
720 }
721
722 void wxNativeFontInfo::SetStyle(wxFontStyle style)
723 {
724 wxString s;
725 switch ( style )
726 {
727 case wxFONTSTYLE_ITALIC:
728 s = _T('i');
729 break;
730
731 case wxFONTSTYLE_SLANT:
732 s = _T('o');
733 break;
734
735 case wxFONTSTYLE_NORMAL:
736 s = _T('r');
737
738 default:
739 wxFAIL_MSG( _T("unknown wxFontStyle in wxNativeFontInfo::SetStyle") );
740 return;
741 }
742
743 SetXFontComponent(wxXLFD_SLANT, s);
744 }
745
746 void wxNativeFontInfo::SetWeight(wxFontWeight weight)
747 {
748 wxString s;
749 switch ( weight )
750 {
751 case wxFONTWEIGHT_BOLD:
752 s = _T("bold");
753 break;
754
755 case wxFONTWEIGHT_LIGHT:
756 s = _T("light");
757 break;
758
759 case wxFONTWEIGHT_NORMAL:
760 s = _T("medium");
761 break;
762
763 default:
764 wxFAIL_MSG( _T("unknown wxFontWeight in wxNativeFontInfo::SetWeight") );
765 return;
766 }
767
768 SetXFontComponent(wxXLFD_WEIGHT, s);
769 }
770
771 void wxNativeFontInfo::SetUnderlined(bool WXUNUSED(underlined))
772 {
773 // can't do this under X
774 }
775
776 void wxNativeFontInfo::SetFaceName(const wxString& facename)
777 {
778 SetXFontComponent(wxXLFD_FAMILY, facename);
779 }
780
781 void wxNativeFontInfo::SetFamily(wxFontFamily WXUNUSED(family))
782 {
783 // wxFontFamily -> X foundry, anyone?
784 wxFAIL_MSG( _T("not implemented") );
785
786 // SetXFontComponent(wxXLFD_FOUNDRY, ...);
787 }
788
789 void wxNativeFontInfo::SetEncoding(wxFontEncoding encoding)
790 {
791 wxNativeEncodingInfo info;
792 if ( wxGetNativeFontEncoding(encoding, &info) )
793 {
794 SetXFontComponent(wxXLFD_ENCODING, info.xencoding);
795 SetXFontComponent(wxXLFD_REGISTRY, info.xregistry);
796 }
797 }
798
799 // ----------------------------------------------------------------------------
800 // common functions
801 // ----------------------------------------------------------------------------
802
803 bool wxGetNativeFontEncoding(wxFontEncoding encoding,
804 wxNativeEncodingInfo *info)
805 {
806 wxCHECK_MSG( info, false, _T("bad pointer in wxGetNativeFontEncoding") );
807
808 if ( encoding == wxFONTENCODING_DEFAULT )
809 {
810 encoding = wxFont::GetDefaultEncoding();
811 }
812
813 switch ( encoding )
814 {
815 case wxFONTENCODING_ISO8859_1:
816 case wxFONTENCODING_ISO8859_2:
817 case wxFONTENCODING_ISO8859_3:
818 case wxFONTENCODING_ISO8859_4:
819 case wxFONTENCODING_ISO8859_5:
820 case wxFONTENCODING_ISO8859_6:
821 case wxFONTENCODING_ISO8859_7:
822 case wxFONTENCODING_ISO8859_8:
823 case wxFONTENCODING_ISO8859_9:
824 case wxFONTENCODING_ISO8859_10:
825 case wxFONTENCODING_ISO8859_11:
826 case wxFONTENCODING_ISO8859_12:
827 case wxFONTENCODING_ISO8859_13:
828 case wxFONTENCODING_ISO8859_14:
829 case wxFONTENCODING_ISO8859_15:
830 {
831 int cp = encoding - wxFONTENCODING_ISO8859_1 + 1;
832 info->xregistry = wxT("iso8859");
833 info->xencoding.Printf(wxT("%d"), cp);
834 }
835 break;
836
837 case wxFONTENCODING_UTF8:
838 info->xregistry = wxT("iso10646");
839 info->xencoding = wxT("*");
840 break;
841
842 case wxFONTENCODING_GB2312:
843 info->xregistry = wxT("GB2312"); // or the otherway round?
844 info->xencoding = wxT("*");
845 break;
846
847 case wxFONTENCODING_KOI8:
848 case wxFONTENCODING_KOI8_U:
849 info->xregistry = wxT("koi8");
850
851 // we don't make distinction between koi8-r, koi8-u and koi8-ru (so far)
852 info->xencoding = wxT("*");
853 break;
854
855 case wxFONTENCODING_CP1250:
856 case wxFONTENCODING_CP1251:
857 case wxFONTENCODING_CP1252:
858 case wxFONTENCODING_CP1253:
859 case wxFONTENCODING_CP1254:
860 case wxFONTENCODING_CP1255:
861 case wxFONTENCODING_CP1256:
862 case wxFONTENCODING_CP1257:
863 {
864 int cp = encoding - wxFONTENCODING_CP1250 + 1250;
865 info->xregistry = wxT("microsoft");
866 info->xencoding.Printf(wxT("cp%d"), cp);
867 }
868 break;
869
870 case wxFONTENCODING_EUC_JP:
871 case wxFONTENCODING_SHIFT_JIS:
872 info->xregistry = "jis*";
873 info->xencoding = "*";
874 break;
875
876 case wxFONTENCODING_SYSTEM:
877 info->xregistry =
878 info->xencoding = wxT("*");
879 break;
880
881 default:
882 // don't know how to translate this encoding into X fontspec
883 return false;
884 }
885
886 info->encoding = encoding;
887
888 return true;
889 }
890
891 bool wxTestFontEncoding(const wxNativeEncodingInfo& info)
892 {
893 wxString fontspec;
894 fontspec.Printf(_T("-*-%s-*-*-*-*-*-*-*-*-*-*-%s-%s"),
895 !info.facename ? _T("*") : info.facename.c_str(),
896 info.xregistry.c_str(),
897 info.xencoding.c_str());
898
899 return wxTestFontSpec(fontspec);
900 }
901
902 // ----------------------------------------------------------------------------
903 // X-specific functions
904 // ----------------------------------------------------------------------------
905
906 wxNativeFont wxLoadQueryNearestFont(int pointSize,
907 int family,
908 int style,
909 int weight,
910 bool underlined,
911 const wxString &facename,
912 wxFontEncoding encoding,
913 wxString* xFontName)
914 {
915 if ( encoding == wxFONTENCODING_DEFAULT )
916 {
917 encoding = wxFont::GetDefaultEncoding();
918 }
919
920 // first determine the encoding - if the font doesn't exist at all in this
921 // encoding, it's useless to do all other approximations (i.e. size,
922 // family &c don't matter much)
923 wxNativeEncodingInfo info;
924 if ( encoding == wxFONTENCODING_SYSTEM )
925 {
926 // This will always work so we don't test to save time
927 wxGetNativeFontEncoding(wxFONTENCODING_SYSTEM, &info);
928 }
929 else
930 {
931 if ( !wxGetNativeFontEncoding(encoding, &info) ||
932 !wxTestFontEncoding(info) )
933 {
934 #if wxUSE_FONTMAP
935 if ( !wxFontMapper::Get()->GetAltForEncoding(encoding, &info) )
936 #endif // wxUSE_FONTMAP
937 {
938 // unspported encoding - replace it with the default
939 //
940 // NB: we can't just return 0 from here because wxGTK code doesn't
941 // check for it (i.e. it supposes that we'll always succeed),
942 // so it would provoke a crash
943 wxGetNativeFontEncoding(wxFONTENCODING_SYSTEM, &info);
944 }
945 }
946 }
947
948 // OK, we have the correct xregistry/xencoding in info structure
949 wxNativeFont font = 0;
950
951 // if we already have the X font name, try to use it
952 if( xFontName && !xFontName->empty() )
953 {
954 //
955 // Make sure point size is correct for scale factor.
956 //
957 wxStringTokenizer tokenizer(*xFontName, _T("-"), wxTOKEN_RET_DELIMS);
958 wxString newFontName;
959
960 for(int i = 0; i < 8; i++)
961 newFontName += tokenizer.NextToken();
962
963 (void) tokenizer.NextToken();
964
965 newFontName += wxString::Format(wxT("%d-"), pointSize);
966
967 while(tokenizer.HasMoreTokens())
968 newFontName += tokenizer.GetNextToken();
969
970 font = wxLoadFont(newFontName);
971
972 if(font)
973 *xFontName = newFontName;
974 }
975
976 if ( !font )
977 {
978 // search up and down by stepsize 10
979 int max_size = pointSize + 20 * (1 + (pointSize/180));
980 int min_size = pointSize - 20 * (1 + (pointSize/180));
981
982 int i, round; // counters
983
984 // first round: search for equal, then for smaller and for larger size with the given weight and style
985 int testweight = weight;
986 int teststyle = style;
987
988 for ( round = 0; round < 3; round++ )
989 {
990 // second round: use normal weight
991 if ( round == 1 )
992 {
993 if ( testweight != wxNORMAL )
994 {
995 testweight = wxNORMAL;
996 }
997 else
998 {
999 ++round; // fall through to third round
1000 }
1001 }
1002
1003 // third round: ... and use normal style
1004 if ( round == 2 )
1005 {
1006 if ( teststyle != wxNORMAL )
1007 {
1008 teststyle = wxNORMAL;
1009 }
1010 else
1011 {
1012 break;
1013 }
1014 }
1015 // Search for equal or smaller size (approx.)
1016 for ( i = pointSize; !font && i >= 10 && i >= min_size; i -= 10 )
1017 {
1018 font = wxLoadQueryFont(i, family, teststyle, testweight, underlined,
1019 facename, info.xregistry, info.xencoding,
1020 xFontName);
1021 }
1022
1023 // Search for larger size (approx.)
1024 for ( i = pointSize + 10; !font && i <= max_size; i += 10 )
1025 {
1026 font = wxLoadQueryFont(i, family, teststyle, testweight, underlined,
1027 facename, info.xregistry, info.xencoding,
1028 xFontName);
1029 }
1030 }
1031
1032 // Try default family
1033 if ( !font && family != wxDEFAULT )
1034 {
1035 font = wxLoadQueryFont(pointSize, wxDEFAULT, style, weight,
1036 underlined, facename,
1037 info.xregistry, info.xencoding,
1038 xFontName );
1039 }
1040
1041 // ignore size, family, style and weight but try to find font with the
1042 // given facename and encoding
1043 if ( !font )
1044 {
1045 font = wxLoadQueryFont(120, wxDEFAULT, wxNORMAL, wxNORMAL,
1046 underlined, facename,
1047 info.xregistry, info.xencoding,
1048 xFontName);
1049
1050 // ignore family as well
1051 if ( !font )
1052 {
1053 font = wxLoadQueryFont(120, wxDEFAULT, wxNORMAL, wxNORMAL,
1054 underlined, wxEmptyString,
1055 info.xregistry, info.xencoding,
1056 xFontName);
1057
1058 // if it still failed, try to get the font of any size but
1059 // with the requested encoding: this can happen if the
1060 // encoding is only available in one size which happens to be
1061 // different from 120
1062 if ( !font )
1063 {
1064 font = wxLoadQueryFont(-1, wxDEFAULT, wxNORMAL, wxNORMAL,
1065 false, wxEmptyString,
1066 info.xregistry, info.xencoding,
1067 xFontName);
1068
1069 // this should never happen as we had tested for it in the
1070 // very beginning, but if it does, do return something non
1071 // NULL or we'd crash in wxFont code
1072 if ( !font )
1073 {
1074 wxFAIL_MSG( _T("this encoding should be available!") );
1075
1076 font = wxLoadQueryFont(-1,
1077 wxDEFAULT, wxNORMAL, wxNORMAL,
1078 false, wxEmptyString,
1079 _T("*"), _T("*"),
1080 xFontName);
1081 }
1082 }
1083 }
1084 }
1085 }
1086
1087 return font;
1088 }
1089
1090 // ----------------------------------------------------------------------------
1091 // private functions
1092 // ----------------------------------------------------------------------------
1093
1094 // returns true if there are any fonts matching this font spec
1095 static bool wxTestFontSpec(const wxString& fontspec)
1096 {
1097 // some X servers will fail to load this font because there are too many
1098 // matches so we must test explicitly for this
1099 if ( fontspec == _T("-*-*-*-*-*-*-*-*-*-*-*-*-*-*") )
1100 {
1101 return true;
1102 }
1103
1104 wxNativeFont test = (wxNativeFont) g_fontHash->Get( fontspec );
1105 if (test)
1106 {
1107 return true;
1108 }
1109
1110 test = wxLoadFont(fontspec);
1111 g_fontHash->Put( fontspec, (wxObject*) test );
1112
1113 if ( test )
1114 {
1115 wxFreeFont(test);
1116
1117 return true;
1118 }
1119 else
1120 {
1121 return false;
1122 }
1123 }
1124
1125 static wxNativeFont wxLoadQueryFont(int pointSize,
1126 int family,
1127 int style,
1128 int weight,
1129 bool WXUNUSED(underlined),
1130 const wxString& facename,
1131 const wxString& xregistry,
1132 const wxString& xencoding,
1133 wxString* xFontName)
1134 {
1135 wxString xfamily;
1136 switch (family)
1137 {
1138 case wxDECORATIVE: xfamily = wxT("lucida"); break;
1139 case wxROMAN: xfamily = wxT("times"); break;
1140 case wxMODERN: xfamily = wxT("courier"); break;
1141 case wxSWISS: xfamily = wxT("helvetica"); break;
1142 case wxTELETYPE: xfamily = wxT("lucidatypewriter"); break;
1143 case wxSCRIPT: xfamily = wxT("utopia"); break;
1144 default: xfamily = wxT("*");
1145 }
1146 #if wxUSE_NANOX
1147 int xweight;
1148 switch (weight)
1149 {
1150 case wxBOLD:
1151 {
1152 xweight = MWLF_WEIGHT_BOLD;
1153 break;
1154 }
1155 case wxLIGHT:
1156 {
1157 xweight = MWLF_WEIGHT_LIGHT;
1158 break;
1159 }
1160 case wxNORMAL:
1161 {
1162 xweight = MWLF_WEIGHT_NORMAL;
1163 break;
1164 }
1165
1166 default:
1167 {
1168 xweight = MWLF_WEIGHT_DEFAULT;
1169 break;
1170 }
1171 }
1172 GR_SCREEN_INFO screenInfo;
1173 GrGetScreenInfo(& screenInfo);
1174
1175 int yPixelsPerCM = screenInfo.ydpcm;
1176
1177 // A point is 1/72 of an inch.
1178 // An inch is 2.541 cm.
1179 // So pixelHeight = (pointSize / 72) (inches) * 2.541 (for cm) * yPixelsPerCM (for pixels)
1180 // In fact pointSize is 10 * the normal point size so
1181 // divide by 10.
1182
1183 int pixelHeight = (int) ( (((float)pointSize) / 720.0) * 2.541 * (float) yPixelsPerCM) ;
1184
1185 // An alternative: assume that the screen is 72 dpi.
1186 //int pixelHeight = (int) (((float)pointSize / 720.0) * 72.0) ;
1187 //int pixelHeight = (int) ((float)pointSize / 10.0) ;
1188
1189 GR_LOGFONT logFont;
1190 logFont.lfHeight = pixelHeight;
1191 logFont.lfWidth = 0;
1192 logFont.lfEscapement = 0;
1193 logFont.lfOrientation = 0;
1194 logFont.lfWeight = xweight;
1195 logFont.lfItalic = (style == wxNORMAL ? 0 : 1) ;
1196 logFont.lfUnderline = 0;
1197 logFont.lfStrikeOut = 0;
1198 logFont.lfCharSet = MWLF_CHARSET_DEFAULT; // TODO: select appropriate one
1199 logFont.lfOutPrecision = MWLF_TYPE_DEFAULT;
1200 logFont.lfClipPrecision = 0; // Not used
1201 logFont.lfRoman = (family == wxROMAN ? 1 : 0) ;
1202 logFont.lfSerif = (family == wxSWISS ? 0 : 1) ;
1203 logFont.lfSansSerif = !logFont.lfSerif ;
1204 logFont.lfModern = (family == wxMODERN ? 1 : 0) ;
1205 logFont.lfProportional = (family == wxTELETYPE ? 0 : 1) ;
1206 logFont.lfOblique = 0;
1207 logFont.lfSmallCaps = 0;
1208 logFont.lfPitch = 0; // 0 = default
1209 strcpy(logFont.lfFaceName, facename.c_str());
1210
1211 XFontStruct* fontInfo = (XFontStruct*) malloc(sizeof(XFontStruct));
1212 fontInfo->fid = GrCreateFont((GR_CHAR*) facename.c_str(), pixelHeight, & logFont);
1213 GrGetFontInfo(fontInfo->fid, & fontInfo->info);
1214 return (wxNativeFont) fontInfo;
1215
1216 #else
1217 wxString fontSpec;
1218 if (!facename.empty())
1219 {
1220 fontSpec.Printf(wxT("-*-%s-*-*-normal-*-*-*-*-*-*-*-*-*"),
1221 facename.c_str());
1222
1223 if ( wxTestFontSpec(fontSpec) )
1224 {
1225 xfamily = facename;
1226 }
1227 //else: no such family, use default one instead
1228 }
1229
1230 wxString xstyle;
1231 switch (style)
1232 {
1233 case wxSLANT:
1234 fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
1235 xfamily.c_str());
1236 if ( wxTestFontSpec(fontSpec) )
1237 {
1238 xstyle = wxT("o");
1239 break;
1240 }
1241 // fall through - try wxITALIC now
1242
1243 case wxITALIC:
1244 fontSpec.Printf(wxT("-*-%s-*-i-*-*-*-*-*-*-*-*-*-*"),
1245 xfamily.c_str());
1246 if ( wxTestFontSpec(fontSpec) )
1247 {
1248 xstyle = wxT("i");
1249 }
1250 else if ( style == wxITALIC ) // and not wxSLANT
1251 {
1252 // try wxSLANT
1253 fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
1254 xfamily.c_str());
1255 if ( wxTestFontSpec(fontSpec) )
1256 {
1257 xstyle = wxT("o");
1258 }
1259 else
1260 {
1261 // no italic, no slant - leave default
1262 xstyle = wxT("*");
1263 }
1264 }
1265 break;
1266
1267 default:
1268 wxFAIL_MSG(_T("unknown font style"));
1269 // fall back to normal
1270
1271 case wxNORMAL:
1272 xstyle = wxT("r");
1273 break;
1274 }
1275
1276 wxString xweight;
1277 switch (weight)
1278 {
1279 case wxBOLD:
1280 {
1281 fontSpec.Printf(wxT("-*-%s-bold-*-*-*-*-*-*-*-*-*-*-*"),
1282 xfamily.c_str());
1283 if ( wxTestFontSpec(fontSpec) )
1284 {
1285 xweight = wxT("bold");
1286 break;
1287 }
1288 fontSpec.Printf(wxT("-*-%s-heavy-*-*-*-*-*-*-*-*-*-*-*"),
1289 xfamily.c_str());
1290 if ( wxTestFontSpec(fontSpec) )
1291 {
1292 xweight = wxT("heavy");
1293 break;
1294 }
1295 fontSpec.Printf(wxT("-*-%s-extrabold-*-*-*-*-*-*-*-*-*-*-*"),
1296 xfamily.c_str());
1297 if ( wxTestFontSpec(fontSpec) )
1298 {
1299 xweight = wxT("extrabold");
1300 break;
1301 }
1302 fontSpec.Printf(wxT("-*-%s-demibold-*-*-*-*-*-*-*-*-*-*-*"),
1303 xfamily.c_str());
1304 if ( wxTestFontSpec(fontSpec) )
1305 {
1306 xweight = wxT("demibold");
1307 break;
1308 }
1309 fontSpec.Printf(wxT("-*-%s-black-*-*-*-*-*-*-*-*-*-*-*"),
1310 xfamily.c_str());
1311 if ( wxTestFontSpec(fontSpec) )
1312 {
1313 xweight = wxT("black");
1314 break;
1315 }
1316 fontSpec.Printf(wxT("-*-%s-ultrablack-*-*-*-*-*-*-*-*-*-*-*"),
1317 xfamily.c_str());
1318 if ( wxTestFontSpec(fontSpec) )
1319 {
1320 xweight = wxT("ultrablack");
1321 break;
1322 }
1323 }
1324 break;
1325 case wxLIGHT:
1326 {
1327 fontSpec.Printf(wxT("-*-%s-light-*-*-*-*-*-*-*-*-*-*-*"),
1328 xfamily.c_str());
1329 if ( wxTestFontSpec(fontSpec) )
1330 {
1331 xweight = wxT("light");
1332 break;
1333 }
1334 fontSpec.Printf(wxT("-*-%s-thin-*-*-*-*-*-*-*-*-*-*-*"),
1335 xfamily.c_str());
1336 if ( wxTestFontSpec(fontSpec) )
1337 {
1338 xweight = wxT("thin");
1339 break;
1340 }
1341 }
1342 break;
1343 case wxNORMAL:
1344 {
1345 fontSpec.Printf(wxT("-*-%s-medium-*-*-*-*-*-*-*-*-*-*-*"),
1346 xfamily.c_str());
1347 if ( wxTestFontSpec(fontSpec) )
1348 {
1349 xweight = wxT("medium");
1350 break;
1351 }
1352 fontSpec.Printf(wxT("-*-%s-normal-*-*-*-*-*-*-*-*-*-*-*"),
1353 xfamily.c_str());
1354 if ( wxTestFontSpec(fontSpec) )
1355 {
1356 xweight = wxT("normal");
1357 break;
1358 }
1359 fontSpec.Printf(wxT("-*-%s-regular-*-*-*-*-*-*-*-*-*-*-*"),
1360 xfamily.c_str());
1361 if ( wxTestFontSpec(fontSpec) )
1362 {
1363 xweight = wxT("regular");
1364 break;
1365 }
1366 xweight = wxT("*");
1367 }
1368 break;
1369 default: xweight = wxT("*"); break;
1370 }
1371
1372 // if pointSize is -1, don't specify any
1373 wxString sizeSpec;
1374 if ( pointSize == -1 )
1375 {
1376 sizeSpec = _T('*');
1377 }
1378 else
1379 {
1380 sizeSpec.Printf(_T("%d"), pointSize);
1381 }
1382
1383 // construct the X font spec from our data
1384 fontSpec.Printf(wxT("-*-%s-%s-%s-normal-*-*-%s-*-*-*-*-%s-%s"),
1385 xfamily.c_str(), xweight.c_str(), xstyle.c_str(),
1386 sizeSpec.c_str(), xregistry.c_str(), xencoding.c_str());
1387
1388 if( xFontName )
1389 *xFontName = fontSpec;
1390
1391 return wxLoadFont(fontSpec);
1392 #endif
1393 // wxUSE_NANOX
1394 }
1395
1396 // ----------------------------------------------------------------------------
1397 // wxFontModule
1398 // ----------------------------------------------------------------------------
1399
1400 class wxFontModule : public wxModule
1401 {
1402 public:
1403 bool OnInit();
1404 void OnExit();
1405
1406 private:
1407 DECLARE_DYNAMIC_CLASS(wxFontModule)
1408 };
1409
1410 IMPLEMENT_DYNAMIC_CLASS(wxFontModule, wxModule)
1411
1412 bool wxFontModule::OnInit()
1413 {
1414 g_fontHash = new wxHashTable( wxKEY_STRING );
1415
1416 return true;
1417 }
1418
1419 void wxFontModule::OnExit()
1420 {
1421 delete g_fontHash;
1422
1423 g_fontHash = (wxHashTable *)NULL;
1424 }
1425
1426 #endif // GTK 2.0/1.x