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