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