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