1 #include <lib/gdi/font.h>
12 #error "no BYTE_ORDER defined!"
15 // use this for init Freetype...
17 #include FT_FREETYPE_H
19 #define FTC_Image_Cache_New(a,b) FTC_ImageCache_New(a,b)
20 #define FTC_Image_Cache_Lookup(a,b,c,d) FTC_ImageCache_Lookup(a,b,c,d,NULL)
21 #define FTC_SBit_Cache_New(a,b) FTC_SBitCache_New(a,b)
22 #define FTC_SBit_Cache_Lookup(a,b,c,d) FTC_SBitCache_Lookup(a,b,c,d,NULL)
25 #include <lib/base/eerror.h>
26 #include <lib/gdi/lcd.h>
27 #include <lib/gdi/grc.h>
28 #include <lib/base/elock.h>
29 #include <lib/base/init.h>
30 #include <lib/base/init_num.h>
33 // until we have it in the cdk
36 #include <fribidi/fribidi.h>
41 fontRenderClass *fontRenderClass::instance;
43 static pthread_mutex_t ftlock=PTHREAD_ADAPTIVE_MUTEX_INITIALIZER_NP;
45 #ifndef HAVE_FREETYPE2
46 static FTC_Font cache_current_font=0;
49 struct fntColorCacheKey
52 fntColorCacheKey(const gRGB &start, const gRGB &end)
53 : start(start), end(end)
56 bool operator <(const fntColorCacheKey &c) const
60 else if (start == c.start)
66 std::map<fntColorCacheKey,gLookup> colorcache;
68 static gLookup &getColor(const gPalette &pal, const gRGB &start, const gRGB &end)
70 fntColorCacheKey key(start, end);
71 std::map<fntColorCacheKey,gLookup>::iterator i=colorcache.find(key);
72 if (i != colorcache.end())
74 gLookup &n=colorcache.insert(std::pair<fntColorCacheKey,gLookup>(key,gLookup())).first->second;
75 // eDebug("[FONT] creating new font color cache entry %02x%02x%02x%02x .. %02x%02x%02x%02x", start.a, start.r, start.g, start.b,
76 // end.a, end.r, end.g, end.b);
77 n.build(16, pal, start, end);
78 // for (int i=0; i<16; i++)
79 // 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);
84 fontRenderClass *fontRenderClass::getInstance()
89 FT_Error myFTC_Face_Requester(FTC_FaceID face_id,
91 FT_Pointer request_data,
94 return ((fontRenderClass*)request_data)->FTC_Face_Requester(face_id, aface);
98 FT_Error fontRenderClass::FTC_Face_Requester(FTC_FaceID face_id, FT_Face* aface)
100 fontListEntry *font=(fontListEntry *)face_id;
104 // eDebug("[FONT] FTC_Face_Requester (%s)", font->face.c_str());
107 if ((error=FT_New_Face(library, font->filename.c_str(), 0, aface)))
109 eDebug(" failed: %s", strerror(error));
112 FT_Select_Charmap(*aface, ft_encoding_unicode);
116 FTC_FaceID fontRenderClass::getFaceID(const std::string &face)
118 for (fontListEntry *f=font; f; f=f->next)
121 return (FTC_FaceID)f;
126 FT_Error fontRenderClass::getGlyphBitmap(FTC_Image_Desc *font, FT_ULong glyph_index, FTC_SBit *sbit)
128 FT_Error res=FTC_SBit_Cache_Lookup(sbitsCache, font, glyph_index, sbit);
132 std::string fontRenderClass::AddFont(const std::string &filename, const std::string &name, int scale)
134 eDebugNoNewLine("[FONT] adding font %s...", filename.c_str());
137 fontListEntry *n=new fontListEntry;
141 singleLock s(ftlock);
143 if ((error=FT_New_Face(library, filename.c_str(), 0, &face)))
144 eFatal(" failed: %s", strerror(error));
146 n->filename=filename;
151 eDebug("OK (%s)", n->face.c_str());
157 fontRenderClass::fontListEntry::~fontListEntry()
161 fontRenderClass::fontRenderClass(): fb(fbClass::getInstance())
164 eDebug("[FONT] initializing lib...");
166 if (FT_Init_FreeType(&library))
168 eDebug("[FONT] initializing failed.");
172 eDebug("[FONT] loading fonts...");
176 int maxbytes=4*1024*1024;
177 eDebug("[FONT] Intializing font cache, using max. %dMB...", maxbytes/1024/1024);
180 if (FTC_Manager_New(library, 8, 8, maxbytes, myFTC_Face_Requester, this, &cacheManager))
182 eDebug("[FONT] initializing font cache failed!");
187 eDebug("[FONT] initializing font cache manager error.");
190 if (FTC_SBit_Cache_New(cacheManager, &sbitsCache))
192 eDebug("[FONT] initializing font cache sbit failed!");
195 if (FTC_Image_Cache_New(cacheManager, &imageCache))
197 eDebug("[FONT] initializing font cache imagecache failed!");
203 float fontRenderClass::getLineHeight(const gFont& font)
208 getFont(fnt, font.family.c_str(), font.pointSize);
211 singleLock s(ftlock);
212 FT_Face current_face;
213 #ifdef HAVE_FREETYPE2
214 if ((FTC_Manager_LookupFace(cacheManager, fnt->scaler.face_id, ¤t_face) < 0) ||
215 (FTC_Manager_LookupSize(cacheManager, &fnt->scaler, &fnt->size) < 0))
217 if (FTC_Manager_Lookup_Size(cacheManager, &fnt->font.font, ¤t_face, &fnt->size)<0)
220 eDebug("FTC_Manager_Lookup_Size failed!");
223 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
224 float height=(current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)/64.0;
228 fontRenderClass::~fontRenderClass()
230 singleLock s(ftlock);
233 fontListEntry *f=font;
237 // auskommentiert weil freetype und enigma die kritische masse des suckens ueberschreiten.
238 // FTC_Manager_Done(cacheManager);
239 // FT_Done_FreeType(library);
242 int fontRenderClass::getFont(ePtr<Font> &font, const std::string &face, int size, int tabwidth)
244 FTC_FaceID id=getFaceID(face);
250 font = new Font(this, id, size * ((fontListEntry*)id)->scale / 100, tabwidth);
254 void addFont(const char *filename, const char *alias, int scale_factor, int is_replacement)
256 fontRenderClass::getInstance()->AddFont(filename, alias, scale_factor);
258 eTextPara::setReplacementFont(alias);
263 Font::Font(fontRenderClass *render, FTC_FaceID faceid, int isize, int tw): tabwidth(tw)
266 #ifdef HAVE_FREETYPE2
267 font.face_id = faceid;
270 font.flags = FT_LOAD_DEFAULT;
271 scaler.face_id = faceid;
272 scaler.width = isize;
273 scaler.height = isize;
276 font.font.face_id=faceid;
277 font.font.pix_width = isize;
278 font.font.pix_height = isize;
279 font.image_type = ftc_image_grays;
284 // font.image_type |= ftc_image_flag_autohinted;
287 FT_Error Font::getGlyphBitmap(FT_ULong glyph_index, FTC_SBit *sbit)
289 return renderer->getGlyphBitmap(&font, glyph_index, sbit);
296 DEFINE_REF(eTextPara);
298 int eTextPara::appendGlyph(Font *current_font, FT_Face current_face, FT_UInt glyphIndex, int flags, int rflags)
301 if (current_font->getGlyphBitmap(glyphIndex, &glyph))
314 glyphString::reverse_iterator i(glyphs.rbegin());
315 /* find first possibility (from end to begin) to break */
316 while (i != glyphs.rend())
318 if (i->flags&(GS_CANBREAK|GS_ISFIRST)) /* stop on either space/hyphen/shy or start of line (giving up) */
325 if (i != glyphs.rend() /* ... we found anything */
326 && (i->flags&GS_CANBREAK) /* ...and this is a space/hyphen/soft-hyphen */
327 && (!(i->flags & GS_ISFIRST)) /* ...and this is not an start of line (line with just a single space/hyphen) */
328 && cnt ) /* ... and there are actual non-space characters after this */
330 /* if we have a soft-hyphen, and used that for breaking, turn it into a real hyphen */
331 if (i->flags & GS_SOFTHYPHEN)
333 i->flags &= ~GS_SOFTHYPHEN;
334 i->flags |= GS_HYPHEN;
336 --i; /* skip the space/hypen/softhyphen */
337 int linelength=cursor.x()-i->x;
338 i->flags|=GS_ISFIRST; /* make this a line start */
339 ePoint offset=ePoint(i->x, i->y);
343 /* and move everything to the end into the next line. */
348 i->bbox.moveBy(-offset.x(), -offset.y());
349 } while (i-- != glyphs.rbegin()); // rearrange them into the next line
350 cursor+=ePoint(linelength, 0); // put the cursor after that line
361 int xadvance=glyph->xadvance, kern=0;
363 if (previous && use_kerning)
366 FT_Get_Kerning(current_face, previous, glyphIndex, ft_kerning_default, &delta);
371 ng.bbox.setLeft( ((flags&GS_ISFIRST)|(cursor.x()-1))+glyph->left );
372 ng.bbox.setTop( cursor.y() - glyph->top );
373 ng.bbox.setWidth( glyph->width );
374 ng.bbox.setHeight( glyph->height );
377 ng.bbox.setWidth(xadvance);
379 ng.x = cursor.x()+kern;
382 ng.font = current_font;
383 ng.glyph_index = glyphIndex;
385 glyphs.push_back(ng);
387 /* when we have a SHY, don't xadvance. It will either be the last in the line (when used for breaking), or not displayed. */
388 if (!(flags & GS_SOFTHYPHEN))
389 cursor += ePoint(xadvance, 0);
390 previous = glyphIndex;
394 void eTextPara::calc_bbox()
405 glyphString::iterator i(glyphs.begin());
410 for (; i != glyphs.end(); ++i)
412 if (i->flags & (GS_ISSPACE|GS_SOFTHYPHEN))
414 if ( i->bbox.left() < boundBox.left() )
415 boundBox.setLeft( i->bbox.left() );
416 if ( i->bbox.top() < boundBox.top() )
417 boundBox.setTop( i->bbox.top() );
418 if ( i->bbox.right() > boundBox.right() )
419 boundBox.setRight( i->bbox.right() );
420 if ( i->bbox.bottom() > boundBox.bottom() )
421 boundBox.setBottom( i->bbox.bottom() );
423 // eDebug("boundBox left = %i, top = %i, right = %i, bottom = %i", boundBox.left(), boundBox.top(), boundBox.right(), boundBox.bottom() );
426 void eTextPara::newLine(int flags)
428 if (maximum.width()<cursor.x())
429 maximum.setWidth(cursor.x());
432 int linegap=current_face->size->metrics.height-(current_face->size->metrics.ascender+current_face->size->metrics.descender);
433 cursor+=ePoint(0, (current_face->size->metrics.ascender+current_face->size->metrics.descender+linegap)>>6);
434 if (maximum.height()<cursor.y())
435 maximum.setHeight(cursor.y());
439 eTextPara::~eTextPara()
444 void eTextPara::setFont(const gFont *font)
446 ePtr<Font> fnt, replacement;
447 fontRenderClass::getInstance()->getFont(fnt, font->family.c_str(), font->pointSize);
449 eWarning("FONT '%s' MISSING!", font->family.c_str());
450 fontRenderClass::getInstance()->getFont(replacement, replacement_facename.c_str(), font->pointSize);
451 setFont(fnt, replacement);
454 std::string eTextPara::replacement_facename;
455 std::set<int> eTextPara::forced_replaces;
457 void eTextPara::setFont(Font *fnt, Font *replacement)
462 replacement_font=replacement;
463 singleLock s(ftlock);
465 // we ask for replacment_font first becauseof the cache
466 if (replacement_font)
468 #ifdef HAVE_FREETYPE2
469 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
470 replacement_font->scaler.face_id,
471 &replacement_face) < 0) ||
472 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
473 &replacement_font->scaler,
474 &replacement_font->size) < 0))
476 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager,
477 &replacement_font->font.font, &replacement_face,
478 &replacement_font->size)<0)
481 eDebug("FTC_Manager_Lookup_Size failed!");
487 #ifdef HAVE_FREETYPE2
488 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
489 current_font->scaler.face_id,
490 ¤t_face) < 0) ||
491 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
492 ¤t_font->scaler,
493 ¤t_font->size) < 0))
495 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
498 eDebug("FTC_Manager_Lookup_Size failed!");
502 #ifndef HAVE_FREETYPE2
503 cache_current_font=¤t_font->font.font;
506 use_kerning=FT_HAS_KERNING(current_face);
510 shape (std::vector<unsigned long> &string, const std::vector<unsigned long> &text);
512 int eTextPara::renderString(const char *string, int rflags)
514 singleLock s(ftlock);
519 #ifdef HAVE_FREETYPE2
520 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
521 current_font->scaler.face_id,
522 ¤t_face) < 0) ||
523 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
524 ¤t_font->scaler,
525 ¤t_font->size) < 0))
527 eDebug("FTC_Manager_Lookup_Size failed!");
531 if (¤t_font->font.font != cache_current_font)
533 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
535 eDebug("FTC_Manager_Lookup_Size failed!");
538 cache_current_font=¤t_font->font.font;
543 eFatal("eTextPara::renderString: no current_face");
544 if (!current_face->size)
545 eFatal("eTextPara::renderString: no current_face->size");
549 cursor=ePoint(area.x(), area.y()+(current_face->size->metrics.ascender>>6));
553 std::vector<unsigned long> uc_string, uc_visual;
555 uc_string.reserve(strlen(string));
557 const char *p = string ? string : "";
561 unsigned int unicode=(unsigned char)*p++;
563 if (unicode & 0x80) // we have (hopefully) UTF8 here, and we assume that the encoding is VALID
565 if ((unicode & 0xE0)==0xC0) // two bytes
570 unicode|=(*p++)&0x3F;
571 } else if ((unicode & 0xF0)==0xE0) // three bytes
576 unicode|=(*p++)&0x3F;
579 unicode|=(*p++)&0x3F;
580 } else if ((unicode & 0xF8)==0xF0) // four bytes
585 unicode|=(*p++)&0x3F;
588 unicode|=(*p++)&0x3F;
591 unicode|=(*p++)&0x3F;
594 uc_string.push_back(unicode);
597 std::vector<unsigned long> uc_shape;
599 // character -> glyph conversion
600 shape(uc_shape, uc_string);
602 // now do the usual logical->visual reordering
604 FriBidiCharType dir=FRIBIDI_TYPE_ON;
606 int size=uc_shape.size();
607 uc_visual.resize(size);
608 // gaaanz lahm, aber anders geht das leider nicht, sorry.
609 FriBidiChar array[size], target[size];
610 std::copy(uc_shape.begin(), uc_shape.end(), array);
611 fribidi_log2vis(array, size, &dir, target, 0, 0, 0);
612 uc_visual.assign(target, target+size);
618 glyphs.reserve(uc_visual.size());
622 for (std::vector<unsigned long>::const_iterator i(uc_visual.begin());
623 i != uc_visual.end(); ++i)
626 int flags = nextflags;
628 unsigned long chr = *i;
630 if (!(rflags&RS_DIRECT))
636 unsigned long c = *(i+1);
655 cursor+=ePoint(current_font->tabwidth, 0);
656 cursor-=ePoint(cursor.x()%current_font->tabwidth, 0);
661 newline:isprintable=0;
663 nextflags|=GS_ISFIRST;
666 case 0x86: case 0xE086:
667 case 0x87: case 0xE087:
668 nprint: isprintable=0;
670 case 0xAD: // soft-hyphen
671 flags |= GS_SOFTHYPHEN;
672 chr = 0x2010; /* hyphen */
688 /* FIXME: our font doesn't seem to have a hyphen, so use hyphen-minus for it. */
692 if (forced_replaces.find(chr) == forced_replaces.end())
693 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(current_face, chr);
697 if (replacement_face)
698 index=(rflags&RS_DIRECT)? chr : FT_Get_Char_Index(replacement_face, chr);
701 eDebug("unicode U+%4lx not present", chr);
703 appendGlyph(replacement_font, replacement_face, index, flags, rflags);
705 appendGlyph(current_font, current_face, index, flags, rflags);
711 if (dir & FRIBIDI_MASK_RTL)
717 void eTextPara::blit(gDC &dc, const ePoint &offset, const gRGB &background, const gRGB &foreground)
719 singleLock s(ftlock);
724 #ifdef HAVE_FREETYPE2
725 if ((FTC_Manager_LookupFace(fontRenderClass::instance->cacheManager,
726 current_font->scaler.face_id,
727 ¤t_face) < 0) ||
728 (FTC_Manager_LookupSize(fontRenderClass::instance->cacheManager,
729 ¤t_font->scaler,
730 ¤t_font->size) < 0))
732 eDebug("FTC_Manager_Lookup_Size failed!");
736 if (¤t_font->font.font != cache_current_font)
738 if (FTC_Manager_Lookup_Size(fontRenderClass::instance->cacheManager, ¤t_font->font.font, ¤t_face, ¤t_font->size)<0)
740 eDebug("FTC_Manager_Lookup_Size failed!");
743 cache_current_font=¤t_font->font.font;
747 ePtr<gPixmap> target;
748 dc.getPixmap(target);
749 gSurface *surface = target->surface;
753 gColor *lookup8, lookup8_invert[16];
754 gColor *lookup8_normal=0;
756 __u16 lookup16_normal[16], lookup16_invert[16], *lookup16;
757 __u32 lookup32_normal[16], lookup32_invert[16], *lookup32;
759 if (surface->bpp == 8)
761 if (surface->clut.data)
763 lookup8_normal=getColor(surface->clut, background, foreground).lookup;
767 lookup8_invert[i] = lookup8_normal[i^0xF];
772 } else if (surface->bpp == 16)
775 for (int i=0; i<16; ++i)
777 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
778 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
782 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
783 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
784 db = BLEND(background.b, foreground.b, sa) & 0xFF;
787 #if BYTE_ORDER == LITTLE_ENDIAN
788 lookup16_normal[i] = bswap_16(((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3));
790 lookup16_normal[i] = ((db >> 3) << 11) | ((dg >> 2) << 5) | (dr >> 3);
794 for (int i=0; i<16; ++i)
795 lookup16_invert[i]=lookup16_normal[i^0xF];
796 } else if (surface->bpp == 32)
799 for (int i=0; i<16; ++i)
801 #define BLEND(y, x, a) (y + (((x-y) * a)>>8))
803 unsigned char da = background.a, dr = background.r, dg = background.g, db = background.b;
807 da = BLEND(background.a, foreground.a, sa) & 0xFF;
808 dr = BLEND(background.r, foreground.r, sa) & 0xFF;
809 dg = BLEND(background.g, foreground.g, sa) & 0xFF;
810 db = BLEND(background.b, foreground.b, sa) & 0xFF;
814 lookup32_normal[i]=db | (dg << 8) | (dr << 16) | (da << 24);;
816 for (int i=0; i<16; ++i)
817 lookup32_invert[i]=lookup32_normal[i^0xF];
820 eWarning("can't render to %dbpp", surface->bpp);
824 gRegion area(eRect(0, 0, surface->x, surface->y));
825 gRegion clip = dc.getClip() & area;
827 int buffer_stride=surface->stride;
829 for (unsigned int c = 0; c < clip.rects.size(); ++c)
831 for (glyphString::iterator i(glyphs.begin()); i != glyphs.end(); ++i)
833 if (i->flags & GS_SOFTHYPHEN)
836 if (!(i->flags & GS_INVERT))
838 lookup8 = lookup8_normal;
839 lookup16 = lookup16_normal;
840 lookup32 = lookup32_normal;
843 lookup8 = lookup8_invert;
844 lookup16 = lookup16_invert;
845 lookup32 = lookup32_invert;
848 static FTC_SBit glyph_bitmap;
849 if (fontRenderClass::instance->getGlyphBitmap(&i->font->font, i->glyph_index, &glyph_bitmap))
851 int rx=i->x+glyph_bitmap->left + offset.x();
852 int ry=i->y-glyph_bitmap->top + offset.y();
854 __u8 *d=(__u8*)(surface->data)+buffer_stride*ry+rx*surface->bypp;
855 __u8 *s=glyph_bitmap->buffer;
856 register int sx=glyph_bitmap->width;
857 int sy=glyph_bitmap->height;
858 if ((sy+ry) >= clip.rects[c].bottom())
859 sy=clip.rects[c].bottom()-ry;
860 if ((sx+rx) >= clip.rects[c].right())
861 sx=clip.rects[c].right()-rx;
862 if (rx < clip.rects[c].left())
864 int diff=clip.rects[c].left()-rx;
868 d+=diff*surface->bypp;
870 if (ry < clip.rects[c].top())
872 int diff=clip.rects[c].top()-ry;
873 s+=diff*glyph_bitmap->pitch;
876 d+=diff*buffer_stride;
881 case 0: // 4bit lookup to 8bit
882 for (int ay=0; ay<sy; ay++)
886 for (ax=0; ax<sx; ax++)
888 register int b=(*s++)>>4;
894 s+=glyph_bitmap->pitch-sx;
898 case 1: // 8bit direct
899 for (int ay=0; ay<sy; ay++)
903 for (ax=0; ax<sx; ax++)
908 s+=glyph_bitmap->pitch-sx;
913 for (int ay=0; ay<sy; ay++)
915 register __u16 *td=(__u16*)d;
917 for (ax=0; ax<sx; ax++)
919 register int b=(*s++)>>4;
925 s+=glyph_bitmap->pitch-sx;
930 for (int ay=0; ay<sy; ay++)
932 register __u32 *td=(__u32*)d;
934 for (ax=0; ax<sx; ax++)
936 register int b=(*s++)>>4;
942 s+=glyph_bitmap->pitch-sx;
953 void eTextPara::realign(int dir) // der code hier ist ein wenig merkwuerdig.
955 glyphString::iterator begin(glyphs.begin()), c(glyphs.begin()), end(glyphs.begin()), last;
958 while (c != glyphs.end())
961 int numspaces=0, num=0;
964 ASSERT( end != glyphs.end());
970 } while ((end != glyphs.end()) && (!(end->flags&GS_ISFIRST)));
971 // end zeigt jetzt auf begin der naechsten zeile
973 for (c=begin; c!=end; ++c)
975 // space am zeilenende skippen
976 if ((c==last) && (c->flags&GS_ISSPACE))
979 if (c->flags&GS_ISSPACE)
990 int offset=area.width()-linelength;
996 begin->bbox.moveBy(offset-begin->x,0);
1005 if (end == glyphs.end()) // letzte zeile linksbuendig lassen
1012 if ((!spacemode) && (num<2))
1014 int off=(area.width()-linelength)*256/(spacemode?numspaces:(num-1));
1016 while (begin != end)
1019 if ((!spacemode) || (begin->flags&GS_ISSPACE))
1021 begin->x+=curoff>>8;
1022 begin->bbox.moveBy(curoff>>8,0);
1035 void eTextPara::clear()
1037 singleLock s(ftlock);
1040 replacement_font = 0;
1045 eAutoInitP0<fontRenderClass> init_fontRenderClass(eAutoInitNumbers::graphic-1, "Font Render Class");