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