lib/gdi/font.cpp: try to fix wrong reordering of some characters
[vuplus_dvbapp] / lib / gdi / font.cpp
1 #include <lib/gdi/font.h>
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <ctype.h>
6 #include <pthread.h>
7 #include <sys/types.h>
8 #include <unistd.h>
9
10 // use this for init Freetype...
11 #include <ft2build.h>
12 #include FT_FREETYPE_H
13 #ifdef HAVE_FREETYPE2
14 #define FTC_Image_Cache_New(a,b)        FTC_ImageCache_New(a,b)
15 #define FTC_Image_Cache_Lookup(a,b,c,d) FTC_ImageCache_Lookup(a,b,c,d,NULL)
16 #define FTC_SBit_Cache_New(a,b)         FTC_SBitCache_New(a,b)
17 #define FTC_SBit_Cache_Lookup(a,b,c,d)  FTC_SBitCache_Lookup(a,b,c,d,NULL)
18 #endif
19
20 #include <lib/base/eerror.h>
21 #include <lib/gdi/lcd.h>
22 #include <lib/gdi/grc.h>
23 #include <lib/base/elock.h>
24 #include <lib/base/init.h>
25 #include <lib/base/init_num.h>
26
27 #define HAVE_FRIBIDI
28 // until we have it in the cdk
29
30 #ifdef HAVE_FRIBIDI
31 #include <fribidi/fribidi.h>
32 #endif
33
34 #include <map>
35
36 fontRenderClass *fontRenderClass::instance;
37
38 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
39
40 #ifndef HAVE_FREETYPE2
41 static FTC_Font cache_current_font=0;
42 #endif
43
44 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         bool mustRealign=false;
601         int pos=0, spos=0;
602         uc_visual.resize(size);
603         // gaaanz lahm, aber anders geht das leider nicht, sorry.
604         FriBidiChar array[size], target[size];
605         std::copy(uc_shape.begin(), uc_shape.end(), array);
606
607         bool line_open = false;
608         while(pos < size)
609         {
610                 int incr=1;
611                 bool line_end = false;
612                 if (!line_open)
613                         line_open = true;
614                 switch((unsigned long)array[pos])
615                 {
616                 case '\\':
617                         if (pos+1 == size || (unsigned long)array[pos+1] != 'n')
618                                 break;
619                         ++incr;
620                 case 0x8A:
621                 case 0xE08A:
622                 case '\n':
623                         line_end = true;
624                 default:
625                         break;
626                 }
627                 if (line_end || pos+incr >= size)
628                 {
629                         int len = pos - spos;
630                         if (len)
631                         {
632                                 FriBidiCharType dir=FRIBIDI_TYPE_ON;
633                                 fribidi_log2vis(array+spos, len, &dir, target+spos, 0, 0, 0);
634                                 if (!mustRealign && dir&FRIBIDI_MASK_RTL)
635                                         mustRealign = true;
636                         }
637                         target[pos] = array[pos];
638                         if (incr > 1)
639                                 target[pos+1] = array[pos+1];
640                         spos = pos+incr;
641                         line_open = false;
642                 }
643                 pos += incr;
644         }
645
646         uc_visual.assign(target, target+size);
647 #else
648         uc_visual=uc_shape;
649 #endif
650
651         glyphs.reserve(size);
652         
653         int nextflags = 0;
654         
655         for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
656                 i != uc_visual.end(); ++i)
657         {
658                 int isprintable=1;
659                 int flags = nextflags;
660                 nextflags = 0;
661                 unsigned long chr = *i;
662
663                 if (!(rflags&RS_DIRECT))
664                 {
665                         switch (chr)
666                         {
667                         case '\\':
668                         {
669                                 unsigned long c = *(i+1);
670                                 switch (c)
671                                 {
672                                         case 'n':
673                                                 i++;
674                                                 goto newline;
675                                         case 't':
676                                                 i++;
677                                                 goto tab;
678                                         case 'r':
679                                                 i++;
680                                                 goto nprint;
681                                         default:
682                                         ;
683                                 }
684                                 break;
685                         }
686                         case '\t':
687 tab:            isprintable=0;
688                                 cursor+=ePoint(current_font->tabwidth, 0);
689                                 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
690                                 break;
691                         case 0x8A:
692                         case 0xE08A:
693                         case '\n':
694 newline:isprintable=0;
695                                 newLine(rflags);
696                                 nextflags|=GS_ISFIRST;
697                                 break;
698                         case '\r':
699                         case 0x86: case 0xE086:
700                         case 0x87: case 0xE087:
701 nprint: isprintable=0;
702                                 break;
703                         case 0xAD: // soft-hyphen
704                                 flags |= GS_SOFTHYPHEN;
705                                 chr = 0x2010; /* hyphen */
706                                 break;
707                         case 0x2010:
708                         case '-':
709                                 flags |= GS_HYPHEN;
710                                 break;
711                         case ' ':
712                                 flags|=GS_ISSPACE;
713                         default:
714                                 break;
715                         }
716                 }
717                 if (isprintable)
718                 {
719                         FT_UInt index = 0;
720
721                                 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
722                         if (chr == 0x2010)
723                                 chr = '-';
724
725                         if (forced_replaces.find(chr) == forced_replaces.end())
726                                 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
727
728                         if (!index)
729                         {
730                                 if (replacement_face)
731                                         index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
732
733                                 if (!index)
734                                         eDebug("unicode U+%4lx not present", chr);
735                                 else
736                                         appendGlyph(replacement_font, replacement_face, index, flags, rflags);
737                         } else
738                                 appendGlyph(current_font, current_face, index, flags, rflags);
739                 }
740         }
741         bboxValid=false;
742         calc_bbox();
743 #ifdef HAVE_FRIBIDI
744         if (mustRealign)
745                 realign(dirRight);
746 #endif
747         return 0;
748 }
749
750 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
751 {
752         singleLock s(ftlock);
753         
754         if (!current_font)
755                 return;
756
757 #ifdef HAVE_FREETYPE2
758         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
759                                     current_font->scaler.face_id,
760                                     &current_face) < 0) ||
761             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
762                                     &current_font->scaler,
763                                     &current_font->size) < 0))
764         {
765                 eDebug("FTC_Manager_Lookup_Size failed!");
766                 return;
767         }
768 #else
769         if (&current_font->font.font != cache_current_font)
770         {
771                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
772                 {
773                         eDebug("FTC_Manager_Lookup_Size failed!");
774                         return;
775                 }
776                 cache_current_font=&current_font->font.font;
777         }
778 #endif
779
780         ePtr<gPixmap> target;
781         dc.getPixmap(target);
782         gSurface *surface = target->surface;
783
784         register int opcode;
785
786         gColor *lookup8, lookup8_invert[16];
787         gColor *lookup8_normal=0;
788
789         __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
790         
791         if (surface->bpp == 8)
792         {
793                 if (surface->clut.data)
794                 {
795                         lookup8_normal=getColor(surface->clut, background, foreground).lookup;
796                         
797                         int i;
798                         for (i=0; i<16; ++i)
799                                 lookup8_invert[i] = lookup8_normal[i^0xF];
800                         
801                         opcode=0;
802                 } else
803                         opcode=1;
804         } else if (surface->bpp == 32)
805         {
806                 opcode=3;
807
808                 for (int i=0; i<16; ++i)
809                 {
810 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
811
812                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
813                         int sa = i * 16;
814                         if (sa < 256)
815                         {
816                                 da = BLEND(background.a, foreground.a, sa) & 0xFF;
817                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
818                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
819                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
820                         }
821 #undef BLEND
822                         da ^= 0xFF;
823                         lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
824                 }
825                 for (int i=0; i<16; ++i)
826                         lookup32_invert[i]=lookup32_normal[i^0xF];
827         } else
828         {
829                 eWarning("can't render to %dbpp", surface->bpp);
830                 return;
831         }
832         
833         gRegion area(eRect(0, 0, surface->x, surface->y));
834         gRegion clip = dc.getClip() & area;
835
836         int buffer_stride=surface->stride;
837         
838         for (unsigned int c = 0; c < clip.rects.size(); ++c)
839         {
840                 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
841                 {
842                         if (i->flags & GS_SOFTHYPHEN)
843                                 continue;
844
845                         if (!(i->flags & GS_INVERT))
846                         {
847                                 lookup8 = lookup8_normal;
848                                 lookup32 = lookup32_normal;
849                         } else
850                         {
851                                 lookup8 = lookup8_invert;
852                                 lookup32 = lookup32_invert;
853                         }
854                 
855                         static FTC_SBit glyph_bitmap;
856                         if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
857                                 continue;
858                         int rx=i->x+glyph_bitmap->left + offset.x();
859                         int ry=i->y-glyph_bitmap->top  + offset.y();
860                 
861                         __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
862                         __u8 *s=glyph_bitmap->buffer;
863                         register int sx=glyph_bitmap->width;
864                         int sy=glyph_bitmap->height;
865                         if ((sy+ry) >= clip.rects[c].bottom())
866                                 sy=clip.rects[c].bottom()-ry;
867                         if ((sx+rx) >= clip.rects[c].right())
868                                 sx=clip.rects[c].right()-rx;
869                         if (rx < clip.rects[c].left())
870                         {
871                                 int diff=clip.rects[c].left()-rx;
872                                 s+=diff;
873                                 sx-=diff;
874                                 rx+=diff;
875                                 d+=diff*surface->bypp;
876                         }
877                         if (ry < clip.rects[c].top())
878                         {
879                                 int diff=clip.rects[c].top()-ry;
880                                 s+=diff*glyph_bitmap->pitch;
881                                 sy-=diff;
882                                 ry+=diff;
883                                 d+=diff*buffer_stride;
884                         }
885                         if (sx>0)
886                                 for (int ay=0; ay<sy; ay++)
887                                 {
888                                         if (!opcode)            // 4bit lookup to 8bit
889                                         {
890                                                 register __u8 *td=d;
891                                                 register int ax;
892                                                 
893                                                 for (ax=0; ax<sx; ax++)
894                                                 {       
895                                                         register int b=(*s++)>>4;
896                                                         if(b)
897                                                                 *td++=lookup8[b];
898                                                         else
899                                                                 td++;
900                                                 }
901                                         } else if (opcode == 1) // 8bit direct
902                                         {
903                                                 register __u8 *td=d;
904                                                 register int ax;
905                                                 for (ax=0; ax<sx; ax++)
906                                                 {       
907                                                         register int b=*s++;
908                                                         *td++^=b;
909                                                 }
910                                         } else
911                                         {
912                                                 register __u32 *td=(__u32*)d;
913                                                 register int ax;
914                                                 for (ax=0; ax<sx; ax++)
915                                                 {       
916                                                         register int b=(*s++)>>4;
917                                                         if(b)
918                                                                 *td++=lookup32[b];
919                                                         else
920                                                                 td++;
921                                                 }
922                                         }
923                                         s+=glyph_bitmap->pitch-sx;
924                                         d+=buffer_stride;
925                                 }
926                 }
927         }
928 }
929
930 void eTextPara::realign(int dir)        // der code hier ist ein wenig merkwuerdig.
931 {
932         glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
933         if (dir==dirLeft)
934                 return;
935         while (c != glyphs.end())
936         {
937                 int linelength=0;
938                 int numspaces=0, num=0;
939                 begin=end;
940                 
941                 ASSERT( end != glyphs.end());
942                 
943                         // zeilenende suchen
944                 do {
945                         last=end;
946                         ++end;
947                 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
948                         // end zeigt jetzt auf begin der naechsten zeile
949                 
950                 for (c=begin; c!=end; ++c)
951                 {
952                                 // space am zeilenende skippen
953                         if ((c==last) && (c->flags&GS_ISSPACE))
954                                 continue;
955
956                         if (c->flags&GS_ISSPACE)
957                                 numspaces++;
958                         linelength+=c->w;
959                         num++;
960                 }
961
962                 switch (dir)
963                 {
964                 case dirRight:
965                 case dirCenter:
966                 {
967                         int offset=area.width()-linelength;
968                         if (dir==dirCenter)
969                                 offset/=2;
970                         offset+=area.left();
971                         while (begin != end)
972                         {
973                                 begin->bbox.moveBy(offset-begin->x,0);
974                                 begin->x=offset;
975                                 offset+=begin->w;
976                                 ++begin;
977                         }
978                         break;
979                 }
980                 case dirBlock:
981                 {
982                         if (end == glyphs.end())                // letzte zeile linksbuendig lassen
983                                 continue;
984                         int spacemode;
985                         if (numspaces)
986                                 spacemode=1;
987                         else
988                                 spacemode=0;
989                         if ((!spacemode) && (num<2))
990                                 break;
991                         int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
992                         int curoff=0;
993                         while (begin != end)
994                         {
995                                 int doadd=0;
996                                 if ((!spacemode) || (begin->flags&GS_ISSPACE))
997                                         doadd=1;
998                                 begin->x+=curoff>>8;
999                                 begin->bbox.moveBy(curoff>>8,0);
1000                                 if (doadd)
1001                                         curoff+=off;
1002                                 ++begin;
1003                         }
1004                         break;
1005                 }
1006                 }
1007         }
1008         bboxValid=false;
1009         calc_bbox();
1010 }
1011
1012 void eTextPara::clear()
1013 {
1014         singleLock s(ftlock);
1015
1016         current_font = 0;
1017         replacement_font = 0;
1018
1019         glyphs.clear();
1020 }
1021
1022 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");