work on asynchron pic loading... to get rid of spinning wheels
[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         if (cursor.y()==-1)
515         {
516                 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
517                 left=cursor.x();
518         }
519                 
520 #ifdef HAVE_FREETYPE2
521         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
522                                     current_font->scaler.face_id,
523                                     &current_face) < 0) ||
524             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
525                                     &current_font->scaler,
526                                     &current_font->size) < 0))
527         {
528                 eDebug("FTC_Manager_Lookup_Size failed!");
529                 return -1;
530         }
531 #else
532         if (&current_font->font.font != cache_current_font)
533         {
534                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
535                 {
536                         eDebug("FTC_Manager_Lookup_Size failed!");
537                         return -1;
538                 }
539                 cache_current_font=&current_font->font.font;
540         }
541 #endif
542         
543         std::vector<unsigned long> uc_string, uc_visual;
544         if (string)
545                 uc_string.reserve(strlen(string));
546         
547         const char *p = string ? string : "";
548
549         while (*p)
550         {
551                 unsigned int unicode=(unsigned char)*p++;
552
553                 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
554                 {
555                         if ((unicode & 0xE0)==0xC0) // two bytes
556                         {
557                                 unicode&=0x1F;
558                                 unicode<<=6;
559                                 if (*p)
560                                         unicode|=(*p++)&0x3F;
561                         } else if ((unicode & 0xF0)==0xE0) // three bytes
562                         {
563                                 unicode&=0x0F;
564                                 unicode<<=6;
565                                 if (*p)
566                                         unicode|=(*p++)&0x3F;
567                                 unicode<<=6;
568                                 if (*p)
569                                         unicode|=(*p++)&0x3F;
570                         } else if ((unicode & 0xF8)==0xF0) // four bytes
571                         {
572                                 unicode&=0x07;
573                                 unicode<<=6;
574                                 if (*p)
575                                         unicode|=(*p++)&0x3F;
576                                 unicode<<=6;
577                                 if (*p)
578                                         unicode|=(*p++)&0x3F;
579                                 unicode<<=6;
580                                 if (*p)
581                                         unicode|=(*p++)&0x3F;
582                         }
583                 }
584                 uc_string.push_back(unicode);
585         }
586
587         std::vector<unsigned long> uc_shape;
588
589                 // character -> glyph conversion
590         shape(uc_shape, uc_string);
591         
592                 // now do the usual logical->visual reordering
593 #ifdef HAVE_FRIBIDI     
594         FriBidiCharType dir=FRIBIDI_TYPE_ON;
595         {
596                 int size=uc_shape.size();
597                 uc_visual.resize(size);
598                 // gaaanz lahm, aber anders geht das leider nicht, sorry.
599                 FriBidiChar array[size], target[size];
600                 std::copy(uc_shape.begin(), uc_shape.end(), array);
601                 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
602                 uc_visual.assign(target, target+size);
603         }
604 #else
605         uc_visual=uc_shape;
606 #endif
607
608         glyphs.reserve(uc_visual.size());
609         
610         int nextflags = 0;
611         
612         for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
613                 i != uc_visual.end(); ++i)
614         {
615                 int isprintable=1;
616                 int flags = nextflags;
617                 nextflags = 0;
618                 unsigned long chr = *i;
619
620                 if (!(rflags&RS_DIRECT))
621                 {
622                         switch (chr)
623                         {
624                         case '\\':
625                         {
626                                 unsigned long c = *(i+1);
627                                 switch (c)
628                                 {
629                                         case 'n':
630                                                 i++;
631                                                 goto newline;
632                                         case 't':
633                                                 i++;
634                                                 goto tab;
635                                         case 'r':
636                                                 i++;
637                                                 goto nprint;
638                                         default:
639                                         ;
640                                 }
641                                 break;
642                         }
643                         case '\t':
644 tab:            isprintable=0;
645                                 cursor+=ePoint(current_font->tabwidth, 0);
646                                 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
647                                 break;
648                         case 0x8A:
649                         case 0xE08A:
650                         case '\n':
651 newline:isprintable=0;
652                                 newLine(rflags);
653                                 nextflags|=GS_ISFIRST;
654                                 break;
655                         case '\r':
656                         case 0x86: case 0xE086:
657                         case 0x87: case 0xE087:
658 nprint: isprintable=0;
659                                 break;
660                         case 0xAD: // soft-hyphen
661                                 flags |= GS_SOFTHYPHEN;
662                                 chr = 0x2010; /* hyphen */
663                                 break;
664                         case 0x2010:
665                         case '-':
666                                 flags |= GS_HYPHEN;
667                                 break;
668                         case ' ':
669                                 flags|=GS_ISSPACE;
670                         default:
671                                 break;
672                         }
673                 }
674                 if (isprintable)
675                 {
676                         FT_UInt index = 0;
677
678                                 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
679                         if (chr == 0x2010)
680                                 chr = '-';
681
682                         if (forced_replaces.find(chr) == forced_replaces.end())
683                                 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
684
685                         if (!index)
686                         {
687                                 if (replacement_face)
688                                         index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
689
690                                 if (!index)
691                                         eDebug("unicode U+%4lx not present", chr);
692                                 else
693                                         appendGlyph(replacement_font, replacement_face, index, flags, rflags);
694                         } else
695                                 appendGlyph(current_font, current_face, index, flags, rflags);
696                 }
697         }
698         bboxValid=false;
699         calc_bbox();
700 #ifdef HAVE_FRIBIDI
701         if (dir & FRIBIDI_MASK_RTL)
702                 realign(dirRight);
703 #endif
704         return 0;
705 }
706
707 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
708 {
709         singleLock s(ftlock);
710         
711         if (!current_font)
712                 return;
713
714 #ifdef HAVE_FREETYPE2
715         if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
716                                     current_font->scaler.face_id,
717                                     &current_face) < 0) ||
718             (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
719                                     &current_font->scaler,
720                                     &current_font->size) < 0))
721         {
722                 eDebug("FTC_Manager_Lookup_Size failed!");
723                 return;
724         }
725 #else
726         if (&current_font->font.font != cache_current_font)
727         {
728                 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, &current_font->font.font, &current_face, &current_font->size)<0)
729                 {
730                         eDebug("FTC_Manager_Lookup_Size failed!");
731                         return;
732                 }
733                 cache_current_font=&current_font->font.font;
734         }
735 #endif
736
737         ePtr<gPixmap> target;
738         dc.getPixmap(target);
739         gSurface *surface = target->surface;
740
741         register int opcode;
742
743         gColor *lookup8, lookup8_invert[16];
744         gColor *lookup8_normal=0;
745
746         __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
747         
748         if (surface->bpp == 8)
749         {
750                 if (surface->clut.data)
751                 {
752                         lookup8_normal=getColor(surface->clut, background, foreground).lookup;
753                         
754                         int i;
755                         for (i=0; i<16; ++i)
756                                 lookup8_invert[i] = lookup8_normal[i^0xF];
757                         
758                         opcode=0;
759                 } else
760                         opcode=1;
761         } else if (surface->bpp == 32)
762         {
763                 opcode=3;
764
765                 for (int i=0; i<16; ++i)
766                 {
767 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
768
769                         unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
770                         int sa = i * 16;
771                         if (sa < 256)
772                         {
773                                 da = BLEND(background.a, foreground.a, sa) & 0xFF;
774                                 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
775                                 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
776                                 db = BLEND(background.b, foreground.b, sa) & 0xFF;
777                         }
778 #undef BLEND
779                         da ^= 0xFF;
780                         lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
781                 }
782                 for (int i=0; i<16; ++i)
783                         lookup32_invert[i]=lookup32_normal[i^0xF];
784         } else
785         {
786                 eWarning("can't render to %dbpp", surface->bpp);
787                 return;
788         }
789         
790         gRegion area(eRect(0, 0, surface->x, surface->y));
791         gRegion clip = dc.getClip() & area;
792
793         int buffer_stride=surface->stride;
794         
795         for (unsigned int c = 0; c < clip.rects.size(); ++c)
796         {
797                 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
798                 {
799                         if (i->flags & GS_SOFTHYPHEN)
800                                 continue;
801
802                         if (!(i->flags & GS_INVERT))
803                         {
804                                 lookup8 = lookup8_normal;
805                                 lookup32 = lookup32_normal;
806                         } else
807                         {
808                                 lookup8 = lookup8_invert;
809                                 lookup32 = lookup32_invert;
810                         }
811                 
812                         static FTC_SBit glyph_bitmap;
813                         if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
814                                 continue;
815                         int rx=i->x+glyph_bitmap->left + offset.x();
816                         int ry=i->y-glyph_bitmap->top  + offset.y();
817                 
818                         __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
819                         __u8 *s=glyph_bitmap->buffer;
820                         register int sx=glyph_bitmap->width;
821                         int sy=glyph_bitmap->height;
822                         if ((sy+ry) >= clip.rects[c].bottom())
823                                 sy=clip.rects[c].bottom()-ry;
824                         if ((sx+rx) >= clip.rects[c].right())
825                                 sx=clip.rects[c].right()-rx;
826                         if (rx < clip.rects[c].left())
827                         {
828                                 int diff=clip.rects[c].left()-rx;
829                                 s+=diff;
830                                 sx-=diff;
831                                 rx+=diff;
832                                 d+=diff*surface->bypp;
833                         }
834                         if (ry < clip.rects[c].top())
835                         {
836                                 int diff=clip.rects[c].top()-ry;
837                                 s+=diff*glyph_bitmap->pitch;
838                                 sy-=diff;
839                                 ry+=diff;
840                                 d+=diff*buffer_stride;
841                         }
842                         if (sx>0)
843                                 for (int ay=0; ay<sy; ay++)
844                                 {
845                                         if (!opcode)            // 4bit lookup to 8bit
846                                         {
847                                                 register __u8 *td=d;
848                                                 register int ax;
849                                                 
850                                                 for (ax=0; ax<sx; ax++)
851                                                 {       
852                                                         register int b=(*s++)>>4;
853                                                         if(b)
854                                                                 *td++=lookup8[b];
855                                                         else
856                                                                 td++;
857                                                 }
858                                         } else if (opcode == 1) // 8bit direct
859                                         {
860                                                 register __u8 *td=d;
861                                                 register int ax;
862                                                 for (ax=0; ax<sx; ax++)
863                                                 {       
864                                                         register int b=*s++;
865                                                         *td++^=b;
866                                                 }
867                                         } else
868                                         {
869                                                 register __u32 *td=(__u32*)d;
870                                                 register int ax;
871                                                 for (ax=0; ax<sx; ax++)
872                                                 {       
873                                                         register int b=(*s++)>>4;
874                                                         if(b)
875                                                                 *td++=lookup32[b];
876                                                         else
877                                                                 td++;
878                                                 }
879                                         }
880                                         s+=glyph_bitmap->pitch-sx;
881                                         d+=buffer_stride;
882                                 }
883                 }
884         }
885 }
886
887 void eTextPara::realign(int dir)        // der code hier ist ein wenig merkwuerdig.
888 {
889         glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
890         if (dir==dirLeft)
891                 return;
892         while (c != glyphs.end())
893         {
894                 int linelength=0;
895                 int numspaces=0, num=0;
896                 begin=end;
897                 
898                 ASSERT( end != glyphs.end());
899                 
900                         // zeilenende suchen
901                 do {
902                         last=end;
903                         ++end;
904                 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
905                         // end zeigt jetzt auf begin der naechsten zeile
906                 
907                 for (c=begin; c!=end; ++c)
908                 {
909                                 // space am zeilenende skippen
910                         if ((c==last) && (c->flags&GS_ISSPACE))
911                                 continue;
912
913                         if (c->flags&GS_ISSPACE)
914                                 numspaces++;
915                         linelength+=c->w;
916                         num++;
917                 }
918
919                 switch (dir)
920                 {
921                 case dirRight:
922                 case dirCenter:
923                 {
924                         int offset=area.width()-linelength;
925                         if (dir==dirCenter)
926                                 offset/=2;
927                         offset+=area.left();
928                         while (begin != end)
929                         {
930                                 begin->bbox.moveBy(offset-begin->x,0);
931                                 begin->x=offset;
932                                 offset+=begin->w;
933                                 ++begin;
934                         }
935                         break;
936                 }
937                 case dirBlock:
938                 {
939                         if (end == glyphs.end())                // letzte zeile linksbuendig lassen
940                                 continue;
941                         int spacemode;
942                         if (numspaces)
943                                 spacemode=1;
944                         else
945                                 spacemode=0;
946                         if ((!spacemode) && (num<2))
947                                 break;
948                         int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
949                         int curoff=0;
950                         while (begin != end)
951                         {
952                                 int doadd=0;
953                                 if ((!spacemode) || (begin->flags&GS_ISSPACE))
954                                         doadd=1;
955                                 begin->x+=curoff>>8;
956                                 begin->bbox.moveBy(curoff>>8,0);
957                                 if (doadd)
958                                         curoff+=off;
959                                 ++begin;
960                         }
961                         break;
962                 }
963                 }
964         }
965         bboxValid=false;
966         calc_bbox();
967 }
968
969 void eTextPara::clear()
970 {
971         singleLock s(ftlock);
972
973         current_font = 0;
974         replacement_font = 0;
975
976         glyphs.clear();
977 }
978
979 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");