Create glyph bitmap without copy if single color
[platform/core/uifw/dali-adaptor.git] / dali / internal / text / text-abstraction / plugin / font-client-utils.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <dali/internal/text/text-abstraction/plugin/font-client-utils.h>
18
19 #include <dali/integration-api/debug.h>
20 #include <dali/internal/imaging/common/image-operations.h>
21
22 #include <memory>
23
24 #if defined(DEBUG_ENABLED)
25 extern Dali::Integration::Log::Filter* gFontClientLogFilter;
26 #endif
27
28 namespace Dali::TextAbstraction::Internal
29 {
30 namespace
31 {
32 // http://www.freedesktop.org/software/fontconfig/fontconfig-user.html
33
34 // NONE            -1  --> DEFAULT_FONT_WIDTH (NORMAL) will be used.
35 // ULTRA_CONDENSED 50
36 // EXTRA_CONDENSED 63
37 // CONDENSED       75
38 // SEMI_CONDENSED  87
39 // NORMAL         100
40 // SEMI_EXPANDED  113
41 // EXPANDED       125
42 // EXTRA_EXPANDED 150
43 // ULTRA_EXPANDED 200
44 const int          FONT_WIDTH_TYPE_TO_INT[] = {-1, 50, 63, 75, 87, 100, 113, 125, 150, 200};
45 const unsigned int NUM_FONT_WIDTH_TYPE      = sizeof(FONT_WIDTH_TYPE_TO_INT) / sizeof(int);
46
47 // NONE                       -1  --> DEFAULT_FONT_WEIGHT (NORMAL) will be used.
48 // THIN                        0
49 // ULTRA_LIGHT, EXTRA_LIGHT   40
50 // LIGHT                      50
51 // DEMI_LIGHT, SEMI_LIGHT     55
52 // BOOK                       75
53 // NORMAL, REGULAR            80
54 // MEDIUM                    100
55 // DEMI_BOLD, SEMI_BOLD      180
56 // BOLD                      200
57 // ULTRA_BOLD, EXTRA_BOLD    205
58 // BLACK, HEAVY, EXTRA_BLACK 210
59 const int          FONT_WEIGHT_TYPE_TO_INT[] = {-1, 0, 40, 50, 55, 75, 80, 100, 180, 200, 205, 210};
60 const unsigned int NUM_FONT_WEIGHT_TYPE      = sizeof(FONT_WEIGHT_TYPE_TO_INT) / sizeof(int);
61
62 // NONE             -1 --> DEFAULT_FONT_SLANT (NORMAL) will be used.
63 // NORMAL, ROMAN     0
64 // ITALIC          100
65 // OBLIQUE         110
66 const int          FONT_SLANT_TYPE_TO_INT[] = {-1, 0, 100, 110};
67 const unsigned int NUM_FONT_SLANT_TYPE      = sizeof(FONT_SLANT_TYPE_TO_INT) / sizeof(int);
68
69 } // namespace
70
71 /**
72  * @brief Returns the FontWidth's enum index for the given width value.
73  *
74  * @param[in] width The width value.
75  *
76  * @return The FontWidth's enum index.
77  */
78 const FontWidth::Type IntToWidthType(int width)
79 {
80   return static_cast<FontWidth::Type>(ValueToIndex(width, FONT_WIDTH_TYPE_TO_INT, NUM_FONT_WIDTH_TYPE - 1u));
81 }
82
83 /**
84  * @brief Returns the FontWeight's enum index for the given weight value.
85  *
86  * @param[in] weight The weight value.
87  *
88  * @return The FontWeight's enum index.
89  */
90 const FontWeight::Type IntToWeightType(int weight)
91 {
92   return static_cast<FontWeight::Type>(ValueToIndex(weight, FONT_WEIGHT_TYPE_TO_INT, NUM_FONT_WEIGHT_TYPE - 1u));
93 }
94
95 /**
96  * @brief Returns the FontSlant's enum index for the given slant value.
97  *
98  * @param[in] slant The slant value.
99  *
100  * @return The FontSlant's enum index.
101  */
102 const FontSlant::Type IntToSlantType(int slant)
103 {
104   return static_cast<FontSlant::Type>(ValueToIndex(slant, FONT_SLANT_TYPE_TO_INT, NUM_FONT_SLANT_TYPE - 1u));
105 }
106
107 const int DEFAULT_FONT_WIDTH(100);
108 const int DEFAULT_FONT_WEIGHT(80);
109 const int DEFAULT_FONT_SLANT(0);
110
111 const FontWidth::Type DefaultFontWidth()
112 {
113   return IntToWidthType(DEFAULT_FONT_WIDTH);
114 }
115 const FontWeight::Type DefaultFontWeight()
116 {
117   return IntToWeightType(DEFAULT_FONT_WEIGHT);
118 }
119 const FontSlant::Type DefaultFontSlant()
120 {
121   return IntToSlantType(DEFAULT_FONT_SLANT);
122 }
123
124 /**
125  * @brief Copy the color bitmap given in @p srcBuffer to @p data.
126  *
127  * @param[out] data The bitmap data.
128  * @param[in] srcWidth The width of the bitmap.
129  * @param[in] srcHeight The height of the bitmap.
130  * @param[in] srcBuffer The buffer of the bitmap.
131  */
132 void ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, unsigned int srcWidth, unsigned int srcHeight, const unsigned char* const srcBuffer)
133 {
134   // Set the input dimensions.
135   const ImageDimensions inputDimensions(srcWidth, srcHeight);
136
137   // Set the output dimensions.
138   // If the output dimension is not given, the input dimension is set
139   // and won't be downscaling.
140   data.width  = (data.width == 0) ? srcWidth : data.width;
141   data.height = (data.height == 0) ? srcHeight : data.height;
142   const ImageDimensions desiredDimensions(data.width, data.height);
143
144   // Creates the output buffer
145   const unsigned int bufferSize = data.width * data.height * 4u;
146   data.buffer                   = (uint8_t*)malloc(bufferSize * sizeof(uint8_t)); // @note The caller is responsible for deallocating the bitmap data using free.
147
148   if(inputDimensions == desiredDimensions)
149   {
150     // There isn't downscaling.
151     memcpy(data.buffer, srcBuffer, bufferSize);
152   }
153   else
154   {
155     Dali::Internal::Platform::LanczosSample4BPP(srcBuffer,
156                                                 inputDimensions,
157                                                 srcWidth,
158                                                 data.buffer,
159                                                 desiredDimensions);
160   }
161 }
162
163 /**
164  * @brief Copy the FreeType bitmap to the given buffer.
165  *
166  * @param[out] data The bitmap data.
167  * @param[in,out] srcBitmap The FreeType bitmap.
168  * @param[in] isShearRequired Whether the bitmap needs a shear transform (for software italics).
169  * @param[in] moveBuffer Whether the bitmap buffer move. True if just copy buffer pointer. False if we use memcpy. (Default is false.)
170  * @note If you set moveBuffer=true, the bitmap's buffer moved frome srcBitmap to data. So srcBitmap buffer changed as nullptr.
171  */
172 void ConvertBitmap(TextAbstraction::FontClient::GlyphBufferData& data, FT_Bitmap& srcBitmap, bool isShearRequired, bool moveBuffer)
173 {
174   if(srcBitmap.width * srcBitmap.rows > 0)
175   {
176     switch(srcBitmap.pixel_mode)
177     {
178       case FT_PIXEL_MODE_GRAY:
179       {
180         if(srcBitmap.pitch == static_cast<int>(srcBitmap.width))
181         {
182           uint8_t*     pixelsIn = srcBitmap.buffer;
183           unsigned int width    = srcBitmap.width;
184           unsigned     height   = srcBitmap.rows;
185
186           uint8_t* releaseRequiredPixelPtr = nullptr;
187
188           if(isShearRequired)
189           {
190             /**
191              * Glyphs' bitmaps with no slant retrieved from FreeType:
192              * __________     ____
193              * |XXXXXXXX|     |XX|
194              * |   XX   |     |XX|
195              * |   XX   |     |XX|
196              * |   XX   |     |XX|
197              * |   XX   |     |XX|
198              * |   XX   |     |XX|
199              * ----------     ----
200              *
201              * Expected glyphs' bitmaps with italic slant:
202              * ____________   ______
203              * |  XXXXXXXX|   |  XX|
204              * |     XX   |   |  XX|
205              * |    XX    |   | XX |
206              * |    XX    |   | XX |
207              * |   XX     |   |XX  |
208              * |   XX     |   |XX  |
209              * ------------   ------
210              *
211              * Glyphs' bitmaps with software italic slant retrieved from FreeType:
212              * __________     ______
213              * |XXXXXXXX|     |  XX|
214              * |   XX   |     |  XX|
215              * |  XX    |     | XX |
216              * |  XX    |     | XX |
217              * | XX     |     |XX  |
218              * | XX     |     |XX  |
219              * ----------     ------
220              *
221              * This difference in some bitmaps' width causes an overlap of some glyphs. This is the reason why a shear operation is done here instead of relying on the experimental FT_GlyphSlot_Oblique() implementation.
222              */
223             unsigned int widthOut  = 0u;
224             unsigned int heightOut = 0u;
225             uint8_t*     pixelsOut = nullptr;
226
227             Dali::Internal::Platform::HorizontalShear(pixelsIn,
228                                                       width,
229                                                       height,
230                                                       width,
231                                                       1u,
232                                                       -TextAbstraction::FontClient::DEFAULT_ITALIC_ANGLE,
233                                                       pixelsOut,
234                                                       widthOut,
235                                                       heightOut);
236
237             if(DALI_LIKELY(pixelsOut))
238             {
239               width  = widthOut;
240               height = heightOut;
241
242               if(moveBuffer)
243               {
244                 releaseRequiredPixelPtr = pixelsIn;
245               }
246               else
247               {
248                 releaseRequiredPixelPtr = pixelsOut;
249               }
250
251               // Change input buffer ptr.
252               pixelsIn = pixelsOut;
253             }
254             else
255             {
256               DALI_LOG_ERROR("ERROR! software italic slant failed!\n");
257             }
258           }
259
260           data.width  = width;
261           data.height = height;
262           data.format = Pixel::L8; // Sets the pixel format.
263
264           if(moveBuffer)
265           {
266             data.buffer = pixelsIn;
267
268             // Happy trick for copyless convert bitmap!
269             srcBitmap.buffer = nullptr;
270           }
271           else
272           {
273             const unsigned int bufferSize = width * height;
274             data.buffer                   = (uint8_t*)malloc(bufferSize * sizeof(uint8_t)); // @note The caller is responsible for deallocating the bitmap data using free.
275
276             memcpy(data.buffer, pixelsIn, bufferSize);
277           }
278
279           if(releaseRequiredPixelPtr)
280           {
281             free(releaseRequiredPixelPtr);
282           }
283         }
284         break;
285       }
286
287 #ifdef FREETYPE_BITMAP_SUPPORT
288       case FT_PIXEL_MODE_BGRA:
289       {
290         if(srcBitmap.pitch == static_cast<int>(srcBitmap.width << 2u))
291         {
292           // Color glyph doesn't support copyless convert bitmap. Just memcpy
293           ConvertBitmap(data, srcBitmap.width, srcBitmap.rows, srcBitmap.buffer);
294
295           // Sets the pixel format.
296           data.format = Pixel::BGRA8888;
297         }
298         break;
299       }
300 #endif
301       default:
302       {
303         DALI_LOG_INFO(gFontClientLogFilter, Debug::General, "FontClient::Plugin::ConvertBitmap. FontClient Unable to create Bitmap of this PixelType\n");
304         break;
305       }
306     }
307   }
308 }
309
310 FcPattern* CreateFontFamilyPattern(const FontDescription& fontDescription)
311 {
312   // create the cached font family lookup pattern
313   // a pattern holds a set of names, each name refers to a property of the font
314   FcPattern* fontFamilyPattern = FcPatternCreate(); // FcPatternCreate creates a new pattern that needs to be destroyed by calling FcPatternDestroy.
315
316   if(!fontFamilyPattern)
317   {
318     return nullptr;
319   }
320
321   // add a property to the pattern for the font family
322   FcPatternAddString(fontFamilyPattern, FC_FAMILY, reinterpret_cast<const FcChar8*>(fontDescription.family.c_str()));
323
324   // add a property to the pattern for local setting.
325   const char* locale = setlocale(LC_MESSAGES, nullptr);
326   if(locale != nullptr)
327   {
328     FcPatternAddString(fontFamilyPattern, FC_LANG, reinterpret_cast<const FcChar8*>(locale));
329   }
330
331   int width = FONT_WIDTH_TYPE_TO_INT[fontDescription.width];
332   if(width < 0)
333   {
334     // Use default.
335     width = DEFAULT_FONT_WIDTH;
336   }
337
338   int weight = FONT_WEIGHT_TYPE_TO_INT[fontDescription.weight];
339   if(weight < 0)
340   {
341     // Use default.
342     weight = DEFAULT_FONT_WEIGHT;
343   }
344
345   int slant = FONT_SLANT_TYPE_TO_INT[fontDescription.slant];
346   if(slant < 0)
347   {
348     // Use default.
349     slant = DEFAULT_FONT_SLANT;
350   }
351
352   FcPatternAddInteger(fontFamilyPattern, FC_WIDTH, width);
353   FcPatternAddInteger(fontFamilyPattern, FC_WEIGHT, weight);
354   FcPatternAddInteger(fontFamilyPattern, FC_SLANT, slant);
355
356   // modify the config, with the mFontFamilyPatterm
357   FcConfigSubstitute(nullptr /* use default configure */, fontFamilyPattern, FcMatchPattern);
358
359   // provide default values for unspecified properties in the font pattern
360   // e.g. patterns without a specified style or weight are set to Medium
361   FcDefaultSubstitute(fontFamilyPattern);
362
363   return fontFamilyPattern;
364 }
365
366 FcCharSet* CreateCharacterSetFromDescription(const FontDescription& description)
367 {
368   FcCharSet* characterSet = nullptr;
369
370   FcPattern* pattern = CreateFontFamilyPattern(description); // Creates a new pattern that needs to be destroyed by calling FcPatternDestroy.
371
372   if(nullptr != pattern)
373   {
374     FcResult   result = FcResultMatch;
375     FcPattern* match  = FcFontMatch(nullptr, pattern, &result); // FcFontMatch creates a new pattern that needs to be destroyed by calling FcPatternDestroy.
376
377     FcPatternGetCharSet(match, FC_CHARSET, 0u, &characterSet);
378
379     // Destroys the created patterns.
380     FcPatternDestroy(match);
381     FcPatternDestroy(pattern);
382   }
383
384   return characterSet;
385 }
386
387 } // namespace Dali::TextAbstraction::Internal