1 #include <lib/gdi/font.h>
12 #error "no BYTE_ORDER defined!"
15 // use this for init Freetype...
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)
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>
30 #include <fribidi/fribidi.h>
34 fontRenderClass *fontRenderClass::instance;
36 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
38 struct fntColorCacheKey
41 fntColorCacheKey(const gRGB &start, const gRGB &end)
42 : start(start), end(end)
45 bool operator <(const fntColorCacheKey &c) const
49 else if (start == c.start)
55 std::map<fntColorCacheKey,gLookup> colorcache;
57 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
59 fntColorCacheKey key(start, end);
60 std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
61 if (i != colorcache.end())
63 gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
64 // eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
65 // end.a, end.r, end.g, end.b);
66 n.build(16, pal, start, end);
67 // for (int i=0; i<16; i++)
68 // eDebugNoNewLine("%02x|%02x%02x%02x%02x ", (int)n.lookup[i], pal.data[n.lookup[i]].a, pal.data[n.lookup[i]].r, pal.data[n.lookup[i]].g, pal.data[n.lookup[i]].b);
73 fontRenderClass *fontRenderClass::getInstance()
78 FT_Error myFTC_Face_Requester(FTC_FaceID face_id,
80 FT_Pointer request_data,
83 return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
87 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
89 fontListEntry *font=(fontListEntry *)face_id;
93 // eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
96 if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
98 eDebug(" failed: %s", strerror(error));
101 FT_Select_Charmap(*aface, ft_encoding_unicode);
105 FTC_FaceID fontRenderClass::getFaceID(const std::string &face)
107 for (fontListEntry *f=font; f; f=f->next)
110 return (FTC_FaceID)f;
115 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
117 FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
121 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale)
123 eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
126 fontListEntry *n=new fontListEntry;
130 singleLock s(ftlock);
132 if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
133 eFatal(" failed: %s", strerror(error));
135 n->filename=filename;
140 eDebug("OK (%s)", n->face.c_str());
146 fontRenderClass::fontListEntry::~fontListEntry()
150 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
153 eDebug("[FONT] initializing lib...");
155 if (FT_Init_FreeType(&library))
157 eDebug("[FONT] initializing failed.");
161 eDebug("[FONT] loading fonts...");
165 int maxbytes=4*1024*1024;
166 eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
169 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
171 eDebug("[FONT] initializing font cache failed!");
176 eDebug("[FONT] initializing font cache manager error.");
179 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
181 eDebug("[FONT] initializing font cache sbit failed!");
184 if (FTC_Image_Cache_New(cacheManager, &imageCache))
186 eDebug("[FONT] initializing font cache imagecache failed!");
192 float fontRenderClass::getLineHeight(const gFont& font)
197 getFont(fnt, font.family.c_str(), font.pointSize);
200 singleLock s(ftlock);
201 FT_Face current_face;
202 if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, ¤t_face) < 0) ||
203 (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
205 eDebug("FTC_Manager_Lookup_Size failed!");
208 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
209 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
213 fontRenderClass::~fontRenderClass()
215 singleLock s(ftlock);
218 fontListEntry *f=font;
222 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
223 // FTC_Manager_Done(cacheManager);
224 // FT_Done_FreeType(library);
227 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
229 FTC_FaceID id=getFaceID(face);
235 font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
239 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
241 fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
243 eTextPara::setReplacementFont(alias);
248 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
251 font.face_id = faceid;
254 font.flags = FT_LOAD_DEFAULT;
255 scaler.face_id = faceid;
256 scaler.width = isize;
257 scaler.height = isize;
262 // font.image_type |= ftc_image_flag_autohinted;
265 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
267 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
274 DEFINE_REF(eTextPara);
276 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
279 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
292 glyphString::reverse_iterator i(glyphs.rbegin());
293 /* find first possibility (from end to begin) to break */
294 while (i != glyphs.rend())
296 if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
303 if (i != glyphs.rend() /* ... we found anything */
304 && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
305 && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
306 && cnt ) /* ... and there are actual non-space characters after this */
308 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
309 if (i->flags & GS_SOFTHYPHEN)
311 i->flags &= ~GS_SOFTHYPHEN;
312 i->flags |= GS_HYPHEN;
314 --i; /* skip the space/hypen/softhyphen */
315 int linelength=cursor.x()-i->x;
316 i->flags|=GS_ISFIRST; /* make this a line start */
317 ePoint offset=ePoint(i->x, i->y);
321 /* and move everything to the end into the next line. */
326 i->bbox.moveBy(-offset.x(), -offset.y());
329 } while (i-- != glyphs.rbegin()); // rearrange them into the next line
330 cursor+=ePoint(linelength, 0); // put the cursor after that line
341 int xadvance=glyph->xadvance, kern=0;
343 if (previous && use_kerning)
346 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
351 ng.bbox.setLeft( ((flags&GS_ISFIRST)|(cursor.x()-1))+glyph->left );
352 ng.bbox.setTop( cursor.y() - glyph->top );
353 ng.bbox.setWidth( glyph->width );
354 ng.bbox.setHeight( glyph->height );
357 ng.bbox.setWidth(xadvance);
359 ng.x = cursor.x()+kern;
362 ng.font = current_font;
363 ng.glyph_index = glyphIndex;
365 glyphs.push_back(ng);
368 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
369 if (!(flags & GS_SOFTHYPHEN))
370 cursor += ePoint(xadvance, 0);
371 previous = glyphIndex;
375 void eTextPara::calc_bbox()
386 glyphString::iterator i(glyphs.begin());
391 for (; i != glyphs.end(); ++i)
393 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
395 if ( i->bbox.left() < boundBox.left() )
396 boundBox.setLeft( i->bbox.left() );
397 if ( i->bbox.top() < boundBox.top() )
398 boundBox.setTop( i->bbox.top() );
399 if ( i->bbox.right() > boundBox.right() )
400 boundBox.setRight( i->bbox.right() );
401 if ( i->bbox.bottom() > boundBox.bottom() )
402 boundBox.setBottom( i->bbox.bottom() );
404 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
407 void eTextPara::newLine(int flags)
409 if (maximum.width()<cursor.x())
410 maximum.setWidth(cursor.x());
413 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
415 lineOffsets.push_back(cursor.y());
416 lineChars.push_back(charCount);
419 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
421 if (maximum.height()<cursor.y())
422 maximum.setHeight(cursor.y());
426 eTextPara::~eTextPara()
431 void eTextPara::setFont(const gFont *font)
433 ePtr<Font> fnt, replacement;
434 fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
436 eWarning("FONT '%s' MISSING!", font->family.c_str());
437 fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
438 setFont(fnt, replacement);
441 std::string eTextPara::replacement_facename;
442 std::set<int> eTextPara::forced_replaces;
444 void eTextPara::setFont(Font *fnt, Font *replacement)
449 replacement_font=replacement;
450 singleLock s(ftlock);
452 // we ask for replacment_font first becauseof the cache
453 if (replacement_font)
455 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
456 replacement_font->scaler.face_id,
457 &replacement_face) < 0) ||
458 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
459 &replacement_font->scaler,
460 &replacement_font->size) < 0))
462 eDebug("FTC_Manager_Lookup_Size failed!");
468 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
469 current_font->scaler.face_id,
470 ¤t_face) < 0) ||
471 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
472 ¤t_font->scaler,
473 ¤t_font->size) < 0))
475 eDebug("FTC_Manager_Lookup_Size failed!");
480 use_kerning=FT_HAS_KERNING(current_face);
484 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
486 int eTextPara::renderString(const char *string, int rflags)
488 singleLock s(ftlock);
493 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
494 current_font->scaler.face_id,
495 ¤t_face) < 0) ||
496 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
497 ¤t_font->scaler,
498 ¤t_font->size) < 0))
500 eDebug("FTC_Manager_Lookup_Size failed!");
505 eFatal("eTextPara::renderString: no current_face");
506 if (!current_face->size)
507 eFatal("eTextPara::renderString: no current_face->size");
511 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
515 std::vector<unsigned long> uc_string, uc_visual;
517 uc_string.reserve(strlen(string));
519 const char *p = string ? string : "";
523 unsigned int unicode=(unsigned char)*p++;
525 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
527 if ((unicode & 0xE0)==0xC0) // two bytes
532 unicode|=(*p++)&0x3F;
533 } else if ((unicode & 0xF0)==0xE0) // three bytes
538 unicode|=(*p++)&0x3F;
541 unicode|=(*p++)&0x3F;
542 } else if ((unicode & 0xF8)==0xF0) // four bytes
547 unicode|=(*p++)&0x3F;
550 unicode|=(*p++)&0x3F;
553 unicode|=(*p++)&0x3F;
556 uc_string.push_back(unicode);
559 std::vector<unsigned long> uc_shape;
561 // character -> glyph conversion
562 shape(uc_shape, uc_string);
564 // now do the usual logical->visual reordering
565 int size=uc_shape.size();
566 FriBidiCharType dir=FRIBIDI_TYPE_ON;
567 uc_visual.resize(size);
568 // gaaanz lahm, aber anders geht das leider nicht, sorry.
569 FriBidiChar array[size], target[size];
570 std::copy(uc_shape.begin(), uc_shape.end(), array);
571 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
572 uc_visual.assign(target, target+size);
574 glyphs.reserve(size);
578 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
579 i != uc_visual.end(); ++i)
582 int flags = nextflags;
584 unsigned long chr = *i;
586 if (!(rflags&RS_DIRECT))
592 unsigned long c = *(i+1);
611 cursor+=ePoint(current_font->tabwidth, 0);
612 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
617 newline:isprintable=0;
619 nextflags|=GS_ISFIRST;
622 case 0x86: case 0xE086:
623 case 0x87: case 0xE087:
624 nprint: isprintable=0;
626 case 0xAD: // soft-hyphen
627 flags |= GS_SOFTHYPHEN;
628 chr = 0x2010; /* hyphen */
644 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
648 if (forced_replaces.find(chr) == forced_replaces.end())
649 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
653 if (replacement_face)
654 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
657 eDebug("unicode U+%4lx not present", chr);
659 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
661 appendGlyph(current_font, current_face, index, flags, rflags);
666 if (dir & FRIBIDI_MASK_RTL)
669 doTopBottomReordering=true;
674 lineOffsets.push_back(cursor.y());
675 lineChars.push_back(charCount);
682 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
684 singleLock s(ftlock);
689 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
690 current_font->scaler.face_id,
691 ¤t_face) < 0) ||
692 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
693 ¤t_font->scaler,
694 ¤t_font->size) < 0))
696 eDebug("FTC_Manager_Lookup_Size failed!");
700 ePtr<gPixmap> target;
701 dc.getPixmap(target);
702 gSurface *surface = target->surface;
706 gColor *lookup8, lookup8_invert[16];
707 gColor *lookup8_normal=0;
709 __u16 lookup16_normal[16], lookup16_invert[16], *lookup16;
710 __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
712 if (surface->bpp == 8)
714 if (surface->clut.data)
716 lookup8_normal=getColor(surface->clut, background, foreground).lookup;
720 lookup8_invert[i] = lookup8_normal[i^0xF];
725 } else if (surface->bpp == 16)
728 for (int i=0; i<16; ++i)
730 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
731 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
735 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
736 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
737 db = BLEND(background.b, foreground.b, sa) & 0xFF;
740 #if BYTE_ORDER == LITTLE_ENDIAN
741 lookup16_normal[i] = bswap_16(((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3));
743 lookup16_normal[i] = ((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3);
747 for (int i=0; i<16; ++i)
748 lookup16_invert[i]=lookup16_normal[i^0xF];
749 } else if (surface->bpp == 32)
752 for (int i=0; i<16; ++i)
754 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
756 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
760 da = BLEND(background.a, foreground.a, sa) & 0xFF;
761 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
762 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
763 db = BLEND(background.b, foreground.b, sa) & 0xFF;
767 lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
769 for (int i=0; i<16; ++i)
770 lookup32_invert[i]=lookup32_normal[i^0xF];
773 eWarning("can't render to %dbpp", surface->bpp);
777 gRegion area(eRect(0, 0, surface->x, surface->y));
778 gRegion clip = dc.getClip() & area;
780 int buffer_stride=surface->stride;
782 for (unsigned int c = 0; c < clip.rects.size(); ++c)
784 std::list<int>::reverse_iterator line_offs_it(lineOffsets.rbegin());
785 std::list<int>::iterator line_chars_it(lineChars.begin());
788 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i, --line_chars)
792 line_offs = *(line_offs_it++);
793 line_chars = *(line_chars_it++);
796 if (i->flags & GS_SOFTHYPHEN)
799 if (!(i->flags & GS_INVERT))
801 lookup8 = lookup8_normal;
802 lookup16 = lookup16_normal;
803 lookup32 = lookup32_normal;
806 lookup8 = lookup8_invert;
807 lookup16 = lookup16_invert;
808 lookup32 = lookup32_invert;
811 static FTC_SBit glyph_bitmap;
812 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
814 int rx=i->x+glyph_bitmap->left + offset.x();
815 int ry=(doTopBottomReordering ? line_offs : i->y) - glyph_bitmap->top + offset.y();
817 __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
818 __u8 *s=glyph_bitmap->buffer;
819 register int sx=glyph_bitmap->width;
820 int sy=glyph_bitmap->height;
821 if ((sy+ry) >= clip.rects[c].bottom())
822 sy=clip.rects[c].bottom()-ry;
823 if ((sx+rx) >= clip.rects[c].right())
824 sx=clip.rects[c].right()-rx;
825 if (rx < clip.rects[c].left())
827 int diff=clip.rects[c].left()-rx;
831 d+=diff*surface->bypp;
833 if (ry < clip.rects[c].top())
835 int diff=clip.rects[c].top()-ry;
836 s+=diff*glyph_bitmap->pitch;
839 d+=diff*buffer_stride;
844 case 0: // 4bit lookup to 8bit
845 for (int ay=0; ay<sy; ay++)
849 for (ax=0; ax<sx; ax++)
851 register int b=(*s++)>>4;
857 s+=glyph_bitmap->pitch-sx;
861 case 1: // 8bit direct
862 for (int ay=0; ay<sy; ay++)
866 for (ax=0; ax<sx; ax++)
871 s+=glyph_bitmap->pitch-sx;
876 for (int ay=0; ay<sy; ay++)
878 register __u16 *td=(__u16*)d;
880 for (ax=0; ax<sx; ax++)
882 register int b=(*s++)>>4;
888 s+=glyph_bitmap->pitch-sx;
893 for (int ay=0; ay<sy; ay++)
895 register __u32 *td=(__u32*)d;
897 for (ax=0; ax<sx; ax++)
899 register int b=(*s++)>>4;
905 s+=glyph_bitmap->pitch-sx;
916 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
918 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
921 while (c != glyphs.end())
924 int numspaces=0, num=0;
927 ASSERT( end != glyphs.end());
933 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
934 // end zeigt jetzt auf begin der naechsten zeile
936 for (c=begin; c!=end; ++c)
938 // space am zeilenende skippen
939 if ((c==last) && (c->flags&GS_ISSPACE))
942 if (c->flags&GS_ISSPACE)
953 int offset=area.width()-linelength;
959 begin->bbox.moveBy(offset-begin->x,0);
968 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
975 if ((!spacemode) && (num<2))
977 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
982 if ((!spacemode) || (begin->flags&GS_ISSPACE))
985 begin->bbox.moveBy(curoff>>8,0);
998 void eTextPara::clear()
1000 singleLock s(ftlock);
1003 replacement_font = 0;
1008 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");