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>
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 std::string &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 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &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)
196 getFont(fnt, font.family.c_str(), font.pointSize);
199 singleLock s(ftlock);
200 FT_Face current_face;
201 if (FTC_Manager_Lookup_Size(cacheManager, &fnt->font.font, ¤t_face, &fnt->size)<0)
204 eDebug("FTC_Manager_Lookup_Size failed!");
207 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
208 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
212 fontRenderClass::~fontRenderClass()
214 singleLock s(ftlock);
217 fontListEntry *f=font;
221 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
222 // FTC_Manager_Done(cacheManager);
223 // FT_Done_FreeType(library);
226 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
228 FTC_FaceID id=getFaceID(face);
234 font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
238 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
240 fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
242 eTextPara::setReplacementFont(alias);
247 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
250 font.font.face_id=faceid;
251 font.font.pix_width = isize;
252 font.font.pix_height = isize;
253 font.image_type = ftc_image_grays;
257 // font.image_type |= ftc_image_flag_autohinted;
260 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
262 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
269 DEFINE_REF(eTextPara);
271 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
274 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
287 glyphString::reverse_iterator i(glyphs.rbegin());
288 while (i != glyphs.rend())
290 if (i->flags&(GS_ISSPACE|GS_ISFIRST))
295 if (i != glyphs.rend()
296 && ((i->flags&(GS_ISSPACE|GS_ISFIRST))==GS_ISSPACE)
300 int linelength=cursor.x()-i->x;
301 i->flags|=GS_ISFIRST;
302 ePoint offset=ePoint(i->x, i->y);
309 i->bbox.moveBy(-offset.x(), -offset.y());
311 while (i-- != glyphs.rbegin()); // rearrange them into the next line
312 cursor+=ePoint(linelength, 0); // put the cursor after that line
324 int xadvance=glyph->xadvance, kern=0;
326 if (previous && use_kerning)
329 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
334 ng.bbox.setLeft( (flags&GS_ISFIRST|cursor.x()-1)+glyph->left );
335 ng.bbox.setTop( cursor.y() - glyph->top );
336 ng.bbox.setWidth( glyph->width );
337 ng.bbox.setHeight( glyph->height );
340 ng.bbox.setWidth(xadvance);
342 ng.x = cursor.x()+kern;
345 ng.font = current_font;
346 ng.glyph_index = glyphIndex;
348 glyphs.push_back(ng);
350 cursor += ePoint(xadvance, 0);
351 previous = glyphIndex;
355 void eTextPara::calc_bbox()
366 glyphString::iterator i(glyphs.begin());
371 for (; i != glyphs.end(); ++i)
373 if ( i->flags & GS_ISSPACE )
375 if ( i->bbox.left() < boundBox.left() )
376 boundBox.setLeft( i->bbox.left() );
377 if ( i->bbox.top() < boundBox.top() )
378 boundBox.setTop( i->bbox.top() );
379 if ( i->bbox.right() > boundBox.right() )
380 boundBox.setRight( i->bbox.right() );
381 if ( i->bbox.bottom() > boundBox.bottom() )
382 boundBox.setBottom( i->bbox.bottom() );
384 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
387 void eTextPara::newLine(int flags)
389 if (maximum.width()<cursor.x())
390 maximum.setWidth(cursor.x());
393 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
394 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
395 if (maximum.height()<cursor.y())
396 maximum.setHeight(cursor.y());
400 eTextPara::~eTextPara()
405 void eTextPara::setFont(const gFont *font)
407 ePtr<Font> fnt, replacement;
408 fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
410 eWarning("FONT '%s' MISSING!", font->family.c_str());
411 fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
412 setFont(fnt, replacement);
415 std::string eTextPara::replacement_facename;
416 std::set<int> eTextPara::forced_replaces;
418 void eTextPara::setFont(Font *fnt, Font *replacement)
423 replacement_font=replacement;
424 singleLock s(ftlock);
426 // we ask for replacment_font first becauseof the cache
427 if (replacement_font)
429 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager,
430 &replacement_font->font.font, &replacement_face,
431 &replacement_font->size)<0)
433 eDebug("FTC_Manager_Lookup_Size failed!");
439 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
441 eDebug("FTC_Manager_Lookup_Size failed!");
445 cache_current_font=¤t_font->font.font;
447 use_kerning=FT_HAS_KERNING(current_face);
451 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
453 int eTextPara::renderString(const char *string, int rflags)
455 singleLock s(ftlock);
462 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
466 if (¤t_font->font.font != cache_current_font)
468 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
470 eDebug("FTC_Manager_Lookup_Size failed!");
473 cache_current_font=¤t_font->font.font;
476 std::vector<unsigned long> uc_string, uc_visual;
478 uc_string.reserve(strlen(string));
480 const char *p = string ? string : "";
484 unsigned int unicode=(unsigned char)*p++;
486 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
488 if ((unicode & 0xE0)==0xC0) // two bytes
493 unicode|=(*p++)&0x3F;
494 } else if ((unicode & 0xF0)==0xE0) // three bytes
499 unicode|=(*p++)&0x3F;
502 unicode|=(*p++)&0x3F;
503 } else if ((unicode & 0xF8)==0xF0) // four bytes
508 unicode|=(*p++)&0x3F;
511 unicode|=(*p++)&0x3F;
514 unicode|=(*p++)&0x3F;
517 uc_string.push_back(unicode);
520 std::vector<unsigned long> uc_shape;
522 // character -> glyph conversion
523 shape(uc_shape, uc_string);
525 // now do the usual logical->visual reordering
527 FriBidiCharType dir=FRIBIDI_TYPE_ON;
529 int size=uc_shape.size();
530 uc_visual.resize(size);
531 // gaaanz lahm, aber anders geht das leider nicht, sorry.
532 FriBidiChar array[size], target[size];
533 std::copy(uc_shape.begin(), uc_shape.end(), array);
534 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
535 uc_visual.assign(target, target+size);
541 glyphs.reserve(uc_visual.size());
545 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
546 i != uc_visual.end(); ++i)
549 int flags = nextflags;
551 if (!(rflags&RS_DIRECT))
557 unsigned long c = *(i+1);
576 cursor+=ePoint(current_font->tabwidth, 0);
577 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
582 newline:isprintable=0;
584 nextflags|=GS_ISFIRST;
587 case 0x86: case 0xE086:
588 case 0x87: case 0xE087:
589 nprint: isprintable=0;
601 if (forced_replaces.find(*i) == forced_replaces.end())
602 index=(rflags&RS_DIRECT)? *i : FT_Get_Char_Index(current_face, *i);
606 if (replacement_face)
607 index=(rflags&RS_DIRECT)? *i : FT_Get_Char_Index(replacement_face, *i);
610 eDebug("unicode %d ('%c') not present", *i, *i);
612 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
614 appendGlyph(current_font, current_face, index, flags, rflags);
620 if (dir & FRIBIDI_MASK_RTL)
626 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
628 singleLock s(ftlock);
633 if (¤t_font->font.font != cache_current_font)
635 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
637 eDebug("FTC_Manager_Lookup_Size failed!");
640 cache_current_font=¤t_font->font.font;
643 ePtr<gPixmap> target;
644 dc.getPixmap(target);
645 gSurface *surface = target->surface;
649 gColor *lookup8, lookup8_invert[16];
650 gColor *lookup8_normal=0;
652 __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
654 if (surface->bpp == 8)
656 if (surface->clut.data)
658 lookup8_normal=getColor(surface->clut, background, foreground).lookup;
662 lookup8_invert[i] = lookup8_normal[i^0xF];
667 } else if (surface->bpp == 32)
670 if (surface->clut.data)
672 lookup8=getColor(surface->clut, background, foreground).lookup;
673 for (int i=0; i<16; ++i)
674 lookup32_normal[i]=((surface->clut.data[lookup8[i]].a<<24)|
675 (surface->clut.data[lookup8[i]].r<<16)|
676 (surface->clut.data[lookup8[i]].g<<8)|
677 (surface->clut.data[lookup8[i]].b))^0xFF000000;
680 for (int i=0; i<16; ++i)
681 lookup32_normal[i]=(0x010101*i)|0xFF000000;
683 for (int i=0; i<16; ++i)
684 lookup32_invert[i]=lookup32_normal[i^0xF];
687 eWarning("can't render to %dbpp", surface->bpp);
691 gRegion area(eRect(0, 0, surface->x, surface->y));
692 gRegion clip = dc.getClip() & area;
694 int buffer_stride=surface->stride;
696 for (unsigned int c = 0; c < clip.rects.size(); ++c)
698 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
700 if (!(i->flags & GS_INVERT))
702 lookup8 = lookup8_normal;
703 lookup32 = lookup32_normal;
706 lookup8 = lookup8_invert;
707 lookup32 = lookup32_invert;
710 static FTC_SBit glyph_bitmap;
711 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
713 int rx=i->x+glyph_bitmap->left + offset.x();
714 int ry=i->y-glyph_bitmap->top + offset.y();
716 __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
717 __u8 *s=glyph_bitmap->buffer;
718 register int sx=glyph_bitmap->width;
719 int sy=glyph_bitmap->height;
720 if ((sy+ry) >= clip.rects[c].bottom())
721 sy=clip.rects[c].bottom()-ry;
722 if ((sx+rx) >= clip.rects[c].right())
723 sx=clip.rects[c].right()-rx;
724 if (rx < clip.rects[c].left())
726 int diff=clip.rects[c].left()-rx;
730 d+=diff*surface->bypp;
732 if (ry < clip.rects[c].top())
734 int diff=clip.rects[c].top()-ry;
735 s+=diff*glyph_bitmap->pitch;
738 d+=diff*buffer_stride;
741 for (int ay=0; ay<sy; ay++)
743 if (!opcode) // 4bit lookup to 8bit
748 for (ax=0; ax<sx; ax++)
750 register int b=(*s++)>>4;
756 } else if (opcode == 1) // 8bit direct
760 for (ax=0; ax<sx; ax++)
767 register __u32 *td=(__u32*)d;
769 for (ax=0; ax<sx; ax++)
771 register int b=(*s++)>>4;
778 s+=glyph_bitmap->pitch-sx;
785 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
787 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
790 while (c != glyphs.end())
793 int numspaces=0, num=0;
796 ASSERT( end != glyphs.end());
802 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
803 // end zeigt jetzt auf begin der naechsten zeile
805 for (c=begin; c!=end; ++c)
807 // space am zeilenende skippen
808 if ((c==last) && (c->flags&GS_ISSPACE))
811 if (c->flags&GS_ISSPACE)
817 if (!num) // line mit nur einem space
825 int offset=area.width()-linelength;
831 begin->bbox.moveBy(offset-begin->x,0);
840 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
847 if ((!spacemode) && (num<2))
849 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
854 if ((!spacemode) || (begin->flags&GS_ISSPACE))
857 begin->bbox.moveBy(curoff>>8,0);
870 void eTextPara::clear()
872 singleLock s(ftlock);
875 replacement_font = 0;
880 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");