1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
use std::ffi::{CString, CStr};
use std::os::raw::{c_int, c_long};
use std::path::Path;
use std::error;
use std::error::Error;
use std::ffi::NulError;
use std::fmt;
use sdl2::surface::Surface;
use sdl2_sys::surface::SDL_Surface;
use sdl2::get_error;
use sdl2::pixels;
use sdl2::pixels::Color;
use sdl2_sys::pixels::SDL_Color;
use ffi;
#[inline]
fn color_to_c_color(color: Color) -> SDL_Color {
match color {
pixels::Color::RGB(r, g, b) => SDL_Color { r: r, g: g, b: b, a: 255 },
pixels::Color::RGBA(r, g, b, a) => SDL_Color { r: r, g: g, b: b, a: a }
}
}
bitflags! {
pub flags FontStyle: ::std::os::raw::c_int {
const STYLE_NORMAL = ::ffi::TTF_STYLE_NORMAL,
const STYLE_BOLD = ::ffi::TTF_STYLE_BOLD,
const STYLE_ITALIC = ::ffi::TTF_STYLE_ITALIC,
const STYLE_UNDERLINE = ::ffi::TTF_STYLE_UNDERLINE,
const STYLE_STRIKETHROUGH = ::ffi::TTF_STYLE_STRIKETHROUGH,
}
}
#[derive(Debug, PartialEq, Clone)]
pub enum Hinting {
Normal = ffi::TTF_HINTING_NORMAL as isize,
Light = ffi::TTF_HINTING_LIGHT as isize,
Mono = ffi::TTF_HINTING_MONO as isize,
None = ffi::TTF_HINTING_NONE as isize
}
#[derive(Debug, PartialEq, Clone)]
pub struct GlyphMetrics {
pub minx: i32,
pub maxx: i32,
pub miny: i32,
pub maxy: i32,
pub advance: i32
}
pub type FontResult<T> = Result<T, FontError>;
#[derive(Debug)]
pub enum FontError {
InvalidLatin1Text(NulError),
SdlError(String),
}
impl error::Error for FontError {
fn description(&self) -> &str {
match *self {
FontError::InvalidLatin1Text(ref error) => {
error.description()
},
FontError::SdlError(ref message) => {
message
},
}
}
fn cause(&self) -> Option<&error::Error> {
match *self {
FontError::InvalidLatin1Text(ref error) => {
Some(error)
},
FontError::SdlError(_) => {
None
},
}
}
}
impl fmt::Display for FontError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
match *self {
FontError::InvalidLatin1Text(ref err) => {
write!(f, "Invalid Latin-1 bytes: {}", err.description())
},
FontError::SdlError(ref msg) => {
write!(f, "SDL2 error: {}", msg)
},
}
}
}
enum RenderableText<'a> {
Utf8(&'a str),
Latin1(&'a [u8]),
Char(String),
}
impl<'a> RenderableText<'a> {
fn convert(&self) -> FontResult<CString> {
match *self {
RenderableText::Utf8(text) => {
Ok(CString::new(text).unwrap())
},
RenderableText::Latin1(bytes) => {
match CString::new(bytes) {
Err(err) => {
Err(FontError::InvalidLatin1Text(err))
},
Ok(cstring) => {
Ok(cstring)
}
}
},
RenderableText::Char(ref string) => {
Ok(CString::new(string.as_bytes()).unwrap())
}
}
}
}
#[must_use]
pub struct PartialRendering<'a> {
text: RenderableText<'a>,
font: &'a Font,
}
fn convert_to_surface<'a>(raw: *mut SDL_Surface) -> FontResult<Surface<'a>> {
if (raw as *mut ()).is_null() {
Err(FontError::SdlError(get_error()))
} else {
Ok(unsafe {
Surface::from_ll(raw)
})
}
}
impl<'a> PartialRendering<'a> {
pub fn solid<'b, T>(self, color: T )
-> FontResult<Surface<'b>> where T: Into<Color> {
let source = try!(self.text.convert());
let color = color_to_c_color(color.into());
let raw = unsafe {
match self.text {
RenderableText::Utf8(_) | RenderableText::Char(_) => {
ffi::TTF_RenderUTF8_Solid(self.font.raw(),
source.as_ptr(), color)
},
RenderableText::Latin1(_) => {
ffi::TTF_RenderText_Solid(self.font.raw(),
source.as_ptr(), color)
},
}
};
convert_to_surface(raw)
}
pub fn shaded<'b, T>(self, color: T, background: T)
-> FontResult<Surface<'b>> where T: Into<Color> {
let source = try!(self.text.convert());
let foreground = color_to_c_color(color.into());
let background = color_to_c_color(background.into());
let raw = unsafe {
match self.text {
RenderableText::Utf8(_) | RenderableText::Char(_) => {
ffi::TTF_RenderUTF8_Shaded(self.font.raw(),
source.as_ptr(), foreground, background)
},
RenderableText::Latin1(_) => {
ffi::TTF_RenderText_Shaded(self.font.raw(),
source.as_ptr(), foreground, background)
},
}
};
convert_to_surface(raw)
}
pub fn blended<'b, T>(self, color: T)
-> FontResult<Surface<'b>> where T: Into<Color> {
let source = try!(self.text.convert());
let color = color_to_c_color(color.into());
let raw = unsafe {
match self.text {
RenderableText::Utf8(_) | RenderableText::Char(_) => {
ffi::TTF_RenderUTF8_Blended(self.font.raw(),
source.as_ptr(), color)
},
RenderableText::Latin1(_) => {
ffi::TTF_RenderText_Blended(self.font.raw(),
source.as_ptr(), color)
},
}
};
convert_to_surface(raw)
}
pub fn blended_wrapped<'b, T>(self, color: T, wrap_max_width: u32)
-> FontResult<Surface<'b>> where T: Into<Color> {
let source = try!(self.text.convert());
let color = color_to_c_color(color.into());
let raw = unsafe {
match self.text {
RenderableText::Utf8(_) | RenderableText::Char(_) => {
ffi::TTF_RenderUTF8_Blended_Wrapped(self.font.raw(),
source.as_ptr(), color, wrap_max_width)
},
RenderableText::Latin1(_) => {
ffi::TTF_RenderText_Blended_Wrapped(self.font.raw(),
source.as_ptr(), color, wrap_max_width)
},
}
};
convert_to_surface(raw)
}
}
#[derive(PartialEq)]
pub struct Font {
raw: *const ffi::TTF_Font,
owned: bool
}
impl Drop for Font {
fn drop(&mut self) {
if self.owned {
unsafe {
if ffi::TTF_WasInit() == 1 {
ffi::TTF_CloseFont(self.raw);
}
}
}
}
}
pub fn internal_load_font(path: &Path, ptsize: u16) -> Result<Font, String> {
unsafe {
let cstring = CString::new(path.to_str().unwrap()).unwrap();
let raw = ffi::TTF_OpenFont(cstring.as_ptr(), ptsize as c_int);
if raw.is_null() {
Err(get_error())
} else {
Ok(Font { raw: raw, owned: true })
}
}
}
pub fn internal_load_font_from_ll(raw: *const ffi::TTF_Font, owned: bool)
-> Font {
Font { raw: raw, owned: owned }
}
pub fn internal_load_font_at_index(path: &Path, index: u32, ptsize: u16)
-> Result<Font, String> {
unsafe {
let cstring = CString::new(path.to_str().unwrap().as_bytes())
.unwrap();
let raw = ffi::TTF_OpenFontIndex(cstring.as_ptr(),
ptsize as c_int, index as c_long);
if raw.is_null() {
Err(get_error())
} else {
Ok(Font { raw: raw, owned: true })
}
}
}
impl Font {
unsafe fn raw(&self) -> *const ffi::TTF_Font {
self.raw
}
pub fn render<'a>(&'a self, text: &'a str) -> PartialRendering<'a> {
PartialRendering {
text: RenderableText::Utf8(text),
font: self,
}
}
pub fn render_latin1<'a>(&'a self, text: &'a [u8]) -> PartialRendering<'a> {
PartialRendering {
text: RenderableText::Latin1(text),
font: self,
}
}
pub fn render_char(&self, ch: char) -> PartialRendering {
let mut s = String::new();
s.push(ch);
PartialRendering {
text: RenderableText::Char(s),
font: self,
}
}
#[allow(unused_mut)]
pub fn size_of(&self, text: &str) -> FontResult<(u32, u32)> {
let c_string = try!(RenderableText::Utf8(text).convert());
let (res, size) = unsafe {
let mut w = 0;
let mut h = 0;
let ret = ffi::TTF_SizeUTF8(self.raw, c_string.as_ptr(), &w, &h);
(ret, (w as u32, h as u32))
};
if res == 0 {
Ok(size)
} else {
Err(FontError::SdlError(get_error()))
}
}
#[allow(unused_mut)]
pub fn size_of_latin1(&self, text: &[u8])
-> FontResult<(u32, u32)> {
let c_string = try!(RenderableText::Latin1(text).convert());
let (res, size) = unsafe {
let mut w = 0;
let mut h = 0;
let ret = ffi::TTF_SizeText(self.raw, c_string.as_ptr(), &w, &h);
(ret, (w as u32, h as u32))
};
if res == 0 {
Ok(size)
} else {
Err(FontError::SdlError(get_error()))
}
}
pub fn size_of_char(&self, ch: char) -> FontResult<(u32, u32)> {
let mut s = String::new();
s.push(ch);
self.size_of(&s)
}
pub fn get_style(&self) -> FontStyle {
unsafe {
let raw = ffi::TTF_GetFontStyle(self.raw);
FontStyle::from_bits_truncate(raw)
}
}
pub fn set_style(&mut self, styles: FontStyle) {
unsafe {
ffi::TTF_SetFontStyle(self.raw, styles.bits())
}
}
pub fn get_outline_width(&self) -> u16 {
unsafe {
ffi::TTF_GetFontOutline(self.raw) as u16
}
}
pub fn set_outline_width(&mut self, width: u16) {
unsafe {
ffi::TTF_SetFontOutline(self.raw, width as c_int)
}
}
pub fn get_hinting(&self) -> Hinting {
unsafe {
match ffi::TTF_GetFontHinting(self.raw) as c_int {
ffi::TTF_HINTING_NORMAL => Hinting::Normal,
ffi::TTF_HINTING_LIGHT => Hinting::Light,
ffi::TTF_HINTING_MONO => Hinting::Mono,
ffi::TTF_HINTING_NONE | _ => Hinting::None
}
}
}
pub fn set_hinting(&mut self, hinting: Hinting) {
unsafe {
ffi::TTF_SetFontHinting(self.raw, hinting as c_int)
}
}
pub fn get_kerning(&self) -> bool {
unsafe {
ffi::TTF_GetFontKerning(self.raw) != 0
}
}
pub fn set_kerning(&mut self, kerning: bool) {
unsafe {
ffi::TTF_SetFontKerning(self.raw, kerning as c_int)
}
}
pub fn height(&self) -> i32 {
unsafe {
ffi::TTF_FontHeight(self.raw) as i32
}
}
pub fn ascent(&self) -> i32 {
unsafe {
ffi::TTF_FontAscent(self.raw) as i32
}
}
pub fn descent(&self) -> i32 {
unsafe {
ffi::TTF_FontDescent(self.raw) as i32
}
}
pub fn recommended_line_spacing(&self) -> i32 {
unsafe {
ffi::TTF_FontLineSkip(self.raw) as i32
}
}
pub fn face_count(&self) -> u16 {
unsafe {
ffi::TTF_FontFaces(self.raw) as u16
}
}
pub fn face_is_fixed_width(&self) -> bool {
unsafe {
ffi::TTF_FontFaceIsFixedWidth(self.raw) != 0
}
}
pub fn face_family_name(&self) -> Option<String> {
unsafe {
let cname = ffi::TTF_FontFaceFamilyName(self.raw);
if cname.is_null() {
None
} else {
Some(String::from_utf8_lossy(CStr::from_ptr(cname).to_bytes()).to_string())
}
}
}
pub fn face_style_name(&self) -> Option<String> {
unsafe {
let cname = ffi::TTF_FontFaceStyleName(self.raw);
if cname.is_null() {
None
} else {
Some(String::from_utf8_lossy(CStr::from_ptr(cname).to_bytes()).to_string())
}
}
}
pub fn find_glyph(&self, ch: char) -> Option<u16> {
unsafe {
let ret = ffi::TTF_GlyphIsProvided(self.raw, ch as u16);
if ret == 0 {
None
} else {
Some(ret as u16)
}
}
}
pub fn find_glyph_metrics(&self, ch: char) -> Option<GlyphMetrics> {
let minx = 0;
let maxx = 0;
let miny = 0;
let maxy = 0;
let advance = 0;
let ret = unsafe {
ffi::TTF_GlyphMetrics(
self.raw, ch as u16, &minx, &maxx, &miny, &maxy, &advance
)
};
if ret == 0 {
Some(GlyphMetrics {
minx: minx as i32, maxx: maxx as i32, miny: miny as i32,
maxy: maxy as i32, advance: advance as i32
} )
} else {
None
}
}
}