9ef1f57168da9c9b81562cb0b926775cded39867
[platform/upstream/harfbuzz.git] / src / hb-ot-hmtx-table.hh
1 /*
2  * Copyright © 2011,2012  Google, Inc.
3  *
4  *  This is part of HarfBuzz, a text shaping library.
5  *
6  * Permission is hereby granted, without written agreement and without
7  * license or royalty fees, to use, copy, modify, and distribute this
8  * software and its documentation for any purpose, provided that the
9  * above copyright notice and the following two paragraphs appear in
10  * all copies of this software.
11  *
12  * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR
13  * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
14  * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
15  * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
16  * DAMAGE.
17  *
18  * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING,
19  * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
20  * FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
21  * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO
22  * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
23  *
24  * Google Author(s): Behdad Esfahbod, Roderick Sheeter
25  */
26
27 #ifndef HB_OT_HMTX_TABLE_HH
28 #define HB_OT_HMTX_TABLE_HH
29
30 #include "hb-open-type.hh"
31 #include "hb-ot-hhea-table.hh"
32 #include "hb-ot-os2-table.hh"
33 #include "hb-ot-var-hvar-table.hh"
34
35 /*
36  * hmtx -- Horizontal Metrics
37  * https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx
38  * vmtx -- Vertical Metrics
39  * https://docs.microsoft.com/en-us/typography/opentype/spec/vmtx
40  */
41 #define HB_OT_TAG_hmtx HB_TAG('h','m','t','x')
42 #define HB_OT_TAG_vmtx HB_TAG('v','m','t','x')
43
44
45 namespace OT {
46
47
48 struct LongMetric
49 {
50   UFWORD        advance; /* Advance width/height. */
51   FWORD         sb; /* Leading (left/top) side bearing. */
52   public:
53   DEFINE_SIZE_STATIC (4);
54 };
55
56 template <typename T, typename H>
57 struct hmtxvmtx
58 {
59   bool sanitize (hb_sanitize_context_t *c HB_UNUSED) const
60   {
61     TRACE_SANITIZE (this);
62     /* We don't check for anything specific here.  The users of the
63      * struct do all the hard work... */
64     return_trace (true);
65   }
66
67
68   bool subset_update_header (hb_subset_plan_t *plan,
69                              unsigned int num_hmetrics) const
70   {
71     hb_blob_t *src_blob = hb_sanitize_context_t ().reference_table<H> (plan->source, H::tableTag);
72     hb_blob_t *dest_blob = hb_blob_copy_writable_or_fail (src_blob);
73     hb_blob_destroy (src_blob);
74
75     if (unlikely (!dest_blob)) {
76       return false;
77     }
78
79     unsigned int length;
80     H *table = (H *) hb_blob_get_data (dest_blob, &length);
81     table->numberOfLongMetrics.set (num_hmetrics);
82
83     bool result = plan->add_table (H::tableTag, dest_blob);
84     hb_blob_destroy (dest_blob);
85
86     return result;
87   }
88
89   bool subset (hb_subset_plan_t *plan) const
90   {
91     typename T::accelerator_t _mtx;
92     _mtx.init (plan->source);
93
94     /* All the trailing glyphs with the same advance can use one LongMetric
95      * and just keep LSB */
96     unsigned int num_output_glyphs = plan->num_output_glyphs ();
97     unsigned int num_advances = _mtx.num_advances_for_subset (plan);
98
99     /* alloc the new table */
100     size_t dest_sz = num_advances * 4
101                   + (num_output_glyphs - num_advances) * 2;
102     void *dest = (void *) malloc (dest_sz);
103     if (unlikely (!dest))
104     {
105       return false;
106     }
107     DEBUG_MSG(SUBSET, nullptr, "%c%c%c%c in src has %d advances, %d lsbs", HB_UNTAG(T::tableTag), _mtx.num_advances, _mtx.num_metrics - _mtx.num_advances);
108     DEBUG_MSG(SUBSET, nullptr, "%c%c%c%c in dest has %d advances, %d lsbs, %u bytes",
109               HB_UNTAG(T::tableTag), num_advances, num_output_glyphs - num_advances, (unsigned int) dest_sz);
110
111     // Copy everything over
112     char * dest_pos = (char *) dest;
113
114     bool failed = false;
115     for (unsigned int i = 0; i < num_output_glyphs; i++)
116     {
117       unsigned int side_bearing = 0;
118       unsigned int advance = 0;
119       hb_codepoint_t old_gid;
120       if (plan->old_gid_for_new_gid (i, &old_gid))
121       {
122         // Glyph is not an empty glyph so copy advance and side bearing
123         // from the input font.
124         side_bearing = _mtx.get_side_bearing (old_gid);
125         advance = _mtx.get_advance (old_gid);
126       }
127
128       bool has_advance = i < num_advances;
129       if (has_advance)
130       {
131         ((LongMetric *) dest_pos)->advance.set (advance);
132         ((LongMetric *) dest_pos)->sb.set (side_bearing);
133       }
134       else
135       {
136         ((FWORD *) dest_pos)->set (side_bearing);
137       }
138       dest_pos += (has_advance ? 4 : 2);
139     }
140     _mtx.fini ();
141
142     // Amend header num hmetrics
143     if (failed || unlikely (!subset_update_header (plan, num_advances)))
144     {
145       free (dest);
146       return false;
147     }
148
149     hb_blob_t *result = hb_blob_create ((const char *)dest,
150                                         dest_sz,
151                                         HB_MEMORY_MODE_READONLY,
152                                         dest,
153                                         free);
154     bool success = plan->add_table (T::tableTag, result);
155     hb_blob_destroy (result);
156     return success;
157   }
158
159   struct accelerator_t
160   {
161     friend struct hmtxvmtx;
162
163     void init (hb_face_t *face,
164                unsigned int default_advance_ = 0)
165     {
166       default_advance = default_advance_ ? default_advance_ : hb_face_get_upem (face);
167
168       bool got_font_extents = false;
169       if (T::os2Tag != HB_TAG_NONE && face->table.OS2->is_typo_metrics ())
170       {
171         ascender = abs (face->table.OS2->sTypoAscender);
172         descender = -abs (face->table.OS2->sTypoDescender);
173         line_gap = face->table.OS2->sTypoLineGap;
174         got_font_extents = (ascender | descender) != 0;
175       }
176
177       hb_blob_t *_hea_blob = hb_sanitize_context_t().reference_table<H> (face);
178       const H *_hea_table = _hea_blob->as<H> ();
179       num_advances = _hea_table->numberOfLongMetrics;
180       if (!got_font_extents)
181       {
182         ascender = abs (_hea_table->ascender);
183         descender = -abs (_hea_table->descender);
184         line_gap = _hea_table->lineGap;
185         got_font_extents = (ascender | descender) != 0;
186       }
187       hb_blob_destroy (_hea_blob);
188
189       has_font_extents = got_font_extents;
190
191       table = hb_sanitize_context_t().reference_table<hmtxvmtx> (face, T::tableTag);
192
193       /* Cap num_metrics() and num_advances() based on table length. */
194       unsigned int len = table.get_length ();
195       if (unlikely (num_advances * 4 > len))
196         num_advances = len / 4;
197       num_metrics = num_advances + (len - 4 * num_advances) / 2;
198
199       /* We MUST set num_metrics to zero if num_advances is zero.
200        * Our get_advance() depends on that. */
201       if (unlikely (!num_advances))
202       {
203         num_metrics = num_advances = 0;
204         table.destroy ();
205         table = hb_blob_get_empty ();
206       }
207
208       var_table = hb_sanitize_context_t().reference_table<HVARVVAR> (face, T::variationsTag);
209     }
210
211     void fini ()
212     {
213       table.destroy ();
214       var_table.destroy ();
215     }
216
217     /* TODO Add variations version. */
218     unsigned int get_side_bearing (hb_codepoint_t glyph) const
219     {
220       if (glyph < num_advances)
221         return table->longMetricZ[glyph].sb;
222
223       if (unlikely (glyph >= num_metrics))
224         return 0;
225
226       const FWORD *bearings = (const FWORD *) &table->longMetricZ[num_advances];
227       return bearings[glyph - num_advances];
228     }
229
230     unsigned int get_advance (hb_codepoint_t glyph) const
231     {
232       if (unlikely (glyph >= num_metrics))
233       {
234         /* If num_metrics is zero, it means we don't have the metrics table
235          * for this direction: return default advance.  Otherwise, it means that the
236          * glyph index is out of bound: return zero. */
237         if (num_metrics)
238           return 0;
239         else
240           return default_advance;
241       }
242
243       return table->longMetricZ[MIN (glyph, (uint32_t) num_advances - 1)].advance;
244     }
245
246     unsigned int get_advance (hb_codepoint_t  glyph,
247                               hb_font_t      *font) const
248     {
249       unsigned int advance = get_advance (glyph);
250       if (likely (glyph < num_metrics))
251       {
252         advance += (font->num_coords ? var_table->get_advance_var (glyph, font->coords, font->num_coords) : 0); // TODO Optimize?!
253       }
254       return advance;
255     }
256
257     unsigned int num_advances_for_subset (const hb_subset_plan_t *plan) const
258     {
259       unsigned int num_advances = plan->num_output_glyphs ();
260       unsigned int last_advance = _advance_for_new_gid (plan,
261                                                         num_advances - 1);
262       while (num_advances > 1 &&
263              last_advance == _advance_for_new_gid (plan,
264                                                    num_advances - 2))
265       {
266         num_advances--;
267       }
268
269       return num_advances;
270     }
271
272     private:
273     unsigned int _advance_for_new_gid (const hb_subset_plan_t *plan,
274                                        hb_codepoint_t new_gid) const
275     {
276       hb_codepoint_t old_gid;
277       if (!plan->old_gid_for_new_gid (new_gid, &old_gid))
278         return 0;
279
280       return get_advance (old_gid);
281     }
282
283     public:
284     bool has_font_extents;
285     int ascender;
286     int descender;
287     int line_gap;
288
289     protected:
290     unsigned int num_metrics;
291     unsigned int num_advances;
292     unsigned int default_advance;
293
294     private:
295     hb_blob_ptr_t<hmtxvmtx> table;
296     hb_blob_ptr_t<HVARVVAR> var_table;
297   };
298
299   protected:
300   UnsizedArrayOf<LongMetric>longMetricZ;/* Paired advance width and leading
301                                          * bearing values for each glyph. The
302                                          * value numOfHMetrics comes from
303                                          * the 'hhea' table. If the font is
304                                          * monospaced, only one entry need
305                                          * be in the array, but that entry is
306                                          * required. The last entry applies to
307                                          * all subsequent glyphs. */
308 /*UnsizedArrayOf<FWORD> leadingBearingX;*//* Here the advance is assumed
309                                          * to be the same as the advance
310                                          * for the last entry above. The
311                                          * number of entries in this array is
312                                          * derived from numGlyphs (from 'maxp'
313                                          * table) minus numberOfLongMetrics.
314                                          * This generally is used with a run
315                                          * of monospaced glyphs (e.g., Kanji
316                                          * fonts or Courier fonts). Only one
317                                          * run is allowed and it must be at
318                                          * the end. This allows a monospaced
319                                          * font to vary the side bearing
320                                          * values for each glyph. */
321   public:
322   DEFINE_SIZE_ARRAY (0, longMetricZ);
323 };
324
325 struct hmtx : hmtxvmtx<hmtx, hhea> {
326   static constexpr hb_tag_t tableTag = HB_OT_TAG_hmtx;
327   static constexpr hb_tag_t variationsTag = HB_OT_TAG_HVAR;
328   static constexpr hb_tag_t os2Tag = HB_OT_TAG_OS2;
329 };
330 struct vmtx : hmtxvmtx<vmtx, vhea> {
331   static constexpr hb_tag_t tableTag = HB_OT_TAG_vmtx;
332   static constexpr hb_tag_t variationsTag = HB_OT_TAG_VVAR;
333   static constexpr hb_tag_t os2Tag = HB_TAG_NONE;
334 };
335
336 struct hmtx_accelerator_t : hmtx::accelerator_t {};
337 struct vmtx_accelerator_t : vmtx::accelerator_t {};
338
339 } /* namespace OT */
340
341
342 #endif /* HB_OT_HMTX_TABLE_HH */