experimental support for freetype 2.1.x and newer versions
[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
10 // use this for init Freetype...
11 #include <ft2build.h>
12 #include FT_FREETYPE_H
13 #ifdef HAVE_FREETYPE2
14 #define FTC_Image_Cache_New(a,b)        FTC_ImageCache_New(a,b)
15 #define FTC_Image_Cache_Lookup(a,b,c,d) FTC_ImageCache_Lookup(a,b,c,d,NULL)
16 #define FTC_SBit_Cache_New(a,b)         FTC_SBitCache_New(a,b)
17 #define FTC_SBit_Cache_Lookup(a,b,c,d)  FTC_SBitCache_Lookup(a,b,c,d,NULL)
18 #endif
19
20 #include <lib/base/eerror.h>
21 #include <lib/gdi/lcd.h>
22 #include <lib/gdi/grc.h>
23 #include <lib/base/elock.h>
24 #include <lib/base/init.h>
25 #include <lib/base/init_num.h>
26
27 #define HAVE_FRIBIDI
28 // until we have it in the cdk
29
30 #ifdef HAVE_FRIBIDI
31 #include <fribidi/fribidi.h>
32 #endif
33
34 #include <map>
35
36 fontRenderClass *fontRenderClass::instance;
37
38 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
39
40 #ifndef HAVE_FREETYPE2
41 static FTC_Font cache_current_font=0;
42 #endif
43
44 struct fntColorCacheKey
45 {
46         gRGB start, end;
47         fntColorCacheKey(const gRGB &start, const gRGB &end)
48                 : start(start), end(end)
49         {
50         }
51         bool operator <(const fntColorCacheKey &c) const
52         {
53                 if (start < c.start)
54                         return 1;
55                 else if (start == c.start)
56                         return end < c.end;
57                 return 0;
58         }
59 };
60
61 std::map<fntColorCacheKey,gLookup> colorcache;
62
63 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
64 {
65         fntColorCacheKey key(start, end);
66         std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
67         if (i != colorcache.end())
68                 return i->second;
69         gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
70 //      eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
71 //              end.a, end.r, end.g, end.b);
72         n.build(16, pal, start, end);
73 //      for (int i=0; i<16; i++)
74 //              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);
75 //      eDebug("");
76         return n;
77 }
78
79 fontRenderClass *fontRenderClass::getInstance()
80 {
81         return instance;
82 }
83
84 FT_Error myFTC_Face_Requester(FTC_FaceID        face_id,
85                                                                                                                         FT_Library      library,
86                                                                                                                         FT_Pointer      request_data,
87                                                                                                                         FT_Face*                aface)
88 {
89         return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
90 }
91
92
93 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
94 {
95         fontListEntry *font=(fontListEntry *)face_id;
96         if (!font)
97                 return -1;
98         
99 //      eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
100
101         int error;
102         if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
103         {
104                 eDebug(" failed: %s", strerror(error));
105                 return error;
106         }
107         FT_Select_Charmap(*aface, ft_encoding_unicode);
108         return 0;
109 }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
110
111 FTC_FaceID fontRenderClass::getFaceID(const std::string &face)
112 {
113         for (fontListEntry *f=font; f; f=f->next)
114         {
115                 if (f->face == face)
116                         return (FTC_FaceID)f;
117         }
118         return 0;
119 }
120
121 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
122 {
123         FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
124         return res;
125 }
126
127 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale)
128 {
129         eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
130         fflush(stdout);
131         int error;
132         fontListEntry *n=new fontListEntry;
133
134         n->scale=scale;
135         FT_Face face;
136         singleLock s(ftlock);
137
138         if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
139                 eFatal(" failed: %s", strerror(error));
140
141         n->filename=filename;
142         n->face=name;
143         FT_Done_Face(face);
144
145         n->next=font;
146         eDebug("OK (%s)", n->face.c_str());
147         font=n;
148
149         return n->face;
150 }
151
152 fontRenderClass::fontListEntry::~fontListEntry()
153 {
154 }
155
156 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
157 {
158         instance=this;
159         eDebug("[FONT] initializing lib...");
160         {
161                 if (FT_Init_FreeType(&library))
162                 {
163                         eDebug("[FONT] initializing failed.");
164                         return;
165                 }
166         }
167         eDebug("[FONT] loading fonts...");
168         fflush(stdout);
169         font=0;
170         
171         int maxbytes=4*1024*1024;
172         eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
173         fflush(stdout);
174         {
175                 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
176                 {
177                         eDebug("[FONT] initializing font cache failed!");
178                         return;
179                 }
180                 if (!cacheManager)
181                 {
182                         eDebug("[FONT] initializing font cache manager error.");
183                         return;
184                 }
185                 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
186                 {
187                         eDebug("[FONT] initializing font cache sbit failed!");
188                         return;
189                 }
190                 if (FTC_Image_Cache_New(cacheManager, &imageCache))
191                 {
192                         eDebug("[FONT] initializing font cache imagecache failed!");
193                 }
194         }
195         return;
196 }
197
198 float fontRenderClass::getLineHeight(const gFont& font)
199 {
200         if (!instance)
201                 return 0;
202         ePtr<Font> fnt;
203         getFont(fnt, font.family.c_str(), font.pointSize);
204         if (!fnt)
205                 return 0;
206         singleLock s(ftlock);
207         FT_Face current_face;
208 #ifdef HAVE_FREETYPE2
209         if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, &current_face) < 0) ||
210             (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
211 #else
212         if (FTC_Manager_Lookup_Size(cacheManager, &fnt->font.font, &current_face, &fnt->size)<0)
213 #endif
214         {
215                 delete fnt;
216                 eDebug("FTC_Manager_Lookup_Size failed!");
217                 return 0;
218         }
219         int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
220         float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
221         return height;
222 }
223
224 fontRenderClass::~fontRenderClass()
225 {
226         singleLock s(ftlock);
227         while(font)
228         {
229                 fontListEntry *f=font;
230                 font=font->next;
231                 delete f;
232         }
233 //      auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten. 
234 //      FTC_Manager_Done(cacheManager);
235 //      FT_Done_FreeType(library);
236 }
237
238 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
239 {
240         FTC_FaceID id=getFaceID(face);
241         if (!id)
242         {
243                 font = 0;
244                 return -1;
245         }
246         font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
247         return 0;
248 }
249
250 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
251 {
252         fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
253         if (is_replacement)
254                 eTextPara::setReplacementFont(alias);
255 }
256
257 DEFINE_REF(Font);
258
259 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
260 {
261         renderer=render;
262 #ifdef HAVE_FREETYPE2
263         font.face_id = faceid;
264         font.width = isize;
265         font.height = isize;
266         font.flags = FT_LOAD_DEFAULT;
267         scaler.face_id = faceid;
268         scaler.width = isize;
269         scaler.height = isize;
270         scaler.pixel = 1;
271 #else
272         font.font.face_id=faceid;
273         font.font.pix_width     = isize;
274         font.font.pix_height = isize;
275         font.image_type = ftc_image_grays;
276 #endif
277         height=isize;
278         if (tabwidth==-1)
279                 tabwidth=8*isize;
280 //      font.image_type |= ftc_image_flag_autohinted;
281 }
282
283 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
284 {
285         return renderer->getGlyphBitmap(&font, glyph_index, sbit);
286 }
287
288 Font::~Font()
289 {
290 }
291
292 DEFINE_REF(eTextPara);
293
294 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
295 {
296         FTC_SBit glyph;
297         if (current_font->getGlyphBitmap(glyphIndex, &glyph))
298                 return 1;
299
300         int nx=cursor.x();
301
302         nx+=glyph->xadvance;
303
304         if (
305                         (rflags&RS_WRAP) && 
306                         (nx >= area.right())
307                 )
308         {
309                 int cnt = 0;
310                 glyphString::reverse_iterator i(glyphs.rbegin());
311                         /* find first possibility (from end to begin) to break */
312                 while (i != glyphs.rend())
313                 {
314                         if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
315                                 break;
316                         cnt++;
317                         ++i;
318                 }
319
320                         /* if ... */
321                 if (i != glyphs.rend()  /* ... we found anything */
322                         && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
323                         && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
324                         && cnt ) /* ... and there are actual non-space characters after this */
325                 {
326                                 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
327                         if (i->flags & GS_SOFTHYPHEN)
328                         {
329                                 i->flags &= ~GS_SOFTHYPHEN;
330                                 i->flags |= GS_HYPHEN;
331                         }
332                         --i; /* skip the space/hypen/softhyphen */
333                         int linelength=cursor.x()-i->x;
334                         i->flags|=GS_ISFIRST; /* make this a line start */
335                         ePoint offset=ePoint(i->x, i->y);
336                         newLine(rflags);
337                         offset-=cursor;
338
339                                 /* and move everything to the end into the next line. */
340                         do
341                         {
342                                 i->x-=offset.x();
343                                 i->y-=offset.y();
344                                 i->bbox.moveBy(-offset.x(), -offset.y());
345                         } while (i-- != glyphs.rbegin()); // rearrange them into the next line
346                         cursor+=ePoint(linelength, 0);  // put the cursor after that line
347                 } else
348                 {
349                         if (cnt)
350                         {
351                                 newLine(rflags);
352                                 flags|=GS_ISFIRST;
353                         }
354                 }
355         }
356
357         int xadvance=glyph->xadvance, kern=0;
358
359         if (previous && use_kerning)
360         {
361                 FT_Vector delta;
362                 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
363                 kern=delta.x>>6;
364         }
365
366         pGlyph ng;
367         ng.bbox.setLeft( (flags&GS_ISFIRST|cursor.x()-1)+glyph->left );
368         ng.bbox.setTop( cursor.y() - glyph->top );
369         ng.bbox.setWidth( glyph->width );
370         ng.bbox.setHeight( glyph->height );
371
372         xadvance += kern;
373         ng.bbox.setWidth(xadvance);
374
375         ng.x = cursor.x()+kern;
376         ng.y = cursor.y();
377         ng.w = xadvance;
378         ng.font = current_font;
379         ng.glyph_index = glyphIndex;
380         ng.flags = flags;
381         glyphs.push_back(ng);
382
383                 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
384         if (!(flags & GS_SOFTHYPHEN))
385                 cursor += ePoint(xadvance, 0);
386         previous = glyphIndex;
387         return 0;
388 }
389
390 void eTextPara::calc_bbox()
391 {
392         if (!glyphs.size())
393         {
394                 bboxValid = 0;
395                 boundBox = eRect();
396                 return;
397         }
398         
399         bboxValid = 1;
400
401         glyphString::iterator i(glyphs.begin());
402         
403         boundBox = i->bbox; 
404         ++i;
405
406         for (; i != glyphs.end(); ++i)
407         {
408                 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
409                         continue;
410                 if ( i->bbox.left() < boundBox.left() )
411                         boundBox.setLeft( i->bbox.left() );
412                 if ( i->bbox.top() < boundBox.top() )
413                         boundBox.setTop( i->bbox.top() );
414                 if ( i->bbox.right() > boundBox.right() )
415                         boundBox.setRight( i->bbox.right() );
416                 if ( i->bbox.bottom() > boundBox.bottom() )
417                         boundBox.setBottom( i->bbox.bottom() );
418         }
419 //      eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
420 }
421
422 void eTextPara::newLine(int flags)
423 {
424         if (maximum.width()<cursor.x())
425                 maximum.setWidth(cursor.x());
426         cursor.setX(left);
427         previous=0;
428         int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
429         cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
430         if (maximum.height()<cursor.y())
431                 maximum.setHeight(cursor.y());
432         previous=0;
433 }
434
435 eTextPara::~eTextPara()
436 {
437         clear();
438 }
439
440 void eTextPara::setFont(const gFont *font)
441 {
442         ePtr<Font> fnt, replacement;
443         fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
444         if (!fnt)
445                 eWarning("FONT '%s' MISSING!", font->family.c_str());
446         fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
447         setFont(fnt, replacement);
448 }
449
450 std::string eTextPara::replacement_facename;
451 std::set<int> eTextPara::forced_replaces;
452
453 void eTextPara::setFont(Font *fnt, Font *replacement)
454 {
455         if (!fnt)
456                 return;
457         current_font=fnt;
458         replacement_font=replacement;
459         singleLock s(ftlock);
460
461                         // we ask for replacment_font first becauseof the cache
462         if (replacement_font)
463         {
464 #ifdef HAVE_FREETYPE2
465                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
466                                             replacement_font->scaler.face_id,
467                                             &replacement_face) < 0) ||
468                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
469                                             &replacement_font->scaler,
470                                             &replacement_font->size) < 0))
471 #else
472                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, 
473                                 &replacement_font->font.font, &replacement_face, 
474                                 &replacement_font->size)<0)
475 #endif
476                 {
477                         eDebug("FTC_Manager_Lookup_Size failed!");
478                         return;
479                 }
480         }
481         if (current_font)
482         {
483 #ifdef HAVE_FREETYPE2
484                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
485                                             current_font->scaler.face_id,
486                                             &current_face) < 0) ||
487                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
488                                             &current_font->scaler,
489                                             &current_font->size) < 0))
490 #else
491                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
492 #endif
493                 {
494                         eDebug("FTC_Manager_Lookup_Size failed!");
495                         return;
496                 }
497         }
498 #ifndef HAVE_FREETYPE2
499         cache_current_font=&current_font->font.font;
500 #endif
501         previous=0;
502         use_kerning=FT_HAS_KERNING(current_face);
503 }
504
505 void
506 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
507
508 int eTextPara::renderString(const char *string, int rflags)
509 {
510         singleLock s(ftlock);
511         
512         if (!current_font)
513                 return -1;
514                 
515         if (cursor.y()==-1)
516         {
517                 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
518                 left=cursor.x();
519         }
520                 
521 #ifdef HAVE_FREETYPE2
522         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
523                                     current_font->scaler.face_id,
524                                     &current_face) < 0) ||
525             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
526                                     &current_font->scaler,
527                                     &current_font->size) < 0))
528         {
529                 eDebug("FTC_Manager_Lookup_Size failed!");
530                 return -1;
531         }
532 #else
533         if (&current_font->font.font != cache_current_font)
534         {
535                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
536                 {
537                         eDebug("FTC_Manager_Lookup_Size failed!");
538                         return -1;
539                 }
540                 cache_current_font=&current_font->font.font;
541         }
542 #endif
543         
544         std::vector<unsigned long> uc_string, uc_visual;
545         if (string)
546                 uc_string.reserve(strlen(string));
547         
548         const char *p = string ? string : "";
549
550         while (*p)
551         {
552                 unsigned int unicode=(unsigned char)*p++;
553
554                 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
555                 {
556                         if ((unicode & 0xE0)==0xC0) // two bytes
557                         {
558                                 unicode&=0x1F;
559                                 unicode<<=6;
560                                 if (*p)
561                                         unicode|=(*p++)&0x3F;
562                         } else if ((unicode & 0xF0)==0xE0) // three bytes
563                         {
564                                 unicode&=0x0F;
565                                 unicode<<=6;
566                                 if (*p)
567                                         unicode|=(*p++)&0x3F;
568                                 unicode<<=6;
569                                 if (*p)
570                                         unicode|=(*p++)&0x3F;
571                         } else if ((unicode & 0xF8)==0xF0) // four bytes
572                         {
573                                 unicode&=0x07;
574                                 unicode<<=6;
575                                 if (*p)
576                                         unicode|=(*p++)&0x3F;
577                                 unicode<<=6;
578                                 if (*p)
579                                         unicode|=(*p++)&0x3F;
580                                 unicode<<=6;
581                                 if (*p)
582                                         unicode|=(*p++)&0x3F;
583                         }
584                 }
585                 uc_string.push_back(unicode);
586         }
587
588         std::vector<unsigned long> uc_shape;
589
590                 // character -> glyph conversion
591         shape(uc_shape, uc_string);
592         
593                 // now do the usual logical->visual reordering
594 #ifdef HAVE_FRIBIDI     
595         FriBidiCharType dir=FRIBIDI_TYPE_ON;
596         {
597                 int size=uc_shape.size();
598                 uc_visual.resize(size);
599                 // gaaanz lahm, aber anders geht das leider nicht, sorry.
600                 FriBidiChar array[size], target[size];
601                 std::copy(uc_shape.begin(), uc_shape.end(), array);
602                 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
603                 uc_visual.assign(target, target+size);
604         }
605 #else
606         uc_visual=uc_shape;
607 #endif
608
609         glyphs.reserve(uc_visual.size());
610         
611         int nextflags = 0;
612         
613         for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
614                 i != uc_visual.end(); ++i)
615         {
616                 int isprintable=1;
617                 int flags = nextflags;
618                 nextflags = 0;
619                 unsigned long chr = *i;
620
621                 if (!(rflags&RS_DIRECT))
622                 {
623                         switch (chr)
624                         {
625                         case '\\':
626                         {
627                                 unsigned long c = *(i+1);
628                                 switch (c)
629                                 {
630                                         case 'n':
631                                                 i++;
632                                                 goto newline;
633                                         case 't':
634                                                 i++;
635                                                 goto tab;
636                                         case 'r':
637                                                 i++;
638                                                 goto nprint;
639                                         default:
640                                         ;
641                                 }
642                                 break;
643                         }
644                         case '\t':
645 tab:            isprintable=0;
646                                 cursor+=ePoint(current_font->tabwidth, 0);
647                                 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
648                                 break;
649                         case 0x8A:
650                         case 0xE08A:
651                         case '\n':
652 newline:isprintable=0;
653                                 newLine(rflags);
654                                 nextflags|=GS_ISFIRST;
655                                 break;
656                         case '\r':
657                         case 0x86: case 0xE086:
658                         case 0x87: case 0xE087:
659 nprint: isprintable=0;
660                                 break;
661                         case 0xAD: // soft-hyphen
662                                 flags |= GS_SOFTHYPHEN;
663                                 chr = 0x2010; /* hyphen */
664                                 break;
665                         case 0x2010:
666                         case '-':
667                                 flags |= GS_HYPHEN;
668                                 break;
669                         case ' ':
670                                 flags|=GS_ISSPACE;
671                         default:
672                                 break;
673                         }
674                 }
675                 if (isprintable)
676                 {
677                         FT_UInt index = 0;
678
679                                 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
680                         if (chr == 0x2010)
681                                 chr = '-';
682
683                         if (forced_replaces.find(chr) == forced_replaces.end())
684                                 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
685
686                         if (!index)
687                         {
688                                 if (replacement_face)
689                                         index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
690
691                                 if (!index)
692                                         eDebug("unicode U+%4lx not present", chr);
693                                 else
694                                         appendGlyph(replacement_font, replacement_face, index, flags, rflags);
695                         } else
696                                 appendGlyph(current_font, current_face, index, flags, rflags);
697                 }
698         }
699         bboxValid=false;
700         calc_bbox();
701 #ifdef HAVE_FRIBIDI
702         if (dir & FRIBIDI_MASK_RTL)
703                 realign(dirRight);
704 #endif
705         return 0;
706 }
707
708 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
709 {
710         singleLock s(ftlock);
711         
712         if (!current_font)
713                 return;
714
715 #ifdef HAVE_FREETYPE2
716         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
717                                     current_font->scaler.face_id,
718                                     &current_face) < 0) ||
719             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
720                                     &current_font->scaler,
721                                     &current_font->size) < 0))
722         {
723                 eDebug("FTC_Manager_Lookup_Size failed!");
724                 return;
725         }
726 #else
727         if (&current_font->font.font != cache_current_font)
728         {
729                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
730                 {
731                         eDebug("FTC_Manager_Lookup_Size failed!");
732                         return;
733                 }
734                 cache_current_font=&current_font->font.font;
735         }
736 #endif
737
738         ePtr<gPixmap> target;
739         dc.getPixmap(target);
740         gSurface *surface = target->surface;
741
742         register int opcode;
743
744         gColor *lookup8, lookup8_invert[16];
745         gColor *lookup8_normal=0;
746
747         __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
748         
749         if (surface->bpp == 8)
750         {
751                 if (surface->clut.data)
752                 {
753                         lookup8_normal=getColor(surface->clut, background, foreground).lookup;
754                         
755                         int i;
756                         for (i=0; i<16; ++i)
757                                 lookup8_invert[i] = lookup8_normal[i^0xF];
758                         
759                         opcode=0;
760                 } else
761                         opcode=1;
762         } else if (surface->bpp == 32)
763         {
764                 opcode=3;
765
766                 for (int i=0; i<16; ++i)
767                 {
768 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
769
770                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
771                         int sa = i * 16;
772                         if (sa < 256)
773                         {
774                                 da = BLEND(background.a, foreground.a, sa) & 0xFF;
775                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
776                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
777                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
778                         }
779 #undef BLEND
780                         da ^= 0xFF;
781                         lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
782                 }
783                 for (int i=0; i<16; ++i)
784                         lookup32_invert[i]=lookup32_normal[i^0xF];
785         } else
786         {
787                 eWarning("can't render to %dbpp", surface->bpp);
788                 return;
789         }
790         
791         gRegion area(eRect(0, 0, surface->x, surface->y));
792         gRegion clip = dc.getClip() & area;
793
794         int buffer_stride=surface->stride;
795         
796         for (unsigned int c = 0; c < clip.rects.size(); ++c)
797         {
798                 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
799                 {
800                         if (i->flags & GS_SOFTHYPHEN)
801                                 continue;
802
803                         if (!(i->flags & GS_INVERT))
804                         {
805                                 lookup8 = lookup8_normal;
806                                 lookup32 = lookup32_normal;
807                         } else
808                         {
809                                 lookup8 = lookup8_invert;
810                                 lookup32 = lookup32_invert;
811                         }
812                 
813                         static FTC_SBit glyph_bitmap;
814                         if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
815                                 continue;
816                         int rx=i->x+glyph_bitmap->left + offset.x();
817                         int ry=i->y-glyph_bitmap->top  + offset.y();
818                 
819                         __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
820                         __u8 *s=glyph_bitmap->buffer;
821                         register int sx=glyph_bitmap->width;
822                         int sy=glyph_bitmap->height;
823                         if ((sy+ry) >= clip.rects[c].bottom())
824                                 sy=clip.rects[c].bottom()-ry;
825                         if ((sx+rx) >= clip.rects[c].right())
826                                 sx=clip.rects[c].right()-rx;
827                         if (rx < clip.rects[c].left())
828                         {
829                                 int diff=clip.rects[c].left()-rx;
830                                 s+=diff;
831                                 sx-=diff;
832                                 rx+=diff;
833                                 d+=diff*surface->bypp;
834                         }
835                         if (ry < clip.rects[c].top())
836                         {
837                                 int diff=clip.rects[c].top()-ry;
838                                 s+=diff*glyph_bitmap->pitch;
839                                 sy-=diff;
840                                 ry+=diff;
841                                 d+=diff*buffer_stride;
842                         }
843                         if (sx>0)
844                                 for (int ay=0; ay<sy; ay++)
845                                 {
846                                         if (!opcode)            // 4bit lookup to 8bit
847                                         {
848                                                 register __u8 *td=d;
849                                                 register int ax;
850                                                 
851                                                 for (ax=0; ax<sx; ax++)
852                                                 {       
853                                                         register int b=(*s++)>>4;
854                                                         if(b)
855                                                                 *td++=lookup8[b];
856                                                         else
857                                                                 td++;
858                                                 }
859                                         } else if (opcode == 1) // 8bit direct
860                                         {
861                                                 register __u8 *td=d;
862                                                 register int ax;
863                                                 for (ax=0; ax<sx; ax++)
864                                                 {       
865                                                         register int b=*s++;
866                                                         *td++^=b;
867                                                 }
868                                         } else
869                                         {
870                                                 register __u32 *td=(__u32*)d;
871                                                 register int ax;
872                                                 for (ax=0; ax<sx; ax++)
873                                                 {       
874                                                         register int b=(*s++)>>4;
875                                                         if(b)
876                                                                 *td++=lookup32[b];
877                                                         else
878                                                                 td++;
879                                                 }
880                                         }
881                                         s+=glyph_bitmap->pitch-sx;
882                                         d+=buffer_stride;
883                                 }
884                 }
885         }
886 }
887
888 void eTextPara::realign(int dir)        // der code hier ist ein wenig merkwuerdig.
889 {
890         glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
891         if (dir==dirLeft)
892                 return;
893         while (c != glyphs.end())
894         {
895                 int linelength=0;
896                 int numspaces=0, num=0;
897                 begin=end;
898                 
899                 ASSERT( end != glyphs.end());
900                 
901                         // zeilenende suchen
902                 do {
903                         last=end;
904                         ++end;
905                 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
906                         // end zeigt jetzt auf begin der naechsten zeile
907                 
908                 for (c=begin; c!=end; ++c)
909                 {
910                                 // space am zeilenende skippen
911                         if ((c==last) && (c->flags&GS_ISSPACE))
912                                 continue;
913
914                         if (c->flags&GS_ISSPACE)
915                                 numspaces++;
916                         linelength+=c->w;
917                         num++;
918                 }
919
920                 switch (dir)
921                 {
922                 case dirRight:
923                 case dirCenter:
924                 {
925                         int offset=area.width()-linelength;
926                         if (dir==dirCenter)
927                                 offset/=2;
928                         offset+=area.left();
929                         while (begin != end)
930                         {
931                                 begin->bbox.moveBy(offset-begin->x,0);
932                                 begin->x=offset;
933                                 offset+=begin->w;
934                                 ++begin;
935                         }
936                         break;
937                 }
938                 case dirBlock:
939                 {
940                         if (end == glyphs.end())                // letzte zeile linksbuendig lassen
941                                 continue;
942                         int spacemode;
943                         if (numspaces)
944                                 spacemode=1;
945                         else
946                                 spacemode=0;
947                         if ((!spacemode) && (num<2))
948                                 break;
949                         int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
950                         int curoff=0;
951                         while (begin != end)
952                         {
953                                 int doadd=0;
954                                 if ((!spacemode) || (begin->flags&GS_ISSPACE))
955                                         doadd=1;
956                                 begin->x+=curoff>>8;
957                                 begin->bbox.moveBy(curoff>>8,0);
958                                 if (doadd)
959                                         curoff+=off;
960                                 ++begin;
961                         }
962                         break;
963                 }
964                 }
965         }
966         bboxValid=false;
967         calc_bbox();
968 }
969
970 void eTextPara::clear()
971 {
972         singleLock s(ftlock);
973
974         current_font = 0;
975         replacement_font = 0;
976
977         glyphs.clear();
978 }
979
980 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");