af4fcb8137099ac77c484b29ce71e95b3f35997c
[platform/upstream/harfbuzz.git] / src / hb-subset-plan.cc
1 /*
2  * Copyright © 2018  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): Garret Rieger, Roderick Sheeter
25  */
26
27 #include "hb-subset-plan.hh"
28 #include "hb-map.hh"
29 #include "hb-set.hh"
30
31 #include "hb-ot-cmap-table.hh"
32 #include "hb-ot-glyf-table.hh"
33 #include "hb-ot-layout-gdef-table.hh"
34 #include "hb-ot-layout-gpos-table.hh"
35 #include "hb-ot-layout-gsub-table.hh"
36 #include "hb-ot-cff1-table.hh"
37 #include "hb-ot-color-colr-table.hh"
38 #include "hb-ot-color-colrv1-closure.hh"
39 #include "hb-ot-var-fvar-table.hh"
40 #include "hb-ot-stat-table.hh"
41 #include "hb-ot-math-table.hh"
42
43
44 typedef hb_hashmap_t<unsigned, hb_set_t *> script_langsys_map;
45 #ifndef HB_NO_SUBSET_CFF
46 static inline void
47 _add_cff_seac_components (const OT::cff1::accelerator_t &cff,
48                           hb_codepoint_t gid,
49                           hb_set_t *gids_to_retain)
50 {
51   hb_codepoint_t base_gid, accent_gid;
52   if (cff.get_seac_components (gid, &base_gid, &accent_gid))
53   {
54     gids_to_retain->add (base_gid);
55     gids_to_retain->add (accent_gid);
56   }
57 }
58 #endif
59
60 static void
61 _remap_palette_indexes (const hb_set_t *palette_indexes,
62                         hb_map_t       *mapping /* OUT */)
63 {
64   unsigned new_idx = 0;
65   for (unsigned palette_index : palette_indexes->iter ())
66   {
67     if (palette_index == 0xFFFF)
68     {
69       mapping->set (palette_index, palette_index);
70       continue;
71     }
72     mapping->set (palette_index, new_idx);
73     new_idx++;
74   }
75 }
76
77 static void
78 _remap_indexes (const hb_set_t *indexes,
79                 hb_map_t       *mapping /* OUT */)
80 {
81   unsigned count = indexes->get_population ();
82
83   for (auto _ : + hb_zip (indexes->iter (), hb_range (count)))
84     mapping->set (_.first, _.second);
85
86 }
87
88 #ifndef HB_NO_SUBSET_LAYOUT
89 typedef void (*layout_collect_func_t) (hb_face_t *face, hb_tag_t table_tag, const hb_tag_t *scripts, const hb_tag_t *languages, const hb_tag_t *features, hb_set_t *lookup_indexes /* OUT */);
90
91
92 template <typename T>
93 static void _collect_layout_indices (hb_face_t            *face,
94                                      const T&              table,
95                                      const hb_set_t       *layout_features_to_retain,
96                                      layout_collect_func_t layout_collect_func,
97                                      hb_set_t             *indices /* OUT */)
98 {
99   hb_vector_t<hb_tag_t> features;
100   if (!features.alloc (table.get_feature_count () + 1))
101     return;
102
103   hb_set_t visited_features;
104   bool retain_all_features = true;
105   for (unsigned i = 0; i < table.get_feature_count (); i++)
106   {
107     hb_tag_t tag = table.get_feature_tag (i);
108     if (!tag) continue;
109     if (!layout_features_to_retain->has (tag))
110     {
111       retain_all_features = false;
112       continue;
113     }
114     
115     if (visited_features.has (tag))
116       continue;
117
118     features.push (tag);
119     visited_features.add (tag);
120   }
121
122   if (!features)
123     return;
124
125   // The collect function needs a null element to signal end of the array.
126   features.push (0);
127
128   if (retain_all_features)
129   {
130     // Looking for all features, trigger the faster collection method.
131     layout_collect_func (face,
132                          T::tableTag,
133                          nullptr,
134                          nullptr,
135                          nullptr,
136                          indices);
137     return;
138   }
139
140   layout_collect_func (face,
141                        T::tableTag,
142                        nullptr,
143                        nullptr,
144                        features.arrayZ,
145                        indices);
146 }
147
148 template <typename T>
149 static inline void
150 _closure_glyphs_lookups_features (hb_face_t          *face,
151                                   hb_set_t           *gids_to_retain,
152                                   const hb_set_t     *layout_features_to_retain,
153                                   hb_map_t           *lookups,
154                                   hb_map_t           *features,
155                                   script_langsys_map *langsys_map)
156 {
157   hb_blob_ptr_t<T> table = hb_sanitize_context_t ().reference_table<T> (face);
158   hb_tag_t table_tag = table->tableTag;
159   hb_set_t lookup_indices;
160   _collect_layout_indices<T> (face,
161                               *table,
162                               layout_features_to_retain,
163                               hb_ot_layout_collect_lookups,
164                               &lookup_indices);
165
166   if (table_tag == HB_OT_TAG_GSUB)
167     hb_ot_layout_lookups_substitute_closure (face,
168                                             &lookup_indices,
169                                              gids_to_retain);
170   table->closure_lookups (face,
171                           gids_to_retain,
172                          &lookup_indices);
173   _remap_indexes (&lookup_indices, lookups);
174
175   // Collect and prune features
176   hb_set_t feature_indices;
177   _collect_layout_indices<T> (face,
178                               *table,
179                               layout_features_to_retain,
180                               hb_ot_layout_collect_features,
181                               &feature_indices);
182
183   table->prune_features (lookups, &feature_indices);
184   hb_map_t duplicate_feature_map;
185   table->find_duplicate_features (lookups, &feature_indices, &duplicate_feature_map);
186
187   feature_indices.clear ();
188   table->prune_langsys (&duplicate_feature_map, langsys_map, &feature_indices);
189   _remap_indexes (&feature_indices, features);
190
191   table.destroy ();
192 }
193
194 #endif
195
196 #ifndef HB_NO_VAR
197 static inline void
198   _collect_layout_variation_indices (hb_face_t *face,
199                                      const hb_set_t *glyphset,
200                                      const hb_map_t *gpos_lookups,
201                                      hb_set_t  *layout_variation_indices,
202                                      hb_map_t  *layout_variation_idx_map)
203 {
204   hb_blob_ptr_t<OT::GDEF> gdef = hb_sanitize_context_t ().reference_table<OT::GDEF> (face);
205   hb_blob_ptr_t<OT::GPOS> gpos = hb_sanitize_context_t ().reference_table<OT::GPOS> (face);
206
207   if (!gdef->has_data ())
208   {
209     gdef.destroy ();
210     gpos.destroy ();
211     return;
212   }
213   OT::hb_collect_variation_indices_context_t c (layout_variation_indices, glyphset, gpos_lookups);
214   gdef->collect_variation_indices (&c);
215
216   if (hb_ot_layout_has_positioning (face))
217     gpos->collect_variation_indices (&c);
218
219   gdef->remap_layout_variation_indices (layout_variation_indices, layout_variation_idx_map);
220
221   gdef.destroy ();
222   gpos.destroy ();
223 }
224 #endif
225
226 static inline void
227 _cmap_closure (hb_face_t           *face,
228                const hb_set_t      *unicodes,
229                hb_set_t            *glyphset)
230 {
231   OT::cmap::accelerator_t cmap (face);
232   cmap.table->closure_glyphs (unicodes, glyphset);
233 }
234
235 static void _colr_closure (hb_face_t *face,
236                            hb_map_t *layers_map,
237                            hb_map_t *palettes_map,
238                            hb_set_t *glyphs_colred)
239 {
240   OT::COLR::accelerator_t colr (face);
241   if (!colr.is_valid ()) return;
242
243   unsigned iteration_count = 0;
244   hb_set_t palette_indices, layer_indices;
245   unsigned glyphs_num;
246   {
247     glyphs_num = glyphs_colred->get_population ();
248     // Collect all glyphs referenced by COLRv0
249     hb_set_t glyphset_colrv0;
250     for (hb_codepoint_t gid : glyphs_colred->iter ())
251       colr.closure_glyphs (gid, &glyphset_colrv0);
252     
253     glyphs_colred->union_ (glyphset_colrv0);
254     
255     //closure for COLRv1
256     colr.closure_forV1 (glyphs_colred, &layer_indices, &palette_indices);
257   } while (iteration_count++ <= HB_CLOSURE_MAX_STAGES &&
258            glyphs_num != glyphs_colred->get_population ());
259
260   colr.closure_V0palette_indices (glyphs_colred, &palette_indices);
261   _remap_indexes (&layer_indices, layers_map);
262   _remap_palette_indexes (&palette_indices, palettes_map);
263 }
264
265 static inline void
266 _math_closure (hb_face_t           *face,
267                hb_set_t            *glyphset)
268 {
269   hb_blob_ptr_t<OT::MATH> math = hb_sanitize_context_t ().reference_table<OT::MATH> (face);
270   if (math->has_data ())
271     math->closure_glyphs (glyphset);
272   math.destroy ();
273 }
274
275
276 static inline void
277 _remove_invalid_gids (hb_set_t *glyphs,
278                       unsigned int num_glyphs)
279 {
280   hb_codepoint_t gid = HB_SET_VALUE_INVALID;
281   while (glyphs->next (&gid))
282   {
283     if (gid >= num_glyphs)
284       glyphs->del (gid);
285   }
286 }
287
288 static void
289 _populate_unicodes_to_retain (const hb_set_t *unicodes,
290                               const hb_set_t *glyphs,
291                               hb_subset_plan_t *plan)
292 {
293   OT::cmap::accelerator_t cmap (plan->source);
294
295   constexpr static const int size_threshold = 4096;
296
297   if (glyphs->is_empty () && unicodes->get_population () < size_threshold)
298   {
299     /* This is the fast path if it's anticipated that size of unicodes
300      * is << than the number of codepoints in the font. */
301     for (hb_codepoint_t cp : *unicodes)
302     {
303       hb_codepoint_t gid;
304       if (!cmap.get_nominal_glyph (cp, &gid))
305       {
306         DEBUG_MSG(SUBSET, nullptr, "Drop U+%04X; no gid", cp);
307         continue;
308       }
309
310       plan->codepoint_to_glyph->set (cp, gid);
311     }
312   }
313   else
314   {
315     hb_map_t unicode_glyphid_map;
316     cmap.collect_mapping (hb_set_get_empty (), &unicode_glyphid_map);
317
318     for (hb_pair_t<hb_codepoint_t, hb_codepoint_t> cp_gid :
319          + unicode_glyphid_map.iter ())
320     {
321       if (!unicodes->has (cp_gid.first) && !glyphs->has (cp_gid.second))
322         continue;
323
324       plan->codepoint_to_glyph->set (cp_gid.first, cp_gid.second);
325     }
326
327     /* Add gids which where requested, but not mapped in cmap */
328     // TODO(garretrieger):
329     // Once https://github.com/harfbuzz/harfbuzz/issues/3169
330     // is implemented, this can be done with union and del_range
331     for (hb_codepoint_t gid : glyphs->iter ())
332     {
333       if (gid >= plan->source->get_num_glyphs ())
334         break;
335       plan->_glyphset_gsub->add (gid);
336     }
337   }
338
339   + plan->codepoint_to_glyph->keys ()   | hb_sink (plan->unicodes);
340   + plan->codepoint_to_glyph->values () | hb_sink (plan->_glyphset_gsub);
341 }
342
343 static void
344 _populate_gids_to_retain (hb_subset_plan_t* plan,
345                           bool close_over_gsub,
346                           bool close_over_gpos,
347                           bool close_over_gdef)
348 {
349   OT::glyf::accelerator_t glyf (plan->source);
350 #ifndef HB_NO_SUBSET_CFF
351   OT::cff1::accelerator_t cff (plan->source);
352 #endif
353
354   plan->_glyphset_gsub->add (0); // Not-def
355
356   _cmap_closure (plan->source, plan->unicodes, plan->_glyphset_gsub);
357
358 #ifndef HB_NO_SUBSET_LAYOUT
359   if (close_over_gsub)
360     // closure all glyphs/lookups/features needed for GSUB substitutions.
361     _closure_glyphs_lookups_features<OT::GSUB> (
362         plan->source,
363         plan->_glyphset_gsub,
364         plan->layout_features,
365         plan->gsub_lookups,
366         plan->gsub_features,
367         plan->gsub_langsys);
368
369   if (close_over_gpos)
370     _closure_glyphs_lookups_features<OT::GPOS> (
371         plan->source,
372         plan->_glyphset_gsub,
373         plan->layout_features,
374         plan->gpos_lookups,
375         plan->gpos_features,
376         plan->gpos_langsys);
377 #endif
378   _remove_invalid_gids (plan->_glyphset_gsub, plan->source->get_num_glyphs ());
379
380   hb_set_set (plan->_glyphset_mathed, plan->_glyphset_gsub);
381   _math_closure (plan->source, plan->_glyphset_mathed);
382   _remove_invalid_gids (plan->_glyphset_mathed, plan->source->get_num_glyphs ());
383
384   hb_set_t cur_glyphset = *plan->_glyphset_mathed;
385   _colr_closure (plan->source, plan->colrv1_layers, plan->colr_palettes, &cur_glyphset);
386   _remove_invalid_gids (&cur_glyphset, plan->source->get_num_glyphs ());
387
388   hb_set_set (plan->_glyphset_colred, &cur_glyphset);
389   // Populate a full set of glyphs to retain by adding all referenced
390   // composite glyphs.
391   for (hb_codepoint_t gid : cur_glyphset.iter ())
392   {
393     glyf.add_gid_and_children (gid, plan->_glyphset);
394 #ifndef HB_NO_SUBSET_CFF
395     if (cff.is_valid ())
396       _add_cff_seac_components (cff, gid, plan->_glyphset);
397 #endif
398   }
399
400   _remove_invalid_gids (plan->_glyphset, plan->source->get_num_glyphs ());
401
402
403 #ifndef HB_NO_VAR
404   if (close_over_gdef)
405     _collect_layout_variation_indices (plan->source,
406                                        plan->_glyphset_gsub,
407                                        plan->gpos_lookups,
408                                        plan->layout_variation_indices,
409                                        plan->layout_variation_idx_map);
410 #endif
411 }
412
413 static void
414 _create_old_gid_to_new_gid_map (const hb_face_t *face,
415                                 bool             retain_gids,
416                                 const hb_set_t  *all_gids_to_retain,
417                                 hb_map_t        *glyph_map, /* OUT */
418                                 hb_map_t        *reverse_glyph_map, /* OUT */
419                                 unsigned int    *num_glyphs /* OUT */)
420 {
421   if (!retain_gids)
422   {
423     + hb_enumerate (hb_iter (all_gids_to_retain), (hb_codepoint_t) 0)
424     | hb_sink (reverse_glyph_map)
425     ;
426     *num_glyphs = reverse_glyph_map->get_population ();
427   } else {
428     + hb_iter (all_gids_to_retain)
429     | hb_map ([] (hb_codepoint_t _) {
430                 return hb_pair_t<hb_codepoint_t, hb_codepoint_t> (_, _);
431               })
432     | hb_sink (reverse_glyph_map)
433     ;
434
435     unsigned max_glyph =
436     + hb_iter (all_gids_to_retain)
437     | hb_reduce (hb_max, 0u)
438     ;
439     *num_glyphs = max_glyph + 1;
440   }
441
442   + reverse_glyph_map->iter ()
443   | hb_map (&hb_pair_t<hb_codepoint_t, hb_codepoint_t>::reverse)
444   | hb_sink (glyph_map)
445   ;
446 }
447
448 static void
449 _nameid_closure (hb_face_t *face,
450                  hb_set_t  *nameids)
451 {
452 #ifndef HB_NO_STYLE
453   face->table.STAT->collect_name_ids (nameids);
454 #endif
455 #ifndef HB_NO_VAR
456   face->table.fvar->collect_name_ids (nameids);
457 #endif
458 }
459
460 /**
461  * hb_subset_plan_create:
462  * @face: font face to create the plan for.
463  * @input: a #hb_subset_input_t input.
464  *
465  * Computes a plan for subsetting the supplied face according
466  * to a provided input. The plan describes
467  * which tables and glyphs should be retained.
468  *
469  * Return value: (transfer full): New subset plan. Destroy with
470  * hb_subset_plan_destroy().
471  *
472  * Since: 1.7.5
473  **/
474 hb_subset_plan_t *
475 hb_subset_plan_create (hb_face_t         *face,
476                        const hb_subset_input_t *input)
477 {
478   hb_subset_plan_t *plan;
479   if (unlikely (!(plan = hb_object_create<hb_subset_plan_t> ())))
480     return const_cast<hb_subset_plan_t *> (&Null (hb_subset_plan_t));
481
482   plan->successful = true;
483   plan->flags = input->flags;
484   plan->unicodes = hb_set_create ();
485   plan->name_ids = hb_set_copy (input->sets.name_ids);
486   _nameid_closure (face, plan->name_ids);
487   plan->name_languages = hb_set_copy (input->sets.name_languages);
488   plan->layout_features = hb_set_copy (input->sets.layout_features);
489   plan->glyphs_requested = hb_set_copy (input->sets.glyphs);
490   plan->drop_tables = hb_set_copy (input->sets.drop_tables);
491   plan->no_subset_tables = hb_set_copy (input->sets.no_subset_tables);
492   plan->source = hb_face_reference (face);
493   plan->dest = hb_face_builder_create ();
494
495   plan->_glyphset = hb_set_create ();
496   plan->_glyphset_gsub = hb_set_create ();
497   plan->_glyphset_mathed = hb_set_create ();
498   plan->_glyphset_colred = hb_set_create ();
499   plan->codepoint_to_glyph = hb_map_create ();
500   plan->glyph_map = hb_map_create ();
501   plan->reverse_glyph_map = hb_map_create ();
502   plan->gsub_lookups = hb_map_create ();
503   plan->gpos_lookups = hb_map_create ();
504
505   if (plan->check_success (plan->gsub_langsys = hb_object_create<script_langsys_map> ()))
506     plan->gsub_langsys->init_shallow ();
507   if (plan->check_success (plan->gpos_langsys = hb_object_create<script_langsys_map> ()))
508     plan->gpos_langsys->init_shallow ();
509
510   plan->gsub_features = hb_map_create ();
511   plan->gpos_features = hb_map_create ();
512   plan->colrv1_layers = hb_map_create ();
513   plan->colr_palettes = hb_map_create ();
514   plan->layout_variation_indices = hb_set_create ();
515   plan->layout_variation_idx_map = hb_map_create ();
516
517   if (plan->in_error ()) {
518     return plan;
519   }
520
521   _populate_unicodes_to_retain (input->sets.unicodes, input->sets.glyphs, plan);
522
523   _populate_gids_to_retain (plan,
524                             !input->sets.drop_tables->has (HB_OT_TAG_GSUB),
525                             !input->sets.drop_tables->has (HB_OT_TAG_GPOS),
526                             !input->sets.drop_tables->has (HB_OT_TAG_GDEF));
527
528   _create_old_gid_to_new_gid_map (face,
529                                   input->flags & HB_SUBSET_FLAGS_RETAIN_GIDS,
530                                   plan->_glyphset,
531                                   plan->glyph_map,
532                                   plan->reverse_glyph_map,
533                                   &plan->_num_output_glyphs);
534
535   return plan;
536 }
537
538 /**
539  * hb_subset_plan_destroy:
540  * @plan: a #hb_subset_plan_t
541  *
542  * Decreases the reference count on @plan, and if it reaches zero, destroys
543  * @plan, freeing all memory.
544  *
545  * Since: 1.7.5
546  **/
547 void
548 hb_subset_plan_destroy (hb_subset_plan_t *plan)
549 {
550   if (!hb_object_destroy (plan)) return;
551
552   hb_set_destroy (plan->unicodes);
553   hb_set_destroy (plan->name_ids);
554   hb_set_destroy (plan->name_languages);
555   hb_set_destroy (plan->layout_features);
556   hb_set_destroy (plan->glyphs_requested);
557   hb_set_destroy (plan->drop_tables);
558   hb_set_destroy (plan->no_subset_tables);
559   hb_face_destroy (plan->source);
560   hb_face_destroy (plan->dest);
561   hb_map_destroy (plan->codepoint_to_glyph);
562   hb_map_destroy (plan->glyph_map);
563   hb_map_destroy (plan->reverse_glyph_map);
564   hb_set_destroy (plan->_glyphset);
565   hb_set_destroy (plan->_glyphset_gsub);
566   hb_set_destroy (plan->_glyphset_mathed);
567   hb_set_destroy (plan->_glyphset_colred);
568   hb_map_destroy (plan->gsub_lookups);
569   hb_map_destroy (plan->gpos_lookups);
570   hb_map_destroy (plan->gsub_features);
571   hb_map_destroy (plan->gpos_features);
572   hb_map_destroy (plan->colrv1_layers);
573   hb_map_destroy (plan->colr_palettes);
574   hb_set_destroy (plan->layout_variation_indices);
575   hb_map_destroy (plan->layout_variation_idx_map);
576
577   if (plan->gsub_langsys)
578   {
579     for (auto _ : plan->gsub_langsys->iter ())
580       hb_set_destroy (_.second);
581
582     hb_object_destroy (plan->gsub_langsys);
583     plan->gsub_langsys->fini_shallow ();
584     hb_free (plan->gsub_langsys);
585   }
586
587   if (plan->gpos_langsys)
588   {
589     for (auto _ : plan->gpos_langsys->iter ())
590       hb_set_destroy (_.second);
591
592     hb_object_destroy (plan->gpos_langsys);
593     plan->gpos_langsys->fini_shallow ();
594     hb_free (plan->gpos_langsys);
595   }
596
597   hb_free (plan);
598 }