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>
31 // until we have it in the cdk
34 #include <fribidi/fribidi.h>
39 fontRenderClass *fontRenderClass::instance;
41 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
43 struct fntColorCacheKey
46 fntColorCacheKey(const gRGB &start, const gRGB &end)
47 : start(start), end(end)
50 bool operator <(const fntColorCacheKey &c) const
54 else if (start == c.start)
60 std::map<fntColorCacheKey,gLookup> colorcache;
62 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
64 fntColorCacheKey key(start, end);
65 std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
66 if (i != colorcache.end())
68 gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
69 // eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
70 // end.a, end.r, end.g, end.b);
71 n.build(16, pal, start, end);
72 // for (int i=0; i<16; i++)
73 // 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);
78 fontRenderClass *fontRenderClass::getInstance()
83 FT_Error myFTC_Face_Requester(FTC_FaceID face_id,
85 FT_Pointer request_data,
88 return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
92 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
94 fontListEntry *font=(fontListEntry *)face_id;
98 // eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
101 if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
103 eDebug(" failed: %s", strerror(error));
106 FT_Select_Charmap(*aface, ft_encoding_unicode);
110 FTC_FaceID fontRenderClass::getFaceID(const std::string &face)
112 for (fontListEntry *f=font; f; f=f->next)
115 return (FTC_FaceID)f;
120 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
122 FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
126 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale)
128 eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
131 fontListEntry *n=new fontListEntry;
135 singleLock s(ftlock);
137 if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
138 eFatal(" failed: %s", strerror(error));
140 n->filename=filename;
145 eDebug("OK (%s)", n->face.c_str());
151 fontRenderClass::fontListEntry::~fontListEntry()
155 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
158 eDebug("[FONT] initializing lib...");
160 if (FT_Init_FreeType(&library))
162 eDebug("[FONT] initializing failed.");
166 eDebug("[FONT] loading fonts...");
170 int maxbytes=4*1024*1024;
171 eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
174 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
176 eDebug("[FONT] initializing font cache failed!");
181 eDebug("[FONT] initializing font cache manager error.");
184 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
186 eDebug("[FONT] initializing font cache sbit failed!");
189 if (FTC_Image_Cache_New(cacheManager, &imageCache))
191 eDebug("[FONT] initializing font cache imagecache failed!");
197 float fontRenderClass::getLineHeight(const gFont& font)
202 getFont(fnt, font.family.c_str(), font.pointSize);
205 singleLock s(ftlock);
206 FT_Face current_face;
207 if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, ¤t_face) < 0) ||
208 (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
210 eDebug("FTC_Manager_Lookup_Size failed!");
213 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
214 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
218 fontRenderClass::~fontRenderClass()
220 singleLock s(ftlock);
223 fontListEntry *f=font;
227 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
228 // FTC_Manager_Done(cacheManager);
229 // FT_Done_FreeType(library);
232 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
234 FTC_FaceID id=getFaceID(face);
240 font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
244 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
246 fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
248 eTextPara::setReplacementFont(alias);
253 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
256 font.face_id = faceid;
259 font.flags = FT_LOAD_DEFAULT;
260 scaler.face_id = faceid;
261 scaler.width = isize;
262 scaler.height = isize;
267 // font.image_type |= ftc_image_flag_autohinted;
270 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
272 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
279 DEFINE_REF(eTextPara);
281 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
284 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
297 glyphString::reverse_iterator i(glyphs.rbegin());
298 /* find first possibility (from end to begin) to break */
299 while (i != glyphs.rend())
301 if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
308 if (i != glyphs.rend() /* ... we found anything */
309 && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
310 && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
311 && cnt ) /* ... and there are actual non-space characters after this */
313 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
314 if (i->flags & GS_SOFTHYPHEN)
316 i->flags &= ~GS_SOFTHYPHEN;
317 i->flags |= GS_HYPHEN;
319 --i; /* skip the space/hypen/softhyphen */
320 int linelength=cursor.x()-i->x;
321 i->flags|=GS_ISFIRST; /* make this a line start */
322 ePoint offset=ePoint(i->x, i->y);
326 /* and move everything to the end into the next line. */
331 i->bbox.moveBy(-offset.x(), -offset.y());
334 } while (i-- != glyphs.rbegin()); // rearrange them into the next line
335 cursor+=ePoint(linelength, 0); // put the cursor after that line
346 int xadvance=glyph->xadvance, kern=0;
348 if (previous && use_kerning)
351 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
356 ng.bbox.setLeft( ((flags&GS_ISFIRST)|(cursor.x()-1))+glyph->left );
357 ng.bbox.setTop( cursor.y() - glyph->top );
358 ng.bbox.setWidth( glyph->width );
359 ng.bbox.setHeight( glyph->height );
362 ng.bbox.setWidth(xadvance);
364 ng.x = cursor.x()+kern;
367 ng.font = current_font;
368 ng.glyph_index = glyphIndex;
370 glyphs.push_back(ng);
373 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
374 if (!(flags & GS_SOFTHYPHEN))
375 cursor += ePoint(xadvance, 0);
376 previous = glyphIndex;
380 void eTextPara::calc_bbox()
391 glyphString::iterator i(glyphs.begin());
396 for (; i != glyphs.end(); ++i)
398 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
400 if ( i->bbox.left() < boundBox.left() )
401 boundBox.setLeft( i->bbox.left() );
402 if ( i->bbox.top() < boundBox.top() )
403 boundBox.setTop( i->bbox.top() );
404 if ( i->bbox.right() > boundBox.right() )
405 boundBox.setRight( i->bbox.right() );
406 if ( i->bbox.bottom() > boundBox.bottom() )
407 boundBox.setBottom( i->bbox.bottom() );
409 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
412 void eTextPara::newLine(int flags)
414 if (maximum.width()<cursor.x())
415 maximum.setWidth(cursor.x());
418 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
420 lineOffsets.push_back(cursor.y());
421 lineChars.push_back(charCount);
424 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
426 if (maximum.height()<cursor.y())
427 maximum.setHeight(cursor.y());
431 eTextPara::~eTextPara()
436 void eTextPara::setFont(const gFont *font)
438 ePtr<Font> fnt, replacement;
439 fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
441 eWarning("FONT '%s' MISSING!", font->family.c_str());
442 fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
443 setFont(fnt, replacement);
446 std::string eTextPara::replacement_facename;
447 std::set<int> eTextPara::forced_replaces;
449 void eTextPara::setFont(Font *fnt, Font *replacement)
454 replacement_font=replacement;
455 singleLock s(ftlock);
457 // we ask for replacment_font first becauseof the cache
458 if (replacement_font)
460 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
461 replacement_font->scaler.face_id,
462 &replacement_face) < 0) ||
463 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
464 &replacement_font->scaler,
465 &replacement_font->size) < 0))
467 eDebug("FTC_Manager_Lookup_Size failed!");
473 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
474 current_font->scaler.face_id,
475 ¤t_face) < 0) ||
476 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
477 ¤t_font->scaler,
478 ¤t_font->size) < 0))
480 eDebug("FTC_Manager_Lookup_Size failed!");
485 use_kerning=FT_HAS_KERNING(current_face);
489 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
491 int eTextPara::renderString(const char *string, int rflags)
493 singleLock s(ftlock);
498 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
499 current_font->scaler.face_id,
500 ¤t_face) < 0) ||
501 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
502 ¤t_font->scaler,
503 ¤t_font->size) < 0))
505 eDebug("FTC_Manager_Lookup_Size failed!");
510 eFatal("eTextPara::renderString: no current_face");
511 if (!current_face->size)
512 eFatal("eTextPara::renderString: no current_face->size");
516 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
520 std::vector<unsigned long> uc_string, uc_visual;
522 uc_string.reserve(strlen(string));
524 const char *p = string ? string : "";
528 unsigned int unicode=(unsigned char)*p++;
530 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
532 if ((unicode & 0xE0)==0xC0) // two bytes
537 unicode|=(*p++)&0x3F;
538 } else if ((unicode & 0xF0)==0xE0) // three bytes
543 unicode|=(*p++)&0x3F;
546 unicode|=(*p++)&0x3F;
547 } else if ((unicode & 0xF8)==0xF0) // four bytes
552 unicode|=(*p++)&0x3F;
555 unicode|=(*p++)&0x3F;
558 unicode|=(*p++)&0x3F;
561 uc_string.push_back(unicode);
564 std::vector<unsigned long> uc_shape;
566 // character -> glyph conversion
567 shape(uc_shape, uc_string);
569 // now do the usual logical->visual reordering
570 int size=uc_shape.size();
572 FriBidiCharType dir=FRIBIDI_TYPE_ON;
573 uc_visual.resize(size);
574 // gaaanz lahm, aber anders geht das leider nicht, sorry.
575 FriBidiChar array[size], target[size];
576 std::copy(uc_shape.begin(), uc_shape.end(), array);
577 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
578 uc_visual.assign(target, target+size);
583 glyphs.reserve(size);
587 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
588 i != uc_visual.end(); ++i)
591 int flags = nextflags;
593 unsigned long chr = *i;
595 if (!(rflags&RS_DIRECT))
601 unsigned long c = *(i+1);
620 cursor+=ePoint(current_font->tabwidth, 0);
621 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
626 newline:isprintable=0;
628 nextflags|=GS_ISFIRST;
631 case 0x86: case 0xE086:
632 case 0x87: case 0xE087:
633 nprint: isprintable=0;
635 case 0xAD: // soft-hyphen
636 flags |= GS_SOFTHYPHEN;
637 chr = 0x2010; /* hyphen */
653 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
657 if (forced_replaces.find(chr) == forced_replaces.end())
658 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
662 if (replacement_face)
663 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
666 eDebug("unicode U+%4lx not present", chr);
668 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
670 appendGlyph(current_font, current_face, index, flags, rflags);
676 if (dir & FRIBIDI_MASK_RTL)
679 doTopBottomReordering=true;
685 lineOffsets.push_back(cursor.y());
686 lineChars.push_back(charCount);
693 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
695 singleLock s(ftlock);
700 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
701 current_font->scaler.face_id,
702 ¤t_face) < 0) ||
703 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
704 ¤t_font->scaler,
705 ¤t_font->size) < 0))
707 eDebug("FTC_Manager_Lookup_Size failed!");
711 ePtr<gPixmap> target;
712 dc.getPixmap(target);
713 gSurface *surface = target->surface;
717 gColor *lookup8, lookup8_invert[16];
718 gColor *lookup8_normal=0;
720 __u16 lookup16_normal[16], lookup16_invert[16], *lookup16;
721 __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
723 if (surface->bpp == 8)
725 if (surface->clut.data)
727 lookup8_normal=getColor(surface->clut, background, foreground).lookup;
731 lookup8_invert[i] = lookup8_normal[i^0xF];
736 } else if (surface->bpp == 16)
739 for (int i=0; i<16; ++i)
741 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
742 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
746 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
747 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
748 db = BLEND(background.b, foreground.b, sa) & 0xFF;
751 #if BYTE_ORDER == LITTLE_ENDIAN
752 lookup16_normal[i] = bswap_16(((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3));
754 lookup16_normal[i] = ((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3);
758 for (int i=0; i<16; ++i)
759 lookup16_invert[i]=lookup16_normal[i^0xF];
760 } else if (surface->bpp == 32)
763 for (int i=0; i<16; ++i)
765 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
767 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
771 da = BLEND(background.a, foreground.a, sa) & 0xFF;
772 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
773 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
774 db = BLEND(background.b, foreground.b, sa) & 0xFF;
778 lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
780 for (int i=0; i<16; ++i)
781 lookup32_invert[i]=lookup32_normal[i^0xF];
784 eWarning("can't render to %dbpp", surface->bpp);
788 gRegion area(eRect(0, 0, surface->x, surface->y));
789 gRegion clip = dc.getClip() & area;
791 int buffer_stride=surface->stride;
793 for (unsigned int c = 0; c < clip.rects.size(); ++c)
795 std::list<int>::reverse_iterator line_offs_it(lineOffsets.rbegin());
796 std::list<int>::iterator line_chars_it(lineChars.begin());
799 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i, --line_chars)
803 line_offs = *(line_offs_it++);
804 line_chars = *(line_chars_it++);
807 if (i->flags & GS_SOFTHYPHEN)
810 if (!(i->flags & GS_INVERT))
812 lookup8 = lookup8_normal;
813 lookup16 = lookup16_normal;
814 lookup32 = lookup32_normal;
817 lookup8 = lookup8_invert;
818 lookup16 = lookup16_invert;
819 lookup32 = lookup32_invert;
822 static FTC_SBit glyph_bitmap;
823 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
825 int rx=i->x+glyph_bitmap->left + offset.x();
826 int ry=(doTopBottomReordering ? line_offs : i->y) - glyph_bitmap->top + offset.y();
828 __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
829 __u8 *s=glyph_bitmap->buffer;
830 register int sx=glyph_bitmap->width;
831 int sy=glyph_bitmap->height;
832 if ((sy+ry) >= clip.rects[c].bottom())
833 sy=clip.rects[c].bottom()-ry;
834 if ((sx+rx) >= clip.rects[c].right())
835 sx=clip.rects[c].right()-rx;
836 if (rx < clip.rects[c].left())
838 int diff=clip.rects[c].left()-rx;
842 d+=diff*surface->bypp;
844 if (ry < clip.rects[c].top())
846 int diff=clip.rects[c].top()-ry;
847 s+=diff*glyph_bitmap->pitch;
850 d+=diff*buffer_stride;
855 case 0: // 4bit lookup to 8bit
856 for (int ay=0; ay<sy; ay++)
860 for (ax=0; ax<sx; ax++)
862 register int b=(*s++)>>4;
868 s+=glyph_bitmap->pitch-sx;
872 case 1: // 8bit direct
873 for (int ay=0; ay<sy; ay++)
877 for (ax=0; ax<sx; ax++)
882 s+=glyph_bitmap->pitch-sx;
887 for (int ay=0; ay<sy; ay++)
889 register __u16 *td=(__u16*)d;
891 for (ax=0; ax<sx; ax++)
893 register int b=(*s++)>>4;
899 s+=glyph_bitmap->pitch-sx;
904 for (int ay=0; ay<sy; ay++)
906 register __u32 *td=(__u32*)d;
908 for (ax=0; ax<sx; ax++)
910 register int b=(*s++)>>4;
916 s+=glyph_bitmap->pitch-sx;
927 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
929 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
932 while (c != glyphs.end())
935 int numspaces=0, num=0;
938 ASSERT( end != glyphs.end());
944 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
945 // end zeigt jetzt auf begin der naechsten zeile
947 for (c=begin; c!=end; ++c)
949 // space am zeilenende skippen
950 if ((c==last) && (c->flags&GS_ISSPACE))
953 if (c->flags&GS_ISSPACE)
964 int offset=area.width()-linelength;
970 begin->bbox.moveBy(offset-begin->x,0);
979 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
986 if ((!spacemode) && (num<2))
988 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
993 if ((!spacemode) || (begin->flags&GS_ISSPACE))
996 begin->bbox.moveBy(curoff>>8,0);
1009 void eTextPara::clear()
1011 singleLock s(ftlock);
1014 replacement_font = 0;
1019 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");