Пример #1
0
        internal static XFontSource GetOrCreateFromWpf(string typefaceKey, WpfGlyphTypeface wpfGlyphTypeface)
        {
            byte[]      bytes      = ReadFontBytesFromWpf(wpfGlyphTypeface);
            XFontSource fontSource = GetOrCreateFrom(typefaceKey, bytes);

            return(fontSource);
        }
Пример #2
0
        internal static string ComputeKey(WpfGlyphTypeface wpfGlyphTypeface)
        {
            string name1      = wpfGlyphTypeface.DesignerNames[FontHelper.CultureInfoEnUs];
            string faceName   = wpfGlyphTypeface.FaceNames[FontHelper.CultureInfoEnUs];
            string familyName = wpfGlyphTypeface.FamilyNames[FontHelper.CultureInfoEnUs];
            string name4      = wpfGlyphTypeface.ManufacturerNames[FontHelper.CultureInfoEnUs];
            string name5      = wpfGlyphTypeface.Win32FaceNames[FontHelper.CultureInfoEnUs];
            string name6      = wpfGlyphTypeface.Win32FamilyNames[FontHelper.CultureInfoEnUs];


            string name        = familyName.ToLower() + '/' + faceName.ToLowerInvariant();
            string style       = wpfGlyphTypeface.Style.ToString();
            string weight      = wpfGlyphTypeface.Weight.ToString();
            string stretch     = wpfGlyphTypeface.Stretch.ToString();
            string simulations = wpfGlyphTypeface.StyleSimulations.ToString();

            //string key = name + '/' + style + '/' + weight + '/' + stretch + '/' + simulations;

            string key = KeyPrefix + name + '/' + style.Substring(0, 1) + '/' + wpfGlyphTypeface.Weight.ToOpenTypeWeight().ToString(CultureInfo.InvariantCulture) + '/' + wpfGlyphTypeface.Stretch.ToOpenTypeStretch().ToString(CultureInfo.InvariantCulture);

            switch (wpfGlyphTypeface.StyleSimulations)
            {
            case WpfStyleSimulations.BoldSimulation: key += "|b+/i-"; break;

            case WpfStyleSimulations.ItalicSimulation: key += "|b-/i+"; break;

            case WpfStyleSimulations.BoldItalicSimulation: key += "|b+/i+"; break;

            case WpfStyleSimulations.None: break;
            }
            return(key.ToLowerInvariant());
        }
Пример #3
0
 public CharInfo(char character, GlyphTypeface font, double size, int fontId, TexFontMetrics metrics)
 {
     this.Character = character;
     this.Font = font;
     this.Size = size;
     this.FontId = fontId;
     this.Metrics = metrics;
 }
Пример #4
0
 public PlatformFontResolverInfo(string faceName, bool mustSimulateBold, bool mustSimulateItalic, WpfFontFamily wpfFontFamily,
                                 WpfTypeface wpfTypeface, WpfGlyphTypeface wpfGlyphTypeface)
     : base(faceName, mustSimulateBold, mustSimulateItalic)
 {
     _wpfFontFamily    = wpfFontFamily;
     _wpfTypeface      = wpfTypeface;
     _wpfGlyphTypeface = wpfGlyphTypeface;
 }
Пример #5
0
 public PlatformFontResolverInfo(string faceName, bool mustSimulateBold, bool mustSimulateItalic, WpfFontFamily wpfFontFamily,
     WpfTypeface wpfTypeface, WpfGlyphTypeface wpfGlyphTypeface)
     : base(faceName, mustSimulateBold, mustSimulateItalic)
 {
     _wpfFontFamily = wpfFontFamily;
     _wpfTypeface = wpfTypeface;
     _wpfGlyphTypeface = wpfGlyphTypeface;
 }
Пример #6
0
 internal ShapeTypeface(
     GlyphTypeface        glyphTypeface,
     IDeviceFont          deviceFont
     )
 {
     Invariant.Assert(glyphTypeface != null);
     _glyphTypeface = glyphTypeface;
     _deviceFont = deviceFont;
 }
Пример #7
0
 public FontMetrics(Typeface tf, GlyphTypeface gtf)
 {
     CapsHeight = tf.CapsHeight;
     UnderlinePosition = tf.UnderlinePosition;
     XHeight = tf.XHeight;
     Baseline = gtf.Baseline;
     Height = gtf.Height;
     TopSideBearing = gtf.TopSideBearings[1000];
     BottomSideBearing = gtf.BottomSideBearings[1000];
 }
Пример #8
0
        internal string GetFont(PDFResources resources, System.Windows.Media.GlyphTypeface typeFace)
        {
            string familyName = typeFace.FamilyNames.Values.FirstOrDefault();

            string key = null;

            if (!fonts.TryGetValue(typeFace, out key))
            {
                key = "R" + resources.ID + "F" + fonts.Count;
                PDFFont pf = PDFDocument.CreateObject <PDFFont>();
                pf.BaseFont         = familyName;
                pf.Subtype          = "Type1";
                pf.Encoding         = "MacRomanEncoding";
                resources.Font[key] = pf;

                var pd = PDFDocument.CreateObject <PDFFontDescriptor>();

                pf.FontDescriptor = pd;

                pd.FontName   = familyName;
                pd.FontFamily = familyName;
                pd.FontWeight = typeFace.Weight.ToOpenTypeWeight();


                pd.XHeight   = typeFace.XHeight;
                pd.CapHeight = typeFace.CapsHeight;
                pd.StemV     = typeFace.StrikethroughThickness;

                pd.Flags = PDFFontFlags.None;

                if (typeFace.Weight == FontWeights.Bold)
                {
                    pd.Flags |= PDFFontFlags.ForceBold;
                }

                if (typeFace.Symbol)
                {
                    pd.Flags |= PDFFontFlags.Symbolic;
                }
                else
                {
                    pd.Flags |= PDFFontFlags.Nonsymbolic;
                }
                pd.Ascent  = typeFace.AdvanceHeights.Select(x => x.Value).Max() - typeFace.Baseline;
                pd.Descent = -(typeFace.DistancesFromHorizontalBaselineToBlackBoxBottom.Select(x => x.Value).Max());

                pd.FontBBox        = new PDFRect();
                pd.FontBBox.Width  = (int)typeFace.AdvanceWidths.Select(x => x.Value).Sum();
                pd.FontBBox.Height = (int)typeFace.AdvanceHeights.Select(x => x.Value).Sum();

                fonts[typeFace] = key;
            }
            return(key);
        }
Пример #9
0
 internal static byte[] ReadFontBytesFromWpf(WpfGlyphTypeface wpfGlyphTypeface)
 {
     using (Stream fontStream = wpfGlyphTypeface.GetFontStream())
     {
         if (fontStream == null)
         {
             throw new InvalidOperationException("Cannot retrieve font data.");
         }
         int    size  = (int)fontStream.Length;
         byte[] bytes = new byte[size];
         fontStream.Read(bytes, 0, size);
         return(bytes);
     }
 }
Пример #10
0
        /// <summary>
        /// Lookup characters nominal glyphs and width
        /// </summary>
        /// <param name="charBufferRange">character buffer range</param>
        /// <param name="emSize">height of Em</param>
        /// <param name="toIdeal"> scaling factor from real to ideal unit </param>
        /// <param name="nominalWidths">glyph nominal advances in ideal units</param>
        /// <param name="idealWidth">total width in ideal units</param>
        /// <returns>true for success</returns>
        /// <remarks>This function is only used in fast path, and can only be called
        /// if CheckFastPathNominalGlyphs has previously returned true.</remarks>
        internal void GetCharacterNominalWidthsAndIdealWidth(
            CharacterBufferRange charBufferRange,
            double emSize,
            float pixelsPerDip,
            double toIdeal,
            TextFormattingMode textFormattingMode,
            bool isSideways,
            out int[]            nominalWidths,
            out int idealWidth
            )
        {
            // This function should only be called if CheckFastPathNominalGlyphs has
            // returned true so we can assume the ITypefaceMetrics is a GlyphTypeface.
            GlyphTypeface glyphTypeface = TryGetGlyphTypeface();

            Invariant.Assert(glyphTypeface != null);

            MS.Internal.Text.TextInterface.GlyphMetrics[] glyphMetrics = BufferCache.GetGlyphMetrics(charBufferRange.Length);

            glyphTypeface.GetGlyphMetricsOptimized(charBufferRange,
                                                   emSize,
                                                   pixelsPerDip,
                                                   textFormattingMode,
                                                   isSideways,
                                                   glyphMetrics);

            nominalWidths = new int[charBufferRange.Length];
            idealWidth    = 0;

            if (TextFormattingMode.Display == textFormattingMode)
            {
                double designToEm = emSize / glyphTypeface.DesignEmHeight;
                for (int i = 0; i < charBufferRange.Length; i++)
                {
                    nominalWidths[i] = (int)Math.Round(TextFormatterImp.RoundDipForDisplayMode(glyphMetrics[i].AdvanceWidth * designToEm, pixelsPerDip) * toIdeal);
                    idealWidth      += nominalWidths[i];
                }
            }
            else
            {
                double designToEm = emSize * toIdeal / glyphTypeface.DesignEmHeight;
                for (int i = 0; i < charBufferRange.Length; i++)
                {
                    nominalWidths[i] = (int)Math.Round(glyphMetrics[i].AdvanceWidth * designToEm);
                    idealWidth      += nominalWidths[i];
                }
            }

            BufferCache.ReleaseGlyphMetrics(glyphMetrics);
        }
Пример #11
0
        XGlyphTypeface(string key, XFontFamily fontFamily, XFontSource fontSource, XStyleSimulations styleSimulations, WpfTypeface wpfTypeface, WpfGlyphTypeface wpfGlyphTypeface)
        {
            _key              = key;
            _fontFamily       = fontFamily;
            _fontSource       = fontSource;
            _styleSimulations = styleSimulations;

            _fontface = OpenTypeFontface.CetOrCreateFrom(fontSource);
            Debug.Assert(ReferenceEquals(_fontSource.Fontface, _fontface));

            _wpfTypeface      = wpfTypeface;
            _wpfGlyphTypeface = wpfGlyphTypeface;

            Initialize();
        }
Пример #12
0
        public TexFontInfo(int fontId, GlyphTypeface font, double xHeight, double space, double quad)
        {
            this.metrics = new double[charCodesCount][];
            this.ligatures = new Dictionary<Tuple<char, char>, char>();
            this.kerns = new Dictionary<Tuple<char, char>, double>();
            this.nextLarger = new CharFont[charCodesCount];
            this.extensions = new int[charCodesCount][];

            this.FontId = fontId;
            this.Font = font;
            this.XHeight = xHeight;
            this.Space = space;
            this.Quad = quad;
            this.SkewCharacter = (char)1;
        }
Пример #13
0
        /// <summary>
        /// Init.
        /// </summary>
        public FontAdapter(Typeface font, double size)
        {
            _font = font;
            _size = size;
            _height = 96d / 72d * _size * _font.FontFamily.LineSpacing;
            _underlineOffset = 96d / 72d * _size * (_font.FontFamily.LineSpacing + font.UnderlinePosition);

            GlyphTypeface typeface;
            if (font.TryGetGlyphTypeface(out typeface))
            {
                _glyphTypeface = typeface;
            }
            else
            {
                foreach (var sysTypeface in Fonts.SystemTypefaces)
                {
                    if (sysTypeface.TryGetGlyphTypeface(out typeface))
                        break;
                }
            }
        }
Пример #14
0
        /// <summary>
        /// Scan through specified character string checking for valid character
        /// nominal glyph.
        /// </summary>
        /// <param name="charBufferRange">character buffer range</param>
        /// <param name="emSize">height of Em</param>
        /// <param name="scalingFactor">This is the factor by which we will scale up
        /// the metrics. Typically this value to used to convert metrics from the real
        /// space to the ideal space</param>
        /// <param name="widthMax">maximum width allowed</param>
        /// <param name="keepAWord">do not stop arbitrarily in the middle of a word</param>
        /// <param name="numberSubstitution">digits require complex shaping</param>
        /// <param name="cultureInfo">CultureInfo of the text</param>
        /// <param name="textFormattingMode">The TextFormattingMode used (Ideal vs. Display)</param>
        /// <param name="isSideways">Indicates whether to rotate glyphs.</param>
        /// <param name="breakOnTabs">Determines whether to stop checking at a tab and
        /// break the run there</param>
        /// <param name="stringLengthFit">number of character fit in given width</param>
        /// <returns>whether the specified string can be optimized by nominal glyph lookup</returns>
        internal bool CheckFastPathNominalGlyphs(
            CharacterBufferRange charBufferRange,
            double emSize,
            double scalingFactor,
            double widthMax,
            bool keepAWord,
            bool numberSubstitution,
            CultureInfo cultureInfo,
            TextFormattingMode textFormattingMode,
            bool isSideways,
            bool breakOnTabs,
            out int stringLengthFit
            )
        {
            stringLengthFit = 0;

            if (CachedTypeface.NullFont)
            {
                return(false);
            }

            GlyphTypeface glyphTypeface = TryGetGlyphTypeface();

            if (glyphTypeface == null)
            {
                return(false);
            }

            double totalWidth = 0;
            int    i          = 0;

            ushort blankGlyph = glyphTypeface.BlankGlyphIndex;
            ushort glyph      = blankGlyph;

            ushort charFlagsMask = numberSubstitution ?
                                   (ushort)(CharacterAttributeFlags.CharacterComplex | CharacterAttributeFlags.CharacterDigit) :
                                   (ushort)CharacterAttributeFlags.CharacterComplex;
            ushort charFlags         = 0;
            ushort charFastTextCheck = (ushort)(CharacterAttributeFlags.CharacterFastText | CharacterAttributeFlags.CharacterIdeo);

            bool symbolTypeface = glyphTypeface.Symbol;

            if (symbolTypeface)
            {
                // we don't care what code points are present if it's a non-Unicode font such as Symbol or Wingdings;
                // the code points don't have any standardized meanings, and we always want to bypass shaping
                charFlagsMask = 0;
            }

            bool ignoreWidths = widthMax == double.MaxValue;

            ushort[] glyphIndices = BufferCache.GetUShorts(charBufferRange.Length);
            MS.Internal.Text.TextInterface.GlyphMetrics[] glyphMetrics = ignoreWidths ? null : BufferCache.GetGlyphMetrics(charBufferRange.Length);

            glyphTypeface.GetGlyphMetricsOptimized(charBufferRange,
                                                   emSize,
                                                   glyphIndices,
                                                   glyphMetrics,
                                                   textFormattingMode,
                                                   isSideways
                                                   );

            double designToEm = emSize / glyphTypeface.DesignEmHeight;

            //
            // This block will advance until one of:
            // 1. The end of the charBufferRange is reached
            // 2. The charFlags have some of the charFlagsMask values
            // 3. The glyph is BlankGlyph (space)
            // 4. Glyph index is 0 (unless symbol font)
            //
            // At this point totalWidth includes all of the widths including the stop character (which fits above)
            // i indexes the next character (not included in the width)
            //
            if (keepAWord)
            {
                do
                {
                    char ch = charBufferRange[i++];
                    if (ch == TextStore.CharLineFeed || ch == TextStore.CharCarriageReturn || (breakOnTabs && ch == TextStore.CharTab))
                    {
                        --i;
                        break;
                    }
                    else
                    {
                        int charClass = (int)Classification.GetUnicodeClassUTF16(ch);
                        charFlags          = Classification.CharAttributeOf(charClass).Flags;
                        charFastTextCheck &= charFlags;

                        glyph = glyphIndices[i - 1];
                        if (!ignoreWidths)
                        {
                            totalWidth += TextFormatterImp.RoundDip(glyphMetrics[i - 1].AdvanceWidth * designToEm, textFormattingMode) * scalingFactor;
                        }
                    }
                } while(
                    i < charBufferRange.Length &&
                    ((charFlags & charFlagsMask) == 0) &&
                    (glyph != 0 || symbolTypeface) &&
                    glyph != blankGlyph
                    );

                // i is now at a character immediately following a leading blank
            }

            //
            // This block will advance until one of:
            // 1. The end of the charBufferRange is reached
            // 2. The charFlags have some of the charFlagsMask values
            // 3. Glyph index is 0 (unless symbol font)
            // 4. totalWidth > widthMax
            //

            while (
                i < charBufferRange.Length &&
                (ignoreWidths || totalWidth <= widthMax) &&
                ((charFlags & charFlagsMask) == 0) &&
                (glyph != 0 || symbolTypeface)
                )
            {
                char ch = charBufferRange[i++];
                if (ch == TextStore.CharLineFeed || ch == TextStore.CharCarriageReturn || (breakOnTabs && ch == TextStore.CharTab))
                {
                    --i;
                    break;
                }
                else
                {
                    int charClass = (int)Classification.GetUnicodeClassUTF16(ch);
                    charFlags          = Classification.CharAttributeOf(charClass).Flags;
                    charFastTextCheck &= charFlags;

                    glyph = glyphIndices[i - 1];
                    if (!ignoreWidths)
                    {
                        totalWidth += TextFormatterImp.RoundDip(glyphMetrics[i - 1].AdvanceWidth * designToEm, textFormattingMode) * scalingFactor;
                    }
                }
            }

            BufferCache.ReleaseUShorts(glyphIndices);
            glyphIndices = null;
            BufferCache.ReleaseGlyphMetrics(glyphMetrics);
            glyphMetrics = null;

            if (symbolTypeface)
            {
                // always optimize for non-Unicode font as we don't support shaping or typographic features;
                // we also don't fall back from non-Unicode fonts so we don't care if there are missing glyphs
                stringLengthFit = i;
                return(true);
            }

            if (glyph == 0)
            {
                // character is not supported by the font
                return(false);
            }

            if ((charFlags & charFlagsMask) != 0)
            {
                // complex character encountered, exclude it
                Debug.Assert(i > 0);

                if (--i <= 0)
                {
                    // first char is complex, fail the call
                    return(false);
                }
            }

            stringLengthFit = i;
            TypographyAvailabilities typography = glyphTypeface.FontFaceLayoutInfo.TypographyAvailabilities;

            if ((charFastTextCheck & (byte)CharacterAttributeFlags.CharacterFastText) != 0)
            {
                // all input code points are Fast Text
                if ((typography &
                     (TypographyAvailabilities.FastTextTypographyAvailable
                      | TypographyAvailabilities.FastTextMajorLanguageLocalizedFormAvailable
                     )
                     ) != 0
                    )
                {
                    // Considered too risky to optimize. It is either because the font
                    // has required features or the font has 'locl' lookup for major languages.
                    return(false);
                }
                else if ((typography & TypographyAvailabilities.FastTextExtraLanguageLocalizedFormAvailable) != 0)
                {
                    // The font has 'locl' lookup for FastText code points for non major languages.
                    // Check whether the input is major langauge. If it is, we are still good to optimize.
                    return(MajorLanguages.Contains(cultureInfo));
                }
                else
                {
                    // No FastText flags are present, safe to optimize
                    return(true);
                }
            }
            else if ((charFastTextCheck & (byte)CharacterAttributeFlags.CharacterIdeo) != 0)
            {
                // The input are all ideographs, check the IdeoTypographyAvailable bit. It is safe if
                // the bit is not set.
                return((typography & TypographyAvailabilities.IdeoTypographyAvailable) == 0);
            }
            else
            {
                // for all the rest of the cases, just check whether there is any required typography
                // present at all. If none exists, it is optimizable. We might under-optimize here but
                // it will be non-major languages.
                return((typography & TypographyAvailabilities.Available) == 0);
            }
        }
Пример #15
0
        /// <summary>
        /// Initializes a new instance of the <c>TextStyle</c> class.
        /// </summary>
        /// <param name="name">Text style name.</param>
        /// <param name="font">Text style font file name with full or relative path.</param>
        /// <param name="checkName">Specifies if the style name has to be checked.</param>
        /// <remarks>If the font file is a true type and is not found in the specified path, the constructor will try to find it in the system font folder.</remarks>
        internal TextStyle(string name, string font, bool checkName)
            : base(name, DxfObjectCode.TextStyle, checkName)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException(nameof(name), "The text style name should be at least one character long.");

            if (string.IsNullOrEmpty(font))
                throw new ArgumentNullException(nameof(font));

            this.IsReserved = name.Equals(DefaultName, StringComparison.OrdinalIgnoreCase);
            this.font = font;
            this.widthFactor = 1.0;
            this.obliqueAngle = 0.0;
            this.height = 0.0;
            this.isVertical = false;
            this.isBackward = false;
            this.isUpsideDown = false;
            this.glyphTypeface = null;
            this.fontFamilyName = Path.GetFileNameWithoutExtension(font);

            // the following information is only applied to ttf not shx fonts
            if (!Path.GetExtension(font).Equals(".ttf", StringComparison.OrdinalIgnoreCase))
                return;

            // try to find the file in the specified directory, if not try it in the fonts system folder
            string fontFile;
            if (File.Exists(font))
                fontFile = Path.GetFullPath(font);
            else
            {
                string file = Path.GetFileName(font);
                fontFile = string.Format("{0}{1}{2}", Environment.GetFolderPath(Environment.SpecialFolder.Fonts), Path.DirectorySeparatorChar, file);
                // if the ttf does not even exist in the font system folder
                if (!File.Exists(fontFile))
                    return;
                this.font = file;
            }
            this.glyphTypeface = new GlyphTypeface(new Uri(fontFile));
            this.fontFamilyName = this.glyphTypeface.FamilyNames[CultureInfo.GetCultureInfo(1033)];
            if (string.IsNullOrEmpty(this.fontFamilyName))
            {
                ICollection<string> names = this.glyphTypeface.FamilyNames.Values;
                IEnumerator<string> enumerator = names.GetEnumerator();
                enumerator.MoveNext();
                this.fontFamilyName = enumerator.Current;
            }
        }
Пример #16
0
        protected bool RenderText(String text, ref List<TextDrawItem> textDrawList, GlyphTypeface glyphType, double fontSize, double maxWidth, double maxHeight, double x, double y, ref double useHeight, SolidColorBrush fontColor, Matrix m)
        {
            double totalHeight = 0;

            string[] lineText = text.Replace("\r", "").Split('\n');
            foreach (string line in lineText)
            {
                totalHeight += Math.Floor(2 + fontSize);
                List<ushort> glyphIndexes = new List<ushort>();
                List<double> advanceWidths = new List<double>();
                double totalWidth = 0;
                for (int n = 0; n < line.Length; n++)
                {
                    ushort glyphIndex = glyphType.CharacterToGlyphMap[line[n]];
                    double width = glyphType.AdvanceWidths[glyphIndex] * fontSize;
                    if (totalWidth + width > maxWidth)
                    {
                        if (glyphIndexes.Count > 0)
                        {
                            double dpix = Math.Ceiling((x + 2) * m.M11);
                            double dpiy = Math.Ceiling((y + totalHeight) * m.M22);
                            Point origin = new Point(dpix / m.M11, dpiy / m.M22);
                            TextDrawItem item = new TextDrawItem();
                            item.FontColor = fontColor;
                            item.Text = new GlyphRun(glyphType, 0, false, fontSize,
                                glyphIndexes, origin, advanceWidths, null, null, null, null,
                                null, null);
                            textDrawList.Add(item);

                        }
                        if (totalHeight > maxHeight)
                        {
                            //次の行無理
                            useHeight = totalHeight;
                            return false;
                        }
                        else
                        {
                            //次の行いける
                            totalHeight += fontSize + 2;

                            glyphIndexes = new List<ushort>();
                            advanceWidths = new List<double>();
                            totalWidth = 0;
                        }
                    }
                    glyphIndexes.Add(glyphIndex);
                    advanceWidths.Add(width);
                    totalWidth += width;
                }
                if (glyphIndexes.Count > 0)
                {
                    double dpix = Math.Ceiling((x + 2) * m.M11);
                    double dpiy = Math.Ceiling((y + totalHeight) * m.M22);
                    Point origin = new Point(dpix / m.M11, dpiy / m.M22);
                    TextDrawItem item = new TextDrawItem();
                    item.FontColor = fontColor;
                    item.Text = new GlyphRun(glyphType, 0, false, fontSize,
                        glyphIndexes, origin, advanceWidths, null, null, null, null,
                        null, null);
                    textDrawList.Add(item);

                }
            }
            useHeight = Math.Floor(totalHeight);
            return true;
        }
Пример #17
0
 /// <summary> 
 /// Obtain a glyph typeface that corresponds to the Typeface object constructed from an OpenType font family.
 /// If the Typeface was constructed from a composite font family, returns null. 
 /// </summary> 
 /// <param name="glyphTypeface">GlyphTypeface object that corresponds to this Typeface, or null if the Typeface
 /// was constructed from a composite font.</param> 
 /// <returns>Whether glyphTypeface is not null.</returns>
 public bool TryGetGlyphTypeface(out GlyphTypeface glyphTypeface)
 {
     glyphTypeface = CachedTypeface.TypefaceMetrics as GlyphTypeface; 
     return glyphTypeface != null;
 } 
Пример #18
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="FontInfo"/>, используя указанное местоположение файла шрифта.
 /// </summary>
 /// <param name="File">Местоположение файла шрифта</param>
 public FontInfo(String File)
 {
     _glyphTypeface = new System.Windows.Media.GlyphTypeface(new Uri(File));
     _typefaces     = Fonts.GetTypefaces(File);
 }
Пример #19
0
		public static unsafe object ToObject (Type type, Value* value)
		{
			if (value == null || value->IsNull) {
				return null;
			}
			if (value->IsGCHandle) {
				IntPtr managed_object = value->u.p;
				GCHandle handle = GCHandle.FromIntPtr (managed_object);
				return handle.Target;
			}
			switch (value->k) {
			case Kind.INVALID:
				return null;
					
			case Kind.DEPENDENCYPROPERTY:
				return DependencyProperty.Lookup (value->u.p);
				
			case Kind.BOOL:
				return value->u.i32 != 0;

			case Kind.DOUBLE:
				return value->u.d;
					
			case Kind.FLOAT:
				return value->u.f;
					
			case Kind.UINT64:
				return value->u.ui64;
					
			case Kind.INT64:
				return value->u.i64;
					
			case Kind.TIMESPAN:
				return new TimeSpan (value->u.i64);
			case Kind.CURSORTYPE:
				return Cursors.FromEnum ((CursorType) value->u.i32);
			case Kind.TEXTDECORATIONS:
				return (value->u.i32 == (int) TextDecorationKind.Underline) ? TextDecorations.Underline : null;
			case Kind.INT32:
				return value->u.i32;
			case Kind.CHAR:
				return (char) value->u.ui32;

			case Kind.SURFACE:
				return NativeDependencyObjectHelper.FromIntPtr (value->u.p);

			case Kind.STRING: {
				string str = Marshal.PtrToStringAuto (value->u.p);
				if (type == null)
					return str;
				
				// marshall back to the .NET type that we simply serialised as 'string' for unmanaged usage
				if (type == typeof (System.Windows.Markup.XmlLanguage))
					return XmlLanguage.GetLanguage (str);
				else
					return str;
			}

			case Kind.URI: {
				UnmanagedUri *uri = (UnmanagedUri*)value->u.p;
				return uri->originalString == IntPtr.Zero
					? new Uri("", UriKind.Relative)
					: new Uri (Marshal.PtrToStringAuto (uri->originalString),
						   uri->isAbsolute ? UriKind.Absolute : UriKind.Relative);
			}

			case Kind.XMLLANGUAGE: {
				string str = Marshal.PtrToStringAuto (value->u.p);
				return XmlLanguage.GetLanguage (str);
			}

			case Kind.FONTFAMILY: {
				UnmanagedFontFamily *family = (UnmanagedFontFamily*)value->u.p;
				return new FontFamily (family == null ? null : Marshal.PtrToStringAuto (family->source));
			}

			case Kind.FONTSTRETCH: {
				UnmanagedFontStretch *stretch = (UnmanagedFontStretch*)value->u.p;
				return new FontStretch (stretch == null ? FontStretchKind.Normal : stretch->stretch);
			}

			case Kind.FONTSTYLE: {
				UnmanagedFontStyle *style = (UnmanagedFontStyle*)value->u.p;
				return new FontStyle (style == null ? FontStyleKind.Normal : style->style);
			}

			case Kind.FONTWEIGHT: {
				UnmanagedFontWeight *weight = (UnmanagedFontWeight*)value->u.p;
				return new FontWeight (weight == null ? FontWeightKind.Normal : weight->weight);
			}

			case Kind.FONTSOURCE: {
				UnmanagedFontSource *fs = (UnmanagedFontSource *) value->u.p;
				ManagedStreamCallbacks callbacks;
				GlyphTypeface typeface;
				StreamWrapper wrapper;
				
				switch (fs->type) {
				case FontSourceType.ManagedStream:
					callbacks = (ManagedStreamCallbacks) Marshal.PtrToStructure (fs->source.stream, typeof (ManagedStreamCallbacks));
					
					wrapper = (StreamWrapper) GCHandle.FromIntPtr (callbacks.handle).Target;
					
					return new FontSource (wrapper.stream);
				case FontSourceType.GlyphTypeface:
					typeface = new GlyphTypeface (fs->source.typeface);
					return new FontSource (typeface);
				default:
					throw new Exception (String.Format ("Do not know how to create a FontSource of type {0}",
									    fs->type.ToString ()));
				}
			}

			case Kind.GLYPHTYPEFACE: {
				return new GlyphTypeface (value->u.p);
			}

			case Kind.PROPERTYPATH: {
				UnmanagedPropertyPath *propertypath = (UnmanagedPropertyPath *) value->u.p;
				if (propertypath == null)
					return new PropertyPath (null);
				if (propertypath->property != IntPtr.Zero)
					return null;
				return new PropertyPath (Marshal.PtrToStringAuto (propertypath->pathString));
			}

			case Kind.POINT: {
				Point *point = (Point*)value->u.p;
				return (point == null) ? new Point (0,0) : *point;
			}
				
			case Kind.RECT: {
				Rect *rect = (Rect*)value->u.p;
				return (rect == null) ? new Rect (0,0,0,0) : *rect;
			}

			case Kind.SIZE: {
				Size *size = (Size*)value->u.p;
				return (size == null) ? new Size (0,0) : *size;
			}

			case Kind.CORNERRADIUS: {
				CornerRadius *corner = (CornerRadius*)value->u.p;
				return (corner == null) ? new CornerRadius (0) : *corner;
			}

			case Kind.AUDIOFORMAT: {
				UnmanagedAudioFormat *format = (UnmanagedAudioFormat*)value->u.p;
				return (format == null) ? new AudioFormat () : format->ToAudioFormat ();
			}

			case Kind.VIDEOFORMAT: {
				UnmanagedVideoFormat *format = (UnmanagedVideoFormat*)value->u.p;
				return (format == null) ? new VideoFormat () : format->ToVideoFormat ();
			}

			case Kind.THICKNESS: {
				Thickness *thickness = (Thickness*)value->u.p;
				return (thickness == null) ? new Thickness (0) : *thickness;
			}
					
			case Kind.COLOR: {
				UnmanagedColor *color = (UnmanagedColor*)value->u.p;
				if (color == null)
					return new Color ();
				return color->ToColor ();
			}

			case Kind.MATRIX:
			case Kind.UNMANAGEDMATRIX: {
				return new Matrix (value->u.p);
			}

			case Kind.MATRIX3D:
			case Kind.UNMANAGEDMATRIX3D: {
				return new Matrix3D (value->u.p);
			}

			case Kind.STYLUSPOINT:
			case Kind.UNMANAGEDSTYLUSPOINT: {
				var kind = value->k;
				var ptr = value->u.p;
				var x = (double) Value.ToObject (typeof (double), NativeMethods.dependency_object_get_value (ptr, kind, UnmanagedStylusPoint.XProperty.Native));
				var y = (double) Value.ToObject (typeof (double), NativeMethods.dependency_object_get_value (ptr, kind, UnmanagedStylusPoint.YProperty.Native));
				var pressure = (double) Value.ToObject (typeof (double), NativeMethods.dependency_object_get_value (ptr, kind, UnmanagedStylusPoint.PressureFactorProperty.Native));
				return new StylusPoint { X = x, Y = y, PressureFactor = (float) pressure };
			}

			case Kind.DURATION: {
				Duration* duration = (Duration*)value->u.p;
				return (duration == null) ? Duration.Automatic : *duration;
			}
					
			case Kind.KEYTIME: {
				KeyTime* keytime = (KeyTime*)value->u.p;
				return (keytime == null) ? KeyTime.FromTimeSpan (TimeSpan.Zero) : *keytime;
			}

			case Kind.GRIDLENGTH: {
				GridLength* gridlength = (GridLength*)value->u.p;
				return (gridlength == null) ? new GridLength () : *gridlength;
			}
					
			case Kind.REPEATBEHAVIOR: {
				RepeatBehavior *repeat = (RepeatBehavior*)value->u.p;
				return (repeat == null) ? new RepeatBehavior () : *repeat;
			}

			case Kind.MEDIAATTRIBUTE_COLLECTION: {
				MediaAttributeCollection attrs = (MediaAttributeCollection) NativeDependencyObjectHelper.Lookup (value->k, value->u.p);
				return attrs.AsDictionary ();
			}

			case Kind.MANAGEDTYPEINFO: {
				ManagedTypeInfo *type_info = (ManagedTypeInfo *) value->u.p;
				if (type_info == null)
					return null;
				return Deployment.Current.Types.KindToType (type_info->Kind);
			}
			default:
				Type tt = Deployment.Current.Types.KindToType (value->k);
				if (tt != null && tt.IsEnum)
					return Enum.ToObject (tt, value->u.i32);
				break;
			}

			if (NativeMethods.type_is_dependency_object (value->k)){
				if (value->u.p == IntPtr.Zero)
					return null;
					
				return NativeDependencyObjectHelper.Lookup (value->k, value->u.p);
			}

			throw new Exception (String.Format ("Do not know how to convert {0}  {1}. Managed type: {2}",
			                                    value->k, (int) value->k, Deployment.Current.Types.KindToType (value->k)));
		}
Пример #20
0
		static bool CheckSameSize(GlyphTypeface gtf) {
			double? width = null, height = null;
			for (char c = ' '; c <= (char)0x7E; c++) {
				ushort glyphIndex;
				if (!gtf.CharacterToGlyphMap.TryGetValue(c, out glyphIndex))
					return false;
				double w;
				if (!gtf.AdvanceWidths.TryGetValue(glyphIndex, out w))
					return false;
				if (width == null)
					width = w;
				else if (width.Value != w)
					return false;

				double h;
				if (!gtf.AdvanceHeights.TryGetValue(glyphIndex, out h))
					return false;
				if (height == null)
					height = h;
				else if (height.Value != h)
					return false;
			}
			return true;
		}
Пример #21
0
        /// <summary>
        /// Create a WPF GlyphTypeface and retrieve font data from it.
        /// </summary>
        internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions,
            out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey)
        {
            if (string.IsNullOrEmpty(typefaceKey))
                typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
            XFontStyle style = fontResolvingOptions.FontStyle;

#if DEBUG
            if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0
                && (style & XFontStyle.BoldItalic) == XFontStyle.Italic)
                familyName.GetType();
#endif

            // Use WPF technique to create font data.
            wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily);
#if DEBUG__
            if (wpfTypeface != null)
            {
                WpfGlyphTypeface glyphTypeface;
                ICollection<WpfTypeface> list = wpfFontFamily.GetTypefaces();
                foreach (WpfTypeface tf in list)
                {
                    if (!tf.TryGetGlyphTypeface(out glyphTypeface))
                        Debug-Break.Break();
                }

                //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface))
                //    throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }
#endif
            if (wpfFontFamily == null)
                wpfFontFamily = new WpfFontFamily(familyName);

            if (wpfTypeface == null)
                wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style);

            // Let WPF choose the right glyph typeface.
            if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
                throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));

            // Get or create the font source and cache it unter the specified typeface key.
            XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);
            return fontSource;
        }
        /// <summary>
        /// Fast text size calculation
        /// </summary>
        /// <param name="glyphTypeface">
        /// The glyph typeface.
        /// </param>
        /// <param name="sizeInEm">
        /// The size.
        /// </param>
        /// <param name="s">
        /// The text.
        /// </param>
        /// <returns>
        /// The text size.
        /// </returns>
        private static OxySize MeasureTextSize(GlyphTypeface glyphTypeface, double sizeInEm, string s)
        {
            double width = 0;
            double lineWidth = 0;
            int lines = 0;
            foreach (char ch in s)
            {
                switch (ch)
                {
                    case '\n':
                        lines++;
                        if (lineWidth > width)
                        {
                            width = lineWidth;
                        }

                        lineWidth = 0;
                        continue;
                    case '\t':
                        continue;
                }

                ushort glyph = glyphTypeface.CharacterToGlyphMap[ch];
                double advanceWidth = glyphTypeface.AdvanceWidths[glyph];
                lineWidth += advanceWidth;
            }

            lines++;
            if (lineWidth > width)
            {
                width = lineWidth;
            }

            return new OxySize(Math.Round(width * sizeInEm, 2), Math.Round(lines * glyphTypeface.Height * sizeInEm, 2));
        }
Пример #23
0
 public GlyphTypefaceWrapper(GlyphTypeface glyphTypeface)
 {
     this.glyphTypeface = glyphTypeface;
 }
        /// <summary>
        /// Width and height in terms of CELLS, not pixels.
        /// </summary>
        public WPFGlyphTypefaceViewer(int width, int height, Theme theme) : base(width, height, theme)
        {
            glyphTypeface = LoadTypeface("Consolas", 13, 7, 15);

            SetSize(width, height);
        }
Пример #25
0
 private void ExtractFont(string origin, int[] keeplist, string output)
 {
     GlyphTypeface gt = new GlyphTypeface(new Uri(origin));
     List<ushort> indexes = new List<ushort>();
     List<int> notexists = new List<int>();
     foreach (int c in keeplist)
     {
         if (gt.CharacterToGlyphMap.ContainsKey(c))
             indexes.Add(gt.CharacterToGlyphMap[c]);
         else
             notexists.Add(c);
     }
     if (notexists.Count > 0)
     {
         var sb = new StringBuilder();
         sb.AppendFormat(",但下列{0}个字符在原始字体文件中不存在:\r\n\r\n", notexists.Count);
         for (int i = 0; i < notexists.Count; ++i)
         {
             var c = Char.ConvertFromUtf32(notexists[i]);
             sb.AppendFormat("{0:X06}({1})", notexists[i], c);
             if ((i + 1) % 7 == 0)
                 sb.AppendLine();
             else
                 sb.Append('\t');
         }
         txtLog.AppendText(sb.ToString());
     }
     if (indexes.Count > 0 && output.Length > 0)
     {
         using (var stream = new System.IO.FileStream(output, System.IO.FileMode.Create))
         {
             var data = gt.ComputeSubset(indexes);
             stream.Write(data, 0, data.Length);
         }
     }
     txtLog.AppendText(string.Format("\r\n\r\n共提取{0}个字符", indexes.Count));
 }
Пример #26
0
        internal string GetFont(PDFResources resources, System.Windows.Media.GlyphTypeface typeFace)
        {
            string familyName = typeFace.FamilyNames.Values.FirstOrDefault();

            string faceName = familyName;

            var fn = typeFace.FaceNames.Where(x => x.Key.LCID == System.Globalization.CultureInfo.CurrentCulture.LCID).Select(x => x.Value).FirstOrDefault();

            if (!string.IsNullOrWhiteSpace(fn))
            {
                if (fn != "Regular")
                {
                    faceName += "," + fn;
                }
            }

            string key = null;

            if (!fonts.TryGetValue(faceName, out key))
            {
                key = "R" + resources.ID + "F" + fonts.Count;
                PDFFont pf = this.PDFDocument.CreateObject <PDFFont>();
                pf.BaseFont         = faceName;
                pf.Subtype          = "Type1";
                pf.Encoding         = "WinAnsiEncoding";
                resources.Font[key] = pf;

                //var pd = PDFDocument.CreateObject<PDFFontDescriptor>();

                //pf.FontDescriptor = pd;

                //pd.FontName = familyName;
                //pd.FontFamily = familyName;
                //pd.FontWeight = typeFace.Weight.ToOpenTypeWeight();


                //pd.XHeight = typeFace.XHeight;
                //pd.CapHeight = typeFace.CapsHeight;
                //pd.StemV = typeFace.StrikethroughThickness;

                //pd.Flags = PDFFontFlags.None;

                //if (typeFace.Weight == FontWeights.Bold)
                //{
                //    pd.Flags |= PDFFontFlags.ForceBold;
                //}

                //if (typeFace.Symbol)
                //{
                //    pd.Flags |= PDFFontFlags.Symbolic;
                //}
                //else
                //{
                //    pd.Flags |= PDFFontFlags.Nonsymbolic;
                //}
                //pd.Ascent = typeFace.AdvanceHeights.Select(x => x.Value).Max() - typeFace.Baseline;
                //pd.Descent = -(typeFace.DistancesFromHorizontalBaselineToBlackBoxBottom.Select(x => x.Value).Max());

                //pd.FontBBox = new PDFRect();
                //pd.FontBBox.Width = (int)typeFace.AdvanceWidths.Select(x => x.Value).Sum();
                //pd.FontBBox.Height = (int)typeFace.AdvanceHeights.Select(x => x.Value).Sum();

                fonts[faceName] = key;
            }
            return(key);
        }
Пример #27
0
        public static XGlyphTypeface GetOrCreateFrom(string familyName, FontResolvingOptions fontResolvingOptions)
        {
            // Check cache for requested type face.
            string         typefaceKey = ComputeKey(familyName, fontResolvingOptions);
            XGlyphTypeface glyphTypeface;

            if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
            {
                // Just return existing one.
                return(glyphTypeface);
            }

            // Resolve typeface by FontFactory.
            FontResolverInfo fontResolverInfo = FontFactory.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey);

            if (fontResolverInfo == null)
            {
                // No fallback - just stop.
                throw new InvalidOperationException("No appropriate font found.");
            }

#if CORE || GDI
            GdiFont gdiFont = null;
#endif
#if WPF
            WpfFontFamily    wpfFontFamily    = null;
            WpfTypeface      wpfTypeface      = null;
            WpfGlyphTypeface wpfGlyphTypeface = null;
#endif
#if UWP
            // Nothing to do.
#endif
            // Now create the font family at the first.
            XFontFamily fontFamily;
            PlatformFontResolverInfo platformFontResolverInfo = fontResolverInfo as PlatformFontResolverInfo;
            if (platformFontResolverInfo != null)
            {
#if CORE || GDI
                // $TODO THHO Lock???
                // Reuse GDI+ font from platform font resolver.
                gdiFont    = platformFontResolverInfo.GdiFont;
                fontFamily = XFontFamily.GetOrCreateFromGdi(gdiFont);
#endif
#if WPF
#if !SILVERLIGHT
                // Reuse WPF font family created from platform font resolver.
                wpfFontFamily    = platformFontResolverInfo.WpfFontFamily;
                wpfTypeface      = platformFontResolverInfo.WpfTypeface;
                wpfGlyphTypeface = platformFontResolverInfo.WpfGlyphTypeface;
                fontFamily       = XFontFamily.GetOrCreateFromWpf(wpfFontFamily);
#else
                fontFamily = XFontFamily.GetOrCreateFromWpf(new WpfFontFamily(familyName));
#endif
#endif
#if NETFX_CORE || UWP
                fontFamily = null;
#endif
            }
            else
            {
                // Create new and exclusively used font family for custom font resolver retrieved font source.
                fontFamily = XFontFamily.CreateSolitary(fontResolverInfo.FaceName);
            }

            // We have a valid font resolver info. That means we also have an XFontSource object loaded in the cache.
            ////XFontSource fontSource = FontFactory.GetFontSourceByTypefaceKey(fontResolverInfo.FaceName);
            XFontSource fontSource = FontFactory.GetFontSourceByFontName(fontResolverInfo.FaceName);
            Debug.Assert(fontSource != null);

            // Each font source already contains its OpenTypeFontface.
#if CORE || GDI
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, gdiFont);
#endif
#if WPF
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, wpfTypeface, wpfGlyphTypeface);
#endif
#if NETFX_CORE || UWP
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations);
#endif
#if __IOS__
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontSource);
#endif
            glyphTypeface = new XGlyphTypeface(typefaceKey, fontSource);
            GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface);

            return(glyphTypeface);
        }
Пример #28
0
		public static Header header;//only keps to get access to other tables. In later versions I don't think the method such as GetAdvanceWidth should be in this table. (or it should be but shouldn't depend on other tables)
		public static void Initialize(string absolutePath)
		{
			typeface = new GlyphTypeface(new Uri(absolutePath, UriKind.Absolute));
		}
Пример #29
0
 private static double GetAdvanceWidth(GlyphTypeface glyphTypeface, ushort glyphIndex, bool sideways)
 {
     double advance = sideways ? glyphTypeface.AdvanceHeights[glyphIndex] : glyphTypeface.AdvanceWidths[glyphIndex]; 
     return advance * EmMultiplier;
 } 
        public bool TryGetGlyphTypeface(out GlyphTypeface glyphTypeface)
        {
            glyphTypeface = default(GlyphTypeface);

            return(default(bool));
        }
Пример #31
0
        // ------------------------------------------------------------------------------
        // Parses a semicolon-delimited list of glyph specifiers, each of which consists 
        // of up to 4 comma-delimited values:
        //   - glyph index (ushort)
        //   - glyph advance (double)
        //   - glyph offset X (double) 
        //   - glyph offset Y (double)
        // A glyph entry can be have a cluster size prefix (int or pair of ints separated by a colon) 
        // Whitespace adjacent to a delimiter (comma or semicolon) is ignored. 
        // Returns the number of glyph specs parsed (number of semicolons plus 1).
        // 


        private int ParseGlyphsProperty(
            GlyphTypeface               fontFace, 
            string                      unicodeString,
            bool                        sideways, 
            out List<ParsedGlyphData>   parsedGlyphs, 
            out ushort[]                clusterMap)
        { 
            string glyphsProp = Indices;

            // init for the whole parse, including the result arrays
            int parsedGlyphCount = 0; 
            int parsedCharacterCount = 0;
 
            int characterClusterSize = 1; 
            int glyphClusterSize = 1;
 
            bool inCluster = false;

            // make reasonable capacity guess on how many glyphs we can expect
            int estimatedNumberOfGlyphs; 

            if (!String.IsNullOrEmpty(unicodeString)) 
            { 
                clusterMap = new ushort[unicodeString.Length];
                estimatedNumberOfGlyphs = unicodeString.Length; 
            }
            else
            {
                clusterMap = null; 
                estimatedNumberOfGlyphs = 8;
            } 
 
            if (!String.IsNullOrEmpty(glyphsProp))
                estimatedNumberOfGlyphs = Math.Max(estimatedNumberOfGlyphs, glyphsProp.Length / 5); 

            parsedGlyphs = new List<ParsedGlyphData>(estimatedNumberOfGlyphs);

            ParsedGlyphData parsedGlyphData = new ParsedGlyphData(); 

            #region Parse Glyphs string 
            if (!String.IsNullOrEmpty(glyphsProp)) 
            {
                // init per-glyph values for the first glyph/position 
                int valueWithinGlyph = 0; // which value we're on (how many commas have we seen in this glyph)?
                int valueStartIndex = 0; // where (what index of Glyphs prop string) did this value start?

                // iterate and parse the characters of the Indices property 
                for (int i = 0; i <= glyphsProp.Length; i++)
                { 
                    // get next char or pseudo-terminator 
                    char c = i < glyphsProp.Length ? glyphsProp[i] : '\0';
 
                    // finished scanning the current per-glyph value?
                    if ((c == ',') || (c == ';') || (i == glyphsProp.Length))
                    {
                        int len = i - valueStartIndex; 

                        string valueSpec = glyphsProp.Substring(valueStartIndex, len); 
 
                        #region Interpret one comma-delimited value
 
                        switch (valueWithinGlyph)
                        {
                            case 0:
                                bool wasInCluster = inCluster; 
                                // interpret cluster size and glyph index spec
                                if (!ReadGlyphIndex( 
                                    valueSpec, 
                                    ref inCluster,
                                    ref glyphClusterSize, 
                                    ref characterClusterSize,
                                    ref parsedGlyphData.glyphIndex))
                                {
                                    if (String.IsNullOrEmpty(unicodeString)) 
                                        throw new ArgumentException(SR.Get(SRID.GlyphsIndexRequiredIfNoUnicode));
 
                                    if (unicodeString.Length <= parsedCharacterCount) 
                                        throw new ArgumentException(SR.Get(SRID.GlyphsUnicodeStringIsTooShort));
 
                                    parsedGlyphData.glyphIndex = GetGlyphFromCharacter(fontFace, unicodeString[parsedCharacterCount]);
                                }

                                if (!wasInCluster && clusterMap != null) 
                                {
                                    // fill out cluster map at the start of each cluster 
                                    if (inCluster) 
                                    {
                                        for (int ch = parsedCharacterCount; ch < parsedCharacterCount + characterClusterSize; ++ch) 
                                        {
                                            SetClusterMapEntry(clusterMap, ch, (ushort)parsedGlyphCount);
                                        }
                                    } 
                                    else
                                    { 
                                        SetClusterMapEntry(clusterMap, parsedCharacterCount, (ushort)parsedGlyphCount); 
                                    }
                                } 
                                parsedGlyphData.advanceWidth = GetAdvanceWidth(fontFace, parsedGlyphData.glyphIndex, sideways);
                                break;

                            case 1: 
                                // interpret glyph advance spec
                                if (!IsEmpty(valueSpec)) 
                                { 
                                    parsedGlyphData.advanceWidth = double.Parse(valueSpec, CultureInfo.InvariantCulture);
                                    if (parsedGlyphData.advanceWidth < 0) 
                                        throw new ArgumentException(SR.Get(SRID.GlyphsAdvanceWidthCannotBeNegative));
                                }
                                break;
 
                            case 2:
                                // interpret glyph offset X 
                                if (!IsEmpty(valueSpec)) 
                                    parsedGlyphData.offsetX = double.Parse(valueSpec, CultureInfo.InvariantCulture);
                                break; 

                            case 3:
                                // interpret glyph offset Y
                                if (!IsEmpty(valueSpec)) 
                                    parsedGlyphData.offsetY = double.Parse(valueSpec, CultureInfo.InvariantCulture);
                                break; 
 
                            default:
                                // too many commas; can't interpret 
                                throw new ArgumentException(SR.Get(SRID.GlyphsTooManyCommas));
                        }
                        #endregion Interpret one comma-delimited value
 
                        // prepare to scan next value (if any)
                        valueWithinGlyph++; 
                        valueStartIndex = i + 1; 
                    }
 
                    // finished processing the current glyph?
                    if ((c == ';') || (i == glyphsProp.Length))
                    {
                        parsedGlyphs.Add(parsedGlyphData); 
                        parsedGlyphData = new ParsedGlyphData();
 
                        if (inCluster) 
                        {
                            --glyphClusterSize; 
                            // when we reach the end of a glyph cluster, increment character index
                            if (glyphClusterSize == 0)
                            {
                                parsedCharacterCount += characterClusterSize; 
                                inCluster = false;
                            } 
                        } 
                        else
                        { 
                            ++parsedCharacterCount;
                        }
                        parsedGlyphCount++;
 
                        // initalize new per-glyph values
                        valueWithinGlyph = 0; // which value we're on (how many commas have we seen in this glyph)? 
                        valueStartIndex = i + 1; // where (what index of Glyphs prop string) did this value start? 
                    }
                } 
            }
            #endregion

            // fill the remaining glyphs with defaults, assuming 1:1 mapping 
            if (unicodeString != null)
            { 
                while (parsedCharacterCount < unicodeString.Length) 
                {
                    if (inCluster) 
                        throw new ArgumentException(SR.Get(SRID.GlyphsIndexRequiredWithinCluster));

                    if (unicodeString.Length <= parsedCharacterCount)
                        throw new ArgumentException(SR.Get(SRID.GlyphsUnicodeStringIsTooShort)); 

                    parsedGlyphData.glyphIndex = GetGlyphFromCharacter(fontFace, unicodeString[parsedCharacterCount]); 
                    parsedGlyphData.advanceWidth = GetAdvanceWidth(fontFace, parsedGlyphData.glyphIndex, sideways); 
                    parsedGlyphs.Add(parsedGlyphData);
                    parsedGlyphData = new ParsedGlyphData(); 
                    SetClusterMapEntry(clusterMap, parsedCharacterCount, (ushort)parsedGlyphCount);
                    ++parsedCharacterCount;
                    ++parsedGlyphCount;
                } 
            }
 
            // return number of glyphs actually specified 
            return parsedGlyphCount;
        } 
Пример #32
0
		public FontSource (GlyphTypeface glyphTypeface)
		{
			type = FontSourceType.GlyphTypeface;
			typeface = glyphTypeface;
		}
Пример #33
0
        private void resetPages()
        {
            pg2.Dispose();
            pg2 = null;		// Need to set it back to null!
            pg3.Dispose();
            pg3 = null;

            cqIDX = 0;
            bookAndAuthor.Clear();
            TOC.Clear();
            extraLinesInBeginning = false;
            extraLinesNotEmpty = false;
            titleLineNumbers.Clear();
            pictureHTMLs.Clear();
            TXTPath = null;
            CoverPath = null;
            CoverPathSlim = null;
            covers[0].Dispose();
            covers[1].Dispose();
            origCover = null;
            coverChanged = true;
            DocName = null;
            Intro = null;
            chapterNumber = 1;
            parchmentNeeded = false;
            embedFontPaths.Clear();
            ALLTITLETEXT.Clear();
            ALLBODYTEXT = new HashSet<Char>();
            IndexT = new List<UInt16>();
            IndexB = new List<UInt16>();
            titleFontPath = null;
            bodyFontPath = null;
            glyphTypefaceT = null;
            glyphTypefaceB = null;
            URIT = null;
            URIB = null;
            wordcount = 0;
            wordcountnr = 0;
            noNeedEmbed = false;
            mimetype = null;
            container = null;
            css.Clear();
            opf.Clear();
            ncx.Clear();
            coverHtml.Clear();
            picHtmlList.Clear();
            txtHtmlList.Clear();
            zipPath = null;
            processedIntro = null;
            stopWatch = null;
            DONE = false;
        }
Пример #34
0
        public string GetFontFileName(DirectoryInfo dir, Font2 fontNameToSearch)
        {
            string fileNameToReturn = "";

            FileInfo[] files = dir.GetFiles("*.ttf");

            foreach (FileInfo file in files)
            {
                GlyphTypeface gtf = new GlyphTypeface(new Uri(file.FullName));
                //Found Name Font for iPhone compatibility

                foreach (System.Globalization.CultureInfo keys in gtf.FamilyNames.Keys)
                {
                    string name = gtf.FamilyNames[keys].ToString();
                    if (name.Equals(fontNameToSearch.FamilyName))
                    {
                        string styleName = fontNameToSearch.Style.ToString();
                        if (gtf.FaceNames.Values.Contains(styleName))
                            return file.FullName;

                    }

                }

            }
            /*foreach (FileInfo file in files)
            {
                FileStream fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
                BinaryReader r = new BinaryReader(fs);
                byte[] buff = r.ReadBytes(Marshal.SizeOf(ttOffsetTable));
                buff = BigEndian(buff);
                IntPtr ptr = Marshal.AllocHGlobal(buff.Length);
                Marshal.Copy(buff, 0x0, ptr, buff.Length);
                TT_OFFSET_TABLE ttResult = (TT_OFFSET_TABLE)Marshal.PtrToStructure(ptr, typeof(TT_OFFSET_TABLE));
                Marshal.FreeHGlobal(ptr);

                //Must be maj =1 minor = 0
                if (ttResult.uMajorVersion != 1 || ttResult.uMinorVersion != 0)
                {
                    r.Close();
                    r.Dispose();
                    fs.Close();
                    fs.Dispose();
                    continue;
                }

                bool bFound = false;
                TT_TABLE_DIRECTORY tbName = new TT_TABLE_DIRECTORY();
                for (int i = 0; i < ttResult.uNumOfTables; i++)
                {
                    byte[] bNameTable = r.ReadBytes(Marshal.SizeOf(tblDir));
                    IntPtr ptrName = Marshal.AllocHGlobal(bNameTable.Length);
                    Marshal.Copy(bNameTable, 0x0, ptrName, bNameTable.Length);
                    tbName = (TT_TABLE_DIRECTORY)Marshal.PtrToStructure(ptrName, typeof(TT_TABLE_DIRECTORY));
                    Marshal.FreeHGlobal(ptrName);
                    string szName = tbName.szTag1.ToString() + tbName.szTag2.ToString() + tbName.szTag3.ToString() + tbName.szTag4.ToString();
                    if (szName != null)
                    {
                        if (szName.ToString() == "name")
                        {
                            bFound = true;
                            byte[] btLength = BitConverter.GetBytes(tbName.uLength);
                            byte[] btOffset = BitConverter.GetBytes(tbName.uOffset);
                            Array.Reverse(btLength);
                            Array.Reverse(btOffset);
                            tbName.uLength = BitConverter.ToUInt32(btLength, 0);
                            tbName.uOffset = BitConverter.ToUInt32(btOffset, 0);
                            break;
                        }
                    }
                }
                if (bFound)
                {
                    fs.Position = tbName.uOffset;
                    byte[] btNTHeader = r.ReadBytes(Marshal.SizeOf(ttNTHeader));
                    btNTHeader = BigEndian(btNTHeader);
                    IntPtr ptrNTHeader = Marshal.AllocHGlobal(btNTHeader.Length);
                    Marshal.Copy(btNTHeader, 0x0, ptrNTHeader, btNTHeader.Length);
                    TT_NAME_TABLE_HEADER ttNTResult = (TT_NAME_TABLE_HEADER)Marshal.PtrToStructure(ptrNTHeader, typeof(TT_NAME_TABLE_HEADER));
                    Marshal.FreeHGlobal(ptrNTHeader);
                    bFound = false;
                    for (int i = 0; i < ttNTResult.uNRCount; i++)
                    {
                        byte[] btNMRecord = r.ReadBytes(Marshal.SizeOf(ttNMRecord));
                        btNMRecord = BigEndian(btNMRecord);
                        IntPtr ptrNMRecord = Marshal.AllocHGlobal(btNMRecord.Length);
                        Marshal.Copy(btNMRecord, 0x0, ptrNMRecord, btNMRecord.Length);
                        TT_NAME_RECORD ttNMResult = (TT_NAME_RECORD)Marshal.PtrToStructure(ptrNMRecord, typeof(TT_NAME_RECORD));
                        Marshal.FreeHGlobal(ptrNMRecord);
                        if (ttNMResult.uNameID == 1)
                        {
                            long fPos = fs.Position;
                            fs.Position = tbName.uOffset + ttNMResult.uStringOffset + ttNTResult.uStorageOffset;
                            char[] szResult = r.ReadChars(ttNMResult.uStringLength);
                            if (szResult.Length != 0)
                            {
                                string name = new string(szResult);
                                if (name.Equals(fontNameToSearch))
                                {
                                    int y = 0;//szResult now contains the font name.

                                    r.Close();
                                    r.Dispose();
                                    fs.Close();
                                    fs.Dispose();

                                    return file.FullName;
                                }
                            }
                        }
                    }
                }

                r.Close();
                r.Dispose();
                fs.Close();
                fs.Dispose();

            }*/

            return fileNameToReturn;
        }
 public GlyphRun(GlyphTypeface glyphTypeface, int bidiLevel, bool isSideways, double renderingEmSize, IList <ushort> glyphIndices, System.Windows.Point baselineOrigin, IList <double> advanceWidths, IList <System.Windows.Point> glyphOffsets, IList <char> characters, string deviceFontName, IList <ushort> clusterMap, IList <bool> caretStops, System.Windows.Markup.XmlLanguage language)
 {
 }
    public bool TryGetGlyphTypeface(out GlyphTypeface glyphTypeface)
    {
      glyphTypeface = default(GlyphTypeface);

      return default(bool);
    }
Пример #37
0
 internal ScaledShapeTypeface(
     GlyphTypeface           glyphTypeface,
     IDeviceFont             deviceFont,
     double                  scaleInEm,
     bool                    nullShape
     )
 {
     _shapeTypeface = new ShapeTypeface(glyphTypeface, deviceFont);
     _scaleInEm = scaleInEm;
     _nullShape = nullShape;
 }
Пример #38
0
 /// <summary>
 /// Obtain a glyph typeface that corresponds to the Typeface object constructed from an OpenType font family.
 /// If the Typeface was constructed from a composite font family, returns null.
 /// </summary>
 /// <param name="glyphTypeface">GlyphTypeface object that corresponds to this Typeface, or null if the Typeface
 /// was constructed from a composite font.</param>
 /// <returns>Whether glyphTypeface is not null.</returns>
 public bool TryGetGlyphTypeface(out GlyphTypeface glyphTypeface)
 {
     glyphTypeface = CachedTypeface.TypefaceMetrics as GlyphTypeface;
     return(glyphTypeface != null);
 }
Пример #39
0
			private static char[] GetDisplayText(GlyphTypeface glyphTypeFace)
			{
				string text = glyphTypeFace.SampleTexts[System.Globalization.CultureInfo.CurrentUICulture];
				if (!string.IsNullOrEmpty(text))
					return text.ToCharArray();

				// else use the default characters, but test if they are present in the typeface
				var chars = new List<char>();
				for (int i = 0; i < _defaultChars.Length && chars.Count < 4; i++)
				{
					var c = _defaultChars[i];
					if (glyphTypeFace.CharacterToGlyphMap.ContainsKey(c))
						chars.Add(c);
				}
				return chars.ToArray();
			}
Пример #40
0
        protected bool RenderText(String text, DrawingContext dc, GlyphTypeface glyphType, double fontSize, double maxWidth, double maxHeight, double x, double y, ref double useHeight)
        {
            if (maxHeight < fontSize + 2)
            {
                useHeight = 0;
                return false;
            }
            double totalHeight = 0;

            string[] lineText = text.Replace("\r", "").Split('\n');
            foreach (string line in lineText)
            {
                totalHeight += Math.Floor(2 + fontSize);
                List<ushort> glyphIndexes = new List<ushort>();
                List<double> advanceWidths = new List<double>();
                double totalWidth = 0;
                for (int n = 0; n < line.Length; n++)
                {
                    ushort glyphIndex = glyphType.CharacterToGlyphMap[line[n]];
                    double width = glyphType.AdvanceWidths[glyphIndex] * fontSize;
                    if (totalWidth + width > maxWidth)
                    {
                        if (totalHeight + fontSize > maxHeight)
                        {
                            //次の行無理
                            glyphIndex = glyphType.CharacterToGlyphMap['…'];
                            glyphIndexes[glyphIndexes.Count - 1] = glyphIndex;
                            advanceWidths[advanceWidths.Count - 1] = width;

                            Point origin = new Point(x + 2, y + totalHeight);
                            GlyphRun glyphRun = new GlyphRun(glyphType, 0, false, fontSize,
                                glyphIndexes, origin, advanceWidths, null, null, null, null,
                                null, null);

                            dc.DrawGlyphRun(Brushes.Black, glyphRun);

                            useHeight = totalHeight;
                            return false;
                        }
                        else
                        {
                            //次の行いけるので今までの分出力
                            //次の行いける
                            Point origin = new Point(x + 2, y + totalHeight);
                            GlyphRun glyphRun = new GlyphRun(glyphType, 0, false, fontSize,
                                glyphIndexes, origin, advanceWidths, null, null, null, null,
                                null, null);

                            dc.DrawGlyphRun(Brushes.Black, glyphRun);
                            totalHeight += fontSize + 2;
                            glyphIndexes = new List<ushort>();
                            advanceWidths = new List<double>();
                            totalWidth = 0;
                        }
                    }
                    glyphIndexes.Add(glyphIndex);
                    advanceWidths.Add(width);
                    totalWidth += width;
                }
                if (glyphIndexes.Count > 0)
                {
                    Point origin = new Point(x + 2, y + totalHeight);
                    GlyphRun glyphRun = new GlyphRun(glyphType, 0, false, fontSize,
                        glyphIndexes, origin, advanceWidths, null, null, null, null,
                        null, null);

                    dc.DrawGlyphRun(Brushes.Black, glyphRun);
                }
                //高さ確認
                if (totalHeight + fontSize > maxHeight)
                {
                    //これ以上は無理
                    useHeight = totalHeight;
                    return false;
                }

            }
            useHeight = Math.Floor(totalHeight);
            return true;
        }
Пример #41
0
        public void Init(Ioctls ioctls, Core core, Runtime runtime)
        {
            ioctls.maFontGetCount = delegate()
            {
                int count = 0;
                MoSync.Util.RunActionOnMainThreadSync(() => count = System.Windows.Media.Fonts.SystemTypefaces.Count);
                return count;
            };

            ioctls.maFontGetName = delegate(int _index, int _buffer, int _bufferLen)
            {
                if (_index > ioctls.maFontGetCount())
                {
                    return MoSync.Constants.RES_FONT_INDEX_OUT_OF_BOUNDS;
                }
                else
                {
                    String fontName = "";
                    MoSync.Util.RunActionOnMainThreadSync(() =>
                    {
                        int count = 0;
                        System.Collections.Generic.IEnumerator<Typeface> en = System.Windows.Media.Fonts.SystemTypefaces.GetEnumerator();
                        while (count < _index)
                        {
                            en.MoveNext();
                            count++;
                        }
                        System.Windows.Media.Typeface currentTypeFace = en.Current;
                        System.Windows.Media.GlyphTypeface currentGlyph;
                        currentTypeFace.TryGetGlyphTypeface(out currentGlyph);
                        fontName = currentGlyph.FontFileName;
                        fontName = (fontName.Split('.'))[0];
                    });

                    if (fontName.Length > _bufferLen) return MoSync.Constants.RES_FONT_INSUFFICIENT_BUFFER;
                    core.GetDataMemory().WriteStringAtAddress(_buffer, fontName, _bufferLen);
                    return MoSync.Constants.RES_FONT_OK;
                }
            };

            ioctls.maFontLoadWithName = delegate(int _postScriptName, int _size)
            {

                String fontName = core.GetDataMemory().ReadStringAtAddress(_postScriptName);
                Typeface typeface = null;
                GlyphTypeface glyphTypeface = null;
                MoSync.Util.RunActionOnMainThreadSync(() =>
                {
                    int count = Fonts.SystemTypefaces.Count;
                    System.Collections.Generic.IEnumerator<Typeface> en = Fonts.SystemTypefaces.GetEnumerator();
                    while (count != 0)
                    {
                        typeface = en.Current;
                        if (typeface.TryGetGlyphTypeface(out glyphTypeface))
                        {
                            if (glyphTypeface.FontFileName.StartsWith(fontName))
                            {
                                break;
                            }
                        }
                        en.MoveNext();
                        count--;
                    }
                });

                if (glyphTypeface == null) return -2;

                mFonts.Add(glyphTypeface);
                return mFonts.Count - 1;
            };

            ioctls.maFontLoadDefault = delegate(int _type, int _style, int _size)
            {

                //RES_FONT_NO_TYPE_STYLE_COMBINATION
                //RES_FONT_INVALID_SIZE

                switch (_type)
                {
                    case MoSync.Constants.FONT_TYPE_MONOSPACE:
                        break;
                    case MoSync.Constants.FONT_TYPE_SERIF:
                        break;
                    case MoSync.Constants.FONT_TYPE_SANS_SERIF:
                        break;
                    default:
                        return MoSync.Constants.RES_FONT_NO_TYPE_STYLE_COMBINATION;
                }

                return 0;
            };

            ioctls.maFontSetCurrent = delegate(int _font)
            {
                mCurrentFont = mFonts[_font];
                mCurrentFontSource = new System.Windows.Documents.FontSource(mCurrentFont);
                return 0;
            };
        }
 public GlyphRun(GlyphTypeface glyphTypeface, int bidiLevel, bool isSideways, double renderingEmSize, IList<ushort> glyphIndices, System.Windows.Point baselineOrigin, IList<double> advanceWidths, IList<System.Windows.Point> glyphOffsets, IList<char> characters, string deviceFontName, IList<ushort> clusterMap, IList<bool> caretStops, System.Windows.Markup.XmlLanguage language)
 {
 }
Пример #43
0
        public static XGlyphTypeface GetOrCreateFrom(string familyName, FontResolvingOptions fontResolvingOptions)
        {
            // Check cache for requested type face.
            string         typefaceKey = ComputeKey(familyName, fontResolvingOptions);
            XGlyphTypeface glyphTypeface;

            try
            {
                // Lock around TryGetGlyphTypeface and AddGlyphTypeface.
                Lock.EnterFontFactory();
                if (GlyphTypefaceCache.TryGetGlyphTypeface(typefaceKey, out glyphTypeface))
                {
                    // Just return existing one.
                    return(glyphTypeface);
                }

                // Resolve typeface by FontFactory.
                FontResolverInfo fontResolverInfo = FontFactory.ResolveTypeface(familyName, fontResolvingOptions, typefaceKey);
                if (fontResolverInfo == null)
                {
                    // No fallback - just stop.
                    throw new InvalidOperationException("No appropriate font found.");
                }

#if CORE && !WITHOUT_DRAWING || GDI
                GdiFont gdiFont = null;
#endif
#if WPF
                WpfFontFamily    wpfFontFamily    = null;
                WpfTypeface      wpfTypeface      = null;
                WpfGlyphTypeface wpfGlyphTypeface = null;
#endif
#if UWP
                // Nothing to do.
#endif
                // Now create the font family at the first.
                XFontFamily fontFamily;
#if !WITHOUT_DRAWING
                PlatformFontResolverInfo platformFontResolverInfo = fontResolverInfo as PlatformFontResolverInfo;
                if (platformFontResolverInfo != null)
                {
                    // Case: fontResolverInfo was created by platform font resolver
                    // and contains platform specific objects that are reused.
#if CORE || GDI
                    // Reuse GDI+ font from platform font resolver.
                    gdiFont    = platformFontResolverInfo.GdiFont;
                    fontFamily = XFontFamily.GetOrCreateFromGdi(gdiFont);
#endif
#if WPF
#if !SILVERLIGHT
                    // Reuse WPF font family created from platform font resolver.
                    wpfFontFamily    = platformFontResolverInfo.WpfFontFamily;
                    wpfTypeface      = platformFontResolverInfo.WpfTypeface;
                    wpfGlyphTypeface = platformFontResolverInfo.WpfGlyphTypeface;
                    fontFamily       = XFontFamily.GetOrCreateFromWpf(wpfFontFamily);
#else
                    fontFamily = XFontFamily.GetOrCreateFromWpf(new WpfFontFamily(familyName));
#endif
#endif
#if NETFX_CORE || UWP
                    fontFamily = null;
#endif
                }
                else
#endif
                {
                    // Case: fontResolverInfo was created by custom font resolver.

                    // Get or create font family for custom font resolver retrieved font source.
                    fontFamily = XFontFamily.GetOrCreateFontFamily(familyName);
                }

                // We have a valid font resolver info. That means we also have an XFontSource object loaded in the cache.
                XFontSource fontSource = FontFactory.GetFontSourceByFontName(fontResolverInfo.FaceName);
                Debug.Assert(fontSource != null);

                // Each font source already contains its OpenTypeFontface.

#if CORE || GDI
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations
#if !WITHOUT_DRAWING
                                                   , gdiFont
#endif
                                                   );
#endif
#if WPF
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations, wpfTypeface, wpfGlyphTypeface);
#endif
#if NETFX_CORE || UWP
                glyphTypeface = new XGlyphTypeface(typefaceKey, fontFamily, fontSource, fontResolverInfo.StyleSimulations);
#endif
                GlyphTypefaceCache.AddGlyphTypeface(glyphTypeface);
            }
            finally { Lock.ExitFontFactory(); }
            return(glyphTypeface);
        }
Пример #44
0
 private ushort GetGlyphFromCharacter(GlyphTypeface glyphTypeface, char character)
 { 
     ushort glyphIndex;
     // TryGetValue will return zero glyph index for missing code points,
     // which is the right thing to display per http://www.microsoft.com/typography/otspec/cmap.htm
     glyphTypeface.CharacterToGlyphMap.TryGetValue(character, out glyphIndex); 
     return glyphIndex;
 } 
Пример #45
0
        public Boolean LoadFont()
        {
            if (this.OriginalPath.Equals("")) return false;
            if (File.Exists(this.OriginalPath))
            {
               /* string fontsfolder = System.Environment.GetFolderPath(
                                            System.Environment.SpecialFolder.Fonts);

                string fileDest = fontsfolder+ "\\" + this.OriginalPath.Substring(this.OriginalPath.LastIndexOf("\\")+1);
                File.Copy(this.OriginalPath,fileDest, true);
                if (File.Exists(fileDest))
                    Console.Write("");*/
                //Load Font in memory
                Uri font = null;
                GlyphTypeface gtf = null;
                try
                {
                    FileInfo info = new FileInfo(this.OriginalPath);

                    font = new Uri(info.FullName);
                    gtf = new GlyphTypeface(font);

                    if (gtf != null)
                    {
                        //Found Name Font for iPhone compatibility
                        foreach (System.Globalization.CultureInfo keys in gtf.FamilyNames.Keys)
                        {
                            this.NameForIphone = gtf.FamilyNames[keys].ToString();

                        }

                        //Load FileName as Android compatibility
                        FileInfo fi = new FileInfo(this.OriginalPath);
                        this.NameForAndroid = fi.Name.Replace(".ttf", "");
                        fi = null;

                        gtf = null;
                        return true;
                    }

                    if (!this.IsFontInstalled())
                    {
                        MessageBox.Show("The True Type Font file \""+ this.NameForIphone+"\" does not seem to be installed on this computer!\n Please close Krea then install the font before using it!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                        return false;
                    }

                }
                catch
                {
                    MessageBox.Show("The True Type Font file \"" + this.NameForIphone + "\" does not seem to be installed on this computer!\n Please close Krea then install the font before using it!", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                    return false;
                }

                gtf = null;
                return false;
            }
            return false;
        }
        /// <summary>
        /// Create a WPF GlyphTypeface and retrieve font data from it.
        /// </summary>
        internal static XFontSource CreateFontSource(string familyName, FontResolvingOptions fontResolvingOptions,
                                                     out WpfFontFamily wpfFontFamily, out WpfTypeface wpfTypeface, out WpfGlyphTypeface wpfGlyphTypeface, string typefaceKey)
        {
            if (string.IsNullOrEmpty(typefaceKey))
            {
                typefaceKey = XGlyphTypeface.ComputeKey(familyName, fontResolvingOptions);
            }
            XFontStyle style = fontResolvingOptions.FontStyle;

#if DEBUG
            if (StringComparer.OrdinalIgnoreCase.Compare(familyName, "Segoe UI Semilight") == 0 &&
                (style & XFontStyle.BoldItalic) == XFontStyle.Italic)
            {
                familyName.GetType();
            }
#endif

            // Use WPF technique to create font data.
            wpfTypeface = XPrivateFontCollection.TryCreateTypeface(familyName, style, out wpfFontFamily);
#if DEBUG__
            if (wpfTypeface != null)
            {
                WpfGlyphTypeface          glyphTypeface;
                ICollection <WpfTypeface> list = wpfFontFamily.GetTypefaces();
                foreach (WpfTypeface tf in list)
                {
                    if (!tf.TryGetGlyphTypeface(out glyphTypeface))
                    {
                        Debug - Break.Break();
                    }
                }

                //if (!WpfTypeface.TryGetGlyphTypeface(out glyphTypeface))
                //    throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }
#endif
            if (wpfFontFamily == null)
            {
                wpfFontFamily = new WpfFontFamily(familyName);
            }

            if (wpfTypeface == null)
            {
                wpfTypeface = FontHelper.CreateTypeface(wpfFontFamily, style);
            }

            // Let WPF choose the right glyph typeface.
            if (!wpfTypeface.TryGetGlyphTypeface(out wpfGlyphTypeface))
            {
                throw new InvalidOperationException(PSSR.CannotGetGlyphTypeface(familyName));
            }

            // Get or create the font source and cache it unter the specified typeface key.
            XFontSource fontSource = XFontSource.GetOrCreateFromWpf(typefaceKey, wpfGlyphTypeface);
            return(fontSource);
        }
Пример #47
0
        private void generateEpub()
        {
            picHtmlList.Clear();
            txtHtmlList.Clear();
            embedFontPaths.Clear();
            ALLBODYTEXT.Clear();
            ALLTITLETEXT.Clear();
            IndexT.Clear();
            IndexB.Clear();
            glyphTypefaceT = new GlyphTypeface();
            glyphTypefaceB = new GlyphTypeface();
            coverHtml.Clear();
            css.Clear();
            opf.Clear();
            ncx.Clear();

            if (TXTPath == null)
            {
                MessageBoxEx.Show(LANG.getString("mainpage3_generateEpub_no_file"));
                return;
            }

            stopWatch = new Stopwatch();
            stopWatch.Start();

            if (DONE)
            {
                if (!coverChanged)
                {
                    deleteAllTempFiles();
                }
                DONE = false;
            }
            if (origCover != null && !File.Exists(CoverPath) && !File.Exists(CoverPathSlim))
            {
                generateCoverFromFilePath();
            }

            /*** Load new TOC ***/
            Boolean validTOC = loadNewTOC();
            if (!validTOC) return;

            /*** Load new Intro ***/
            Intro = pg1.cover_intro_textbox.Text;
            if (Intro != "")
            {
                Intro = "&lt;span class=\"Apple-style-span\"&gt;" + Intro + "&lt;/span&gt;";
                if (Intro.Contains("\r\n"))
                {
                    Intro = Intro.Replace("\r\n", "&lt;/span&gt;&lt;br/&gt;&lt;span class=\"Apple-style-span\"&gt;");
                }
            }

            /*** Load settings ***/
            Int32 translation = translationState(stsObj.StT, stsObj.TtS);
            String temp1 = bookAndAuthor[0];
            String temp2 = bookAndAuthor[1];
            bookAndAuthor.Clear();
            bookAndAuthor.Add(translate(temp1, translation));
            bookAndAuthor.Add(translate(temp2, translation));

            if (stsObj.embedFontSubset)
            {
                titleFontPath = FontNameFile.getFontFileName(stsObj.titleFont);
                if (titleFontPath.CompareTo("") == 0)
                    MessageBoxEx.Show(LANG.getString("mainpage3_generateEpub_title_not_ttf"));
                else
                {
                    URIT = new Uri(titleFontPath);
                    glyphTypefaceT = new GlyphTypeface(URIT);
                }
                bodyFontPath = FontNameFile.getFontFileName(stsObj.bodyFont);
                if (bodyFontPath.CompareTo("") == 0)
                    MessageBoxEx.Show(LANG.getString("mainpage3_generateEpub_body_not_ttf"));
                else
                {
                    URIB = new Uri(bodyFontPath);
                    glyphTypefaceB = new GlyphTypeface(URIB);
                }
            }
            epubWorker.ReportProgress(20);

            /*** Generate temp HTML ***/
            Boolean HTML = generateHTML(stsObj.coverFirstPage, translation, stsObj.verticalText, stsObj.replaceNumByHan, stsObj.embedFontSubset, stsObj.dropCap, stsObj.stickupCap);
            if (!HTML) { broken = true; return; }
            epubWorker.ReportProgress(60);

            /*** Generate CSS ***/
            generateCSS(stsObj.verticalText, stsObj.marginL, stsObj.marginR, stsObj.marginT, stsObj.marginB, stsObj.lineSpacing, stsObj.addParagraphSpacing, stsObj.titleFont, stsObj.titleColor, stsObj.bodyFont, stsObj.bodyColor, stsObj.pageColor, stsObj.embedFontSubset);

            /*** Image File ***/
            Boolean IMG = copyImageFile(stsObj.verticalText, stsObj.bookNameFont, stsObj.authorNameFont);
            if (!IMG) { broken = true; return; }
            /*if (!coverFirstPage)
                if (File.Exists(getIMGFolderPath() + "\\cover~slim.jpg"))
                    File.Delete(getIMGFolderPath() + "\\cover~slim.jpg");*/

            /*** Generate OPF ***/
            generateOPF(stsObj.coverFirstPage, translation, stsObj.verticalText, stsObj.embedFontSubset);

            /*** Generate NCX ***/
            generateNCX(stsObj.coverFirstPage, stsObj.coverNoTOC, translation, stsObj.replaceNumByHan);

            /*** Generate other files ***/
            mimetype = "application/epub+zip";
            container = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n<container version=\"1.0\" xmlns=\"urn:oasis:names:tc:opendocument:xmlns:container\">\n\t<rootfiles>\n\t\t<rootfile full-path=\"OEBPS/content.opf\" media-type=\"application/oebps-package+xml\" />\n\t</rootfiles>\n</container>";
            display_options = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\" ?>\n<display_options>\n\t<platform name=\"*\">\n\t\t<option name=\"specified-fonts\">true</option>\n\t</platform>\n</display_options>";
            epubWorker.ReportProgress(80);

            /*** ZIP ***/
            if (bookAndAuthor_isChinese)
                DocName = "《" + bookAndAuthor[0] + "》作者:" + bookAndAuthor[1];
            else
                DocName = bookAndAuthor[0] + " By " + bookAndAuthor[1];
            zipPath = stsObj.fileLocation + "\\" + DocName + ".epub";

            using (ZipFile zip = new ZipFile())
            {
                zip.EmitTimesInWindowsFormatWhenSaving = false;					// Exclude extra attribute (timestamp); same as -X command
                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.None;		// Ensure mimetype file is NOT compressed
                zip.Encryption = EncryptionAlgorithm.None;						// Ensure mimetype file is NOT encryped
                zip.AddEntry("mimetype", mimetype, Encoding.ASCII);		// yet another way to generate flawless mimetype file
                zip.Save(zipPath);

                zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
                zip.AddDirectoryByName("META-INF");
                zip.AddEntry("META-INF\\container.xml", container, Encoding.UTF8);
                zip.AddEntry("META-INF\\com.apple.ibooks.display-options.xml", display_options, Encoding.UTF8);
                zip.AddDirectoryByName("OEBPS");
                zip.AddDirectoryByName("OEBPS\\Images");
                zip.AddDirectoryByName("OEBPS\\Styles");
                zip.AddDirectoryByName("OEBPS\\Text");
                zip.AddEntry("OEBPS\\Styles\\main.css", css.ToString(), Encoding.UTF8);
                zip.AddEntry("OEBPS\\content.opf", opf.ToString(), Encoding.UTF8);
                zip.AddEntry("OEBPS\\toc.ncx", ncx.ToString(), Encoding.UTF8);
                if (stsObj.coverFirstPage) zip.AddEntry("OEBPS\\Text\\coverpage.html", coverHtml.ToString(), Encoding.UTF8);
                for (Int32 i = 1; i <= txtHtmlList.Count; i++) zip.AddEntry("OEBPS\\Text\\chapter" + i + ".html", txtHtmlList[i - 1], Encoding.UTF8);
                for (Int32 i = 0; i < picHtmlList.Count; i++) zip.AddEntry("OEBPS\\Text\\picture" + i + ".html", picHtmlList[i], Encoding.UTF8);
                zip.AddFile(CoverPath, "OEBPS\\Images\\");
                zip.AddFile(CoverPathSlim, "OEBPS\\Images\\");
                for (Int32 i = 0; i < pictureHTMLs.Count; i++)
                {
                    String origPic = tempPath + "\\picture" + i + ".jpg";
                    String origPicSlim = tempPath + "\\picture" + i + "~slim.jpg";
                    zip.AddFile(origPic, "OEBPS\\Images\\");
                    zip.AddFile(origPicSlim, "OEBPS\\Images\\");
                }
                if (parchmentNeeded) zip.AddFile(tempPath + "\\parchment.jpg", "OEBPS\\Images\\");
                if (hasFootNote)
                {
                    // Use the note.png from resourses
                    //Extract(resourcesPath, "Resources", "note.png");
                    //zip.AddFile(resourcesPath + "\\note.png", "OEBPS\\Images\\");

                    // Use auto-generated note.png
                    generateNotePic();
                    zip.AddFile(tempPath + "\\note.png", "OEBPS\\Images\\");
                }
                if (stsObj.embedFontSubset)
                {
                    for (Int32 i = 0; i < embedFontPaths.Count; i++)
                    {
                        zip.AddFile(embedFontPaths[i], "OEBPS\\Fonts\\");
                    }
                }
                zip.Save(zipPath);
            }

            processedIntro = Intro;
            if (processedIntro != "")
            {
                if (processedIntro.Contains("&lt;/span&gt;&lt;br/&gt;&lt;span class=\"Apple-style-span\"&gt;"))
                {
                    processedIntro = processedIntro.Replace("&lt;/span&gt;&lt;br/&gt;&lt;span class=\"Apple-style-span\"&gt;", "\r\n");
                }
                processedIntro = processedIntro.Replace("&lt;span class=\"Apple-style-span\"&gt;", "").Replace("&lt;/span&gt;", "");
            }

            epubWorker.ReportProgress(100);

            /*** Generate MOBI from EPUB ***/
            if (stsObj.generateMOBI)
            {
                generateMobi();
                epubWorker.ReportProgress(110);
            }
        }