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