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