1 #include <lib/gdi/font.h>
10 // use this for init Freetype...
12 #include FT_FREETYPE_H
14 #include <lib/base/eerror.h>
15 #include <lib/gdi/lcd.h>
16 #include <lib/gdi/grc.h>
17 #include <lib/base/elock.h>
18 #include <lib/base/init.h>
19 #include <lib/base/init_num.h>
21 //#define HAVE_FRIBIDI
22 // until we have it in the cdk
25 #include <fribidi/fribidi.h>
30 fontRenderClass *fontRenderClass::instance;
32 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
33 static pthread_mutex_t refcntlck=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
35 static FTC_Font cache_current_font=0;
37 struct fntColorCacheKey
40 fntColorCacheKey(const gRGB &start, const gRGB &end)
41 : start(start), end(end)
44 bool operator <(const fntColorCacheKey &c) const
48 else if (start == c.start)
54 std::map<fntColorCacheKey,gLookup> colorcache;
56 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
58 fntColorCacheKey key(start, end);
59 std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
60 if (i != colorcache.end())
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);
72 fontRenderClass *fontRenderClass::getInstance()
77 FT_Error myFTC_Face_Requester(FTC_FaceID face_id,
79 FT_Pointer request_data,
82 return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
86 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
88 fontListEntry *font=(fontListEntry *)face_id;
92 // eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
95 if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
97 eDebug(" failed: %s", strerror(error));
100 FT_Select_Charmap(*aface, ft_encoding_unicode);
104 FTC_FaceID fontRenderClass::getFaceID(const eString &face)
106 for (fontListEntry *f=font; f; f=f->next)
109 return (FTC_FaceID)f;
114 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
116 FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
120 eString fontRenderClass::AddFont(const eString &filename, const eString &name, int scale)
122 eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
125 fontListEntry *n=new fontListEntry;
129 singleLock s(ftlock);
131 if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
132 eFatal(" failed: %s", strerror(error));
134 n->filename=filename;
139 eDebug("OK (%s)", n->face.c_str());
145 fontRenderClass::fontListEntry::~fontListEntry()
149 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
152 eDebug("[FONT] initializing lib...");
154 if (FT_Init_FreeType(&library))
156 eDebug("[FONT] initializing failed.");
160 eDebug("[FONT] loading fonts...");
164 int maxbytes=4*1024*1024;
165 eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
168 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
170 eDebug("[FONT] initializing font cache failed!");
175 eDebug("[FONT] initializing font cache manager error.");
178 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
180 eDebug("[FONT] initializing font cache sbit failed!");
183 if (FTC_Image_Cache_New(cacheManager, &imageCache))
185 eDebug("[FONT] initializing font cache imagecache failed!");
191 float fontRenderClass::getLineHeight(const gFont& font)
195 Font *fnt = getFont( font.family.c_str(), font.pointSize);
198 singleLock s(ftlock);
199 FT_Face current_face;
200 if (FTC_Manager_Lookup_Size(cacheManager, &fnt->font.font, ¤t_face, &fnt->size)<0)
202 eDebug("FTC_Manager_Lookup_Size failed!");
205 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
206 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap/2.0)/64;
212 fontRenderClass::~fontRenderClass()
214 singleLock s(ftlock);
215 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
216 // FTC_Manager_Done(cacheManager);
217 // FT_Done_FreeType(library);
220 Font *fontRenderClass::getFont(const eString &face, int size, int tabwidth)
222 FTC_FaceID id=getFaceID(face);
225 return new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
228 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
231 font.font.face_id=faceid;
232 font.font.pix_width = isize;
233 font.font.pix_height = isize;
234 font.image_type = ftc_image_grays;
239 // font.image_type |= ftc_image_flag_autohinted;
242 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
244 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
263 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
266 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
279 glyphString::iterator i(glyphs.end());
281 while (i != glyphs.begin())
283 if (i->flags&(GS_ISSPACE|GS_ISFIRST))
288 if (i != glyphs.begin() && ((i->flags&(GS_ISSPACE|GS_ISFIRST))==GS_ISSPACE) && (++i != glyphs.end())) // skip space
290 int linelength=cursor.x()-i->x;
291 i->flags|=GS_ISFIRST;
292 ePoint offset=ePoint(i->x, i->y);
295 while (i != glyphs.end()) // rearrange them into the next line
299 i->bbox.moveBy(-offset.x(), -offset.y());
302 cursor+=ePoint(linelength, 0); // put the cursor after that line
313 int xadvance=glyph->xadvance, kern=0;
315 if (previous && use_kerning)
318 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
324 ng.bbox.setLeft( (flags&GS_ISFIRST|glyphs.empty()?cursor.x():cursor.x()-1) + glyph->left );
325 ng.bbox.setTop( cursor.y() - glyph->top );
326 ng.bbox.setWidth( glyph->width );
327 ng.bbox.setHeight( glyph->height );
331 ng.x=cursor.x()+kern;
335 ng.font=current_font;
337 ng.glyph_index=glyphIndex;
339 glyphs.push_back(ng);
341 cursor+=ePoint(xadvance, 0);
346 void eTextPara::calc_bbox()
348 boundBox.setLeft( 32000 );
349 boundBox.setTop( 32000 );
350 boundBox.setRight( -32000 ); // for each glyph image, compute its bounding box, translate it,
351 boundBox.setBottom( -32000 );
352 // and grow the string bbox
354 for ( glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
356 if ( i->bbox.left() < boundBox.left() )
357 boundBox.setLeft( i->bbox.left() );
358 if ( i->bbox.top() < boundBox.top() )
359 boundBox.setTop( i->bbox.top() );
360 if ( i->bbox.right() > boundBox.right() )
361 boundBox.setRight( i->bbox.right() );
362 if ( i->bbox.bottom() > boundBox.bottom() )
363 boundBox.setBottom( i->bbox.bottom() );
365 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
369 void eTextPara::newLine(int flags)
371 if (maximum.width()<cursor.x())
372 maximum.setWidth(cursor.x());
375 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
376 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap*1/2)>>6);
377 if (maximum.height()<cursor.y())
378 maximum.setHeight(cursor.y());
382 eTextPara::~eTextPara()
386 eFatal("verdammt man der war noch gelockt :/\n");
389 void eTextPara::destroy()
391 singleLock s(refcntlck);
397 eTextPara *eTextPara::grab()
399 singleLock s(refcntlck);
405 void eTextPara::setFont(const gFont &font)
408 eFatal("mod. after lock");
409 Font *fnt=fontRenderClass::getInstance()->getFont(font.family.c_str(), font.pointSize);
411 eWarning("FONT '%s' MISSING!", font.family.c_str());
413 fontRenderClass::getInstance()->getFont(replacement_facename.c_str(), font.pointSize));
416 eString eTextPara::replacement_facename;
418 void eTextPara::setFont(Font *fnt, Font *replacement)
421 eFatal("mod. after lock");
424 if (current_font && !current_font->ref)
427 replacement_font=replacement;
428 singleLock s(ftlock);
430 // we ask for replacment_font first becauseof the cache
431 if (replacement_font)
433 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager,
434 &replacement_font->font.font, &replacement_face,
435 &replacement_font->size)<0)
437 eDebug("FTC_Manager_Lookup_Size failed!");
443 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
445 eDebug("FTC_Manager_Lookup_Size failed!");
449 cache_current_font=¤t_font->font.font;
451 use_kerning=FT_HAS_KERNING(current_face);
455 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
457 int eTextPara::renderString(const eString &string, int rflags)
459 singleLock s(ftlock);
462 eFatal("mod. after lock");
469 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
473 if (¤t_font->font.font != cache_current_font)
475 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
477 eDebug("FTC_Manager_Lookup_Size failed!");
480 cache_current_font=¤t_font->font.font;
483 std::vector<unsigned long> uc_string, uc_visual;
484 uc_string.reserve(string.length());
486 std::string::const_iterator p(string.begin());
488 while(p != string.end())
490 unsigned int unicode=*p++;
492 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
494 if ((unicode & 0xE0)==0xC0) // two bytes
498 if (p != string.end())
499 unicode|=(*p++)&0x3F;
500 } else if ((unicode & 0xF0)==0xE0) // three bytes
504 if (p != string.end())
505 unicode|=(*p++)&0x3F;
507 if (p != string.end())
508 unicode|=(*p++)&0x3F;
509 } else if ((unicode & 0xF8)==0xF0) // four bytes
513 if (p != string.end())
514 unicode|=(*p++)&0x3F;
516 if (p != string.end())
517 unicode|=(*p++)&0x3F;
519 if (p != string.end())
520 unicode|=(*p++)&0x3F;
523 uc_string.push_back(unicode);
526 std::vector<unsigned long> uc_shape;
528 // character -> glyph conversion
529 shape(uc_shape, uc_string);
531 // now do the usual logical->visual reordering
533 FriBidiCharType dir=FRIBIDI_TYPE_ON;
535 int size=uc_shape.size();
536 uc_visual.resize(size);
537 // gaaanz lahm, aber anders geht das leider nicht, sorry.
538 FriBidiChar array[size], target[size];
539 std::copy(uc_shape.begin(), uc_shape.end(), array);
540 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
541 uc_visual.assign(target, target+size);
547 glyphs.reserve(uc_visual.size());
549 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
550 i != uc_visual.end(); ++i)
554 if (!(rflags&RS_DIRECT))
560 unsigned long c = *(i+1);
579 cursor+=ePoint(current_font->tabwidth, 0);
580 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
585 newline:isprintable=0;
590 case 0x86: case 0xE086:
591 case 0x87: case 0xE087:
592 nprint: isprintable=0;
604 index=(rflags&RS_DIRECT)? *i : FT_Get_Char_Index(current_face, *i);
608 if (replacement_face)
609 index=(rflags&RS_DIRECT)? *i : FT_Get_Char_Index(replacement_face, *i);
612 eDebug("unicode %d ('%c') not present", *i, *i);
614 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
616 appendGlyph(current_font, current_face, index, flags, rflags);
622 if (dir & FRIBIDI_MASK_RTL)
628 void eTextPara::blit(gPixmapDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
630 singleLock s(ftlock);
635 if (¤t_font->font.font != cache_current_font)
637 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
639 eDebug("FTC_Manager_Lookup_Size failed!");
642 cache_current_font=¤t_font->font.font;
645 ePtr<gPixmap> target;
646 dc.getPixmap(target);
652 if (target->bpp == 8)
654 if (target->clut.data)
656 lookup8=getColor(target->clut, background, foreground).lookup;
660 } else if (target->bpp == 32)
663 if (target->clut.data)
665 lookup8=getColor(target->clut, background, foreground).lookup;
666 for (int i=0; i<16; ++i)
667 lookup32[i]=((target->clut.data[lookup8[i]].a<<24)|
668 (target->clut.data[lookup8[i]].r<<16)|
669 (target->clut.data[lookup8[i]].g<<8)|
670 (target->clut.data[lookup8[i]].b))^0xFF000000;
673 for (int i=0; i<16; ++i)
674 lookup32[i]=(0x010101*i)|0xFF000000;
678 eWarning("can't render to %dbpp", target->bpp);
682 eRect clip(0, 0, target->x, target->y);
685 int buffer_stride=target->stride;
687 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
689 static FTC_SBit glyph_bitmap;
690 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
692 int rx=i->x+glyph_bitmap->left + offset.x();
693 int ry=i->y-glyph_bitmap->top + offset.y();
694 __u8 *d=(__u8*)(target->data)+buffer_stride*ry+rx*target->bypp;
695 __u8 *s=glyph_bitmap->buffer;
696 register int sx=glyph_bitmap->width;
697 int sy=glyph_bitmap->height;
698 if ((sy+ry) >= clip.bottom())
700 if ((sx+rx) >= clip.right())
702 if (rx < clip.left())
704 int diff=clip.left()-rx;
708 d+=diff*target->bypp;
712 int diff=clip.top()-ry;
713 s+=diff*glyph_bitmap->pitch;
716 d+=diff*buffer_stride;
719 for (int ay=0; ay<sy; ay++)
721 if (!opcode) // 4bit lookup to 8bit
725 for (ax=0; ax<sx; ax++)
727 register int b=(*s++)>>4;
733 } else if (opcode == 1) // 8bit direct
737 for (ax=0; ax<sx; ax++)
744 register __u32 *td=(__u32*)d;
746 for (ax=0; ax<sx; ax++)
748 register int b=(*s++)>>4;
755 s+=glyph_bitmap->pitch-sx;
761 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
763 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
766 while (c != glyphs.end())
769 int numspaces=0, num=0;
772 ASSERT( end != glyphs.end());
778 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
779 // end zeigt jetzt auf begin der naechsten zeile
781 for (c=begin; c!=end; ++c)
783 // space am zeilenende skippen
784 if ((c==last) && (c->flags&GS_ISSPACE))
787 if (c->flags&GS_ISSPACE)
792 if (!num) // line mit nur einem space
800 int offset=area.width()-linelength;
806 begin->bbox.moveBy(offset-begin->x,0);
815 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
822 if ((!spacemode) && (num<2))
824 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
829 if ((!spacemode) || (begin->flags&GS_ISSPACE))
832 begin->bbox.moveBy(curoff>>8,0);
845 void eTextPara::clear()
847 singleLock s(ftlock);
849 for (glyphString::iterator i(glyphs.begin()); i!=glyphs.end(); ++i)
855 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");