lib/gdi/picload.cpp: add missing fclose (this fixes a ePicload fd leak when thumbnail...
[enigma2.git] / lib / gdi / font.cpp
1 #include <lib/gdi/font.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <ctype.h>
6 #include <pthread.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9 #include <byteswap.h>
10
11 #ifndef BYTE_ORDER
12 #error "no BYTE_ORDER defined!"
13 #endif
14
15 // use this for init Freetype...
16 #include <ft2build.h>
17 #include FT_FREETYPE_H
18 #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                                 --lineChars.back();
350                                 ++charCount;
351                         } while (i-- != glyphs.rbegin()); // rearrange them into the next line
352                         cursor+=ePoint(linelength, 0);  // put the cursor after that line
353                 } else
354                 {
355                         if (cnt)
356                         {
357                                 newLine(rflags);
358                                 flags|=GS_ISFIRST;
359                         }
360                 }
361         }
362
363         int xadvance=glyph->xadvance, kern=0;
364
365         if (previous && use_kerning)
366         {
367                 FT_Vector delta;
368                 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
369                 kern=delta.x>>6;
370         }
371
372         pGlyph ng;
373         ng.bbox.setLeft( ((flags&GS_ISFIRST)|(cursor.x()-1))+glyph->left );
374         ng.bbox.setTop( cursor.y() - glyph->top );
375         ng.bbox.setWidth( glyph->width );
376         ng.bbox.setHeight( glyph->height );
377
378         xadvance += kern;
379         ng.bbox.setWidth(xadvance);
380
381         ng.x = cursor.x()+kern;
382         ng.y = cursor.y();
383         ng.w = xadvance;
384         ng.font = current_font;
385         ng.glyph_index = glyphIndex;
386         ng.flags = flags;
387         glyphs.push_back(ng);
388         ++charCount;
389
390                 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
391         if (!(flags & GS_SOFTHYPHEN))
392                 cursor += ePoint(xadvance, 0);
393         previous = glyphIndex;
394         return 0;
395 }
396
397 void eTextPara::calc_bbox()
398 {
399         if (!glyphs.size())
400         {
401                 bboxValid = 0;
402                 boundBox = eRect();
403                 return;
404         }
405         
406         bboxValid = 1;
407
408         glyphString::iterator i(glyphs.begin());
409         
410         boundBox = i->bbox; 
411         ++i;
412
413         for (; i != glyphs.end(); ++i)
414         {
415                 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
416                         continue;
417                 if ( i->bbox.left() < boundBox.left() )
418                         boundBox.setLeft( i->bbox.left() );
419                 if ( i->bbox.top() < boundBox.top() )
420                         boundBox.setTop( i->bbox.top() );
421                 if ( i->bbox.right() > boundBox.right() )
422                         boundBox.setRight( i->bbox.right() );
423                 if ( i->bbox.bottom() > boundBox.bottom() )
424                         boundBox.setBottom( i->bbox.bottom() );
425         }
426 //      eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
427 }
428
429 void eTextPara::newLine(int flags)
430 {
431         if (maximum.width()<cursor.x())
432                 maximum.setWidth(cursor.x());
433         cursor.setX(left);
434         previous=0;
435         int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
436
437         lineOffsets.push_back(cursor.y());
438         lineChars.push_back(charCount);
439         charCount=0;
440
441         cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
442
443         if (maximum.height()<cursor.y())
444                 maximum.setHeight(cursor.y());
445         previous=0;
446 }
447
448 eTextPara::~eTextPara()
449 {
450         clear();
451 }
452
453 void eTextPara::setFont(const gFont *font)
454 {
455         ePtr<Font> fnt, replacement;
456         fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
457         if (!fnt)
458                 eWarning("FONT '%s' MISSING!", font->family.c_str());
459         fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
460         setFont(fnt, replacement);
461 }
462
463 std::string eTextPara::replacement_facename;
464 std::set<int> eTextPara::forced_replaces;
465
466 void eTextPara::setFont(Font *fnt, Font *replacement)
467 {
468         if (!fnt)
469                 return;
470         current_font=fnt;
471         replacement_font=replacement;
472         singleLock s(ftlock);
473
474                         // we ask for replacment_font first becauseof the cache
475         if (replacement_font)
476         {
477 #ifdef HAVE_FREETYPE2
478                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
479                                             replacement_font->scaler.face_id,
480                                             &replacement_face) < 0) ||
481                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
482                                             &replacement_font->scaler,
483                                             &replacement_font->size) < 0))
484 #else
485                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, 
486                                 &replacement_font->font.font, &replacement_face, 
487                                 &replacement_font->size)<0)
488 #endif
489                 {
490                         eDebug("FTC_Manager_Lookup_Size failed!");
491                         return;
492                 }
493         }
494         if (current_font)
495         {
496 #ifdef HAVE_FREETYPE2
497                 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
498                                             current_font->scaler.face_id,
499                                             &current_face) < 0) ||
500                     (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
501                                             &current_font->scaler,
502                                             &current_font->size) < 0))
503 #else
504                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
505 #endif
506                 {
507                         eDebug("FTC_Manager_Lookup_Size failed!");
508                         return;
509                 }
510         }
511 #ifndef HAVE_FREETYPE2
512         cache_current_font=&current_font->font.font;
513 #endif
514         previous=0;
515         use_kerning=FT_HAS_KERNING(current_face);
516 }
517
518 void
519 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
520
521 int eTextPara::renderString(const char *string, int rflags)
522 {
523         singleLock s(ftlock);
524         
525         if (!current_font)
526                 return -1;
527
528 #ifdef HAVE_FREETYPE2
529         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
530                                     current_font->scaler.face_id,
531                                     &current_face) < 0) ||
532             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
533                                     &current_font->scaler,
534                                     &current_font->size) < 0))
535         {
536                 eDebug("FTC_Manager_Lookup_Size failed!");
537                 return -1;
538         }
539 #else
540         if (&current_font->font.font != cache_current_font)
541         {
542                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
543                 {
544                         eDebug("FTC_Manager_Lookup_Size failed!");
545                         return -1;
546                 }
547                 cache_current_font=&current_font->font.font;
548         }
549 #endif
550
551         if (!current_face)
552                 eFatal("eTextPara::renderString: no current_face");
553         if (!current_face->size)
554                 eFatal("eTextPara::renderString: no current_face->size");
555
556         if (cursor.y()==-1)
557         {
558                 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
559                 left=cursor.x();
560         }
561
562         std::vector<unsigned long> uc_string, uc_visual;
563         if (string)
564                 uc_string.reserve(strlen(string));
565         
566         const char *p = string ? string : "";
567
568         while (*p)
569         {
570                 unsigned int unicode=(unsigned char)*p++;
571
572                 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
573                 {
574                         if ((unicode & 0xE0)==0xC0) // two bytes
575                         {
576                                 unicode&=0x1F;
577                                 unicode<<=6;
578                                 if (*p)
579                                         unicode|=(*p++)&0x3F;
580                         } else if ((unicode & 0xF0)==0xE0) // three bytes
581                         {
582                                 unicode&=0x0F;
583                                 unicode<<=6;
584                                 if (*p)
585                                         unicode|=(*p++)&0x3F;
586                                 unicode<<=6;
587                                 if (*p)
588                                         unicode|=(*p++)&0x3F;
589                         } else if ((unicode & 0xF8)==0xF0) // four bytes
590                         {
591                                 unicode&=0x07;
592                                 unicode<<=6;
593                                 if (*p)
594                                         unicode|=(*p++)&0x3F;
595                                 unicode<<=6;
596                                 if (*p)
597                                         unicode|=(*p++)&0x3F;
598                                 unicode<<=6;
599                                 if (*p)
600                                         unicode|=(*p++)&0x3F;
601                         }
602                 }
603                 uc_string.push_back(unicode);
604         }
605
606         std::vector<unsigned long> uc_shape;
607
608                 // character -> glyph conversion
609         shape(uc_shape, uc_string);
610         
611                 // now do the usual logical->visual reordering
612         int size=uc_shape.size();
613 #ifdef HAVE_FRIBIDI
614         FriBidiCharType dir=FRIBIDI_TYPE_ON;
615         uc_visual.resize(size);
616         // gaaanz lahm, aber anders geht das leider nicht, sorry.
617         FriBidiChar array[size], target[size];
618         std::copy(uc_shape.begin(), uc_shape.end(), array);
619         fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
620         uc_visual.assign(target, target+size);
621 #else
622         uc_visual=uc_shape;
623 #endif
624
625         glyphs.reserve(size);
626         
627         int nextflags = 0;
628         
629         for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
630                 i != uc_visual.end(); ++i)
631         {
632                 int isprintable=1;
633                 int flags = nextflags;
634                 nextflags = 0;
635                 unsigned long chr = *i;
636
637                 if (!(rflags&RS_DIRECT))
638                 {
639                         switch (chr)
640                         {
641                         case '\\':
642                         {
643                                 unsigned long c = *(i+1);
644                                 switch (c)
645                                 {
646                                         case 'n':
647                                                 i++;
648                                                 goto newline;
649                                         case 't':
650                                                 i++;
651                                                 goto tab;
652                                         case 'r':
653                                                 i++;
654                                                 goto nprint;
655                                         default:
656                                         ;
657                                 }
658                                 break;
659                         }
660                         case '\t':
661 tab:            isprintable=0;
662                                 cursor+=ePoint(current_font->tabwidth, 0);
663                                 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
664                                 break;
665                         case 0x8A:
666                         case 0xE08A:
667                         case '\n':
668 newline:isprintable=0;
669                                 newLine(rflags);
670                                 nextflags|=GS_ISFIRST;
671                                 break;
672                         case '\r':
673                         case 0x86: case 0xE086:
674                         case 0x87: case 0xE087:
675 nprint: isprintable=0;
676                                 break;
677                         case 0xAD: // soft-hyphen
678                                 flags |= GS_SOFTHYPHEN;
679                                 chr = 0x2010; /* hyphen */
680                                 break;
681                         case 0x2010:
682                         case '-':
683                                 flags |= GS_HYPHEN;
684                                 break;
685                         case ' ':
686                                 flags|=GS_ISSPACE;
687                         default:
688                                 break;
689                         }
690                 }
691                 if (isprintable)
692                 {
693                         FT_UInt index = 0;
694
695                                 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
696                         if (chr == 0x2010)
697                                 chr = '-';
698
699                         if (forced_replaces.find(chr) == forced_replaces.end())
700                                 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
701
702                         if (!index)
703                         {
704                                 if (replacement_face)
705                                         index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
706
707                                 if (!index)
708                                         eDebug("unicode U+%4lx not present", chr);
709                                 else
710                                         appendGlyph(replacement_font, replacement_face, index, flags, rflags);
711                         } else
712                                 appendGlyph(current_font, current_face, index, flags, rflags);
713                 }
714         }
715         bboxValid=false;
716         calc_bbox();
717 #ifdef HAVE_FRIBIDI
718         if (dir & FRIBIDI_MASK_RTL)
719         {
720                 realign(dirRight);
721                 doTopBottomReordering=true;
722         }
723 #endif
724
725         if (charCount)
726         {
727                 lineOffsets.push_back(cursor.y());
728                 lineChars.push_back(charCount);
729                 charCount=0;
730         }
731
732         return 0;
733 }
734
735 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
736 {
737         singleLock s(ftlock);
738         
739         if (!current_font)
740                 return;
741
742 #ifdef HAVE_FREETYPE2
743         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
744                                     current_font->scaler.face_id,
745                                     &current_face) < 0) ||
746             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
747                                     &current_font->scaler,
748                                     &current_font->size) < 0))
749         {
750                 eDebug("FTC_Manager_Lookup_Size failed!");
751                 return;
752         }
753 #else
754         if (&current_font->font.font != cache_current_font)
755         {
756                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
757                 {
758                         eDebug("FTC_Manager_Lookup_Size failed!");
759                         return;
760                 }
761                 cache_current_font=&current_font->font.font;
762         }
763 #endif
764
765         ePtr<gPixmap> target;
766         dc.getPixmap(target);
767         gSurface *surface = target->surface;
768
769         register int opcode;
770
771         gColor *lookup8, lookup8_invert[16];
772         gColor *lookup8_normal=0;
773
774         __u16 lookup16_normal[16], lookup16_invert[16], *lookup16;
775         __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
776
777         if (surface->bpp == 8)
778         {
779                 if (surface->clut.data)
780                 {
781                         lookup8_normal=getColor(surface->clut, background, foreground).lookup;
782                         
783                         int i;
784                         for (i=0; i<16; ++i)
785                                 lookup8_invert[i] = lookup8_normal[i^0xF];
786                         
787                         opcode=0;
788                 } else
789                         opcode=1;
790         } else if (surface->bpp == 16)
791         {
792                 opcode=2;
793                 for (int i=0; i<16; ++i)
794                 {
795 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
796                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
797                         int sa = i * 16;
798                         if (sa < 256)
799                         {
800                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
801                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
802                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
803                         }
804 #undef BLEND
805 #if BYTE_ORDER == LITTLE_ENDIAN
806                         lookup16_normal[i] = bswap_16(((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3));
807 #else
808                         lookup16_normal[i] = ((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3);
809 #endif
810                         da ^= 0xFF;
811                 }
812                 for (int i=0; i<16; ++i)
813                         lookup16_invert[i]=lookup16_normal[i^0xF];
814         } else if (surface->bpp == 32)
815         {
816                 opcode=3;
817                 for (int i=0; i<16; ++i)
818                 {
819 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
820
821                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
822                         int sa = i * 16;
823                         if (sa < 256)
824                         {
825                                 da = BLEND(background.a, foreground.a, sa) & 0xFF;
826                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
827                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
828                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
829                         }
830 #undef BLEND
831                         da ^= 0xFF;
832                         lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
833                 }
834                 for (int i=0; i<16; ++i)
835                         lookup32_invert[i]=lookup32_normal[i^0xF];
836         } else
837         {
838                 eWarning("can't render to %dbpp", surface->bpp);
839                 return;
840         }
841
842         gRegion area(eRect(0, 0, surface->x, surface->y));
843         gRegion clip = dc.getClip() & area;
844
845         int buffer_stride=surface->stride;
846
847         for (unsigned int c = 0; c < clip.rects.size(); ++c)
848         {
849                 std::list<int>::reverse_iterator line_offs_it(lineOffsets.rbegin());
850                 std::list<int>::iterator line_chars_it(lineChars.begin());
851                 int line_offs=0;
852                 int line_chars=0;
853                 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i, --line_chars)
854                 {
855                         while(!line_chars)
856                         {
857                                 line_offs = *(line_offs_it++);
858                                 line_chars = *(line_chars_it++);
859                         }
860
861                         if (i->flags & GS_SOFTHYPHEN)
862                                 continue;
863
864                         if (!(i->flags & GS_INVERT))
865                         {
866                                 lookup8 = lookup8_normal;
867                                 lookup16 = lookup16_normal;
868                                 lookup32 = lookup32_normal;
869                         } else
870                         {
871                                 lookup8 = lookup8_invert;
872                                 lookup16 = lookup16_invert;
873                                 lookup32 = lookup32_invert;
874                         }
875
876                         static FTC_SBit glyph_bitmap;
877                         if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
878                                 continue;
879                         int rx=i->x+glyph_bitmap->left + offset.x();
880                         int ry=(doTopBottomReordering ? line_offs : i->y) - glyph_bitmap->top + offset.y();
881
882                         __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
883                         __u8 *s=glyph_bitmap->buffer;
884                         register int sx=glyph_bitmap->width;
885                         int sy=glyph_bitmap->height;
886                         if ((sy+ry) >= clip.rects[c].bottom())
887                                 sy=clip.rects[c].bottom()-ry;
888                         if ((sx+rx) >= clip.rects[c].right())
889                                 sx=clip.rects[c].right()-rx;
890                         if (rx < clip.rects[c].left())
891                         {
892                                 int diff=clip.rects[c].left()-rx;
893                                 s+=diff;
894                                 sx-=diff;
895                                 rx+=diff;
896                                 d+=diff*surface->bypp;
897                         }
898                         if (ry < clip.rects[c].top())
899                         {
900                                 int diff=clip.rects[c].top()-ry;
901                                 s+=diff*glyph_bitmap->pitch;
902                                 sy-=diff;
903                                 ry+=diff;
904                                 d+=diff*buffer_stride;
905                         }
906                         if (sx>0)
907                         {
908                                 switch(opcode) {
909                                 case 0: // 4bit lookup to 8bit
910                                         for (int ay=0; ay<sy; ay++)
911                                         {
912                                                 register __u8 *td=d;
913                                                 register int ax;
914                                                 for (ax=0; ax<sx; ax++)
915                                                 {
916                                                         register int b=(*s++)>>4;
917                                                         if(b)
918                                                                 *td++=lookup8[b];
919                                                         else
920                                                                 td++;
921                                                 }
922                                                 s+=glyph_bitmap->pitch-sx;
923                                                 d+=buffer_stride;
924                                         }
925                                         break;
926                                 case 1: // 8bit direct
927                                         for (int ay=0; ay<sy; ay++)
928                                         {
929                                                 register __u8 *td=d;
930                                                 register int ax;
931                                                 for (ax=0; ax<sx; ax++)
932                                                 {
933                                                         register int b=*s++;
934                                                         *td++^=b;
935                                                 }
936                                                 s+=glyph_bitmap->pitch-sx;
937                                                 d+=buffer_stride;
938                                         }
939                                         break;
940                                 case 2: // 16bit
941                                         for (int ay=0; ay<sy; ay++)
942                                         {
943                                                 register __u16 *td=(__u16*)d;
944                                                 register int ax;
945                                                 for (ax=0; ax<sx; ax++)
946                                                 {
947                                                         register int b=(*s++)>>4;
948                                                         if(b)
949                                                                 *td++=lookup16[b];
950                                                         else
951                                                                 td++;
952                                                 }
953                                                 s+=glyph_bitmap->pitch-sx;
954                                                 d+=buffer_stride;
955                                         }
956                                         break;
957                                 case 3: // 32bit
958                                         for (int ay=0; ay<sy; ay++)
959                                         {
960                                                 register __u32 *td=(__u32*)d;
961                                                 register int ax;
962                                                 for (ax=0; ax<sx; ax++)
963                                                 {
964                                                         register int b=(*s++)>>4;
965                                                         if(b)
966                                                                 *td++=lookup32[b];
967                                                         else
968                                                                 td++;
969                                                 }
970                                                 s+=glyph_bitmap->pitch-sx;
971                                                 d+=buffer_stride;
972                                         }
973                                 default:
974                                         break;
975                                 }
976                         }
977                 }
978         }
979 }
980
981 void eTextPara::realign(int dir)        // der code hier ist ein wenig merkwuerdig.
982 {
983         glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
984         if (dir==dirLeft)
985                 return;
986         while (c != glyphs.end())
987         {
988                 int linelength=0;
989                 int numspaces=0, num=0;
990                 begin=end;
991                 
992                 ASSERT( end != glyphs.end());
993                 
994                         // zeilenende suchen
995                 do {
996                         last=end;
997                         ++end;
998                 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
999                         // end zeigt jetzt auf begin der naechsten zeile
1000                 
1001                 for (c=begin; c!=end; ++c)
1002                 {
1003                                 // space am zeilenende skippen
1004                         if ((c==last) && (c->flags&GS_ISSPACE))
1005                                 continue;
1006
1007                         if (c->flags&GS_ISSPACE)
1008                                 numspaces++;
1009                         linelength+=c->w;
1010                         num++;
1011                 }
1012
1013                 switch (dir)
1014                 {
1015                 case dirRight:
1016                 case dirCenter:
1017                 {
1018                         int offset=area.width()-linelength;
1019                         if (dir==dirCenter)
1020                                 offset/=2;
1021                         offset+=area.left();
1022                         while (begin != end)
1023                         {
1024                                 begin->bbox.moveBy(offset-begin->x,0);
1025                                 begin->x=offset;
1026                                 offset+=begin->w;
1027                                 ++begin;
1028                         }
1029                         break;
1030                 }
1031                 case dirBlock:
1032                 {
1033                         if (end == glyphs.end())                // letzte zeile linksbuendig lassen
1034                                 continue;
1035                         int spacemode;
1036                         if (numspaces)
1037                                 spacemode=1;
1038                         else
1039                                 spacemode=0;
1040                         if ((!spacemode) && (num<2))
1041                                 break;
1042                         int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
1043                         int curoff=0;
1044                         while (begin != end)
1045                         {
1046                                 int doadd=0;
1047                                 if ((!spacemode) || (begin->flags&GS_ISSPACE))
1048                                         doadd=1;
1049                                 begin->x+=curoff>>8;
1050                                 begin->bbox.moveBy(curoff>>8,0);
1051                                 if (doadd)
1052                                         curoff+=off;
1053                                 ++begin;
1054                         }
1055                         break;
1056                 }
1057                 }
1058         }
1059         bboxValid=false;
1060         calc_bbox();
1061 }
1062
1063 void eTextPara::clear()
1064 {
1065         singleLock s(ftlock);
1066
1067         current_font = 0;
1068         replacement_font = 0;
1069
1070         glyphs.clear();
1071 }
1072
1073 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");