aboutsummaryrefslogtreecommitdiffstats
path: root/src/components/gfx/font_context.rs
blob: 2f8b514d127cec42acbadbdcd05dcda5628fc4f7 (plain) (blame)
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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

use font::{Font, FontDescriptor, FontGroup, FontHandleMethods, SelectorPlatformIdentifier};
use font::{SpecifiedFontStyle, UsedFontStyle};
use font_list::FontList;
use platform::font::FontHandle;
use platform::font_context::FontContextHandle;

use azure::azure_hl::BackendType;
use collections::hashmap::HashMap;
use servo_util::cache::{Cache, LRUCache};
use servo_util::time::ProfilerChan;

use std::rc::Rc;
use std::cell::RefCell;

/// Information needed to create a font context.
#[deriving(Clone)]
pub struct FontContextInfo {
    /// The painting backend we're using.
    pub backend: BackendType,

    /// Whether we need a font list.
    pub needs_font_list: bool,

    /// A channel up to the profiler.
    pub profiler_chan: ProfilerChan,
}

pub trait FontContextHandleMethods {
    fn create_font_from_identifier(&self, ~str, UsedFontStyle) -> Result<FontHandle, ()>;
}

pub struct FontContext {
    pub instance_cache: LRUCache<FontDescriptor, Rc<RefCell<Font>>>,
    pub font_list: Option<FontList>, // only needed by layout
    pub group_cache: LRUCache<SpecifiedFontStyle, Rc<RefCell<FontGroup>>>,
    pub handle: FontContextHandle,
    pub backend: BackendType,
    pub generic_fonts: HashMap<~str,~str>,
    pub profiler_chan: ProfilerChan,
}

impl FontContext {
    pub fn new(info: FontContextInfo) -> FontContext {
        let handle = FontContextHandle::new();
        let font_list = if info.needs_font_list {
            Some(FontList::new(&handle, info.profiler_chan.clone()))
        } else {
            None
        };

        // TODO: Allow users to specify these.
        let mut generic_fonts = HashMap::with_capacity(5);
        generic_fonts.insert(~"serif", ~"Times New Roman");
        generic_fonts.insert(~"sans-serif", ~"Arial");
        generic_fonts.insert(~"cursive", ~"Apple Chancery");
        generic_fonts.insert(~"fantasy", ~"Papyrus");
        generic_fonts.insert(~"monospace", ~"Menlo");

        FontContext {
            instance_cache: LRUCache::new(10),
            font_list: font_list,
            group_cache: LRUCache::new(10),
            handle: handle,
            backend: info.backend,
            generic_fonts: generic_fonts,
            profiler_chan: info.profiler_chan.clone(),
        }
    }

    pub fn get_resolved_font_for_style(&mut self, style: &SpecifiedFontStyle)
                                       -> Rc<RefCell<FontGroup>> {
        match self.group_cache.find(style) {
            Some(fg) => {
                debug!("font group cache hit");
                fg
            },
            None => {
                debug!("font group cache miss");
                let fg = self.create_font_group(style);
                self.group_cache.insert(style.clone(), fg.clone());
                fg
            }
        }
    }

    pub fn get_font_by_descriptor(&mut self, desc: &FontDescriptor)
                                  -> Result<Rc<RefCell<Font>>, ()> {
        match self.instance_cache.find(desc) {
            Some(f) => {
                debug!("font cache hit");
                Ok(f)
            },
            None => {
                debug!("font cache miss");
                let result = self.create_font_instance(desc);
                match result.clone() {
                    Ok(ref font) => {
                        self.instance_cache.insert(desc.clone(), font.clone());
                    }, _ => {}
                };
                result
            }
        }
    }

    fn transform_family(&self, family: &~str) -> ~str {
        debug!("(transform family) searching for `{:s}`", family.as_slice());
        match self.generic_fonts.find(family) {
            None => family.to_owned(),
            Some(mapped_family) => (*mapped_family).clone()
        }
    }

    fn create_font_group(&mut self, style: &SpecifiedFontStyle) -> Rc<RefCell<FontGroup>> {
        let mut fonts = ~[];

        debug!("(create font group) --- starting ---");

        // TODO(Issue #193): make iteration over 'font-family' more robust.
        for family in style.families.iter() {
            let transformed_family_name = self.transform_family(family);
            debug!("(create font group) transformed family is `{:s}`", transformed_family_name);
            let mut found = false;

            let result = match self.font_list {
                Some(ref mut fl) => {
                    let font_in_family = fl.find_font_in_family(&transformed_family_name, style);
                    match font_in_family {
                        Some(font_entry) => {
                            let font_id =
                                SelectorPlatformIdentifier(font_entry.handle.face_identifier());
                            let font_desc = FontDescriptor::new((*style).clone(), font_id);
                            Some(font_desc)
                        },
                        None => {
                            None
                        }
                    }
                }
                None => None,
            };

            match result {
                Some(ref result) => {
                    found = true;
                    let instance = self.get_font_by_descriptor(result);
                    let _ = instance.map(|font| fonts.push(font.clone()));
                },
                _ => {}
            }

            if !found {
                debug!("(create font group) didn't find `{:s}`", transformed_family_name);
            }
        }

        if fonts.len() == 0 {
            let last_resort = FontList::get_last_resort_font_families();
            for family in last_resort.iter() {
                let font_desc = match self.font_list {
                    Some(ref mut font_list) => {
                        let font_desc = {
                            let font_entry = font_list.find_font_in_family(family, style);
                            match font_entry {
                                Some(v) => {
                                    let font_id =
                                        SelectorPlatformIdentifier(v.handle.face_identifier());
                                    Some(FontDescriptor::new((*style).clone(), font_id))
                                },
                                None => {
                                    None
                                }
                            }
                        };
                        font_desc
                    },
                    None => {
                        None
                    }
                };

                match font_desc {
                    Some(ref fd) => {
                        let instance = self.get_font_by_descriptor(fd);
                        let _ = instance.map(|font| fonts.push(font.clone()));
                    },
                    None => { }
                };
            }
        }
        assert!(fonts.len() > 0);
        // TODO(Issue #179): Split FontStyle into specified and used styles
        let used_style = (*style).clone();

        debug!("(create font group) --- finished ---");

        Rc::new(
            RefCell::new(
                FontGroup::new(style.families.to_owned(), &used_style, fonts)))
    }

    fn create_font_instance(&self, desc: &FontDescriptor) -> Result<Rc<RefCell<Font>>, ()> {
        return match &desc.selector {
            // TODO(Issue #174): implement by-platform-name font selectors.
            &SelectorPlatformIdentifier(ref identifier) => {
                let result_handle = self.handle.create_font_from_identifier((*identifier).clone(),
                                                                            desc.style.clone());
                result_handle.and_then(|handle| {
                    Ok(
                        Rc::new(
                            RefCell::new(
                                Font::new_from_adopted_handle(self,
                                                              handle,
                                                              &desc.style,
                                                              self.backend))))
                })
            }
        };
    }
}