Extrenal srt problem gst-1 solved.
[openblackhole/openblackhole-enigma2.git] / lib / gdi / font.cpp
1 #include <lib/gdi/font.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <ctype.h>
6 #include <pthread.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9 #include <byteswap.h>
10
11 #ifndef BYTE_ORDER
12 #error "no BYTE_ORDER defined!"
13 #endif
14
15 // use this for init Freetype...
16 #include <ft2build.h>
17 #include FT_FREETYPE_H
18 #define FTC_Image_Cache_New(a,b)        FTC_ImageCache_New(a,b)
19 #define FTC_SBit_Cache_New(a,b)         FTC_SBitCache_New(a,b)
20 #define FTC_SBit_Cache_Lookup(a,b,c,d)  FTC_SBitCache_Lookup(a,b,c,d,NULL)
21
22 #include <lib/base/eerror.h>
23 #include <lib/gdi/lcd.h>
24 #include <lib/gdi/grc.h>
25 #include <lib/base/elock.h>
26 #include <lib/base/init.h>
27 #include <lib/base/init_num.h>
28
29 #include <fribidi/fribidi.h>
30
31 #include <map>
32
33 fontRenderClass *fontRenderClass::instance;
34
35 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
36
37 struct fntColorCacheKey
38 {
39         gRGB start, end;
40         fntColorCacheKey(const gRGB &start, const gRGB &end)
41                 : start(start), end(end)
42         {
43         }
44         bool operator <(const fntColorCacheKey &c) const
45         {
46                 if (start < c.start)
47                         return 1;
48                 else if (start == c.start)
49                         return end < c.end;
50                 return 0;
51         }
52 };
53
54 std::map<fntColorCacheKey,gLookup> colorcache;
55
56 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
57 {
58         fntColorCacheKey key(start, end);
59         std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
60         if (i != colorcache.end())
61                 return i->second;
62         gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
63 //      eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
64 //              end.a, end.r, end.g, end.b);
65         n.build(16, pal, start, end);
66 //      eDebugNoNewLineStart("[FONT] ");
67 //      for (int i=0; i<16; i++)
68 //              eDebugNoNewLine("%02x|%02x%02x%02x%02x ", (int)n.lookup[i], pal.data[n.lookup[i]].a, pal.data[n.lookup[i]].r, pal.data[n.lookup[i]].g, pal.data[n.lookup[i]].b);
69 //      eDebugNoNewLine("\n");
70         return n;
71 }
72
73 fontRenderClass *fontRenderClass::getInstance()
74 {
75         return instance;
76 }
77
78 FT_Error myFTC_Face_Requester(  FTC_FaceID      face_id,
79                                 FT_Library      library,
80                                 FT_Pointer      request_data,
81                                 FT_Face*        aface)
82 {
83         return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
84 }
85
86
87 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
88 {
89         fontListEntry *font=(fontListEntry *)face_id;
90         if (!font)
91                 return -1;
92
93 //      eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
94
95         int error;
96         if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
97         {
98                 eDebug("[FONT] failed: %m");
99                 return error;
100         }
101         FT_Select_Charmap(*aface, ft_encoding_unicode);
102         return 0;
103 }
104
105 int fontRenderClass::getFaceProperties(const std::string &face, FTC_FaceID &id, int &renderflags)
106 {
107         for (fontListEntry *f=font; f; f=f->next)
108         {
109                 if (f->face == face)
110                 {
111                         id = (FTC_FaceID)f;
112                         renderflags = f->renderflags;
113                         return 0;
114                 }
115         }
116         return -1;
117 }
118
119 #ifdef HAVE_FREETYPE2
120 inline FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_UInt glyph_index, FTC_SBit *sbit)
121 #else
122 inline FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
123 #endif
124 {
125         return FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
126 }
127
128 #ifdef HAVE_FREETYPE2
129 inline FT_Error fontRenderClass::getGlyphImage(FTC_Image_Desc *font, FT_UInt glyph_index, FT_Glyph *glyph, FT_Glyph *borderglyph, int bordersize)
130 #else
131 inline FT_Error fontRenderClass::getGlyphImage(FTC_Image_Desc *font, FT_ULong glyph_index, FT_Glyph *glyph, FT_Glyph *borderglyph, int bordersize)
132 #endif
133 {
134         FT_Glyph image;
135         FT_Error err = FTC_ImageCache_Lookup(imageCache, font, glyph_index, &image, NULL);
136         if (err) return err;
137
138         if (glyph)
139         {
140                 err = FT_Glyph_Copy(image, glyph);
141                 if (err) return err;
142         }
143
144         if (borderglyph && bordersize)
145         {
146                 err = FT_Glyph_Copy(image, borderglyph);
147                 if (err) return err;
148                 if (bordersize != strokerRadius)
149                 {
150                         strokerRadius = bordersize;
151                         FT_Stroker_Set(stroker, strokerRadius, FT_STROKER_LINECAP_ROUND, FT_STROKER_LINEJOIN_ROUND, 0);
152                 }
153                 err = FT_Glyph_Stroke(borderglyph, stroker, 1);
154         }
155         return err;
156 }
157
158 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale, int renderflags)
159 {
160         eDebugNoNewLine("[FONT] adding font %s", filename.c_str());
161         int error;
162         fontListEntry *n=new fontListEntry;
163
164         n->scale=scale;
165         FT_Face face;
166         singleLock s(ftlock);
167
168         if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
169                 eFatal("[FONT] failed: %m");
170
171         n->filename=filename;
172         n->face=name;
173         n->renderflags=renderflags;
174         FT_Done_Face(face);
175
176         n->next=font;
177         eDebug("[FONT] OK (%s)", n->face.c_str());
178         font=n;
179
180         return n->face;
181 }
182
183 fontRenderClass::fontListEntry::~fontListEntry()
184 {
185 }
186
187 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
188 {
189         instance=this;
190         eDebug("[FONT] initializing lib...");
191         {
192                 if (FT_Init_FreeType(&library))
193                 {
194                         eDebug("[FONT] initializing failed.");
195                         return;
196                 }
197         }
198         eDebug("[FONT] loading fonts...");
199         font=0;
200
201         int maxbytes=4*1024*1024;
202         eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
203         fflush(stdout);
204         {
205                 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
206                 {
207                         eDebug("[FONT] initializing font cache failed!");
208                         return;
209                 }
210                 if (!cacheManager)
211                 {
212                         eDebug("[FONT] initializing font cache manager error.");
213                         return;
214                 }
215                 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
216                 {
217                         eDebug("[FONT] initializing font cache sbit failed!");
218                         return;
219                 }
220                 if (FTC_Image_Cache_New(cacheManager, &imageCache))
221                 {
222                         eDebug("[FONT] initializing font cache imagecache failed!");
223                 }
224                 if (FT_Stroker_New(library, &stroker))
225                 {
226                         eDebug("[FONT] initializing font stroker failed!");
227                 }
228         }
229         strokerRadius = -1;
230         return;
231 }
232
233 float fontRenderClass::getLineHeight(const gFont& font)
234 {
235         if (!instance)
236                 return 0;
237         ePtr<Font> fnt;
238         getFont(fnt, font.family.c_str(), font.pointSize);
239         if (!fnt)
240                 return 0;
241         singleLock s(ftlock);
242         FT_Face current_face;
243         if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, &current_face) < 0) ||
244             (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
245         {
246                 eDebug("[FONT] FTC_Manager_Lookup_Size failed!");
247                 return 0;
248         }
249         int height = current_face->size->metrics.height;
250         if (!height)
251         {
252                 /* some fonts don't have height filled in. Estimate it based on the bbox dimensions. */
253                 /* Usually, 'height' is less than the complete boundingbox height, so we use only yMax, to avoid getting a much too large line spacing */
254                 height = FT_MulFix(current_face->bbox.yMax, current_face->size->metrics.y_scale);
255         }
256         return (height>>6);
257 }
258
259 fontRenderClass::~fontRenderClass()
260 {
261         singleLock s(ftlock);
262         while(font)
263         {
264                 fontListEntry *f=font;
265                 font=font->next;
266                 delete f;
267         }
268 //      auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
269 //      FTC_Manager_Done(cacheManager);
270 //      FT_Done_FreeType(library);
271 }
272
273 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
274 {
275         FTC_FaceID id;
276         int renderflags;
277         if (getFaceProperties(face, id, renderflags) < 0)
278         {
279                 font = 0;
280                 return -1;
281         }
282         font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth, renderflags);
283         return 0;
284 }
285
286 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement, int renderflags)
287 {
288         fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor, renderflags);
289         if (is_replacement)
290                 eTextPara::setReplacementFont(alias);
291 }
292
293 DEFINE_REF(Font);
294
295 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw, int renderflags): tabwidth(tw)
296 {
297         renderer=render;
298         font.face_id = faceid;
299         font.width = isize;
300         font.height = isize;
301         font.flags = renderflags;
302         scaler.face_id = faceid;
303         scaler.width = isize;
304         scaler.height = isize;
305         scaler.pixel = 1;
306         height=isize;
307         if (tabwidth==-1)
308                 tabwidth=8*isize;
309 //      font.image_type |= ftc_image_flag_autohinted;
310 }
311
312 #ifdef HAVE_FREETYPE2
313 inline FT_Error Font::getGlyphBitmap(FT_UInt glyph_index, FTC_SBit *sbit)
314 #else
315 inline FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
316 #endif
317 {
318         return renderer->getGlyphBitmap(&font, glyph_index, sbit);
319 }
320
321 #ifdef HAVE_FREETYPE2
322 inline FT_Error Font::getGlyphImage(FT_UInt glyph_index, FT_Glyph *glyph, FT_Glyph *borderglyph, int bordersize)
323 #else
324 inline FT_Error Font::getGlyphImage(FT_ULong glyph_index, FT_Glyph *glyph, FT_Glyph *borderglyph, int bordersize)
325 #endif
326 {
327         return renderer->getGlyphImage(&font, glyph_index, glyph, borderglyph, bordersize);
328 }
329
330 Font::~Font()
331 {
332 }
333
334 DEFINE_REF(eTextPara);
335 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags, int border, bool last,
336                 bool activate_newcolor, unsigned long newcolor)
337 {
338         int xadvance, top, left, height;
339         pGlyph ng;
340         int xborder = 0;
341
342         if (border)
343         {
344                 /* TODO: scale border radius with current_font scaling */
345                 if (current_font->getGlyphImage(glyphIndex, &ng.image, &ng.borderimage, 64 * border))
346                         return 1;
347                 if (ng.image && ng.image->format != FT_GLYPH_FORMAT_BITMAP)
348                 {
349                         FT_Glyph_To_Bitmap(&ng.image, FT_RENDER_MODE_NORMAL, NULL, 1);
350                         if (ng.image->format != FT_GLYPH_FORMAT_BITMAP) return 1;
351                 }
352                 if (ng.borderimage && ng.borderimage->format != FT_GLYPH_FORMAT_BITMAP)
353                 {
354                         FT_Glyph_To_Bitmap(&ng.borderimage, FT_RENDER_MODE_NORMAL, NULL, 1);
355                         if (ng.borderimage->format != FT_GLYPH_FORMAT_BITMAP) return 1;
356                 }
357                 FT_BitmapGlyph glyph = NULL;
358                 if (ng.borderimage)
359                 {
360                         xadvance = ng.borderimage->advance.x;
361                         /*
362                          * NOTE: our boundingbox calculation uses xadvance, and ignores glyph width.
363                          * This is fine for all glyphs, except the last one (i.e. rightmost, for left-to-right rendering)
364                          * For border glyphs, xadvance is significantly smaller than the glyph width.
365                          * In fact, border glyphs often have the same xadvance as normal glyphs, borders
366                          * are allowed to overlap.
367                          * As a result, the boundingbox is calculated too small, the actual glyphs won't
368                          * fit into it, and depending on the alignment, one of the borders on the sides
369                          * will be cut off.
370                          * Ideally, the boundingbox calculation should be rewritten, to use both advance and glyph dimensions.
371                          * However, for now we adjust xadvance of the last glyph, so the current calculation will produce
372                          * a better fitting boundingbox for border glyphs.
373                          *
374                          * The compensation equals half of the difference between 'normal' glyph width,
375                          * and border glyph width. (half the width difference is on the left, and half on the right
376                          * of the glyph, we only need to compensate for the part on the right)
377                          * And since xadvance is in 16.16 units, we use (dW/2) << 16 = dW << 15
378                          */
379                         if (last)
380                         {
381                                 xadvance += (((FT_BitmapGlyph)ng.borderimage)->bitmap.width - ((FT_BitmapGlyph)ng.image)->bitmap.width) << 15;
382                         }
383                         if (!previous)
384                         {
385                                 /* Move the first character, to make sure the border does not get cut off by the boundingbox (xborder is in pixel units, so just divide the width difference by two)  */
386                                 xborder = (((FT_BitmapGlyph)ng.borderimage)->bitmap.width - ((FT_BitmapGlyph)ng.image)->bitmap.width) / 2;
387                         }
388                         glyph = (FT_BitmapGlyph)ng.borderimage;
389                 }
390                 else if (ng.image)
391                 {
392                         xadvance = ng.image->advance.x;
393                         glyph = (FT_BitmapGlyph)ng.image;
394                 }
395                 else
396                 {
397                         return 1;
398                 }
399                 xadvance >>= 16;
400
401                 top = glyph->top;
402                 left = glyph->left;
403                 height = glyph->bitmap.rows;
404         }
405         else
406         {
407                 FTC_SBit glyph;
408                 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
409                         return 1;
410
411                 xadvance = glyph->xadvance;
412                 top = glyph->top;
413                 left = glyph->left;
414                 height = glyph->height;
415         }
416
417         int nx=cursor.x();
418
419         nx+=xadvance;
420
421         if ((rflags & RS_WRAP) && (nx >= area.right()))
422         {
423                 int cnt = 0;
424                 glyphString::reverse_iterator i(glyphs.rbegin());
425                         /* find first possibility (from end to begin) to break */
426                 while (i != glyphs.rend())
427                 {
428                         if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
429                                 break;
430                         cnt++;
431                         ++i;
432                 }
433
434                         /* if ... */
435                 if (i != glyphs.rend()  /* ... we found anything */
436                         && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
437                         && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
438                         && cnt ) /* ... and there are actual non-space characters after this */
439                 {
440                                 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
441                         if (i->flags & GS_SOFTHYPHEN)
442                         {
443                                 i->flags &= ~GS_SOFTHYPHEN;
444                                 i->flags |= GS_HYPHEN;
445                         }
446                         --i; /* skip the space/hypen/softhyphen */
447                         int linelength=cursor.x()-i->x;
448                         i->flags|=GS_ISFIRST; /* make this a line start */
449                         ePoint offset=ePoint(i->x, i->y);
450                         newLine(rflags);
451                         offset-=cursor;
452
453                                 /* and move everything to the end into the next line. */
454                         do
455                         {
456                                 i->x-=offset.x();
457                                 i->y-=offset.y();
458                                 i->bbox.moveBy(-offset.x(), -offset.y());
459                                 --lineChars.back();
460                                 ++charCount;
461                         } while (i-- != glyphs.rbegin()); // rearrange them into the next line
462                         cursor+=ePoint(linelength, 0);  // put the cursor after that line
463                 } else
464                 {
465                         if (cnt)
466                         {
467                                 newLine(rflags);
468                                 flags|=GS_ISFIRST;
469                         }
470                 }
471         }
472
473         int kern=0;
474         if (previous && use_kerning)
475         {
476                 FT_Vector delta;
477                 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
478                 kern=delta.x>>6;
479         }
480
481         ng.bbox.setLeft(((flags&GS_ISFIRST)|cursor.x()) + left + xborder);
482         ng.bbox.setTop( cursor.y() - top );
483         ng.bbox.setHeight( height );
484
485         xadvance += kern + xborder;
486         ng.bbox.setWidth(xadvance);
487
488         ng.x = cursor.x() + kern + xborder;
489         ng.y = cursor.y();
490         ng.w = xadvance;
491
492         ng.font = current_font;
493         ng.glyph_index = glyphIndex;
494         ng.flags = flags;
495
496         if (activate_newcolor)
497         {
498                 ng.flags |= GS_COLORCHANGE;
499                 ng.newcolor = newcolor;
500         }
501
502         glyphs.push_back(ng);
503         ++charCount;
504
505                 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
506         if (!(flags & GS_SOFTHYPHEN))
507                 cursor += ePoint(xadvance, 0);
508         previous = glyphIndex;
509         return 0;
510 }
511
512 void eTextPara::calc_bbox()
513 {
514         if (!glyphs.size())
515         {
516                 bboxValid = 0;
517                 boundBox = eRect();
518                 return;
519         }
520
521         bboxValid = 1;
522
523         glyphString::iterator i(glyphs.begin());
524
525         boundBox = i->bbox;
526         ++i;
527
528         for (; i != glyphs.end(); ++i)
529         {
530                 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
531                         continue;
532                 if ( i->bbox.left() < boundBox.left() )
533                         boundBox.setLeft( i->bbox.left() );
534                 if ( i->bbox.right() > boundBox.right() )
535                         boundBox.setRight( i->bbox.right() );
536         }
537         boundBox.setTop(area.y());
538         boundBox.setBottom(area.y() + totalheight);
539 //      eDebug("[eTextPara] boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
540 }
541
542 void eTextPara::newLine(int flags)
543 {
544         if (maximum.width()<cursor.x())
545                 maximum.setWidth(cursor.x());
546         cursor.setX(left);
547         int height = current_face->size->metrics.height;
548         if (!height)
549         {
550                 /* some fonts don't have height filled in. Estimate it based on the bbox dimensions. */
551                 /* Usually, 'height' is less than the complete boundingbox height, so we use only yMax, to avoid getting a much too large line spacing */
552                 height = FT_MulFix(current_face->bbox.yMax, current_face->size->metrics.y_scale);
553         }
554         height >>= 6;
555
556         lineOffsets.push_back(cursor.y());
557         lineChars.push_back(charCount);
558         charCount=0;
559
560         cursor+=ePoint(0, height);
561         if (maximum.height()<cursor.y())
562                 maximum.setHeight(cursor.y());
563         previous=0;
564         totalheight += height;
565 }
566
567 eTextPara::~eTextPara()
568 {
569         clear();
570 }
571
572 void eTextPara::setFont(const gFont *font)
573 {
574         ePtr<Font> fnt, replacement;
575         fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
576         if (!fnt)
577                 eWarning("[eTextPara] FONT '%s' MISSING!", font->family.c_str());
578         fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
579         setFont(fnt, replacement);
580 }
581
582 std::string eTextPara::replacement_facename;
583 std::set<int> eTextPara::forced_replaces;
584
585 void eTextPara::setFont(Font *fnt, Font *replacement)
586 {
587         if (!fnt)
588                 return;
589         current_font=fnt;
590         replacement_font=replacement;
591         singleLock s(ftlock);
592
593                         // we ask for replacment_font first becauseof the cache
594         if (replacement_font)
595         {
596                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
597                                             replacement_font->scaler.face_id,
598                                             &replacement_face) < 0) ||
599                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
600                                             &replacement_font->scaler,
601                                             &replacement_font->size) < 0))
602                 {
603                         eDebug("[eTextPara] setFont FTC_Manager_Lookup_Size replacement_font failed!");
604                         return;
605                 }
606         }
607         if (current_font)
608         {
609                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
610                                             current_font->scaler.face_id,
611                                             &current_face) < 0) ||
612                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
613                                             &current_font->scaler,
614                                             &current_font->size) < 0))
615                 {
616                         eDebug("[eTextPara] setFont FTC_Manager_Lookup_Size current_font failed!");
617                         return;
618                 }
619         }
620         previous=0;
621         use_kerning=FT_HAS_KERNING(current_face);
622 }
623
624 void
625 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
626
627 int eTextPara::renderString(const char *string, int rflags, int border)
628 {
629         singleLock s(ftlock);
630
631         if (!current_font)
632                 return -1;
633
634         if (!current_face)
635                 eFatal("[eTextPara] renderString: no current_face");
636         if (!current_face->size)
637                 eFatal("[eTextPara] renderString: no current_face->size");
638
639         if (cursor.y()==-1)
640         {
641                 int height = current_face->size->metrics.height;
642                 int ascender = current_face->size->metrics.ascender;
643                 if (!height || !ascender)
644                 {
645                         int ymax = FT_MulFix(current_face->bbox.yMax, current_face->size->metrics.y_scale);
646                         if (!height)
647                         {
648                                 /* some fonts don't have height filled in. Estimate it based on the bbox dimensions. */
649                                 /* For the first line we calculate the full boundingbox height, this gives the best result when centering vertically */
650                                 height = ymax - FT_MulFix(current_face->bbox.yMin, current_face->size->metrics.y_scale);
651                         }
652                         if (!ascender)
653                         {
654                                 /* some fonts don't have ascender filled in. Estimate it based on the bbox dimensions. */
655                                 ascender = ymax;
656                         }
657                 }
658                 totalheight = height >> 6;
659                 cursor=ePoint(area.x(), area.y()+(ascender>>6));
660                 left=cursor.x();
661         }
662
663         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
664                                     current_font->scaler.face_id,
665                                     &current_face) < 0) ||
666             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
667                                     &current_font->scaler,
668                                     &current_font->size) < 0))
669         {
670                 eDebug("[eTextPara] renderString FTC_Manager_Lookup_Size current_font failed!");
671                 return -1;
672         }
673
674         std::vector<unsigned long> uc_string, uc_visual;
675         if (string)
676                 uc_string.reserve(strlen(string));
677
678         const char *p = string ? string : "";
679
680         while (*p)
681         {
682                 unsigned int unicode=(unsigned char)*p++;
683
684                 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
685                 {
686                         if ((unicode & 0xE0)==0xC0) // two bytes
687                         {
688                                 unicode&=0x1F;
689                                 unicode<<=6;
690                                 if (*p)
691                                         unicode|=(*p++)&0x3F;
692                         } else if ((unicode & 0xF0)==0xE0) // three bytes
693                         {
694                                 unicode&=0x0F;
695                                 unicode<<=6;
696                                 if (*p)
697                                         unicode|=(*p++)&0x3F;
698                                 unicode<<=6;
699                                 if (*p)
700                                         unicode|=(*p++)&0x3F;
701                         } else if ((unicode & 0xF8)==0xF0) // four bytes
702                         {
703                                 unicode&=0x07;
704                                 unicode<<=6;
705                                 if (*p)
706                                         unicode|=(*p++)&0x3F;
707                                 unicode<<=6;
708                                 if (*p)
709                                         unicode|=(*p++)&0x3F;
710                                 unicode<<=6;
711                                 if (*p)
712                                         unicode|=(*p++)&0x3F;
713                         }
714                 }
715                 uc_string.push_back(unicode);
716         }
717
718         std::vector<unsigned long> uc_shape;
719
720                 // character -> glyph conversion
721         shape(uc_shape, uc_string);
722
723                 // now do the usual logical->visual reordering
724         int size=uc_shape.size();
725         FriBidiCharType dir=FRIBIDI_TYPE_ON;
726         uc_visual.resize(size);
727                 // gaaanz lahm, aber anders geht das leider nicht, sorry.
728         FriBidiChar array[size], target[size];
729         std::copy(uc_shape.begin(), uc_shape.end(), array);
730         fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
731         uc_visual.assign(target, target+size);
732
733         glyphs.reserve(size);
734
735         unsigned long newcolor = 0;
736         bool activate_newcolor = false;
737         int nextflags = 0;
738
739         for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
740                 i != uc_visual.end(); ++i)
741         {
742                 int isprintable=1;
743                 int flags = nextflags;
744                 nextflags = 0;
745                 unsigned long chr = *i;
746
747                 if (!(rflags&RS_DIRECT))
748                 {
749                         /* detect linefeeds and set flag GS_LF for the last glyph in this line */
750                         if ((i + 1) != uc_visual.end())
751                         {
752                                 unsigned long c = *(i + 1);
753                                 if (c == '\n' || c == 0x8A || c == 0xE08A /* linefeed */
754                                         || (c == '\\' && (i + 2) != uc_visual.end() && *(i + 2) == 'n')) /* escaped linefeed */
755                                 {
756                                         flags |= GS_LF;
757                                 }
758                         }
759
760                         switch (chr)
761                         {
762                         case '\\':
763                         {
764                                 if ((i + 1) != uc_visual.end())
765                                 {
766                                         unsigned long c = *(i+1);
767                                         switch (c)
768                                         {
769                                                 case 'n':
770                                                         i++;
771                                                         goto newline;
772                                                 case 't':
773                                                         i++;
774                                                         goto tab;
775                                                 case 'r':
776                                                         i++;
777                                                         goto nprint;
778                                                 case 'c':
779                                                 {
780                                                         char color[8];
781                                                         int codeidx;
782                                                         for (codeidx = 0; codeidx < 8; codeidx++)
783                                                         {
784                                                                 if ((i + 2 + codeidx) == uc_visual.end()) break;
785                                                                 color[codeidx] = (char)((*(i + 2 + codeidx)) & 0xff);
786                                                         }
787                                                         if (codeidx == 8)
788                                                         {
789                                                                 newcolor = gRGB(color).argb();
790                                                                 activate_newcolor = true;
791                                                                 isprintable = 0;
792                                                                 i += 1 + codeidx;
793                                                         }
794                                                         break;
795                                                 }
796                                                 default:
797                                                 ;
798                                         }
799                                 }
800                                 break;
801                         }
802                         case '\t':
803 tab:                            isprintable=0;
804                                 cursor+=ePoint(current_font->tabwidth, 0);
805                                 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
806                                 break;
807                         case 0x8A:
808                         case 0xE08A:
809                         case '\n':
810 newline:                        isprintable=0;
811                                 newLine(rflags);
812                                 nextflags|=GS_ISFIRST;
813                                 break;
814                         case '\r':
815                         case 0x86: case 0xE086:
816                         case 0x87: case 0xE087:
817 nprint:                         isprintable=0;
818                                 break;
819                         case 0xAD: // soft-hyphen
820                                 flags |= GS_SOFTHYPHEN;
821                                 chr = 0x2010; /* hyphen */
822                                 break;
823                         case 0x2010:
824                         case '-':
825                                 flags |= GS_HYPHEN;
826                                 break;
827                         case ' ':
828                                 flags|=GS_ISSPACE;
829                         default:
830                                 break;
831                         }
832                 }
833                 if (isprintable)
834                 {
835                         FT_UInt index = 0;
836
837                                 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
838                         if (chr == 0x2010)
839                                 chr = '-';
840
841                         if (forced_replaces.find(chr) == forced_replaces.end())
842                                 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
843
844                         if (!index)
845                         {
846                                 if (replacement_face)
847                                         index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
848
849                                 if (!index)
850                                         eDebug("[eTextPara] unicode U+%4lx not present", chr);
851                                 else
852                                         appendGlyph(replacement_font, replacement_face, index, flags, rflags, border, i == uc_visual.end() - 1, activate_newcolor, newcolor);
853                         } else
854                                 appendGlyph(current_font, current_face, index, flags, rflags, border, i == uc_visual.end() - 1, activate_newcolor, newcolor);
855
856                         activate_newcolor = false;
857                 }
858         }
859         bboxValid=false;
860         calc_bbox();
861         if (dir & FRIBIDI_MASK_RTL)
862         {
863                 doTopBottomReordering=true;
864         }
865         if (charCount)
866         {
867                 lineOffsets.push_back(cursor.y());
868                 lineChars.push_back(charCount);
869                 charCount=0;
870         }
871         return 0;
872 }
873
874 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground, bool border)
875 {
876         if (glyphs.empty()) return;
877
878         singleLock s(ftlock);
879
880         if (!current_font)
881                 return;
882
883         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
884                                     current_font->scaler.face_id,
885                                     &current_face) < 0) ||
886             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
887                                     &current_font->scaler,
888                                     &current_font->size) < 0))
889         {
890                 eDebug("[eTextPara] FTC_Manager_Lookup_Size failed!");
891                 return;
892         }
893
894         ePtr<gPixmap> target;
895         dc.getPixmap(target);
896         gUnmanagedSurface *surface = target->surface;
897         gRGB currentforeground = foreground;
898
899         register int opcode = -1;
900
901         __u32 lookup32_normal[16];
902         __u32 lookup32_invert[16];
903         __u16 *lookup16_normal = (__u16*)lookup32_normal; // shares the same memory
904         __u16 *lookup16_invert = (__u16*)lookup32_invert;
905         gColor *lookup8_normal = 0;
906         gColor *lookup8_invert = (gColor*)lookup32_invert;
907         __u32 *lookup32;
908         __u16 *lookup16;
909         gColor *lookup8;
910
911         gRegion sarea(eRect(0, 0, surface->x, surface->y));
912         gRegion clip = dc.getClip() & sarea;
913         clip &= eRect(area.left() + offset.x(), area.top() + offset.y(), area.width(), area.height()+(current_face->size->metrics.ascender>>6));
914
915         int buffer_stride=surface->stride;
916
917         bool setcolor = true;
918         std::list<int>::reverse_iterator line_offs_it(lineOffsets.rbegin());
919         std::list<int>::iterator line_chars_it(lineChars.begin());
920         int line_offs=0;
921         int line_chars=0;
922         for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i, --line_chars)
923         {
924                 while(!line_chars)
925                 {
926                         line_offs = *(line_offs_it++);
927                         line_chars = *(line_chars_it++);
928                 }
929                 if (i->flags & GS_COLORCHANGE)
930                 {
931                         /* don't do colorchanges in borders */
932                         if (!border)
933                         {
934                                 currentforeground = i->newcolor;
935                                 setcolor = true;
936                         }
937                 }
938                 if (setcolor)
939                 {
940                         setcolor = false;
941                         if (surface->bpp == 8)
942                         {
943                                 if (surface->clut.data)
944                                 {
945                                         lookup8_normal=getColor(surface->clut, background, currentforeground).lookup;
946
947                                         int i;
948                                         for (i=0; i<16; ++i)
949                                                 lookup8_invert[i] = lookup8_normal[i^0xF];
950
951                                         opcode=0;
952                                 } else
953                                         opcode=1;
954                         } else if (surface->bpp == 32)
955                         {
956                                 opcode=3;
957
958                                 for (int i=0; i<16; ++i)
959                                 {
960 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
961
962                                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
963                                         int sa = i * 16;
964                                         if (sa < 256)
965                                         {
966                                                 da = BLEND(background.a, currentforeground.a, sa) & 0xFF;
967                                                 dr = BLEND(background.r, currentforeground.r, sa) & 0xFF;
968                                                 dg = BLEND(background.g, currentforeground.g, sa) & 0xFF;
969                                                 db = BLEND(background.b, currentforeground.b, sa) & 0xFF;
970                                         }
971 #undef BLEND
972                                         da ^= 0xFF;
973                                         lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
974                                 }
975                                 for (int i=0; i<16; ++i)
976                                         lookup32_invert[i]=lookup32_normal[i^0xF];
977                         } else if (surface->bpp == 16)
978                         {
979                                 opcode=2;
980                                 for (int i = 0; i != 16; ++i)
981                                 {
982 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
983                                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
984                                         int sa = i * 16;
985                                         if (sa < 256)
986                                         {
987                                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
988                                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
989                                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
990                                         }
991 #undef BLEND
992 #if BYTE_ORDER == LITTLE_ENDIAN
993                                         lookup16_normal[i] = bswap_16(((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3));
994 #else
995                                         lookup16_normal[i] = ((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3);
996 #endif
997                                         da ^= 0xFF;
998                                 }
999                                 for (int i=0; i<16; ++i)
1000                                         lookup16_invert[i]=lookup16_normal[i^0xF];
1001                         } else
1002                         {
1003                                 eWarning("[eTextPara] can't render to %dbpp", surface->bpp);
1004                                 return;
1005                         }
1006                 }
1007                 if (i->flags & GS_SOFTHYPHEN)
1008                         continue;
1009
1010                 if (!(i->flags & GS_INVERT))
1011                 {
1012                         lookup8 = lookup8_normal;
1013                         lookup16 = lookup16_normal;
1014                         lookup32 = lookup32_normal;
1015                 } else
1016                 {
1017                         lookup8 = lookup8_invert;
1018                         lookup16 = lookup16_invert;
1019                         lookup32 = lookup32_invert;
1020                 }
1021
1022                 int rxbase, rybase;
1023                 __u8 *dbase;
1024                 __u8 *sbase;
1025                 int sxbase;
1026                 int sybase;
1027                 int pitch;
1028                 if (i->image)
1029                 {
1030                         FT_BitmapGlyph glyph = border ? (FT_BitmapGlyph)i->borderimage : (FT_BitmapGlyph)i->image;
1031                         if (!glyph->bitmap.buffer) continue;
1032                         rxbase = i->x + glyph->left + offset.x();
1033                         rybase = i->y - glyph->top + offset.y();
1034                         rybase=(doTopBottomReordering ? line_offs : i->y) - glyph->top + offset.y();
1035                         sbase = glyph->bitmap.buffer;
1036                         sxbase = glyph->bitmap.width;
1037                         sybase = glyph->bitmap.rows;
1038                         pitch = glyph->bitmap.pitch;
1039                 }
1040                 else
1041                 {
1042                         static FTC_SBit glyph_bitmap;
1043                         if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
1044                                 continue;
1045                         rxbase=i->x+glyph_bitmap->left + offset.x();
1046                         rybase=(doTopBottomReordering ? line_offs : i->y) - glyph_bitmap->top + offset.y();
1047                         sbase=glyph_bitmap->buffer;
1048                         sxbase=glyph_bitmap->width;
1049                         sybase=glyph_bitmap->height;
1050                         pitch = glyph_bitmap->pitch;
1051                 }
1052                 dbase = (__u8*)(surface->data)+buffer_stride*rybase+rxbase*surface->bypp;
1053                 for (unsigned int c = 0; c < clip.rects.size(); ++c)
1054                 {
1055                         int rx = rxbase, ry = rybase;
1056                         __u8 *d = dbase;
1057                         __u8 *s = sbase;
1058                         register int sx = sxbase;
1059                         int sy = sybase;
1060                         if ((sy+ry) >= clip.rects[c].bottom())
1061                                 sy = clip.rects[c].bottom()-ry;
1062                         if ((sx+rx) >= clip.rects[c].right())
1063                                 sx = clip.rects[c].right()-rx;
1064                         if (rx < clip.rects[c].left())
1065                         {
1066                                 int diff=clip.rects[c].left()-rx;
1067                                 s+=diff;
1068                                 sx-=diff;
1069                                 rx+=diff;
1070                                 d+=diff*surface->bypp;
1071                         }
1072                         if (ry < clip.rects[c].top())
1073                         {
1074                                 int diff=clip.rects[c].top()-ry;
1075                                 s+=diff*pitch;
1076                                 sy-=diff;
1077                                 ry+=diff;
1078                                 d+=diff*buffer_stride;
1079                         }
1080                         if ((sx>0) && (sy>0))
1081                         {
1082                                 int extra_source_stride = pitch - sx;
1083                                 switch (opcode)
1084                                 {
1085                                 case 0:                 // 4bit lookup to 8bit
1086                                         {
1087                                         register int extra_buffer_stride = buffer_stride - sx;
1088                                         register __u8 *td=d;
1089                                         for (int ay = 0; ay < sy; ay++)
1090                                         {
1091                                                 register int ax;
1092
1093                                                 for (ax=0; ax<sx; ax++)
1094                                                 {
1095                                                         register int b=(*s++)>>4;
1096                                                         if(b)
1097                                                                 *td=lookup8[b];
1098                                                         ++td;
1099                                                 }
1100                                                 s += extra_source_stride;
1101                                                 td += extra_buffer_stride;
1102                                         }
1103                                         }
1104                                         break;
1105                                 case 1: // 8bit direct
1106                                         {
1107                                         register int extra_buffer_stride = buffer_stride - sx;
1108                                         register __u8 *td=d;
1109                                         for (int ay = 0; ay < sy; ay++)
1110                                         {
1111                                                 register int ax;
1112                                                 for (ax=0; ax<sx; ax++)
1113                                                 {
1114                                                         register int b=*s++;
1115                                                         *td++^=b;
1116                                                 }
1117                                                 s += extra_source_stride;
1118                                                 td += extra_buffer_stride;
1119                                         }
1120                                         }
1121                                         break;
1122                                 case 2: // 16bit
1123                                         {
1124                                         int extra_buffer_stride = (buffer_stride >> 1) - sx;
1125                                         register __u16 *td = (__u16*)d;
1126                                         for (int ay = 0; ay != sy; ay++)
1127                                         {
1128                                                 register int ax;
1129                                                 for (ax = 0; ax != sx; ax++)
1130                                                 {
1131                                                         register int b = (*s++) >> 4;
1132                                                         if (b)
1133                                                                 *td = lookup16[b];
1134                                                         ++td;
1135                                                 }
1136                                                 s += extra_source_stride;
1137                                                 td += extra_buffer_stride;
1138                                         }
1139                                         }
1140                                         break;
1141                                 case 3: // 32bit
1142                                         {
1143                                         register int extra_buffer_stride = (buffer_stride >> 2) - sx;
1144                                         register __u32 *td=(__u32*)d;
1145                                         for (int ay = 0; ay < sy; ay++)
1146                                         {
1147                                                 register int ax;
1148                                                 for (ax=0; ax<sx; ax++)
1149                                                 {
1150                                                         register int b=(*s++)>>4;
1151                                                         if(b)
1152                                                                 *td=lookup32[b];
1153                                                         ++td;
1154                                                 }
1155                                                 s += extra_source_stride;
1156                                                 td += extra_buffer_stride;
1157                                         }
1158                                         }
1159                                         break;
1160                                 }
1161                         }
1162                 }
1163         }
1164 }
1165
1166 void eTextPara::realign(int dir)        // der code hier ist ein wenig merkwuerdig.
1167 {
1168         glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
1169         if (dir==dirLeft || (dir==dirBidi && !doTopBottomReordering))
1170                 return;
1171         while (c != glyphs.end())
1172         {
1173                 int linelength=0;
1174                 int numspaces=0, num=0;
1175                 begin=end;
1176
1177                 ASSERT( end != glyphs.end());
1178
1179                         // zeilenende suchen
1180                 do {
1181                         last=end;
1182                         ++end;
1183                 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
1184                         // end zeigt jetzt auf begin der naechsten zeile
1185
1186                 for (c=begin; c!=end; ++c)
1187                 {
1188                                 // space am zeilenende skippen
1189                         if ((c==last) && (c->flags&GS_ISSPACE))
1190                                 continue;
1191
1192                         if (c->flags&GS_ISSPACE)
1193                                 numspaces++;
1194                         linelength+=c->w;
1195                         num++;
1196                 }
1197
1198                 switch (dir)
1199                 {
1200                 case dirCenterIfFits:
1201                         // If the text is larger than the available space,
1202                         // don't re-align but align left.
1203                         if (linelength > area.width())
1204                                 return;
1205                         dir = dirCenter;
1206                         // fall-through on purpose
1207                 case dirRight:
1208                 case dirCenter:
1209                 case dirBidi:
1210                 {
1211                         int offset=area.width()-linelength;
1212                         if (dir==dirCenter)
1213                                 offset/=2;
1214                         while (begin != end)
1215                         {
1216                                 begin->bbox.moveBy(offset,0);
1217                                 begin->x += offset;
1218                                 ++begin;
1219                         }
1220                         break;
1221                 }
1222                 case dirBlock:
1223                 {
1224                         if (end == glyphs.end())
1225                         {
1226                                 /* last line, use left alignment */
1227                                 continue;
1228                         }
1229
1230                         if (!numspaces)
1231                         {
1232                                 /* no spaces, use left alignment */
1233                                 continue;
1234                         }
1235
1236                         if (last->flags & GS_LF)
1237                         {
1238                                 /* line ends with a linefeed, use left alignment */
1239                                 continue;
1240                         }
1241
1242                         int off=(area.width()-linelength)*256/(numspaces?numspaces:(num-1));
1243                         int curoff=0;
1244                         while (begin != end)
1245                         {
1246                                 int doadd=0;
1247                                 if (begin->flags & GS_ISSPACE)
1248                                         doadd=1;
1249                                 begin->x+=curoff>>8;
1250                                 begin->bbox.moveBy(curoff>>8,0);
1251                                 if (doadd)
1252                                         curoff+=off;
1253                                 ++begin;
1254                         }
1255                         break;
1256                 }
1257                 }
1258         }
1259         bboxValid=false;
1260         calc_bbox();
1261 }
1262
1263 void eTextPara::clear()
1264 {
1265         singleLock s(ftlock);
1266
1267         current_font = 0;
1268         replacement_font = 0;
1269
1270         for (unsigned int i = 0; i < glyphs.size(); i++)
1271         {
1272                 if (glyphs[i].image) FT_Done_Glyph(glyphs[i].image);
1273                 if (glyphs[i].borderimage) FT_Done_Glyph(glyphs[i].borderimage);
1274         }
1275         glyphs.clear();
1276         totalheight = 0;
1277 }
1278
1279 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");