internal Glyph(GlyphRec rec, Library parentLibrary) { this.rec = rec; this.parentLibrary = parentLibrary; parentLibrary.AddChildGlyph(this); }
internal Glyph(IntPtr reference, Library parentLibrary) { Reference = reference; this.parentLibrary = parentLibrary; parentLibrary.AddChildGlyph(this); }
public static FontTexture CreateFont(Library ftLibrary, string filename, ushort fontSize) { if(ftLibrary != null) { var glf = new FontTexture(); Face face = null; try { face = new Face(ftLibrary, filename, 0); } catch { return null; } glf.FTFace = face; Array.Resize(ref glf.Glyphs, glf.FTFace.GlyphCount); glf.GLMaxTexWidth = GL.GetInteger(GetPName.MaxTextureSize); glf.GLTexWidth = glf.GLMaxTexWidth; glf.GLTexIndexes = new uint[0]; glf.GLRealTexIndexesCount = 0; glf.GLFontColor = new [] {0.0f, 0.0f, 0.0f, 1.0f}; Resize(glf, fontSize); glf.FTFace.SelectCharmap(Encoding.Unicode); return glf; } return null; }
private void ExampleForm_Load(object sender, EventArgs e) { lib = new Library(); RebuildFontList(); if (listBoxFont.Items.Count > 0) listBoxFont.SelectedIndex = 0; }
/// <summary> /// Initializes a new instance of the <see cref="FTBitmap"/> class. /// </summary> /// <param name="library">The parent <see cref="Library"/>.</param> public FTBitmap(Library library) { IntPtr bitmapRef; FT.FT_Bitmap_New(out bitmapRef); Reference = bitmapRef; this.library = library; this.user = true; }
/// <summary> /// Initializes a new instance of the <see cref="Font"/> class. /// </summary> public Font() { _library = null; _face = null; _stroker = null; _familyName = string.Empty; _pages = new Dictionary <int, Page>(); _fontData = null; }
/// <summary> /// Initializes a new instance of the <see cref="FTBitmap"/> class. /// </summary> /// <param name="library">The parent <see cref="Library"/>.</param> public FTBitmap(Library library) { IntPtr bitmapRef = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(BitmapRec))); FT.FT_Bitmap_New(bitmapRef); Reference = bitmapRef; this.library = library; this.user = true; }
/// <summary> /// Creates a new VectorFont with the File specified at path and the specified size in pixels. /// It is assumed that the font is either Monospaced or only single chars are used. /// </summary> /// <param name="path">path to the font-file</param> /// <param name="size">size in pixles</param> public VectorFont(string path, uint size) { lib = new Library(); face = new Face(lib, path); face.SetPixelSizes(0, size); this.size = face.Size; }
/// <summary> /// Initializes a new instance of the <see cref="Face"/> class. /// </summary> /// <param name="library">The parent library.</param> /// <param name="path">The path of the font file.</param> /// <param name="faceIndex">The index of the face to take from the file.</param> public Face(Library library, string path, int faceIndex) : this(library) { IntPtr reference; Error err = FT.FT_New_Face(library.Reference, path, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; }
public Outline(Library library, uint pointsCount, int contoursCount) { IntPtr reference; Error err = FT.FT_Outline_New(library.Reference, pointsCount, contoursCount, out reference); if (err != Error.Ok) throw new FreeTypeException(err); parentLibrary = library; parentLibrary.AddChildOutline(this); }
/// <summary> /// Initializes a new instance of the <see cref="Stroker"/> class. /// </summary> /// <param name="library">FreeType library handle.</param> public Stroker(Library library) { IntPtr strokerRef; Error err = FT.FT_Stroker_New(library.Reference, out strokerRef); if (err != Error.Ok) throw new FreeTypeException(err); Reference = strokerRef; library.AddChildStroker(this); parentLibrary = library; }
static void Main(string[] args) { Console.WriteLine("Version string: " + HB.VersionString); Version v = HB.Version; Console.WriteLine("Version: " + v.Major + "." + v.Minor + "." + v.Build); Console.WriteLine("VersionCheck: " + HB.VersionAtLeast(v)); var lib = new Library(); var face = new SharpFont.Face(lib, @"C:\Windows\Fonts\tahoma.ttf"); face.SetCharSize(0, 50, 72, 72); var font = HarfBuzz.Font.FromFTFace(face); var buf = new HarfBuzz.Buffer(); buf.Direction = Direction.RightToLeft; buf.Script = Script.Arabic; buf.AddText("متن"); font.Shape(buf); var glyphInfos = buf.GlyphInfo(); var glyphPositions = buf.GlyphPositions(); int height = (face.MaxAdvanceHeight - face.Descender) >> 6; int width = 0; for (int i = 0; i < glyphInfos.Length; ++i) { width += glyphPositions[i].xAdvance >> 6; } Bitmap bmp = new Bitmap(width, height); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.Gray); int penX = 0, penY = face.MaxAdvanceHeight >> 6; //draw the string for (int i = 0; i < glyphInfos.Length; ++i) { face.LoadGlyph(glyphInfos[i].codepoint, LoadFlags.Default, LoadTarget.Normal); face.Glyph.RenderGlyph(RenderMode.Normal); Bitmap cBmp = face.Glyph.Bitmap.ToGdipBitmap(Color.Firebrick); g.DrawImageUnscaled(cBmp, penX + (glyphPositions[i].xOffset >> 6) + face.Glyph.BitmapLeft, penY - (glyphPositions[i].yOffset >> 6) - face.Glyph.BitmapTop); penX += glyphPositions[i].xAdvance >> 6; penY -= glyphPositions[i].yAdvance >> 6; } g.Dispose(); bmp.Save("output.bmp"); }
/// <summary> /// Initializes a new instance of the <see cref="RenderContextImp"/> class. /// </summary> /// <param name="renderCanvas">The render canvas interface.</param> public RenderContextImp(IRenderCanvasImp renderCanvas) { _currentTextureUnit = 0; _shaderParam2TexUnit = new Dictionary<int, int>(); // Due to the right-handed nature of OpenGL and the left-handed design of FUSEE // the meaning of what's Front and Back of a face simply flips. // TODO - implement this in render states!!! GL.CullFace(CullFaceMode.Back); _sharpFont = new Library(); }
private RasterInterf() { PlatformID pid = Environment.OSVersion.Platform; if ( pid != PlatformID.Unix && pid != PlatformID.MacOSX ) { string path = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); path = Path.Combine(path, IntPtr.Size == 8 ? "Win64" : "Win32"); if (!SetDllDirectory(path)) throw new System.ComponentModel.Win32Exception(); } _lib = new Library(); //Console.WriteLine("FreeType version: " + _lib.Version); }
public TextGenerator(string path, string fontName, uint fontSize = 12) { if (_textPs == null) { LoadProgramShader(); } FontName = fontName; FontSize = fontSize; SharpFont.Library fontLib = new SharpFont.Library(); SharpFont.Face fontFace = new SharpFont.Face(fontLib, path); fontFace.SetPixelSizes(0, FontSize); GL.PixelStore(PixelStoreParameter.UnpackAlignment, 1); for (char c = (char)0x20; c <= (char)0x7E; c++) { fontFace.LoadChar(c, LoadFlags.Render, LoadTarget.Normal); Texture texture = Texture.CreateTexture( fontFace.Glyph.Bitmap.Width, fontFace.Glyph.Bitmap.Rows, PixelInternalFormat.R8, PixelFormat.Red, fontFace.Glyph.Bitmap.Buffer); Character character = new Character( texture.ID, new Vector2(fontFace.Glyph.Bitmap.Width, fontFace.Glyph.Bitmap.Rows), new Vector2(fontFace.Glyph.BitmapLeft, fontFace.Glyph.BitmapTop), (int)fontFace.Glyph.Advance.X); _characters.Add(c, character); } fontFace.Dispose(); fontLib.Dispose(); vao = VAO.Create(); vao.LinkPS(_textPs); vbo = VBO.Create <float>(vertices.Length, 4, "vertex"); indices = new IndicesCollection(); indices.Add(4, vertices.Length); vao.AddVBuff(vbo); vao.AddIndicesCollection(indices); }
/// <summary> /// If multithreading, each thread should have its own FontService. /// </summary> internal FontService() { lib = new Library(); _size = 8.25f; SupportedFormats = new FontFormatCollection(); AddFormat("TrueType", "ttf"); AddFormat("OpenType", "otf"); // Not so sure about these... //AddFormat("TrueType Collection", "ttc"); //AddFormat("Type 1", "pfa"); // pfb? //AddFormat("PostScript", "pfm"); // ext? //AddFormat("FNT", "fnt"); //AddFormat("X11 PCF", "pcf"); //AddFormat("BDF", "bdf"); //AddFormat("Type 42", ""); }
public void Import(FontDescription options, string fontName) { lib = new Library (); // Create a bunch of GDI+ objects. Face face = CreateFontFace (options, fontName); try { using (Brush brush = new SolidBrush(System.Drawing.Color.White)) using (StringFormat stringFormat = new StringFormat(StringFormatFlags.NoFontFallback)) using (Bitmap bitmap = new Bitmap(MaxGlyphSize, MaxGlyphSize, PixelFormat.Format32bppArgb)) using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap)) { graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.TextRenderingHint = TextRenderingHint.AntiAliasGridFit; // Which characters do we want to include? var characters = CharacterRegion.Flatten(options.CharacterRegions); var glyphList = new List<Glyph>(); // Rasterize each character in turn. foreach (char character in characters) { Glyph glyph = ImportGlyph(character, face, brush, stringFormat, bitmap, graphics); glyphList.Add(glyph); } Glyphs = glyphList; // Store the font height. LineSpacing = 0; foreach (var glyph in Glyphs) { LineSpacing = (glyph.Subrect.Height > LineSpacing) ? glyph.Subrect.Height : LineSpacing; } } } finally { if (face != null) face.Dispose (); if (lib != null) { lib.Dispose (); lib = null; } } }
private void Initialize() { // Initialize FreeType // Note: we initialize FreeType for every font instance in order to avoid having a single // global manager that would create a lot of issues regarding creation and destruction order. _library = new SharpFont.Library(); // Load the new font face from the specified data _face = new SharpFont.Face(_library, _fontData, 0); // Load the stroker that will be used to outline the font _stroker = new SharpFont.Stroker(_library); // Select the unicode character map _face.SelectCharmap(SharpFont.Encoding.Unicode); // Store the font family name _familyName = _face.FamilyName; }
public static void Main(string[] args) { //TODO make several examples in an example browser try { using (Library lib = new Library()) { Console.WriteLine("FreeType version: " + lib.Version + "\n"); using (Face face = lib.NewFace(@"Fonts/Cousine-Regular-Latin.ttf", 0)) { //attach a finalizer delegate face.Generic = new Generic(IntPtr.Zero, OnFaceDestroyed); //write out some basic font information Console.WriteLine("Information for font " + face.FamilyName); Console.WriteLine("===================================="); Console.WriteLine("Number of faces: " + face.FaceCount); Console.WriteLine("Face flags: " + face.FaceFlags); Console.WriteLine("Style: " + face.StyleName); Console.WriteLine("Style flags: " + face.StyleFlags); face.SetCharSize(0, 32 * 64, 0, 96); Console.WriteLine("\nWriting string \"Hello World!\":"); Bitmap bmp = RenderString(face, "Hello World!"); bmp.Save("helloworld.png", ImageFormat.Png); bmp.Dispose(); Console.WriteLine("Done!\n"); } } } catch (FreeTypeException e) { Console.Write(e.Error.ToString()); } Console.ReadKey(); }
public void Import(FontDescription options, string fontName) { lib = new Library(); // Create a bunch of GDI+ objects. var face = CreateFontFace(options, fontName); try { // Which characters do we want to include? var characters = options.Characters; var glyphList = new List<Glyph>(); // Rasterize each character in turn. foreach (char character in characters) { var glyph = ImportGlyph(character, face); glyphList.Add(glyph); } Glyphs = glyphList; // Store the font height. LineSpacing = face.Size.Metrics.Height >> 6; // The height used to calculate the Y offset for each character. YOffsetMin = -face.Size.Metrics.Ascender >> 6; } finally { if (face != null) face.Dispose(); if (lib != null) { lib.Dispose(); lib = null; } } }
/// <summary> /// Initializes a new instance of the <see cref="Face"/> class from a file that's already loaded into memory. /// </summary> /// <param name="library">The parent library.</param> /// <param name="bufferPtr"></param> /// <param name="length"></param> /// <param name="faceIndex">The index of the face to take from the file.</param> public Face(Library library, IntPtr bufferPtr, int length, int faceIndex) : this() { Error err = FT.FT_New_Memory_Face(library.Reference, bufferPtr, length, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; parentLibrary = library; parentLibrary.AddChildFace(this); }
/// <summary> /// Initializes a new instance of the Face class. /// </summary> /// <param name="reference">A pointer to the unmanaged memory containing the Face.</param> /// <param name="parent">The parent <see cref="Library"/>.</param> internal Face(IntPtr reference, Library parent) : this() { Reference = reference; if (parent != null) { parentLibrary = parent; parentLibrary.AddChildFace(this); } else { //if there's no parent, this is a marshalled duplicate. FT.FT_Reference_Face(Reference); } }
/// <summary> /// Note: There is some performance overhead to initializing this. /// </summary> private void InitializeFontData() { FontNameToFiles = new Dictionary <string, FontGroup>(); if (NoteFontsWeCantInstall) { FontsWeCantInstall = new HashSet <string>(); } #if __MonoCS__ using (var lib = new SharpFont.Library()) { // Find all the font files in the standard system location (/usr/share/font) and $HOME/.font (if it exists) foreach (var fontFile in FindLinuxFonts()) { try { using (var face = new SharpFont.Face(lib, fontFile)) { var embeddingTypes = face.GetFSTypeFlags(); if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense || (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly) { if (NoteFontsWeCantInstall) { FontsWeCantInstall.Add(face.FamilyName); } continue; } var name = face.FamilyName; // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(face, fontFile); } } catch (Exception) { } } } #else foreach (var fontFile in FindWindowsFonts()) { GlyphTypeface gtf; try { gtf = new GlyphTypeface(new Uri("file:///" + fontFile)); } catch (Exception) { continue; // file is somehow corrupt or not really a font file? Just ignore it. } switch (gtf.EmbeddingRights) { case FontEmbeddingRight.Editable: case FontEmbeddingRight.EditableButNoSubsetting: case FontEmbeddingRight.Installable: case FontEmbeddingRight.InstallableButNoSubsetting: case FontEmbeddingRight.PreviewAndPrint: case FontEmbeddingRight.PreviewAndPrintButNoSubsetting: break; default: if (NoteFontsWeCantInstall) { string name1 = GetFontNameFromFile(fontFile); if (name1 != null) { FontsWeCantInstall.Add(name1); } } continue; // not allowed to embed } string name = GetFontNameFromFile(fontFile); if (name == null) { continue; // not sure how this can happen but I've seen it. } // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(gtf, fontFile); } #endif }
internal FTBitmap(IntPtr reference, Library library) { Reference = reference; this.library = library; user = true; }
/// <summary> /// Initializes a new instance of the <see cref="Face"/> class from a file that's already loaded into memory. /// </summary> /// <param name="library">The parent library.</param> /// <param name="bufferPtr">A pointer to a buffer of a loaded file. Must not be freed before <see cref="Dispose()"/>.</param> /// <param name="length">The length of bufferPtr.</param> /// <param name="faceIndex">The index of the face to take from the file.</param> public Face(Library library, IntPtr bufferPtr, int length, int faceIndex) : this(library) { IntPtr reference; Error err = FT.FT_New_Memory_Face(library.Reference, bufferPtr, length, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; }
internal FTBitmap(BitmapRec bmpInt, Library library) { this.rec = bmpInt; this.library = library; }
public FontManager() { fontLibrary = new Library(); fadeValue = 0.0f; fadeDirection = true; }
/// <summary> /// Note: There is some performance overhead to initializing this. /// </summary> private void InitializeFontData() { FontNameToFiles = new Dictionary <string, FontGroup>(); FontsWeCantInstall = new HashSet <string>(); #if __MonoCS__ using (var lib = new SharpFont.Library()) { // Find all the font files in the standard system location (/usr/share/font) and $HOME/.local/share/fonts (if it exists) foreach (var fontFile in FindLinuxFonts()) { try { using (var face = new SharpFont.Face(lib, fontFile)) { var embeddingTypes = face.GetFSTypeFlags(); if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense || (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly) { // Our font UI allows any font on the computer, but gives the user indications that some are more // useable in publishing Bloom books. The NoteFontsWeCantInstall prop is only true when we call this // from BloomPubMaker so that it can note that certain fonts are unsuitable for embedding in ePUBs. if (NoteFontsWeCantInstall) { FontsWeCantInstall.Add(face.FamilyName); continue; } } var name = face.FamilyName; // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(face, fontFile); } } catch (Exception) { continue; } } } #else foreach (var fontFile in FindWindowsFonts()) { GlyphTypeface gtf; try { gtf = new GlyphTypeface(new Uri("file:///" + fontFile)); } catch (Exception) { continue; // file is somehow corrupt or not really a font file? Just ignore it. } // Our font UI allows any font on the computer, but gives the user indications that some are more // useable in publishing Bloom books. The NoteFontsWeCantInstall prop is only true when we call this // from BloomPubMaker so that it can note that certain fonts are unsuitable for embedding in ePUBs. if (!FontIsEmbeddable(gtf.EmbeddingRights) && NoteFontsWeCantInstall) { string name1 = GetFontNameFromFile(fontFile); if (name1 != null) { FontsWeCantInstall.Add(name1); } continue; // not allowed to embed in ePUB } string name = GetFontNameFromFile(fontFile); if (name == null) { continue; // not sure how this can happen but I've seen it. } // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(gtf, fontFile); } #endif }
public void Dispose() { // terminate the build thread bitmapShouldEndThread = true; bitmapBuildSignal.Set(); #if !SILICONSTUDIO_PLATFORM_WINDOWS_RUNTIME bitmapBuilderThread.Join(); #endif // free and clear the list of generated bitmaps foreach (var character in generatedBitmaps) { if (character.Bitmap != null) { character.Bitmap.Dispose(); character.Bitmap = null; } } generatedBitmaps.Clear(); // free font faces foreach (var font in cachedFontFaces.Values) font.Dispose(); cachedFontFaces.Clear(); // free freetype library if (freetypeLibrary != null) freetypeLibrary.Dispose(); freetypeLibrary = null; }
public const string kInvalid = "invalid"; // bad file format (eg, .ttc) /// <summary> /// On Window, we can use System.Windows.Media (which provides the GlyphTypeface class) to /// provide all the font metadata information. /// On Linux, we have to use Sharpfont from nuget (which provides the Sharpfont.Face class) /// for reading the font's embedding flag plus running /usr/bin/otfino for everything else. /// We get /usr/bin/otfinfo as part of the lcdf-typetools package that is specified in the /// debian/control file. /// </summary> public FontMetadata(string fontName, FontGroup group) { name = fontName; fileExtension = Path.GetExtension(group.Normal); // First we detect invalid font types that we don't know how to handle (like .ttc) var bloomKnows = fontFileTypesBloomKnows.Contains(fileExtension.ToLowerInvariant()); if (!bloomKnows) { determinedSuitability = kInvalid; determinedSuitabilityNotes = "Bloom does not support " + fileExtension + " fonts."; return; } #if __MonoCS__ try { using (var lib = new SharpFont.Library()) { using (var face = new Face(lib, group.Normal)) { var embeddingFlags = face.GetFSTypeFlags(); /* * Quoting from the standard (https://docs.microsoft.com/en-us/typography/opentype/spec/os2#fstype) * Valid fonts must set at most one of bits 1, 2 or 3; bit 0 is permanently reserved and must be zero. * Valid values for this sub-field are 0, 2, 4 or 8. The meaning of these values is as follows: * 0: Installable embedding * 2: Restricted License embedding * 4: Preview & Print embedding * 8: Editable embedding * * The specification for versions 0 to 2 did not specify that bits 0 to 3 must be mutually exclusive. * Rather, those specifications stated that, in the event that more than one of bits 0 to 3 are set in * a given font, then the least-restrictive permission indicated take precedence. * So we pay attention to RestrictedLicense only if neither Editable nor PreviewAndPrint is set. (This * is apparently what Microsoft does in the GlyphTypeFace implementation.) */ if ((embeddingFlags & (EmbeddingTypes.RestrictedLicense | EmbeddingTypes.Editable | EmbeddingTypes.PreviewAndPrint)) == EmbeddingTypes.RestrictedLicense) { fsType = "Restricted License"; } else if ((embeddingFlags & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly) { fsType = "Bitmaps Only"; } else if ((embeddingFlags & EmbeddingTypes.Editable) == EmbeddingTypes.Editable) { fsType = "Editable"; } else if ((embeddingFlags & EmbeddingTypes.PreviewAndPrint) == EmbeddingTypes.PreviewAndPrint) { fsType = "Print and preview"; } else { fsType = "Installable"; // but is it really? } // Every call to face.GetSfntName(i) throws a null object exception. // Otherwise the code would build on this fragment. //var count = face.GetSfntNameCount(); //for (uint i = 0; i < count; ++i) //{ // try // { // var sfntName = face.GetSfntName(i); // ... // } // catch (Exception ex) // { // } //} } } } catch (Exception ex) { Console.WriteLine("SharpLib threw an exception for {0}: {1}", group.Normal, ex); determinedSuitability = kInvalid; determinedSuitabilityNotes = $"SharpLib exception: {ex}"; return; } try { var process = new Process { StartInfo = new ProcessStartInfo() { FileName = "/usr/bin/otfinfo", Arguments = $"-i \"{group.Normal}\"", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, }, }; process.Start(); process.WaitForExit(); var standardOutput = process.StandardOutput.ReadToEnd(); var standardError = process.StandardError.ReadToEnd(); if (process.ExitCode == 0 && standardError.Length == 0) { ParseOtfinfoOutput(standardOutput); } else { Console.WriteLine("otfinfo -i \"{0}\" returned {1}. Standard Error =\n{2}", group.Normal, process.ExitCode, standardError); determinedSuitability = kInvalid; determinedSuitabilityNotes = $"otfinfo returned: {process.ExitCode}. Standard Error={Environment.NewLine}{standardError}"; return; } } catch (Exception e) { Console.WriteLine("Process.Start() of otfinfo -i \"{0}\" threw an exception: {1}", group.Normal, e); determinedSuitability = kInvalid; determinedSuitabilityNotes = $"Process.Start of \"otfinfo\" exception: {e}"; return; } #else GlyphTypeface gtf = null; try { gtf = new GlyphTypeface(new Uri("file:///" + group.Normal)); var english = System.Globalization.CultureInfo.GetCultureInfo("en-US"); version = gtf.VersionStrings[english]; // Most fonts include the text "Version x" here, but our UI provides the // (possibly localized) text, so we strip it out here. if (version.StartsWith("Version ")) { version = version.Replace("Version ", ""); } copyright = gtf.Copyrights[english]; var embeddingRights = gtf.EmbeddingRights; switch (embeddingRights) { case FontEmbeddingRight.Editable: case FontEmbeddingRight.EditableButNoSubsetting: fsType = "Editable"; break; case FontEmbeddingRight.Installable: case FontEmbeddingRight.InstallableButNoSubsetting: fsType = "Installable"; break; case FontEmbeddingRight.PreviewAndPrint: case FontEmbeddingRight.PreviewAndPrintButNoSubsetting: fsType = "Print and preview"; break; case FontEmbeddingRight.RestrictedLicense: fsType = "Restricted License"; break; case FontEmbeddingRight.EditableButNoSubsettingAndWithBitmapsOnly: case FontEmbeddingRight.EditableButWithBitmapsOnly: case FontEmbeddingRight.InstallableButNoSubsettingAndWithBitmapsOnly: case FontEmbeddingRight.InstallableButWithBitmapsOnly: case FontEmbeddingRight.PreviewAndPrintButNoSubsettingAndWithBitmapsOnly: case FontEmbeddingRight.PreviewAndPrintButWithBitmapsOnly: fsType = "Bitmaps Only"; break; } designer = gtf.DesignerNames[english]; designerURL = gtf.DesignerUrls[english]; license = gtf.LicenseDescriptions[english]; manufacturer = gtf.ManufacturerNames[english]; manufacturerURL = gtf.VendorUrls[english]; trademark = gtf.Trademarks[english]; } catch (Exception e) { // file is somehow corrupt or not really a font file? Just ignore it. Console.WriteLine("GlyphTypeface for \"{0}\" threw an exception: {1}", group.Normal, e); determinedSuitability = kInvalid; determinedSuitabilityNotes = $"GlyphTypeface exception: {e}"; return; } #endif variants = group.GetAvailableVariants().ToArray(); // Now for the hard part: setting DeterminedSuitability // Check out the license information. if (!String.IsNullOrEmpty(license)) { if (license.Contains("Open Font License") || license.Contains("OFL") || license.StartsWith("Licensed under the Apache License") || license.Contains("GNU GPL") || license.Contains("GNU General Public License") || license.Contains(" GPL ") || license.Contains(" GNU ") || (license.Contains("GNU license") && license.Contains("www.gnu.org")) || license.Contains("GNU LGPL") || license.Contains("GNU Lesser General Public License")) { determinedSuitability = kOK; if (license.Contains("Open Font License") || license.Contains("OFL")) { determinedSuitabilityNotes = "Open Font License"; } else if (license.StartsWith("Licensed under the Apache License")) { determinedSuitabilityNotes = "Apache License"; } else if (license.Contains("GNU LGPL") || license.Contains("GNU Lesser General Public License")) { determinedSuitabilityNotes = "GNU LGPL"; } else { determinedSuitabilityNotes = "GNU GPL"; } return; } if (license.Replace('\n', ' ').Contains("free of charge") && license.Contains("Bitstream")) { determinedSuitability = kOK; determinedSuitabilityNotes = "Bitstream free license"; return; } } if (licenseURL == "http://dejavu-fonts.org/wiki/License") { determinedSuitability = kOK; determinedSuitabilityNotes = "Bitstream free license"; return; } if (!String.IsNullOrEmpty(copyright)) { // some people put license information in the copyright string. if (copyright.Contains("Artistic License")) { determinedSuitability = kOK; determinedSuitabilityNotes = "Artistic License"; return; } if (copyright.Contains("GNU General Public License") || copyright.Contains(" GPL ")) { determinedSuitability = kOK; determinedSuitabilityNotes = "GNU GPL"; return; } if (copyright.Contains("SIL Open Font License")) { determinedSuitability = kOK; determinedSuitabilityNotes = "Open Font License"; return; } if (copyright.Contains("Ubuntu Font Licence")) // British spelling I assume... { determinedSuitability = kOK; determinedSuitabilityNotes = "Ubuntu Font Licence"; return; } } if (fsType == "Restricted License" || fsType == "Bitmaps Only") { determinedSuitability = kUnsuitable; determinedSuitabilityNotes = "unambiguous fsType value"; return; } if (manufacturer == "Microsoft Corporation" || manufacturer == "Microsoft Corp." || (license != null && license.Contains("Microsoft supplied font") && manufacturer != null && manufacturer.Contains("Monotype")) || (license == null && manufacturer == null && copyright != null && copyright.Contains("Microsoft Corporation") && trademark != null && trademark.Contains("is a trademark of Microsoft Corporation")) ) { // Review what about "Print and Preview"? determinedSuitability = kOK; determinedSuitabilityNotes = "fsType from reliable source"; return; } // Give up. More heuristics may suggest themselves. determinedSuitability = kUnknown; determinedSuitabilityNotes = "no reliable information"; }
public static void Init() { Lib = new Library(); }
/// <summary> /// Create an empty register. /// </summary> public FontManager() { assetManager = new AssetManager(); // Preload proper freetype native library (depending on CPU type) Core.NativeLibrary.PreloadLibrary("freetype.dll"); // create a freetype library used to generate the bitmaps freetypeLibrary = new Library(); #if SILICONSTUDIO_PLATFORM_WINDOWS_RUNTIME Windows.System.Threading.ThreadPool.RunAsync(operation => SafeAction.Wrap(BuildBitmapThread)()); #else // launch the thumbnail builder thread bitmapBuilderThread = new Thread(SafeAction.Wrap(BuildBitmapThread)) { IsBackground = true, Name = "Bitmap Builder thread" }; bitmapBuilderThread.Start(); #endif }
internal GlyphSlot(IntPtr reference, Face parentFace, Library parentLibrary) { Reference = reference; this.parentFace = parentFace; this.parentLibrary = parentLibrary; }
/// <summary> /// Initializes a new instance of the <see cref="Face"/> class with a default faceIndex of 0. /// </summary> /// <param name="library">The parent library.</param> /// <param name="path">The path of the font file.</param> public Face(Library library, string path) : this(library, path, 0) { }
public override CompiledSpriteFont Process(SpriteFontContent input, string filename, ContentProcessorContext context) { string fontFile; if (!FontConfig.Instance.GetFontFile(input.FontName, input.Size, input.Style, out fontFile)) { context.RaiseBuildMessage(filename, $"'{input.FontName}' was not found, using fallback font", BuildMessageEventArgs.BuildMessageType.Warning); } if (fontFile == null) { context.RaiseBuildMessage(filename, $"'{input.FontName}' was not found, no fallback font provided", BuildMessageEventArgs.BuildMessageType.Error); return(null); } //Initialization SharpFont.Library lib = new SharpFont.Library(); var face = lib.NewFace(fontFile, 0); Bitmap dummyBitmap = new Bitmap(1, 1); System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(dummyBitmap); face.SetCharSize(new Fixed26Dot6(0), new Fixed26Dot6(input.Size), (uint)g.DpiX, (uint)g.DpiY); CompiledSpriteFont compiled = new CompiledSpriteFont(); compiled.Spacing = input.Spacing; compiled.DefaultCharacter = input.DefaultCharacter; var glyphs = new Dictionary <uint, GlyphSlot>(); var characters = input.CharacterRegions.SelectMany( r => r.GetChararcters().Select(c => Tuple.Create(c, face.GetCharIndex(c)))).Where(x => x.Item2 != 0).ToList(); var bitmaps = new List <Tuple <char, FTBitmap, int, GlyphMetrics> >(); compiled.LineSpacing = face.Size.Metrics.Height.Value >> 6; compiled.BaseLine = face.Size.Metrics.Ascender.Value >> 6; //Loading Glyphs, Calculate Kernings and Create Bitmaps int totalWidth = 0, maxWidth = 0, maxHeight = 0; foreach (var l in characters) { var character = l.Item1; var glyphIndex = l.Item2; //Load Glyphs face.LoadGlyph(glyphIndex, LoadFlags.Color, LoadTarget.Normal); var glyph = face.Glyph; glyph.Tag = character; glyphs.Add(character, glyph); //Calculate Kernings if (input.UseKerning) { foreach (var r in characters) { var kerning = face.GetKerning(l.Item2, r.Item2, KerningMode.Default); if (kerning == default(FTVector26Dot6)) { continue; } compiled.kernings[(int)l.Item1 << 16 | (int)r.Item1] = kerning.X.Value >> 6; } } //Create bitmaps glyph.OwnBitmap(); var glyphActual = glyph.GetGlyph(); glyphActual.ToBitmap(RenderMode.Normal, default(FTVector26Dot6), false); var bmg = glyphActual.ToBitmapGlyph(); if (bmg.Bitmap.Width == 0 || bmg.Bitmap.Rows == 0) { totalWidth += 2 + 1; maxWidth = Math.Max(maxWidth, 1 + 2); maxHeight = Math.Max(maxHeight, 1 + 2); bitmaps.Add(Tuple.Create(character, (FTBitmap)null, glyph.Advance.X.Value >> 6, glyph.Metrics)); } else { var bmp = bmg.Bitmap; totalWidth += 2 + bmp.Width; maxWidth = Math.Max(maxWidth, bmp.Width + 2);//TODO: divide by 3? maxHeight = Math.Max(maxHeight, bmp.Rows + 2); bitmaps.Add(Tuple.Create(character, bmp, glyph.Advance.X.Value >> 6, glyph.Metrics)); } } g.Dispose(); dummyBitmap.Dispose(); int cellCount = (int)Math.Ceiling(Math.Sqrt(bitmaps.Count)); var target = new Bitmap(cellCount * maxWidth, cellCount * maxHeight); var targetRectangle = new Rectangle(0, 0, target.Width, target.Height); var targetData = target.LockBits(new System.Drawing.Rectangle(0, 0, target.Width, target.Height), ImageLockMode.WriteOnly, target.PixelFormat); int offsetX = 0, offsetY = 0; //Create Glyph Atlas foreach (var bmpKvp in bitmaps) { var bmp = bmpKvp.Item2; var character = bmpKvp.Item1; if (bmp == null) { compiled.characterMap.Add(character, new FontCharacter(character, targetRectangle, new Rectangle(offsetX, offsetY, 1, 1), new Vector2(bmpKvp.Item4.HorizontalBearingX.Value >> 6, compiled.BaseLine - (bmpKvp.Item4.HorizontalBearingY.Value >> 6)), bmpKvp.Item3)); if (offsetX++ > target.Width) { offsetY += maxHeight; offsetX = 0; } continue; } int width = bmp.Width; int height = bmp.Rows; if (offsetX + width > target.Width) { offsetY += maxHeight; offsetX = 0; } //TODO divide width by 3? compiled.characterMap.Add(character, new FontCharacter(character, targetRectangle, new Rectangle(offsetX, offsetY, width, height), new Vector2(bmpKvp.Item4.HorizontalBearingX.Value >> 6, compiled.BaseLine - (bmpKvp.Item4.HorizontalBearingY.Value >> 6)), bmpKvp.Item3)); unsafe { switch (bmp.PixelMode) { case PixelMode.Mono: CopyFTBitmapToAtlas_Mono((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Gray: CopyFTBitmapToAtlas_Gray((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Lcd: CopyFTBitmapToAtlas_LcdBGR((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; case PixelMode.Bgra: CopyFTBitmapToAtlas_BGRA((uint *)targetData.Scan0 + offsetX + offsetY * target.Width, offsetX, offsetY, target.Width, bmp, width, height);//TODO: divide width by 3? break; default: throw new NotImplementedException("Pixel Mode not supported"); } } offsetX += width;//TODO divide by 3? bmp.Dispose(); } compiled.texture = new TextureContent(context.GraphicsDevice, false, 1, targetData.Scan0, target.Width, target.Height, TextureContentFormat.Png, TextureContentFormat.Png); compiled.Spacing = input.Spacing; compiled.DefaultCharacter = input.DefaultCharacter; target.UnlockBits(targetData); //Saving files //target.Save("test.png",ImageFormat.Png); target.Dispose(); //System.Diagnostics.Process.Start("test.png"); //TODO: Remove later return(compiled); }
//TODO make an overload with a FileStream instead of a byte[] /// <summary> /// Initializes a new instance of the <see cref="Face"/> class from a file that's already loaded into memory. /// </summary> /// <param name="library">The parent library.</param> /// <param name="file">The loaded file.</param> /// <param name="faceIndex">The index of the face to take from the file.</param> public unsafe Face(Library library, byte[] file, int faceIndex) : this() { memoryFaceHandle = GCHandle.Alloc(file, GCHandleType.Pinned); IntPtr reference; Error err = FT.FT_New_Memory_Face(library.Reference, memoryFaceHandle.AddrOfPinnedObject(), file.Length, faceIndex, out reference); if (err != Error.Ok) throw new FreeTypeException(err); Reference = reference; parentLibrary = library; parentLibrary.AddChildFace(this); }
public FontGroup GetGroupForFont(string fontName) { // Review Linux: very likely something here is not portable. if (FontNameToFiles == null) { FontNameToFiles = new Dictionary <string, FontGroup>(); #if __MonoCS__ using (var lib = new SharpFont.Library()) { // Find all the font files in the standard system location (/usr/share/font) and $HOME/.font (if it exists) foreach (var fontFile in FindLinuxFonts()) { try { using (var face = new SharpFont.Face(lib, fontFile)) { var embeddingTypes = face.GetFSTypeFlags(); if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense || (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly) { continue; } var name = face.FamilyName; // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(face, fontFile); } } catch (Exception) { } } } #else foreach (var fontFile in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Fonts))) { // ePUB only understands these types, so skip anything else. switch (Path.GetExtension(fontFile)) { case ".ttf": case ".otf": case ".woff": break; default: continue; } GlyphTypeface gtf; try { gtf = new GlyphTypeface(new Uri("file:///" + fontFile)); } catch (Exception) { continue; // file is somehow corrupt or not really a font file? Just ignore it. } switch (gtf.EmbeddingRights) { case FontEmbeddingRight.Editable: case FontEmbeddingRight.EditableButNoSubsetting: case FontEmbeddingRight.Installable: case FontEmbeddingRight.InstallableButNoSubsetting: case FontEmbeddingRight.PreviewAndPrint: case FontEmbeddingRight.PreviewAndPrintButNoSubsetting: break; default: continue; // not allowed to embed (enhance: warn user?) } var fc = new PrivateFontCollection(); try { fc.AddFontFile(fontFile); } catch (FileNotFoundException) { continue; // not sure how this can happen but I've seen it. } var name = fc.Families[0].Name; // If you care about bold, italic, etc, you can filter here. FontGroup files; if (!FontNameToFiles.TryGetValue(name, out files)) { files = new FontGroup(); FontNameToFiles[name] = files; } files.Add(gtf, fontFile); } #endif } FontGroup result; FontNameToFiles.TryGetValue(fontName, out result); return(result); }
/// <summary> /// Initializes a new instance of the <see cref="Face"/> class. /// </summary> /// <param name="reference">A pointer to the unmanaged memory containing the Face.</param> /// <param name="parent">The parent <see cref="Library"/>.</param> internal Face(IntPtr reference, Library parent) : this(parent) { Reference = reference; }
private Face(Library parent) : base(IntPtr.Zero) { childSizes = new List<FTSize>(); if (parent != null) { parentLibrary = parent; parentLibrary.AddChildFace(this); } else { //if there's no parent, this is a marshalled duplicate. FT.FT_Reference_Face(Reference); } }