1 #include <lib/gdi/font.h>
10 // use this for init Freetype...
12 #include FT_FREETYPE_H
14 #define FTC_Image_Cache_New(a,b) FTC_ImageCache_New(a,b)
15 #define FTC_Image_Cache_Lookup(a,b,c,d) FTC_ImageCache_Lookup(a,b,c,d,NULL)
16 #define FTC_SBit_Cache_New(a,b) FTC_SBitCache_New(a,b)
17 #define FTC_SBit_Cache_Lookup(a,b,c,d) FTC_SBitCache_Lookup(a,b,c,d,NULL)
20 #include <lib/base/eerror.h>
21 #include <lib/gdi/lcd.h>
22 #include <lib/gdi/grc.h>
23 #include <lib/base/elock.h>
24 #include <lib/base/init.h>
25 #include <lib/base/init_num.h>
28 // until we have it in the cdk
31 #include <fribidi/fribidi.h>
36 fontRenderClass *fontRenderClass::instance;
38 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
40 #ifndef HAVE_FREETYPE2
41 static FTC_Font cache_current_font=0;
44 struct fntColorCacheKey
47 fntColorCacheKey(const gRGB &start, const gRGB &end)
48 : start(start), end(end)
51 bool operator <(const fntColorCacheKey &c) const
55 else if (start == c.start)
61 std::map<fntColorCacheKey,gLookup> colorcache;
63 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
65 fntColorCacheKey key(start, end);
66 std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
67 if (i != colorcache.end())
69 gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
70 // eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
71 // end.a, end.r, end.g, end.b);
72 n.build(16, pal, start, end);
73 // for (int i=0; i<16; i++)
74 // 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);
79 fontRenderClass *fontRenderClass::getInstance()
84 FT_Error myFTC_Face_Requester(FTC_FaceID face_id,
86 FT_Pointer request_data,
89 return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
93 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
95 fontListEntry *font=(fontListEntry *)face_id;
99 // eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
102 if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
104 eDebug(" failed: %s", strerror(error));
107 FT_Select_Charmap(*aface, ft_encoding_unicode);
111 FTC_FaceID fontRenderClass::getFaceID(const std::string &face)
113 for (fontListEntry *f=font; f; f=f->next)
116 return (FTC_FaceID)f;
121 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
123 FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
127 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale)
129 eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
132 fontListEntry *n=new fontListEntry;
136 singleLock s(ftlock);
138 if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
139 eFatal(" failed: %s", strerror(error));
141 n->filename=filename;
146 eDebug("OK (%s)", n->face.c_str());
152 fontRenderClass::fontListEntry::~fontListEntry()
156 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
159 eDebug("[FONT] initializing lib...");
161 if (FT_Init_FreeType(&library))
163 eDebug("[FONT] initializing failed.");
167 eDebug("[FONT] loading fonts...");
171 int maxbytes=4*1024*1024;
172 eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
175 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
177 eDebug("[FONT] initializing font cache failed!");
182 eDebug("[FONT] initializing font cache manager error.");
185 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
187 eDebug("[FONT] initializing font cache sbit failed!");
190 if (FTC_Image_Cache_New(cacheManager, &imageCache))
192 eDebug("[FONT] initializing font cache imagecache failed!");
198 float fontRenderClass::getLineHeight(const gFont& font)
203 getFont(fnt, font.family.c_str(), font.pointSize);
206 singleLock s(ftlock);
207 FT_Face current_face;
208 #ifdef HAVE_FREETYPE2
209 if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, ¤t_face) < 0) ||
210 (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
212 if (FTC_Manager_Lookup_Size(cacheManager, &fnt->font.font, ¤t_face, &fnt->size)<0)
215 eDebug("FTC_Manager_Lookup_Size failed!");
218 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
219 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
223 fontRenderClass::~fontRenderClass()
225 singleLock s(ftlock);
228 fontListEntry *f=font;
232 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
233 // FTC_Manager_Done(cacheManager);
234 // FT_Done_FreeType(library);
237 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
239 FTC_FaceID id=getFaceID(face);
245 font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
249 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
251 fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
253 eTextPara::setReplacementFont(alias);
258 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
261 #ifdef HAVE_FREETYPE2
262 font.face_id = faceid;
265 font.flags = FT_LOAD_DEFAULT;
266 scaler.face_id = faceid;
267 scaler.width = isize;
268 scaler.height = isize;
271 font.font.face_id=faceid;
272 font.font.pix_width = isize;
273 font.font.pix_height = isize;
274 font.image_type = ftc_image_grays;
279 // font.image_type |= ftc_image_flag_autohinted;
282 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
284 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
291 DEFINE_REF(eTextPara);
293 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
296 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
309 glyphString::reverse_iterator i(glyphs.rbegin());
310 /* find first possibility (from end to begin) to break */
311 while (i != glyphs.rend())
313 if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
320 if (i != glyphs.rend() /* ... we found anything */
321 && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
322 && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
323 && cnt ) /* ... and there are actual non-space characters after this */
325 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
326 if (i->flags & GS_SOFTHYPHEN)
328 i->flags &= ~GS_SOFTHYPHEN;
329 i->flags |= GS_HYPHEN;
331 --i; /* skip the space/hypen/softhyphen */
332 int linelength=cursor.x()-i->x;
333 i->flags|=GS_ISFIRST; /* make this a line start */
334 ePoint offset=ePoint(i->x, i->y);
338 /* and move everything to the end into the next line. */
343 i->bbox.moveBy(-offset.x(), -offset.y());
346 } while (i-- != glyphs.rbegin()); // rearrange them into the next line
347 cursor+=ePoint(linelength, 0); // put the cursor after that line
358 int xadvance=glyph->xadvance, kern=0;
360 if (previous && use_kerning)
363 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
368 ng.bbox.setLeft( (flags&GS_ISFIRST|cursor.x()-1)+glyph->left );
369 ng.bbox.setTop( cursor.y() - glyph->top );
370 ng.bbox.setWidth( glyph->width );
371 ng.bbox.setHeight( glyph->height );
374 ng.bbox.setWidth(xadvance);
376 ng.x = cursor.x()+kern;
379 ng.font = current_font;
380 ng.glyph_index = glyphIndex;
382 glyphs.push_back(ng);
385 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
386 if (!(flags & GS_SOFTHYPHEN))
387 cursor += ePoint(xadvance, 0);
388 previous = glyphIndex;
392 void eTextPara::calc_bbox()
403 glyphString::iterator i(glyphs.begin());
408 for (; i != glyphs.end(); ++i)
410 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
412 if ( i->bbox.left() < boundBox.left() )
413 boundBox.setLeft( i->bbox.left() );
414 if ( i->bbox.top() < boundBox.top() )
415 boundBox.setTop( i->bbox.top() );
416 if ( i->bbox.right() > boundBox.right() )
417 boundBox.setRight( i->bbox.right() );
418 if ( i->bbox.bottom() > boundBox.bottom() )
419 boundBox.setBottom( i->bbox.bottom() );
421 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
424 void eTextPara::newLine(int flags)
426 if (maximum.width()<cursor.x())
427 maximum.setWidth(cursor.x());
430 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
432 lineOffsets.push_back(cursor.y());
433 lineChars.push_back(charCount);
436 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
438 if (maximum.height()<cursor.y())
439 maximum.setHeight(cursor.y());
443 eTextPara::~eTextPara()
448 void eTextPara::setFont(const gFont *font)
450 ePtr<Font> fnt, replacement;
451 fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
453 eWarning("FONT '%s' MISSING!", font->family.c_str());
454 fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
455 setFont(fnt, replacement);
458 std::string eTextPara::replacement_facename;
459 std::set<int> eTextPara::forced_replaces;
461 void eTextPara::setFont(Font *fnt, Font *replacement)
466 replacement_font=replacement;
467 singleLock s(ftlock);
469 // we ask for replacment_font first becauseof the cache
470 if (replacement_font)
472 #ifdef HAVE_FREETYPE2
473 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
474 replacement_font->scaler.face_id,
475 &replacement_face) < 0) ||
476 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
477 &replacement_font->scaler,
478 &replacement_font->size) < 0))
480 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager,
481 &replacement_font->font.font, &replacement_face,
482 &replacement_font->size)<0)
485 eDebug("FTC_Manager_Lookup_Size failed!");
491 #ifdef HAVE_FREETYPE2
492 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
493 current_font->scaler.face_id,
494 ¤t_face) < 0) ||
495 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
496 ¤t_font->scaler,
497 ¤t_font->size) < 0))
499 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
502 eDebug("FTC_Manager_Lookup_Size failed!");
506 #ifndef HAVE_FREETYPE2
507 cache_current_font=¤t_font->font.font;
510 use_kerning=FT_HAS_KERNING(current_face);
514 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
516 int eTextPara::renderString(const char *string, int rflags)
518 singleLock s(ftlock);
523 #ifdef HAVE_FREETYPE2
524 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
525 current_font->scaler.face_id,
526 ¤t_face) < 0) ||
527 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
528 ¤t_font->scaler,
529 ¤t_font->size) < 0))
531 eDebug("FTC_Manager_Lookup_Size failed!");
535 if (¤t_font->font.font != cache_current_font)
537 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
539 eDebug("FTC_Manager_Lookup_Size failed!");
542 cache_current_font=¤t_font->font.font;
547 eFatal("eTextPara::renderString: no current_face");
548 if (!current_face->size)
549 eFatal("eTextPara::renderString: no current_face->size");
553 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
557 std::vector<unsigned long> uc_string, uc_visual;
559 uc_string.reserve(strlen(string));
561 const char *p = string ? string : "";
565 unsigned int unicode=(unsigned char)*p++;
567 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
569 if ((unicode & 0xE0)==0xC0) // two bytes
574 unicode|=(*p++)&0x3F;
575 } else if ((unicode & 0xF0)==0xE0) // three bytes
580 unicode|=(*p++)&0x3F;
583 unicode|=(*p++)&0x3F;
584 } else if ((unicode & 0xF8)==0xF0) // four bytes
589 unicode|=(*p++)&0x3F;
592 unicode|=(*p++)&0x3F;
595 unicode|=(*p++)&0x3F;
598 uc_string.push_back(unicode);
601 std::vector<unsigned long> uc_shape;
603 // character -> glyph conversion
604 shape(uc_shape, uc_string);
606 // now do the usual logical->visual reordering
607 int size=uc_shape.size();
609 FriBidiCharType dir=FRIBIDI_TYPE_ON;
610 uc_visual.resize(size);
611 // gaaanz lahm, aber anders geht das leider nicht, sorry.
612 FriBidiChar array[size], target[size];
613 std::copy(uc_shape.begin(), uc_shape.end(), array);
614 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
615 uc_visual.assign(target, target+size);
620 glyphs.reserve(size);
624 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
625 i != uc_visual.end(); ++i)
628 int flags = nextflags;
630 unsigned long chr = *i;
632 if (!(rflags&RS_DIRECT))
638 unsigned long c = *(i+1);
657 cursor+=ePoint(current_font->tabwidth, 0);
658 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
663 newline:isprintable=0;
665 nextflags|=GS_ISFIRST;
668 case 0x86: case 0xE086:
669 case 0x87: case 0xE087:
670 nprint: isprintable=0;
672 case 0xAD: // soft-hyphen
673 flags |= GS_SOFTHYPHEN;
674 chr = 0x2010; /* hyphen */
690 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
694 if (forced_replaces.find(chr) == forced_replaces.end())
695 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
699 if (replacement_face)
700 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
703 eDebug("unicode U+%4lx not present", chr);
705 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
707 appendGlyph(current_font, current_face, index, flags, rflags);
713 if (dir & FRIBIDI_MASK_RTL)
716 doTopBottomReordering=true;
722 lineOffsets.push_back(cursor.y());
723 lineChars.push_back(charCount);
730 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
732 singleLock s(ftlock);
737 #ifdef HAVE_FREETYPE2
738 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
739 current_font->scaler.face_id,
740 ¤t_face) < 0) ||
741 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
742 ¤t_font->scaler,
743 ¤t_font->size) < 0))
745 eDebug("FTC_Manager_Lookup_Size failed!");
749 if (¤t_font->font.font != cache_current_font)
751 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
753 eDebug("FTC_Manager_Lookup_Size failed!");
756 cache_current_font=¤t_font->font.font;
760 ePtr<gPixmap> target;
761 dc.getPixmap(target);
762 gSurface *surface = target->surface;
766 gColor *lookup8, lookup8_invert[16];
767 gColor *lookup8_normal=0;
769 __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
771 if (surface->bpp == 8)
773 if (surface->clut.data)
775 lookup8_normal=getColor(surface->clut, background, foreground).lookup;
779 lookup8_invert[i] = lookup8_normal[i^0xF];
784 } else if (surface->bpp == 32)
788 for (int i=0; i<16; ++i)
790 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
792 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
796 da = BLEND(background.a, foreground.a, sa) & 0xFF;
797 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
798 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
799 db = BLEND(background.b, foreground.b, sa) & 0xFF;
803 lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
805 for (int i=0; i<16; ++i)
806 lookup32_invert[i]=lookup32_normal[i^0xF];
809 eWarning("can't render to %dbpp", surface->bpp);
813 gRegion area(eRect(0, 0, surface->x, surface->y));
814 gRegion clip = dc.getClip() & area;
816 int buffer_stride=surface->stride;
818 for (unsigned int c = 0; c < clip.rects.size(); ++c)
820 std::list<int>::reverse_iterator line_offs_it(lineOffsets.rbegin());
821 std::list<int>::iterator line_chars_it(lineChars.begin());
824 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i, --line_chars)
828 line_offs = *(line_offs_it++);
829 line_chars = *(line_chars_it++);
832 if (i->flags & GS_SOFTHYPHEN)
835 if (!(i->flags & GS_INVERT))
837 lookup8 = lookup8_normal;
838 lookup32 = lookup32_normal;
841 lookup8 = lookup8_invert;
842 lookup32 = lookup32_invert;
845 static FTC_SBit glyph_bitmap;
846 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
848 int rx=i->x+glyph_bitmap->left + offset.x();
849 int ry=(doTopBottomReordering ? line_offs : i->y) - glyph_bitmap->top + offset.y();
851 __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
852 __u8 *s=glyph_bitmap->buffer;
853 register int sx=glyph_bitmap->width;
854 int sy=glyph_bitmap->height;
855 if ((sy+ry) >= clip.rects[c].bottom())
856 sy=clip.rects[c].bottom()-ry;
857 if ((sx+rx) >= clip.rects[c].right())
858 sx=clip.rects[c].right()-rx;
859 if (rx < clip.rects[c].left())
861 int diff=clip.rects[c].left()-rx;
865 d+=diff*surface->bypp;
867 if (ry < clip.rects[c].top())
869 int diff=clip.rects[c].top()-ry;
870 s+=diff*glyph_bitmap->pitch;
873 d+=diff*buffer_stride;
876 for (int ay=0; ay<sy; ay++)
878 if (!opcode) // 4bit lookup to 8bit
883 for (ax=0; ax<sx; ax++)
885 register int b=(*s++)>>4;
891 } else if (opcode == 1) // 8bit direct
895 for (ax=0; ax<sx; ax++)
902 register __u32 *td=(__u32*)d;
904 for (ax=0; ax<sx; ax++)
906 register int b=(*s++)>>4;
913 s+=glyph_bitmap->pitch-sx;
920 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
922 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
925 while (c != glyphs.end())
928 int numspaces=0, num=0;
931 ASSERT( end != glyphs.end());
937 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
938 // end zeigt jetzt auf begin der naechsten zeile
940 for (c=begin; c!=end; ++c)
942 // space am zeilenende skippen
943 if ((c==last) && (c->flags&GS_ISSPACE))
946 if (c->flags&GS_ISSPACE)
957 int offset=area.width()-linelength;
963 begin->bbox.moveBy(offset-begin->x,0);
972 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
979 if ((!spacemode) && (num<2))
981 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
986 if ((!spacemode) || (begin->flags&GS_ISSPACE))
989 begin->bbox.moveBy(curoff>>8,0);
1002 void eTextPara::clear()
1004 singleLock s(ftlock);
1007 replacement_font = 0;
1012 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");