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