Ejemplo n.º 1
0
			private static void InternalGetInformation(Graphics g, FontInfo result, FontX font)
			{
				// get some properties of the font
				var gdiFont = GdiFontManager.ToGdi(font);
				result.Size = gdiFont.Size;
				result.cyLineSpace = gdiFont.GetHeight(g); // space between two lines
				int iCellSpace = gdiFont.FontFamily.GetLineSpacing(gdiFont.Style);
				int iCellAscent = gdiFont.FontFamily.GetCellAscent(gdiFont.Style);
				int iCellDescent = gdiFont.FontFamily.GetCellDescent(gdiFont.Style);
				result.cyAscent = result.cyLineSpace * iCellAscent / iCellSpace;
				result.cyDescent = result.cyLineSpace * iCellDescent / iCellSpace;
			}
Ejemplo n.º 2
0
        public Options(FontInfo taskFont)
        {
            InitializeComponent();

            tbArchiveFile.Text = User.Default.ArchiveFilePath;
            cbAutoArchive.IsChecked = User.Default.AutoArchive;
            cbAutoRefresh.IsChecked = User.Default.AutoRefresh;
            cbCaseSensitiveFilter.IsChecked = User.Default.FilterCaseSensitive;
            cbAddCreationDate.IsChecked = User.Default.AddCreationDate;
            cbDebugOn.IsChecked = User.Default.DebugLoggingOn;
            cbMinToSysTray.IsChecked = User.Default.MinimiseToSystemTray;
            cbRequireCtrlEnter.IsChecked = User.Default.RequireCtrlEnter;
            this.TaskListFont = taskFont;
        }
Ejemplo n.º 3
0
        public FontViewer( FontInfo[] f, String Font, String FontPngDir, int Fontblock, String[] Textlines, bool BoxByBox, bool ApproxDialogueColor )
        {
            InitializeComponent();
            this.FontInfos = f;
            this.BoxByBox = BoxByBox;
            this.checkBoxApproxDialogue.Checked = ApproxDialogueColor;
            this.FontPngDir = FontPngDir;

            numericUpDownTileNumber.Value = Fontblock;
            comboBoxFilename.Text = Font;
            bgcolor = Color.FromArgb( 0xFF, 0xFF, 0xFF, 0xED );
            UpdateTextures( comboBoxFilename.Text );

            UpdateText( Textlines );
            UpdateAny();
        }
Ejemplo n.º 4
0
        public Options(FontInfo taskFont)
        {
            InitializeComponent();

            tbArchiveFile.Text = User.Default.ArchiveFilePath;
            cbAutoArchive.IsChecked = User.Default.AutoArchive;
            cbAutoRefresh.IsChecked = User.Default.AutoRefresh;
            cbCaseSensitiveFilter.IsChecked = User.Default.FilterCaseSensitive;
            cbIntellisenseCaseSensitive.IsChecked = User.Default.IntellisenseCaseSensitive;
            cbAddCreationDate.IsChecked = User.Default.AddCreationDate;
            cbDebugOn.IsChecked = User.Default.DebugLoggingOn;
            cbMinToSysTray.IsChecked = User.Default.MinimiseToSystemTray;
            cbRequireCtrlEnter.IsChecked = User.Default.RequireCtrlEnter;
            cbAllowGrouping.IsChecked = User.Default.AllowGrouping;
            cbMoveFocusToTaskListAfterAddingNewTask.IsChecked = User.Default.MoveFocusToTaskListAfterAddingNewTask;
            cbPreserveWhiteSpace.IsChecked = User.Default.PreserveWhiteSpace;
            cbWordWrap.IsChecked = User.Default.WordWrap;
            this.TaskListFont = taskFont;
        }
        private void TurnOffCategory(FontCategory category, bool notifyChanges)
        {
            Guid categoryId = category.Id;
              var flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS;
              if ( notifyChanges ) {
            flags |= __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES;
              }

              int hr = fontsAndColors.OpenCategory(ref categoryId, (uint)flags);

              if ( ErrorHandler.Succeeded(hr) ) {
            FontInfo[] fontInfo = new FontInfo[] {
              category.FontInfo
            };
            fontInfo[0].bFaceNameValid = 0;
            fontInfo[0].bCharSetValid = 0;
            fontInfo[0].bPointSizeValid = 1;
            fontsAndColors.SetFont(fontInfo);
            fontsAndColors.CloseCategory();
              }
        }
Ejemplo n.º 6
0
        public static Font GetFont(string name)
        {
            MySqlDataProviderPackage package = MySqlDataProviderPackage.Instance as MySqlDataProviderPackage;
            IVsFontAndColorStorage pStorage;
            pStorage = (IVsFontAndColorStorage)package.GetVsService(
                typeof(IVsFontAndColorStorage));

            Guid textCategory = new Guid("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}");
            int result = pStorage.OpenCategory(ref textCategory, (int)( __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS));
            if (result == VSConstants.S_OK)
            {
                FontInfo[] fi = new FontInfo[1];
                fi[0] = new FontInfo();
                result = pStorage.GetFont(null, fi);
                pStorage.CloseCategory();
                if (result == VSConstants.S_OK)
                {
                    return new Font(fi[0].bstrFaceName, (float)fi[0].wPointSize);
                }
            }
            return null;
        }
Ejemplo n.º 7
0
        public IIncludedObject Load(Project project, XElement xmlNode)
        {
            var info = new FontInfo();

            info.Name = xmlNode.RequireAttribute("name").Value;
            info.CharWidth = xmlNode.GetAttribute<int>("charwidth");
            info.CaseSensitive = xmlNode.GetAttribute<bool>("cased");

            foreach (var lineNode in xmlNode.Elements("Line"))
            {
                var x = lineNode.GetAttribute<int>("x");
                var y = lineNode.GetAttribute<int>("y");

                var lineText = lineNode.Value;

                info.AddLine(x, y, lineText);
            }

            info.ImagePath = FilePath.FromRelative(xmlNode.RequireAttribute("image").Value, project.BaseDir);

            project.AddFont(info);
            return info;
        }
        private void TurnOffCategory(FontCategory category, bool notifyChanges)
        {
            Guid categoryId = category.Id;
            var  flags      = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS;

            if (notifyChanges)
            {
                flags |= __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES;
            }

            int hr = fontsAndColors.OpenCategory(ref categoryId, (uint)flags);

            if (ErrorHandler.Succeeded(hr))
            {
                FontInfo[] fontInfo = new FontInfo[] {
                    category.FontInfo
                };
                fontInfo[0].bFaceNameValid  = 0;
                fontInfo[0].bCharSetValid   = 0;
                fontInfo[0].bPointSizeValid = 1;
                fontsAndColors.SetFont(fontInfo);
                fontsAndColors.CloseCategory();
            }
        }
Ejemplo n.º 9
0
        public void LoadData(BinaryReader reader, FontInfo info)
        {
            this.reader = reader;
            this.info = info;

            VerifyHeader();

            while (reader.BaseStream.Position < reader.BaseStream.Length)
            {
                switch (reader.ReadByte())
                {
                    case 1:
                        LoadInfo(); break;
                    case 2:
                        LoadCommon(); break;
                    case 3:
                        LoadPages(); break;
                    case 4:
                        LoadChars(); break;
                    case 5:
                        LoadKerningPairs(); break;
                }
            }
        }
        private static bool TryGetFontInfoByFamily(string family, out FontInfo info, string subfamily = null, bool fallbackIfNoSubfamily = false)
        {
            ThrowIfNotInitialized();

            if (subfamily == null)
            {
                fallbackIfNoSubfamily = true;
            }
            subfamily ??= "Regular"; // this is a typical default family name

            lock (fontInfoLookup)
            {
                if (fontInfoLookup.TryGetValue(family, out var fonts))
                {
                    info = fonts.FirstOrDefault(p => p?.Info.Subfamily == subfamily);
                    if (info == null)
                    {
                        if (!fallbackIfNoSubfamily)
                        {
                            return(false);
                        }
                        else
                        {
                            info = fonts.First();
                        }
                    }

                    return(true);
                }
                else
                {
                    info = null;
                    return(false);
                }
            }
        }
Ejemplo n.º 11
0
        public static Font GetFont(string name)
        {
            MySqlDataProviderPackage package = MySqlDataProviderPackage.Instance as MySqlDataProviderPackage;
            IVsFontAndColorStorage   pStorage;

            pStorage = (IVsFontAndColorStorage)package.GetVsService(
                typeof(IVsFontAndColorStorage));

            Guid textCategory = new Guid("{A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0}");
            int  result       = pStorage.OpenCategory(ref textCategory, (int)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS));

            if (result == VSConstants.S_OK)
            {
                FontInfo[] fi = new FontInfo[1];
                fi[0]  = new FontInfo();
                result = pStorage.GetFont(null, fi);
                pStorage.CloseCategory();
                if (result == VSConstants.S_OK)
                {
                    return(new Font(fi[0].bstrFaceName, (float)fi[0].wPointSize));
                }
            }
            return(null);
        }
Ejemplo n.º 12
0
        public static bool GetGlyphBox(
            FontInfo info, int glyphIndex, out Rect glyphBox)
        {
            if (info == null)
            {
                throw new ArgumentNullException(nameof(info));
            }

            if (info.cff.Size != 0)
            {
                return(GetGlyphInfoT2(info, glyphIndex, out glyphBox) != 0);
            }
            else
            {
                int g = GetGlyphOffset(info, glyphIndex);
                if (g < 0)
                {
                    glyphBox = default;
                    return(false);
                }

                var data = info.data.Span;
                glyphBox = Rect.FromEdgePoints(
                    tlX: ReadInt16(data[(g + 2)..]),
Ejemplo n.º 13
0
        public int MaxFont(string text, int w, int h, int[] fonts, FontInfo fontInfo)
        {
            int li = 0, hi = fonts.Length - 1;

            while (li <= hi)
            {
                int mid    = li + (hi - li) / 2;
                var height = fontInfo.GetHeight(fonts[mid]);
                var width  = 0;
                foreach (var letter in text)
                {
                    width += fontInfo.GetWidth(fonts[mid], letter);
                }
                if (height <= h && width <= w)
                {
                    li = mid + 1;
                }
                else
                {
                    hi = mid - 1;
                }
            }
            return(hi < 0 ? -1 : fonts[hi]);
        }
Ejemplo n.º 14
0
        private double GetFontSize(FontAndColorsResourceKey key)
        {
            const __FCSTORAGEFLAGS flags = __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS |
                                           __FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS;
            const double defaultFontSize = 9;

            fncStorage.OpenCategory(key.Category, (uint)flags);
            try {
                var fontInfos = new FontInfo[1];
                if (fncStorage.GetFont(null, fontInfos) != VSConstants.S_OK)
                {
                    return(defaultFontSize);
                }

                if (fontInfos[0].bPointSizeValid == 1)
                {
                    return(FontUtils.FontSizeFromPointSize(fontInfos[0].wPointSize));
                }

                return(defaultFontSize);
            } finally {
                fncStorage.CloseCategory();
            }
        }
Ejemplo n.º 15
0
        public override void Load()
        {
            //draw 1
            FormTestWinGLControl form = new FormTestWinGLControl();
            var canvas = PixelFarm.Drawing.DrawingGL.CanvasGLPortal.P.CreateCanvas(0, 0, 800, 600);

            form.SetOnDestroyHandler((o, s) =>
            {
                canvas.Dispose();
            });
            FontInfo fontinfo = null;

            form.SetGLPaintHandler((o, s) =>
            {
                canvas.Orientation = CanvasOrientation.LeftTop;
                if (fontinfo == null)
                {
                    fontinfo           = PixelFarm.Drawing.DrawingGL.CanvasGLPortal.GetFontInfo("tahoma", 10, PixelFarm.Drawing.DrawingGL.FontLoadTechnique.GdiBitmapFont);
                    canvas.CurrentFont = fontinfo.ResolvedFont;
                }
                canvas.ClearSurface(PixelFarm.Drawing.Color.White);
                canvas.FillRectangle(PixelFarm.Drawing.Color.Yellow, 3, 3, 200, 200);
                canvas.DrawRectangle(PixelFarm.Drawing.Color.Red, 0, 0, 400, 400);
                //test draw text

                canvas.DrawText("AaBbCc0123 +*/%$".ToCharArray(), 0, 0);
                canvas.CurrentTextColor = PixelFarm.Drawing.Color.Red;
                canvas.DrawText("AaBbCc0123 +*/%$".ToCharArray(), 0, 50);
                canvas.CurrentTextColor = PixelFarm.Drawing.Color.Green;
                canvas.DrawText("AaBbCc0123 +*/%$".ToCharArray(), 0, 100);
                canvas.CurrentTextColor = PixelFarm.Drawing.Color.Blue;
                canvas.DrawText("AaBbCc0123 +*/%$".ToCharArray(), 0, 150);
                canvas.CurrentTextColor = PixelFarm.Drawing.Color.Black;
            });
            form.Show();
        }
Ejemplo n.º 16
0
        public static async Task AdjustFontSizeAsync(string categoryGuid, short change)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            IVsFontAndColorStorage storage = await VS.Shell.GetFontAndColorStorageAsync();

            Assumes.Present(storage);
            // ReSharper disable once SuspiciousTypeConversion.Global
            var utilities = storage as IVsFontAndColorUtilities;

            if (utilities == null)
            {
                return;
            }

            var pLOGFONT = new LOGFONTW[1];
            var pInfo    = new FontInfo[1];
            var category = new Guid(categoryGuid);

            ErrorHandler.ThrowOnFailure(storage.OpenCategory(category, (uint)(__FCSTORAGEFLAGS.FCSF_LOADDEFAULTS | __FCSTORAGEFLAGS.FCSF_PROPAGATECHANGES)));
            try
            {
                if (!ErrorHandler.Succeeded(storage.GetFont(pLOGFONT, pInfo)))
                {
                    return;
                }

                pInfo[0].wPointSize = checked ((ushort)(pInfo[0].wPointSize + change));
                ErrorHandler.ThrowOnFailure(storage.SetFont(pInfo));
                ErrorHandler.ThrowOnFailure(utilities.FreeFontInfo(pInfo));
            }
            finally
            {
                storage.CloseCategory();
            }
        }
Ejemplo n.º 17
0
        private TextNode GetTextNode(PrintFieldType fieldType, FontInfo font)
        {
            TextNode node = null;
            string   text = string.Empty;

            switch (fieldType)
            {
            case PrintFieldType.Title:
                text = _song.Title;
                break;

            case PrintFieldType.Artist:
                text = _song.Artist;
                break;

            case PrintFieldType.CCLI:
                text = _song.CCLI;
                break;

            case PrintFieldType.Copyright:
                text = _song.Copyright;
                break;

            case PrintFieldType.PageNum:
                text = "#PageNum";
                break;

            case PrintFieldType.PageNumOfTotal:
                text = "#PageNum of #PageTotal";
                break;
            }

            node = new TextNode(text, font);

            return(node);
        }
Ejemplo n.º 18
0
        private static void GetSize()
        {
            try
            {
                IVsFontAndColorStorage storage = (IVsFontAndColorStorage)EditorExtensionsPackage.GetGlobalService(typeof(IVsFontAndColorStorage));
                var guid = new Guid("A27B4E24-A735-4d1d-B8E7-9716E1E3D8E0");
                if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_READONLY | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == VS.VSConstants.S_OK)
                {
                    LOGFONTW[] Fnt = new LOGFONTW[] { new LOGFONTW() };
                    FontInfo[] Info = new FontInfo[] { new FontInfo() };
                    storage.GetFont(Fnt, Info);
                    _fontSize = (int)Info[0].wPointSize;
                }

                if (storage != null && storage.OpenCategory(ref guid, (uint)(__FCSTORAGEFLAGS.FCSF_NOAUTOCOLORS | __FCSTORAGEFLAGS.FCSF_LOADDEFAULTS)) == VS.VSConstants.S_OK)
                {
                    var info = new ColorableItemInfo[1];
                    storage.GetItem("Plain Text", info);
                    _backgroundColor = ConvertFromWin32Color((int)info[0].crBackground);
                }

            }
            catch { }
        }
Ejemplo n.º 19
0
 public void FixtureSetUp()
 {
     fi = new Style().Font;
 }
Ejemplo n.º 20
0
        internal void PaintDecoration(Canvas g, RectangleF rectangle, bool isFirst, bool isLast)
        {
            float y = 0f;

            switch (this.TextDecoration)
            {
            default:
                return;

            case Css.CssTextDecoration.Underline:
            {
                //TODO: correct this ...
                //var h = g.MeasureString(" ", ActualFont).Height;
                //float desc = FontsUtils.GetDescentPx(ActualFont);
                //y = (float)Math.Round(rectangle.Top + h - desc + 0.5);
                FontInfo fontInfo = ActualFont.FontInfo;
                var      h        = fontInfo.LineHeight;
                float    desc     = fontInfo.DescentPx;
                y = (float)Math.Round(rectangle.Top + h - desc);
            }
            break;

            case Css.CssTextDecoration.LineThrough:
            {
                y = rectangle.Top + rectangle.Height / 2f;
            }
            break;

            case Css.CssTextDecoration.Overline:
            {
                y = rectangle.Top;
            }
            break;
            }


            //y -= ActualPaddingBottom - ActualBorderBottomWidth;
            y -= (ActualPaddingBottom + ActualBorderBottomWidth);

            float x1 = rectangle.X;

            if (isFirst)
            {
                x1 += ActualPaddingLeft + ActualBorderLeftWidth;
            }


            float x2 = rectangle.Right;

            if (isLast)
            {
                x2 -= ActualPaddingRight + ActualBorderRightWidth;
            }

            var prevColor = g.StrokeColor;

            g.StrokeColor = ActualColor;
            g.DrawLine(x1, y, x2, y);

            g.StrokeColor = prevColor;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Metoda vrátí text, který má být zobrazen v grafickém prvku
        /// </summary>
        /// <param name="e"></param>
        /// <param name="boundsAbsolute"></param>
        /// <param name="boundsVisibleAbsolute"></param>
        /// <param name="fontInfo"></param>
        /// <param name="textPosition"></param>
        /// <returns></returns>
        protected string GetCaption(GInteractiveDrawArgs e, Rectangle boundsAbsolute, Rectangle boundsVisibleAbsolute, FontInfo fontInfo, ExtendedContentAlignment textPosition)
        {
            // 1. Pokud je text v prvku uveden explicitně, pak jej použijeme:
            string text = this._FirstItem.Text;

            if (text != null)
            {
                return(text);
            }

            // 2. Text pro aktuální velikost je pravděpodobně uložený v paměti (od posledně):
            Size size = boundsAbsolute.Size;

            text = this.GetCaptionForSize(size);
            if (text != null)
            {
                return(text);
            }

            // 3. Pro danou velikost ještě text není zapamatován => Získáme text Caption z datového zdroje grafu a zapamatujeme si ho:
            CreateTextArgs args = new CreateTextArgs(this._ParentGraph, e, fontInfo, this, this._FirstItem, GraphControlPosition.Group, boundsAbsolute, boundsVisibleAbsolute);

            text = this._ParentGraph.GraphItemGetCaptionText(args);
            this.SetCaptionForSize(size, text);

            return(text);
        }
Ejemplo n.º 22
0
		// Set the font in the return dialog object.
		private void SetFont()
				{
					FontStyle style = FontStyle.Regular;
					if(bold.Checked)
					{
						style |= FontStyle.Bold;
					}
					if(italic.Checked)
					{
						style |= FontStyle.Italic;
					}
					if(underline.Checked)
					{
						style |= FontStyle.Underline;
					}
					if(strikeout.Checked)
					{
						style |= FontStyle.Strikeout;
					}
					String family = name.Text.Trim();
					float fontSize;
					try
					{
					#if CONFIG_EXTENDED_NUMERICS
						fontSize = Single.Parse(size.Text);
					#else
						fontSize = Int32.Parse(size.Text);
					#endif
					}
					catch
					{
						fontSize = 0.0f;
					}

					// Sanity-check the values a little.
					if(family == null || family == String.Empty)
					{
						return;
					}
					if(fontSize <= 0.0f)
					{
						return;
					}

					// Look for a font that matches the requirements.
					FontInfo info = new FontInfo(family, fontSize, style);
					info = (FontInfo)(fonts[info]);
					if(info == null)
					{
						Font font = new Font(family, fontSize, style);
						info = new FontInfo(font, true);
						fonts[info] = info;
					}
					dialog.Font = info.font;
				}
Ejemplo n.º 23
0
    private static void customBuilder(TextAsset import, string exportPath, Texture2D texture)
    {
        if (!import)
        {
            throw new UnityException(import.name + "is not a valid font file");
        }
        Stream       ms  = new MemoryStream(import.bytes);
        BinaryReader br  = new BinaryReader(ms);
        long         sig = br.ReadInt32();

        if (sig != 0x42544e46)// BTNF header
        {
            throw new UnityException(import.name + "is not a valid BTNF fontfile");
        }
        float texW       = texture.width;
        float texH       = texture.height;
        int   char_nums  = br.ReadInt32();
        float m_FontSize = 0;
        Rect  r;

        CharacterInfo[] charInfos = new CharacterInfo[char_nums];
        for (int i = 0; i < char_nums; i++)
        {
            FontInfo mFontInfo = new FontInfo(br.ReadInt32(),
                                              br.ReadInt32(),
                                              br.ReadInt32(),
                                              br.ReadInt32(),
                                              br.ReadInt32());
            br.ReadInt32();
            CharacterInfo charInfo = new CharacterInfo();
            r        = new Rect();
            r.x      = ((float)mFontInfo.x) / texW;
            r.y      = ((float)mFontInfo.y) / texH;
            r.width  = ((float)mFontInfo.width) / texW;
            r.height = ((float)mFontInfo.height) / texH;
            r.y      = 1f - r.y - r.height;
            charInfo.uvBottomLeft  = new Vector2(r.xMin, r.yMin);
            charInfo.uvBottomRight = new Vector2(r.xMax, r.yMin);
            charInfo.uvTopLeft     = new Vector2(r.xMin, r.yMax);
            charInfo.uvTopRight    = new Vector2(r.xMax, r.yMax);
            charInfo.index         = (int)mFontInfo.index;
            charInfo.advance       = (int)mFontInfo.width;

            m_FontSize    = (float)mFontInfo.height;
            r             = new Rect();
            r.x           = (float)0f;
            r.y           = (float)0f;
            r.width       = (float)mFontInfo.width;
            r.height      = (float)mFontInfo.height;
            r.y           = -r.y;
            r.height      = -r.height;
            charInfo.minX = (int)r.xMin;
            charInfo.maxX = (int)r.xMax;
            charInfo.minY = (int)r.yMax;
            charInfo.maxY = (int)r.yMin;

            charInfos[i] = charInfo;
        }

        br.Close();
        ms.Close();

        Shader   shader   = Shader.Find("UI/Default");
        Material material = new Material(shader);

        material.mainTexture = texture;
        AssetDatabase.CreateAsset(material, exportPath + ".mat");

        // Create font
        Font font = new Font();

        font.material      = material;
        font.name          = import.name;
        font.characterInfo = charInfos;

        SerializedObject mFont = new SerializedObject(font);

        mFont.FindProperty("m_FontSize").floatValue    = m_FontSize - 2f;
        mFont.FindProperty("m_LineSpacing").floatValue = m_FontSize + 2f;
        mFont.ApplyModifiedProperties();

        AssetDatabase.CreateAsset(font, exportPath + ".fontsettings");
        Debug.Log(String.Format("创建自定义字库完成!{0}", import.name));
    }
Ejemplo n.º 24
0
        // generate source/header strings from a block list
        private void generateStringsFromCharacterDescriptorBlockList(FontInfo fontInfo, ArrayList characterBlockList,
            ref string resultTextSource, ref string resultTextHeader,
            ref bool blockLookupGenerated)
        {
            // get wheter there are multiple block lsits
            bool multipleDescBlocksExist = characterBlockList.Count > 1;

            // set whether we'll generate lookups
            blockLookupGenerated = multipleDescBlocksExist;

            //
            // Generate descriptor arrays
            //

            // iterate over blocks
            foreach (CharacterDescriptorArrayBlock block in characterBlockList)
            {
                // according to config
                if (m_outputConfig.commentVariableName)
                {
                    string blockNumberString = String.Format("(block #{0})", characterBlockList.IndexOf(block));

                    // result string
                    resultTextSource += String.Format("{0}Character descriptors for {1} {2}pt{3}{4}" + nl,
                                                        m_commentStartString, fontInfo.font.Name,
                                                        Math.Round(fontInfo.font.Size), multipleDescBlocksExist ? blockNumberString : "",
                                                        m_commentEndString);

                    // describe character array
                    resultTextSource += String.Format("{0}{{ {1}{2}[Offset into {3}CharBitmaps in bytes] }}{4}" + nl,
                                                        m_commentStartString,
                                                        getCharacterDescName("width", m_outputConfig.descCharWidth),
                                                        getCharacterDescName("height", m_outputConfig.descCharHeight),
                                                        getFontName(ref fontInfo.font),
                                                        m_commentEndString);
                }

                // output block header
                resultTextSource += String.Format("{0} = "+ nl+"{{" + nl, charDescArrayGetBlockName(fontInfo, characterBlockList.IndexOf(block), true, multipleDescBlocksExist));

                // iterate characters
                foreach (CharacterDescriptorArrayBlock.Character character in block.characters)
                {
                    // add character
                    resultTextSource += String.Format("\t{{{0}{1}{2}}}, \t\t{3}{4}{5}" + nl,
                                                    getCharacterDescString(m_outputConfig.descCharWidth, character.width),
                                                    getCharacterDescString(m_outputConfig.descCharHeight, character.height),
                                                    character.offset,
                                                    m_commentStartString,
                                                    character.character != '\\' ? character.character.ToString() : "'\\'",
                                                    m_commentEndString + " ");
                }

                // terminate current block
                resultTextSource += "};" + nl + nl;
            }

            //
            // Generate block lookup
            //

            // if there is more than one block, we need to generate a block lookup
            if (multipleDescBlocksExist)
            {
                // start with comment, if required
                if (m_outputConfig.commentVariableName)
                {
                    // result string
                    resultTextSource += String.Format("{0}Block lookup array for {1} {2}pt {3}" + nl,
                                                        m_commentStartString, fontInfo.font.Name,
                                                        Math.Round(fontInfo.font.Size), m_commentEndString);

                    // describe character array
                    resultTextSource += String.Format("{0}{{ start character, end character, ptr to descriptor block array }}{1}" + nl,
                                                        m_commentStartString,
                                                        m_commentEndString);
                }

                // format the block lookup header
                resultTextSource += String.Format("const FONT_CHAR_INFO_LOOKUP {0} = " + nl+"{{" + nl,
                                                    getCharacterDescriptorArrayLookupDisplayString(fontInfo));

                // iterate
                foreach (CharacterDescriptorArrayBlock block in characterBlockList)
                {
                    // get first/last chars
                    CharacterDescriptorArrayBlock.Character firstChar = (CharacterDescriptorArrayBlock.Character)block.characters[0],
                                                            lastChar = (CharacterDescriptorArrayBlock.Character)block.characters[block.characters.Count - 1];

                    // create current block description
                    resultTextSource += String.Format("\t{{{0}, {1}, &{2}}}," + nl,
                                                                getCharacterDisplayString(firstChar.character),
                                                                getCharacterDisplayString(lastChar.character),
                                                                charDescArrayGetBlockName(fontInfo, characterBlockList.IndexOf(block), false, true));
                }

                // terminate block lookup
                resultTextSource += "};" + nl + nl;
            }
        }
Ejemplo n.º 25
0
        // generate lookup array
        private void generateCharacterDescriptorArray(FontInfo fontInfo, ref string resultTextSource, 
            ref string resultTextHeader, ref bool blockLookupGenerated)
        {
            // check if required by configuration
            if (m_outputConfig.generateLookupArray)
            {
                ArrayList characterBlockList = new ArrayList();

                // populate list of blocks
                generateCharacterDescriptorBlockList(fontInfo, ref characterBlockList);

                // generate strings from block list
                generateStringsFromCharacterDescriptorBlockList(fontInfo, characterBlockList, ref resultTextSource,
                                                                ref resultTextHeader, ref blockLookupGenerated);
            }
        }
Ejemplo n.º 26
0
        // add a character to teh current char descriptor array
        private void charDescArrayAddCharacter(CharacterDescriptorArrayBlock desciptorBlock,
            FontInfo fontInfo,
            char character,
            int width, int height, int offset)
        {
            // create character descriptor
            CharacterDescriptorArrayBlock.Character charDescriptor = new CharacterDescriptorArrayBlock.Character();
                charDescriptor.character = character;
                charDescriptor.font = fontInfo;
                charDescriptor.height = height;
                charDescriptor.width = width;
                charDescriptor.offset = offset;

            // shove this character to the descriptor block
            desciptorBlock.characters.Add(charDescriptor);
        }
Ejemplo n.º 27
0
        // populate the font info
        private FontInfo populateFontInfo(Font font)
        {
            // the font information
            FontInfo fontInfo = new FontInfo();

            // get teh characters we need to generate from the input text, removing duplicates
            fontInfo.generatedChars = getCharactersToGenerate();

            // set font into into
            fontInfo.font = font;

            // array holding all bitmaps and info per character
            fontInfo.characters = new CharacterGenerationInfo[fontInfo.generatedChars.Length];

            //
            // init char infos
            //
            for (int charIdx = 0; charIdx < fontInfo.generatedChars.Length; ++charIdx)
            {
                // create char info entity
                fontInfo.characters[charIdx] = new CharacterGenerationInfo();

                // point back to teh font
                fontInfo.characters[charIdx].fontInfo = fontInfo;

                // set the character
                fontInfo.characters[charIdx].character = fontInfo.generatedChars[charIdx];
            }

            //
            // Find the widest bitmap size we are going to draw
            //
            Rectangle largestBitmap = getLargestBitmapFromCharInfo(fontInfo.characters);

            //
            // create bitmaps per characater
            //

            // iterate over characters
            for (int charIdx = 0; charIdx < fontInfo.generatedChars.Length; ++charIdx)
            {
                // generate the original bitmap for the character
                convertCharacterToBitmap(fontInfo.generatedChars[charIdx],
                                         font,
                                         out fontInfo.characters[charIdx].bitmapOriginal, largestBitmap);

                // save
                // fontInfo.characters[charIdx].bitmapOriginal.Save(String.Format("C:/bms/{0}.bmp", fontInfo.characters[charIdx].character));
            }

            //
            // iterate through all bitmaps and find the tightest common border. only perform
            // this if the configuration specifies
            //

            // this will contain the values of the tightest border around the characters
            BitmapBorder tightestCommonBorder = new BitmapBorder();

            // only perform if padding type specifies
            if (m_outputConfig.paddingRemovalHorizontal == OutputConfiguration.PaddingRemoval.Fixed ||
                m_outputConfig.paddingRemovalVertical == OutputConfiguration.PaddingRemoval.Fixed)
            {
                // find the common tightest border
                findTightestCommonBitmapBorder(fontInfo.characters, ref tightestCommonBorder);
            }

            //
            // iterate thruogh all bitmaps and generate the bitmap we will convert to string
            // this means performing all manipulation (pad remove, flip)
            //

            // iterate over characters
            for (int charIdx = 0; charIdx < fontInfo.generatedChars.Length; ++charIdx)
            {
                // generate the original bitmap for the character
                manipulateBitmap(fontInfo.characters[charIdx].bitmapOriginal,
                                 tightestCommonBorder,
                                 out fontInfo.characters[charIdx].bitmapToGenerate,
                                 m_outputConfig.spaceGenerationPixels,
                                 fontInfo.characters[charIdx].bitmapOriginal.Height);

                // for debugging
                // fontInfo.characters[charIdx].bitmapToGenerate.Save(String.Format("C:/bms/{0}_cropped.bmp", fontInfo.characters[charIdx].character));
            }

            //
            // iterate through all characters and create the page array
            //

            // iterate over characters
            for (int charIdx = 0; charIdx < fontInfo.generatedChars.Length; ++charIdx)
            {
                // check if bitmap exists
                if (fontInfo.characters[charIdx].bitmapToGenerate != null)
                {
                    // create the page array for the character
                    convertBitmapToPageArray(fontInfo.characters[charIdx].bitmapToGenerate, out fontInfo.characters[charIdx].pages);
                }
            }

            // populate font info
            populateFontInfoFromCharacters(ref fontInfo);

            // return the font info
            return fontInfo;
        }
Ejemplo n.º 28
0
 //
 private string getCharacterDescriptorArrayLookupDisplayString(FontInfo fontInfo)
 {
     // return the string
     return String.Format("{0}BlockLookup", getFontName(ref fontInfo.font));
 }
Ejemplo n.º 29
0
        private static string Convert(FontInfo font)
        {
            if (font == null)
            {
                return("null");
            }

            string family         = string.Empty;
            string size           = string.Empty;
            string weight         = string.Empty;
            string style          = string.Empty;
            string textDecoration = string.Empty;

            if (!string.IsNullOrEmpty(font.Name))
            {
                family = font.Name;
            }

            if ((font.Names != null) && (font.Names.Length > 0))
            {
                family += ", " + string.Join(", ", font.Names);
            }

            if (font.Size.IsEmpty)
            {
                size = font.Size.ToString(CultureInfo.InvariantCulture);
            }

            if (font.Bold)
            {
                weight = "bold";
            }

            if (font.Italic)
            {
                style = "italic";
            }

            if (font.Underline)
            {
                textDecoration = "underline";
            }

            if (font.Overline)
            {
                if (textDecoration.Length > 0)
                {
                    textDecoration += " ";
                }

                textDecoration += "overline";
            }

            if (font.Strikeout)
            {
                if (textDecoration.Length > 0)
                {
                    textDecoration += " ";
                }

                textDecoration += "line-through";
            }

            return(string.Format(CultureInfo.InvariantCulture, "new AjaxDataControls.FontInfo('{0}', '{1}', '{2}', '{3}', '{4}')", family, size, weight, style, textDecoration));
        }
Ejemplo n.º 30
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Updates the form based on a style being selected.
        /// </summary>
        /// <param name="styleInfo">The style info.</param>
        /// ------------------------------------------------------------------------------------
        public void UpdateForStyle(StyleInfo styleInfo)
        {
            CheckDisposed();
#if __MonoCS__
            // On Mono, the sequence of events when changing styles can cause this to be
            // called even when switching to a character style.  See FWNX-870.
            if (!styleInfo.IsParagraphStyle)
            {
                return;
            }
#endif
            m_dontUpdateInheritance = true;

            bool fDifferentStyle = m_StyleInfo == null ? true : (styleInfo.Name != m_StyleInfo.Name);

            // Don't use a 0 size bullet. Fixes FWNX-575.
            if (styleInfo != null && styleInfo.IBullet != null)
            {
                if (styleInfo.IBullet.Value.FontInfo.FontSize.Value == 0)
                {
                    styleInfo.IBullet.Value.FontInfo.m_fontSize =
                        new InheritableStyleProp <int>(FontInfo.kDefaultFontSize);
                }
            }

            m_StyleInfo             = styleInfo;
            m_preview.IsRightToLeft = m_StyleInfo.DirectionIsRightToLeft == TriStateBool.triNotSet ?
                                      m_DefaultTextDirectionRtoL : m_StyleInfo.DirectionIsRightToLeft == TriStateBool.triTrue;
            m_preview.WritingSystemFactory = m_StyleInfo.Cache.WritingSystemFactory;
            m_preview.WritingSystemCode    = m_StyleInfo.Cache.ServiceLocator.WritingSystems.DefaultVernacularWritingSystem.Handle;

            VwBulNum bulletType;
            // Note: don't assign m_currentStyleBulletInfo until the end of this method
            // since setting some of the values change m_currentStyleBulletInfo before we have set
            // everything.
            BulletInfo bulletInfo = new BulletInfo(styleInfo.IBullet.Value);
            bulletType = bulletInfo.m_numberScheme;

            // If we have a different style, we have to reload the font info. If it is the same
            // style we were here before so we keep the font info that we already have.
            if (fDifferentStyle)
            {
                if ((int)bulletType >= (int)VwBulNum.kvbnBulletBase)
                {
                    // use font from style for bullets
                    m_BulletsFontInfo = bulletInfo.FontInfo;
                    // create a number font based on the font for bullets
                    m_NumberFontInfo = new FontInfo(m_BulletsFontInfo);
                    m_NumberFontInfo.m_fontName.ResetToInherited(styleInfo.FontInfoForWs(-1).UIFontName());
                }
                else
                {
                    // use font from style for numbers
                    m_NumberFontInfo = bulletInfo.FontInfo;

                    if (bulletType == VwBulNum.kvbnNone)
                    {
                        m_NumberFontInfo.m_fontName.ResetToInherited(styleInfo.FontInfoForWs(-1).UIFontName());
                    }

                    // create a bullets font based on the font for numbers
                    m_BulletsFontInfo = new FontInfo(m_NumberFontInfo);

                    // The font for bullets is hard-coded in the views code, so there is no point
                    // in letting the user select any other font for bullets.
                    m_BulletsFontInfo.m_fontName.ResetToInherited("Quivira");
                    m_BulletsFontInfo.m_fontName.SetDefaultValue("Quivira");
                }
            }

            m_nudStartAt.Value   = bulletInfo.m_start;
            m_chkStartAt.Checked = (bulletInfo.m_start != 1);

            m_tbTextBefore.Text = bulletInfo.m_textBefore;
            m_tbTextAfter.Text  = bulletInfo.m_textAfter;

            m_rbUnspecified.Enabled = styleInfo.Inherits;
            if (styleInfo.IBullet.IsInherited && styleInfo.Inherits)
            {
                m_rbUnspecified.Checked = true;
            }
            else if (bulletType == VwBulNum.kvbnNone)
            {
                m_rbNone.Checked = true;
            }
            else if ((int)bulletType >= (int)VwBulNum.kvbnBulletBase)
            {
                m_rbBullet.Checked = true;
            }
            else             // NumberBase
            {
                m_rbNumber.Checked = true;
            }

            m_cboBulletScheme.SelectedIndex = GetBulletIndexForType(bulletType);
            m_cboNumberScheme.SelectedIndex = GetNumberSchemeIndexForType(bulletType);

            m_currentStyleBulletInfo = bulletInfo;
            UpdateBulletSchemeComboBox();

            m_dontUpdateInheritance = false;
        }
Ejemplo n.º 31
0
 public void MergeWith(FontInfo f)
 {
 }
Ejemplo n.º 32
0
        public override object GetValue(object component)
        {
            try
            {
                if (this.property is Property <MousePointers> )
                {
                    return(((Property <MousePointers>) this.property).Value);
                }
                else if (property is PropertyColor)
                {
                    ThW.UI.Utils.Color c = (ThW.UI.Utils.Color)((PropertyColor)this.property).Value;

                    if (null == c)
                    {
                        return(System.Drawing.Color.FromArgb(0));
                    }
                    else
                    {
                        return(System.Drawing.Color.FromArgb((int)(c.A * 255), (int)(c.R * 255), (int)(c.G * 255), (int)(c.B * 255)));
                    }
                }
                else if (this.property is PropertyFont)
                {
                    PropertyFont propertyFont = (PropertyFont)this.property;

                    FontInfo font = this.control.FontInfo;

                    FontStyle style = FontStyle.Regular;

                    if (true == font.Bold)
                    {
                        style |= FontStyle.Bold;
                    }

                    if (true == font.Italic)
                    {
                        style |= FontStyle.Italic;
                    }
                    try
                    {
                        return(new Font(font.Name, (float)font.Size, style));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        return(new Font(font.Name, (float)font.Size));
                    }
                }
                else if (this.property is PropertyAnchor)
                {
                    AnchorStyle s = (AnchorStyle)this.property.Value;

                    AnchorStyles result = AnchorStyles.None;

                    if ((s & AnchorStyle.AnchorTop) > 0)
                    {
                        result |= AnchorStyles.Top;
                    }

                    if ((s & AnchorStyle.AnchorLeft) > 0)
                    {
                        result |= AnchorStyles.Left;
                    }

                    if ((s & AnchorStyle.AnchorRight) > 0)
                    {
                        result |= AnchorStyles.Right;
                    }

                    if ((s & AnchorStyle.AnchorBottom) > 0)
                    {
                        result |= AnchorStyles.Bottom;
                    }

                    return(result);
                }
                else if (null != this.property.Value)
                {
                    return(this.property.Value);
                }
                else
                {
                    return("");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);

                return("");
            }
        }
Ejemplo n.º 33
0
 /// <summary>
 /// </summary>
 /// <param name="fontInfo"></param>
 public void SetupFontInfo(FontInfo fontInfo)
 {
     this.fontInfo  = fontInfo;
     this.fontSetup = new FontSetup(
         fontInfo, (options == null) ? FontType.Link : options.FontType);
 }
Ejemplo n.º 34
0
        public static int Execute(List <string> args)
        {
            /*
             * FontDisplay
             * -fontinfofile tov.elf
             * -fontinfofiletype elf/fontinfo
             * -fontpngdir FontTex
             * -textfile text.txt
             * -mode gui/png
             * -font FONTTEX10
             * -fontblock 0
             * -outfile text.png
             */

            string      Filepath         = "ffinfo.bin";
            int         FontInfoOffset   = 0;
            String      Textfile         = null;
            ProgramMode Mode             = ProgramMode.GUI;
            String      Font             = "FONTTEX10.TXV";
            int         Fontblock        = 0;
            String      Outfile          = "out.png";
            bool        BoxByBox         = false;
            bool        DialogueBoxColor = false;
            String      FontPngDir       = @"FontTex";

            try {
                for (int i = 0; i < args.Count; i++)
                {
                    switch (args[i].ToLowerInvariant())
                    {
                    case "-fontinfofile":
                        Filepath = args[++i];
                        break;

                    case "-fontinfofiletype":
                        switch (args[++i].ToLowerInvariant())
                        {
                        case "elf":
                            FontInfoOffset = 0x00720860;
                            break;

                        case "fontinfo":
                            FontInfoOffset = 0;
                            break;
                        }
                        break;

                    case "-textfile":
                        Textfile = args[++i];
                        break;

                    case "-fontpngdir":
                        FontPngDir = args[++i];
                        break;

                    case "-mode":
                        switch (args[++i].ToLowerInvariant())
                        {
                        case "gui":
                            Mode = ProgramMode.GUI;
                            break;

                        case "png":
                            Mode = ProgramMode.png;
                            break;
                        }
                        break;

                    case "-font":
                        Font = args[++i];
                        break;

                    case "-fontblock":
                        Fontblock = Int32.Parse(args[++i]);
                        break;

                    case "-outfile":
                        Outfile = args[++i];
                        break;

                    case "-boxbybox":
                        BoxByBox = true;
                        break;

                    case "-dialoguebubble":
                        DialogueBoxColor = true;
                        break;
                    }
                }
            } catch (IndexOutOfRangeException) {
                PrintUsage();
                return(-1);
            }



            try {
                byte[] File = System.IO.File.ReadAllBytes(Filepath);

                FontInfo[] f = new FontInfo[6];
                f[0] = new FontInfo(File, FontInfoOffset);
                f[1] = new FontInfo(File, FontInfoOffset + 0x880);
                f[2] = new FontInfo(File, FontInfoOffset + 0x880 * 2);
                f[3] = new FontInfo(File, FontInfoOffset + 0x880 * 3);
                f[4] = new FontInfo(File, FontInfoOffset + 0x880 * 4);
                f[5] = new FontInfo(File, FontInfoOffset + 0x880 * 5);

                String[] TextLines = null;
                if (Textfile != null)
                {
                    TextLines = System.IO.File.ReadAllLines(Textfile);
                }

                FontViewer form = new FontViewer(f, Font, FontPngDir, Fontblock, TextLines, BoxByBox, DialogueBoxColor);
                form.Filepath       = Filepath;
                form.FontInfoOffset = FontInfoOffset;

                if (Mode == ProgramMode.GUI)
                {
                    form.Show();
                }
                else if (Mode == ProgramMode.png)
                {
                    form.SaveAsPng(Outfile);
                }
            } catch (Exception ex) {
                Console.WriteLine(ex.ToString());
                PrintUsage();
                return(-1);
            }

            return(0);
        }
Ejemplo n.º 35
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Appends the underline information to the description.
        /// </summary>
        /// <param name="fontInfo"></param>
        /// <param name="text">The text.</param>
        /// ------------------------------------------------------------------------------------
        private static void AppendUnderline(FontInfo fontInfo, StringBuilder text)
        {
            string sUnder = "";

            if (fontInfo.m_underlineColor.IsExplicit)
            {
                string sColor = ColorUtil.ColorToName(fontInfo.m_underlineColor.Value);
                if (fontInfo.m_underline.IsExplicit)
                {
                    switch (fontInfo.m_underline.Value)
                    {
                    case FwUnderlineType.kuntNone:
                        sUnder = String.Format(FwCoreDlgControls.ksNoColorUnderline, sColor);
                        break;

                    case FwUnderlineType.kuntSingle:
                        sUnder = String.Format(FwCoreDlgControls.ksSingleColorUnderline, sColor);
                        break;

                    case FwUnderlineType.kuntDouble:
                        sUnder = String.Format(FwCoreDlgControls.ksDoubleColorUnderline, sColor);
                        break;

                    case FwUnderlineType.kuntDotted:
                        sUnder = String.Format(FwCoreDlgControls.ksDottedColorUnderline, sColor);
                        break;

                    case FwUnderlineType.kuntDashed:
                        sUnder = String.Format(FwCoreDlgControls.ksDashedColorUnderline, sColor);
                        break;

                    case FwUnderlineType.kuntStrikethrough:
                        sUnder = String.Format(FwCoreDlgControls.ksColorStrikethrough, sColor);
                        break;
                    }
                }
                else
                {
                    sUnder = String.Format(FwCoreDlgControls.ksColorUnderline, sColor);
                }
            }
            else if (fontInfo.m_underline.IsExplicit)
            {
                switch (fontInfo.m_underline.Value)
                {
                case FwUnderlineType.kuntNone:
                    sUnder = FwCoreDlgControls.ksNoUnderline;
                    break;

                case FwUnderlineType.kuntSingle:
                    sUnder = FwCoreDlgControls.ksSingleUnderline;
                    break;

                case FwUnderlineType.kuntDouble:
                    sUnder = FwCoreDlgControls.ksDoubleUnderline;
                    break;

                case FwUnderlineType.kuntDotted:
                    sUnder = FwCoreDlgControls.ksDottedUnderline;
                    break;

                case FwUnderlineType.kuntDashed:
                    sUnder = FwCoreDlgControls.ksDashedUnderline;
                    break;

                case FwUnderlineType.kuntStrikethrough:
                    sUnder = FwCoreDlgControls.ksStrikethrough;
                    break;
                }
            }
            AppendToString(text, sUnder);
        }
 internal static extern bool GetCurrentConsoleFontEx(IntPtr hConsoleOutput, bool MaximumWindow, ref FontInfo ConsoleCurrentFontEx);
        private static Font GetNewFont(FontInfo fontInfo, Boolean ignoreMod = true)
        {
            var font = new Font();
            var bold = (fontInfo.Font.BoldModified || ignoreMod) && fontInfo.Font.Bold ? new Bold() : null;
            var italic = (fontInfo.Font.ItalicModified || ignoreMod) && fontInfo.Font.Italic ? new Italic() : null;
            var underline = (fontInfo.Font.UnderlineModified || ignoreMod) &&
                            fontInfo.Font.Underline != XLFontUnderlineValues.None
                ? new Underline {Val = fontInfo.Font.Underline.ToOpenXml()}
                : null;
            var strike = (fontInfo.Font.StrikethroughModified || ignoreMod) && fontInfo.Font.Strikethrough
                ? new Strike()
                : null;
            var verticalAlignment = fontInfo.Font.VerticalAlignmentModified || ignoreMod
                ? new VerticalTextAlignment {Val = fontInfo.Font.VerticalAlignment.ToOpenXml()}
                : null;
            var shadow = (fontInfo.Font.ShadowModified || ignoreMod) && fontInfo.Font.Shadow ? new Shadow() : null;
            var fontSize = fontInfo.Font.FontSizeModified || ignoreMod
                ? new FontSize {Val = fontInfo.Font.FontSize}
                : null;
            var color = fontInfo.Font.FontColorModified || ignoreMod ? GetNewColor(fontInfo.Font.FontColor) : null;

            var fontName = fontInfo.Font.FontNameModified || ignoreMod
                ? new FontName {Val = fontInfo.Font.FontName}
                : null;
            var fontFamilyNumbering = fontInfo.Font.FontFamilyNumberingModified || ignoreMod
                ? new FontFamilyNumbering {Val = (Int32)fontInfo.Font.FontFamilyNumbering}
                : null;

            if (bold != null)
                font.AppendChild(bold);
            if (italic != null)
                font.AppendChild(italic);
            if (underline != null)
                font.AppendChild(underline);
            if (strike != null)
                font.AppendChild(strike);
            if (verticalAlignment != null)
                font.AppendChild(verticalAlignment);
            if (shadow != null)
                font.AppendChild(shadow);
            if (fontSize != null)
                font.AppendChild(fontSize);
            if (color != null)
                font.AppendChild(color);
            if (fontName != null)
                font.AppendChild(fontName);
            if (fontFamilyNumbering != null)
                font.AppendChild(fontFamilyNumbering);

            return font;
        }
Ejemplo n.º 38
0
 protected void Page_Load(object sender, EventArgs e)
 {
     GreetLabel.Text          = "Greetings, visitor!";
     LabelChangingButton.Text = "Change label!";
     defaultFont = GreetLabel.Font;
 }
Ejemplo n.º 39
0
 public void CopyFrom(FontInfo f)
 {
 }
Ejemplo n.º 40
0
	private Font(String name, bool unused)
			{
				this.family = null;
				this.pointSize = 0;
				this.style = FontStyle.Normal;
				this.xname = name;
				this.infoList = null;
			}
Ejemplo n.º 41
0
 private void Test(Type ctrlType)
 {
     string[] textArray2;
     try
     {
         this.GHTSubTestBegin(ctrlType, "Set legal value");
         textArray2 = new string[] { "David", "Times New Roman", "Courier New" };
         this.TestedControl.ControlStyle.Font.Names = textArray2;
     }
     catch (Exception exception8)
     {
         // ProjectData.SetProjectError(exception8);
         Exception exception1 = exception8;
         this.GHTSubTestUnexpectedExceptionCaught(exception1);
         // ProjectData.ClearProjectError();
     }
     this.GHTSubTestEnd();
     try
     {
         this.GHTSubTestBegin(ctrlType, "Change Order");
         FontInfo info1 = this.TestedControl.ControlStyle.Font;
         textArray2  = new string[] { "David", "Times New Roman", "Courier New" };
         info1.Names = textArray2;
         string text1 = info1.Names[1];
         info1.Names[1] = info1.Names[0];
         info1.Names[0] = text1;
         info1          = null;
     }
     catch (Exception exception9)
     {
         // ProjectData.SetProjectError(exception9);
         Exception exception2 = exception9;
         this.GHTSubTestUnexpectedExceptionCaught(exception2);
         // ProjectData.ClearProjectError();
     }
     this.GHTSubTestEnd();
     try
     {
         this.GHTSubTestBegin(ctrlType, "Setting Name changes Names.");
         textArray2 = new string[] { "David", "Times New Roman", "Courier New" };
         this.TestedControl.ControlStyle.Font.Names = textArray2;
         this.TestedControl.ControlStyle.Font.Name  = "Arial";
         string   text2      = string.Empty;
         string[] textArray1 = this.TestedControl.ControlStyle.Font.Names;
         for (int num1 = 0; num1 < textArray1.Length; num1++)
         {
             string text3 = textArray1[num1];
             text2 = text2 + text3;
         }
         this.Compare(text2, this.TestedControl.ControlStyle.Font.Name);
     }
     catch (Exception exception10)
     {
         // ProjectData.SetProjectError(exception10);
         Exception exception3 = exception10;
         this.GHTSubTestUnexpectedExceptionCaught(exception3);
         // ProjectData.ClearProjectError();
     }
     this.GHTSubTestEnd();
     try
     {
         this.GHTSubTestBegin(ctrlType, "Set Names in code + Names in CssClass.");
         this.TestedControl.ControlStyle.CssClass = "NamesCssClass";
         textArray2 = new string[] { "Times New Roman", "Arial", "Courier New" };
         this.TestedControl.ControlStyle.Font.Names = textArray2;
     }
     catch (ArgumentException exception11)
     {
         // ProjectData.SetProjectError(exception11);
         ArgumentException exception4 = exception11;
         this.GHTSubTestExpectedExceptionCaught(exception4);
         // ProjectData.ClearProjectError();
     }
     catch (Exception exception12)
     {
         // ProjectData.SetProjectError(exception12);
         Exception exception5 = exception12;
         this.GHTSubTestUnexpectedExceptionCaught(exception5);
         // ProjectData.ClearProjectError();
     }
     this.GHTSubTestEnd();
     try
     {
         this.GHTSubTestBegin(ctrlType, "Set Names in code + Name in CssClass.");
         this.TestedControl.ControlStyle.CssClass = "NameCssClass";
         textArray2 = new string[] { "Times New Roman", "Arial", "Courier New" };
         this.TestedControl.ControlStyle.Font.Names = textArray2;
     }
     catch (ArgumentException exception13)
     {
         // ProjectData.SetProjectError(exception13);
         ArgumentException exception6 = exception13;
         this.GHTSubTestExpectedExceptionCaught(exception6);
         // ProjectData.ClearProjectError();
     }
     catch (Exception exception14)
     {
         // ProjectData.SetProjectError(exception14);
         Exception exception7 = exception14;
         this.GHTSubTestUnexpectedExceptionCaught(exception7);
         // ProjectData.ClearProjectError();
     }
     this.GHTSubTestEnd();
 }
Ejemplo n.º 42
0
	internal IntPtr GetFontSet(Display dpy, out FontExtents extents)
			{
				lock(typeof(Font))
				{
					// Map this object to the one that actually stores
					// the font set information.
					Font font = (Font)(dpy.fonts[this]);
					if(font == null)
					{
						font = this;
						dpy.fonts[this] = this;
					}

					// Search for existing font set information.
					FontInfo info = font.infoList;
					while(info != null)
					{
						if(info.dpy == dpy)
						{
							extents = info.extents;
							return info.fontSet;
						}
						info = info.next;
					}

					// Create a new font set.
					IntPtr fontSet;
					int ascent, descent, maxWidth;
					try
					{
						IntPtr display = dpy.Lock();
						fontSet = CreateFontSet
							(display, out ascent, out descent, out maxWidth);
						if(fontSet == IntPtr.Zero)
						{
							extents = null;
							return IntPtr.Zero;
						}
					}
					finally
					{
						dpy.Unlock();
					}

					// Associate the font set with the display.
					info = new FontInfo();
					info.next = font.infoList;
					info.extents = new FontExtents(ascent, descent, maxWidth);
					info.dpy = dpy;
					info.fontSet = fontSet;
					font.infoList = info;

					// Return the font set to the caller.
					extents = info.extents;
					return fontSet;
				}
			}
Ejemplo n.º 43
0
 public void SetFontInfo(
     FontInfo fontInfo)
 {
     this.fontInfo = fontInfo;
 }
Ejemplo n.º 44
0
	// Constructors.
	private Font(String family, int pointSize, FontStyle style)
			{
				if(family != null)
					this.family = family;
				else
					this.family = SansSerif;
				if(pointSize < 0 || pointSize > 10000)
					this.pointSize = 120;
				else
					this.pointSize = pointSize;
				this.style = style;
				this.xname = null;
				this.infoList = null;
			}
Ejemplo n.º 45
0
        // get the descriptors
        private string getFontInfoDescriptorsString(FontInfo fontInfo, bool blockLookupGenerated)
        {
            string descriptorString = "";

            // if a lookup arrays are required, point to it
            if (m_outputConfig.generateLookupBlocks)
            {
                // add to string
                descriptorString += String.Format("\t{0}, {1} Character block lookup{2}" + nl,
                                                    blockLookupGenerated ? getCharacterDescriptorArrayLookupDisplayString(fontInfo) : "NULL",
                                                    m_commentStartString, m_commentEndString);

                // add to string
                descriptorString += String.Format("\t{0}, {1} Character descriptor array{2}" + nl,
                                                    blockLookupGenerated ? "NULL" : getVariableNameFromExpression(String.Format(m_outputConfig.varNfCharInfo, getFontName(ref fontInfo.font))),
                                                    m_commentStartString, m_commentEndString);
            }
            else
            {
                // add descriptor array
                descriptorString += String.Format("\t{0}, {1} Character descriptor array{2}" + nl,
                                                    getVariableNameFromExpression(String.Format(m_outputConfig.varNfCharInfo, getFontName(ref fontInfo.font))),
                                                    m_commentStartString, m_commentEndString);
            }

            // return the string
            return descriptorString;
        }
Ejemplo n.º 46
0
	// Disassociate this font from a particular display.
	internal void Disassociate(Display dpy)
			{
				lock(typeof(Font))
				{
					FontInfo info, prev;
					info = infoList;
					prev = null;
					while(info != null && info.dpy != dpy)
					{
						prev = info;
						info = info.next;
					}
					if(info != null)
					{
						if(prev != null)
						{
							prev.next = info.next;
						}
						else
						{
							infoList = info.next;
						}
						FreeFontSet(dpy.dpy, info.fontSet);
					}
				}
			}
Ejemplo n.º 47
0
        // get font info from string
        private void populateFontInfoFromCharacters(ref FontInfo fontInfo)
        {
            // do nothing if no chars defined
            if (fontInfo.characters.Length == 0) return;

            // total offset
            int charByteOffset = 0;
            int dummy = 0;

            // set start char
            fontInfo.startChar = (char)0xFFFF;
            fontInfo.endChar = ' ';

            // the fixed absolute character height
            // int fixedAbsoluteCharHeight;
            getAbsoluteCharacterDimensions(ref fontInfo.characters[0].bitmapToGenerate, ref dummy, ref fontInfo.charHeight);

            // iterate through letter string
            for (int charIdx = 0; charIdx < fontInfo.characters.Length; ++charIdx)
            {
                // skip empty bitmaps
                if (fontInfo.characters[charIdx].bitmapToGenerate == null) continue;

                // get char
                char currentChar = fontInfo.characters[charIdx].character;

                // is this character smaller than start char?
                if (currentChar < fontInfo.startChar) fontInfo.startChar = currentChar;

                // is this character bigger than end char?
                if (currentChar > fontInfo.endChar) fontInfo.endChar = currentChar;

                // populate number of rows
                getAbsoluteCharacterDimensions(ref fontInfo.characters[charIdx].bitmapToGenerate,
                                                ref fontInfo.characters[charIdx].width,
                                                ref fontInfo.characters[charIdx].height);

                // populate offset of character
                fontInfo.characters[charIdx].offsetInBytes = charByteOffset;

                // increment byte offset
                charByteOffset += fontInfo.characters[charIdx].pages.Count;
            }
        }
Ejemplo n.º 48
0
 /// <summary>
 ///     Initialize a new instance of <see cref="SystemFontSource" /> with the specified value.
 /// </summary>
 /// <param name="fontInfo">The new <see cref="WpfColorFontDialog.FontInfo" />.</param>
 public SystemFontSource(FontInfo fontInfo)
 {
     FontInfo = fontInfo;
 }
Ejemplo n.º 49
0
        // get character descriptor array block name
        private string charDescArrayGetBlockName(FontInfo fontInfo, int currentBlockIndex, 
            bool includeTypeDefinition, bool includeBlockIndex)
        {
            // get block id
            string blockIdString = String.Format("Block{0}", currentBlockIndex);

            // variable name
            string variableName = String.Format(m_outputConfig.varNfCharInfo, getFontName(ref fontInfo.font));

            // remove type unless required
            if (!includeTypeDefinition) variableName = getVariableNameFromExpression(variableName);

            // return the block name
            return String.Format("{0}{1}",
                                    variableName,
                                    includeBlockIndex ? blockIdString : "");
        }
Ejemplo n.º 50
0
        private void Calculate(string text, FontInfo fontInfo, bool isWrapped)
        {
            var textLength = GetTextLength(fontInfo, text, isWrapped);

            var showTooltip = false;
            switch (_cutTextKind)
            {
                case CutTextKind.Height:
                    showTooltip = (textLength.Height > _owner.DesiredSize.Height);
                    break;
                case CutTextKind.Width:
                    showTooltip = (textLength.Width > _owner.DesiredSize.Width);
                    break;
                case CutTextKind.WithAndHeight:
                    showTooltip = (textLength.Width > _owner.DesiredSize.Width || textLength.Height > _owner.DesiredSize.Height);
                    break;
            }

            _owner.ToolTip = showTooltip ? text : null;
        }
Ejemplo n.º 51
0
        // gnereate a list of blocks describing the characters
        private void generateCharacterDescriptorBlockList(FontInfo fontInfo, ref ArrayList characterBlockList)
        {
            char currentCharacter, previousCharacter = '\0';

            // initialize first block
            CharacterDescriptorArrayBlock characterBlock = null;

            // get the difference between two characters required to create a new group
            int differenceBetweenCharsForNewGroup = m_outputConfig.generateLookupBlocks ?
                    m_outputConfig.lookupBlocksNewAfterCharCount : int.MaxValue;

            // iterate over characters, saving previous character each time
            for (int charIndex = 0;
                 charIndex < fontInfo.characters.Length;
                 ++charIndex)
            {
                // get character
                currentCharacter = fontInfo.characters[charIndex].character;

                // check if this character is too far from the previous character and it isn't the first char
                if (currentCharacter - previousCharacter < differenceBetweenCharsForNewGroup && previousCharacter != '\0')
                {
                    // it may not be far enough to generate a new group but it still may be non-sequential
                    // in this case we need to generate place holders
                   /* for (char sequentialCharIndex = (char)(previousCharacter + 1);
                            sequentialCharIndex < currentCharacter;
                            ++sequentialCharIndex)
                    {
                        // add the character placeholder to the current char block
                        charDescArrayAddCharacter(characterBlock, fontInfo, sequentialCharIndex, 0, 0, 0);
                    }*/

                    // fall through and add to current block
                }
                else
                {
                    // done with current block, add to list (null is for first character which hasn't
                    // created a group yet)
                    if (characterBlock != null) characterBlockList.Add(characterBlock);

                    // create new block
                    characterBlock = new CharacterDescriptorArrayBlock();
                    characterBlock.characters = new ArrayList();
                }

                // add to current block
                charDescArrayAddCharacter(characterBlock, fontInfo, currentCharacter,
                                          fontInfo.characters[charIndex].width,
                                          fontInfo.characters[charIndex].height,
                                          fontInfo.characters[charIndex].offsetInBytes);

                // save previous char
                previousCharacter = currentCharacter;
            }

            // done; add current block to list
            characterBlockList.Add(characterBlock);
        }
Ejemplo n.º 52
0
        private Size GetTextLength(FontInfo fontInfo, string text, bool isWrapped)
        {
            var typeface = new Typeface(fontInfo.FontFamily, fontInfo.FontStyle, fontInfo.FontWeight, fontInfo.FontStretch);
            var formattedText = new FormattedText(text, Thread.CurrentThread.CurrentCulture, fontInfo.FlowDirection, typeface, fontInfo.FontSize, fontInfo.Foreground);

            if (isWrapped)
                formattedText.MaxTextWidth = fontInfo.ActualWidth;

            var padding = GetPadding();
            return new Size(formattedText.Width + padding.Left + padding.Right, formattedText.Height + padding.Bottom + padding.Top);
        }
Ejemplo n.º 53
0
        // generate the strings
        private void generateStringsFromFontInfo(FontInfo fontInfo, ref string resultTextSource, ref string resultTextHeader)
        {
            //
            // Character bitmaps
            //

            // according to config
            if (m_outputConfig.commentVariableName)
            {
                // add source header
                resultTextSource += String.Format("{0}Character bitmaps for {1} {2}pt{3}" + nl,
                                                    m_commentStartString, fontInfo.font.Name,
                                                    Math.Round(fontInfo.font.Size), m_commentEndString);
            }

            // get bitmap name
            string charBitmapVarName = String.Format(m_outputConfig.varNfBitmaps, getFontName(ref fontInfo.font));

            // Add the definition file for our structures
            resultTextHeader += "#include \"font.h\"" + nl + nl;

            // header var
            resultTextHeader += String.Format("extern {0};" + nl, charBitmapVarName);

            // source var
            resultTextSource += String.Format("{0} = " + nl+"{{" + nl, charBitmapVarName);

            // iterate through letters
            for (int charIdx = 0; charIdx < fontInfo.characters.Length; ++charIdx)
            {
                // skip empty bitmaps
                if (fontInfo.characters[charIdx].bitmapToGenerate == null) continue;

                // according to config
                if (m_outputConfig.commentCharDescriptor)
                {
                    // output character header
                    resultTextSource += String.Format("\t{0}@{1} '{2}' ({3} pixels wide){4}" + nl,
                                                        m_commentStartString,
                                                        fontInfo.characters[charIdx].offsetInBytes,
                                                        fontInfo.characters[charIdx].character,
                                                        fontInfo.characters[charIdx].width,
                                                        m_commentEndString);
                }

                // now add letter array
                var charInfo = fontInfo.characters[charIdx];
                var bitmap = fontInfo.characters[charIdx].bitmapToGenerate;
                resultTextSource += generateStringFromPageArray(bitmap.Width, bitmap.Height, charInfo.pages);

                // space out
                if (charIdx != fontInfo.characters.Length - 1 && m_outputConfig.commentCharDescriptor)
                {
                    // space between chars
                    resultTextSource += nl;
                }
            }

            // space out
            resultTextSource += "};" + nl + nl;

            //
            // Charater descriptor
            //

            // whether or not block lookup was generated
            bool blockLookupGenerated = false;

            // generate the lookup array
            generateCharacterDescriptorArray(fontInfo, ref resultTextSource, ref resultTextHeader, ref blockLookupGenerated);

            //
            // Font descriptor
            //

            // according to config
            if (m_outputConfig.commentVariableName)
            {
                // result string
                resultTextSource += String.Format("{0}Font information for {1} {2}pt{3}" + nl,
                                                    m_commentStartString,
                                                    fontInfo.font.Name, Math.Round(fontInfo.font.Size),
                                                    m_commentEndString);
            }

            // character name
            string fontInfoVarName = String.Format(m_outputConfig.varNfFontInfo, getFontName(ref fontInfo.font));

            // add character array for header
            resultTextHeader += String.Format("extern {0};" + nl, fontInfoVarName);

            // the font character height
            string fontCharHeightString = "", spaceCharacterPixelWidthString = "";

            // get character height sstring - displayed according to output configuration
            if (m_outputConfig.descFontHeight != OutputConfiguration.DescriptorFormat.DontDisplay)
            {
                // convert the value
                fontCharHeightString = String.Format("\t{0}, {1} Character height{2}" + nl,
                                              convertValueByDescriptorFormat(m_outputConfig.descFontHeight, fontInfo.charHeight),
                                              m_commentStartString,
                                              m_commentEndString);
            }

            // get space char width, if it is up to driver to generate
            if (!m_outputConfig.generateSpaceCharacterBitmap)
            {
                // convert the value
                spaceCharacterPixelWidthString = String.Format("\t{0}, {1} Width, in pixels, of space character{2}" + nl,
                                                                m_outputConfig.spaceGenerationPixels,
                                                                m_commentStartString,
                                                                m_commentEndString);
            }

            // Generate the get function
            string getFunctionName = getFontName(ref fontInfo.font) + "GetFunction";

            resultTextSource += "uint8_t " + getFunctionName + "(char c)" + nl + "{" + nl
                + "\tuint8_t b = (uint8_t)c;" + nl + nl;

            {
                int start_pos = 0;
                byte start_val = Convert.ToByte(fontInfo.characters[0].character);
                byte prev_val = start_val;
                bool first = true;

                for (int charIdx = 1; charIdx < fontInfo.characters.Length; ++charIdx)
                {
                    byte b = Convert.ToByte(fontInfo.characters[charIdx].character);

                    // If we don't have a continuous span, close the previous span and start a new one
                    if (prev_val + 1 < b)
                    {
                        byte prev = Convert.ToByte(fontInfo.characters[charIdx - 1].character);

                        if (first)
                        {
                            resultTextSource += "\t";
                            first = false;
                        }
                        else
                            resultTextSource += "\telse ";

                        resultTextSource += "if (";

                        // If the old span is greater than one character
                        if (charIdx > start_pos + 1)
                        {
                            if (first)
                                resultTextSource += "b >= " + start_val.ToString() + " && ";

                            resultTextSource += "b <= " + prev.ToString() + ") return (c - " + start_val.ToString() + ") + " + start_pos.ToString() + ";" + nl;

                        }
                        // If it's just one character
                        else
                            resultTextSource += "b == " + start_val.ToString() + ") return " + start_pos.ToString() + ";" + nl;

                        start_pos = charIdx;
                        start_val = Convert.ToByte(fontInfo.characters[charIdx].character);
                    }

                    prev_val = b;
                }

                // Add the final condition
                int lastIdx = fontInfo.characters.Length - 1;
                byte last = Convert.ToByte(fontInfo.characters[lastIdx].character);

                if (!first)
                    resultTextSource += "\telse ";
                else
                    resultTextSource += "\t";

                resultTextSource += "if (";

                // If the old span is greater than one character
                if (lastIdx > start_pos + 1)
                    resultTextSource += "b >= " + start_val.ToString() + " && " + "b <= " + last.ToString() + ") return (c - " + start_val.ToString() + ") + " + start_pos.ToString() + ";" + nl;
                // If it's just one character
                else
                    resultTextSource += "b == " + start_val.ToString() + ") return " + start_pos.ToString() + ";" + nl;

                resultTextSource += "\telse return 0;" + nl;
            }

            resultTextSource += "}" + nl + nl;

            // font info
            resultTextSource += String.Format("{2} =" + nl+"{{" + nl +
                                              "{3}" +
                                              "\t{4}, {0} Start character{1}" + nl +
                                              "\t{5}, {0} End character{1}" + nl +
                                              "{6}" +
                                              "{7}" +
                                              "\t{8}, {0} Character bitmap array{1}" + nl +
                                              "\t{9}, {0} The function that translates regular characters to this font's characters{1}" + nl +
                                              "}};" + nl,
                                              m_commentStartString,
                                              m_commentEndString,
                                              fontInfoVarName,
                                              fontCharHeightString,
                                              getCharacterDisplayString(fontInfo.startChar),
                                              getCharacterDisplayString(fontInfo.endChar),
                                              spaceCharacterPixelWidthString,
                                              getFontInfoDescriptorsString(fontInfo, blockLookupGenerated),
                                              getVariableNameFromExpression(String.Format(m_outputConfig.varNfBitmaps, getFontName(ref fontInfo.font))),
                                              getFunctionName);

            // add the appropriate entity to the header
            if (blockLookupGenerated)
            {
                // add block lookup to header
                resultTextHeader += String.Format("extern const FONT_CHAR_INFO_LOOKUP {0};" + nl, getCharacterDescriptorArrayLookupDisplayString(fontInfo));
            }
            else
            {
                // add block lookup to header
                resultTextHeader += String.Format("extern {0};" + nl, String.Format(m_outputConfig.varNfCharInfo, getFontName(ref fontInfo.font)));
            }

            resultTextHeader = Regex.Replace(resultTextHeader, "\\s?PROGMEM", "");
        }
        public override void Rebuild(CanvasUpdate update)
        {
            if (update == CanvasUpdate.LatePreRender)
            {
                MainThreadInvoker.Invoke(() =>
                {
                    ClearImages();
                });
                for (int i = 0; i < textInfo.characterCount; i++)
                {
                    TMP_CharacterInfo c = textInfo.characterInfo[i];
                    if (!c.isVisible || string.IsNullOrEmpty(text) || c.index >= text.Length)
                    {
                        // Skip invisible/empty/out of range chars
                        continue;
                    }

                    uint character = text[c.index];
                    if (c.index + 1 < text.Length && char.IsSurrogatePair(text[c.index], text[c.index + 1]))
                    {
                        // If it's a surrogate pair, convert the character
                        character = (uint)char.ConvertToUtf32(text[c.index], text[c.index + 1]);
                    }

                    if (FontInfo == null || !FontInfo.TryGetImageInfo(character, out var imageInfo) || imageInfo is null)
                    {
                        // Skip characters that have no imageInfo registered
                        continue;
                    }

                    MainThreadInvoker.Invoke(() =>
                    {
                        var img = _imagePool.Alloc();
                        try
                        {
                            if (imageInfo.AnimControllerData != null)
                            {
                                img.animStateUpdater.controllerData = imageInfo.AnimControllerData;
                                img.sprite = imageInfo.AnimControllerData.sprites[imageInfo.AnimControllerData.uvIndex];
                            }
                            else
                            {
                                img.sprite = imageInfo.Sprite;
                            }
                            img.material = BeatSaberUtils.UINoGlowMaterial;
                            img.rectTransform.localScale = new Vector3(fontScale * 1.08f, fontScale * 1.08f, fontScale * 1.08f);
                            img.rectTransform.sizeDelta  = new Vector2(imageInfo.Width, imageInfo.Height);
                            img.rectTransform.SetParent(rectTransform, false);
                            img.rectTransform.localPosition = c.topLeft - new Vector3(0, imageInfo.Height * fontScale * 0.558f / 2);
                            img.rectTransform.localRotation = Quaternion.identity;
                            img.gameObject.SetActive(true);
                            _currentImages.Add(img);
                        }
                        catch (Exception ex)
                        {
                            Logger.log.Error($"Exception while trying to overlay sprite. {ex.ToString()}");
                            _imagePool.Free(img);
                        }
                    });
                }
            }
            base.Rebuild(update);
            if (update == CanvasUpdate.LatePreRender)
            {
                MainThreadInvoker.Invoke(OnLatePreRenderRebuildComplete);
            }
        }
Ejemplo n.º 55
0
		}; // class FontInfo

		// Constructor.
		public FontDialogForm(FontDialog dialog)
				{
					// Record the parent for later access.
					this.dialog = dialog;

					// Create the initial font cache.
					fonts = new Hashtable();
					FontInfo info = new FontInfo(dialog.Font, false);
					fonts.Add(info, info);

					// Set the title.
					Text = S._("SWF_FontDialog_Title", "Font");

					// Construct the layout boxes for the font dialog.
					hbox = new HBoxLayout();
					hbox.Dock = DockStyle.Fill;
					vbox1 = new VBoxLayout();
					vbox2 = new VBoxLayout();
					vbox3 = new VBoxLayout();
					hbox2 = new HBoxLayout();
					grid = new GridLayout(2, 3);
					grid.StretchColumn = 0;
					effects = new GroupBox();
					effects.Text = S._("SWF_FontDialog_Effects", "Effects");
					effects.Width = 80;
					hbox.Controls.Add(vbox1);
					hbox.Controls.Add(vbox2);
					hbox.StretchControl = vbox1;
					hbox2.Controls.Add(grid);
					hbox2.Controls.Add(effects);
					hbox2.StretchControl = grid;
					vbox1.Controls.Add(hbox2);
					vbox1.StretchControl = hbox2;
					effects.Controls.Add(vbox3);
					vbox3.Dock = DockStyle.Fill;

					// Create the main display area.
					Label label;
					label = new Label();
					label.Text = S._("SWF_FontDialog_Name", "Font:");
					name = new TextBox();
					name.ReadOnly = true;
					nameList = new ListBox();
					grid.SetControl(0, 0, label);
					grid.SetControl(0, 1, name);
					grid.SetControl(0, 2, nameList);
					label = new Label();
					label.Text = S._("SWF_FontDialog_Size", "Size:");
					size = new TextBox();
					size.Width = 40;
					size.ReadOnly = true;
					sizeList = new ListBox();
					sizeList.Width = 40;
					grid.SetControl(1, 0, label);
					grid.SetControl(1, 1, size);
					grid.SetControl(1, 2, sizeList);

					// Create the buttons.
					okButton = new Button();
					okButton.Text = S._("SWF_MessageBox_OK", "OK");
					cancelButton = new Button();
					cancelButton.Text = S._("SWF_MessageBox_Cancel", "Cancel");
					applyButton = new Button();
					applyButton.Text = S._("SWF_MessageBox_Apply", "Apply");
					helpButton = new Button();
					helpButton.Text = S._("SWF_MessageBox_Help", "Help");
					vbox2.Controls.Add(okButton);
					vbox2.Controls.Add(cancelButton);
					vbox2.Controls.Add(applyButton);
					vbox2.Controls.Add(helpButton);
					vbox2.Controls.Add(new EmptyControl());
					AcceptButton = okButton;
					CancelButton = cancelButton;

					// Create the effects controls.
					bold = new CheckBox();
					bold.Text = S._("SWF_FontDialog_Bold", "Bold");
					italic = new CheckBox();
					italic.Text = S._("SWF_FontDialog_Italic", "Italic");
					underline = new CheckBox();
					underline.Text =
						S._("SWF_FontDialog_Underline", "Underline");
					strikeout = new CheckBox();
					strikeout.Text =
						S._("SWF_FontDialog_Strikeout", "Strikeout");
					Control spacing = new Control();
					vbox3.Spacing = 0;
					vbox3.Controls.Add(bold);
					vbox3.Controls.Add(italic);
					vbox3.Controls.Add(underline);
					vbox3.Controls.Add(strikeout);
					vbox3.Controls.Add(spacing);

					// Create the sample box.
					sample = new Control();
					sample.ForeColor = SystemColors.WindowText;
					sample.BackColor = SystemColors.Window;
					sample.BorderStyleInternal = BorderStyle.Fixed3D;
					sample.Height = 60;
					vbox1.Controls.Add(sample);

					// Add the top-level hbox to the dialog and set the size.
					Controls.Add(hbox);
					Size drawsize = hbox.RecommendedSize;
					if(drawsize.Width < 450)
					{
						drawsize.Width = 450;
					}
					if(drawsize.Height < 280)
					{
						drawsize.Height = 280;
					}
					ClientSize = drawsize;
					MinimumSize = drawsize;
					MinimizeBox = false;
					ShowInTaskbar = false;

					// Fill in the font names and sizes.
					nameList.BeginUpdate();
					foreach(FontFamily family in FontFamily.Families)
					{
						nameList.Items.Add(family.Name);
					}
					nameList.EndUpdate();
					sizeList.BeginUpdate();
					foreach(int value in sizes)
					{
						sizeList.Items.Add(value);
					}
					sizeList.EndUpdate();

					// Hook up interesting events.
					okButton.Click += new EventHandler(AcceptDialog);
					cancelButton.Click += new EventHandler(CancelDialog);
					applyButton.Click += new EventHandler(ApplyButtonClicked);
					helpButton.Click += new EventHandler(HelpButtonClicked);
					nameList.SelectedIndexChanged
						+= new EventHandler(NameIndexChanged);
					sizeList.SelectedIndexChanged
						+= new EventHandler(SizeIndexChanged);
					bold.CheckedChanged
						+= new EventHandler(FontStyleChanged);
					italic.CheckedChanged
						+= new EventHandler(FontStyleChanged);
					underline.CheckedChanged
						+= new EventHandler(FontStyleChanged);
					strikeout.CheckedChanged
						+= new EventHandler(FontStyleChanged);
					sample.Paint += new PaintEventHandler(PaintSample);

					// Match the requested settings from the dialog parent.
					UpdateDialog();
				}
Ejemplo n.º 56
0
        private Bitmap CreateGlyphForText(string text, ref int width, ref int height)
        {
            byte[] bitmapData = null;
            Bitmap bmp        = new Bitmap(512, 512, PixelFormat.Format24bppRgb);

            //Read ttf file into byte array
            byte[] ttfFileContent = File.ReadAllBytes(ttfSampleDir + '\\' + FontSelectorComboBox.SelectedItem as string);
            using (var ttf = new PinnedArray <byte>(ttfFileContent))
            {
                //get pointer of the ttf file content
                var ttf_buffer = ttf.Pointer;
                //Initialize fontinfo
                FontInfo font = new FontInfo();
                STBTrueType.InitFont(ref font, ttf_buffer, STBTrueType.GetFontOffsetForIndex(ttf_buffer, 0));
            }

            //TODO build packed characters' bitmap for ASCII/Chinese/Japanse/Korean characters etc.

            PackContext pc = new PackContext();

            width      = 512;
            height     = 512;
            bitmapData = new byte[width * height];
            STBTrueType.PackBegin(ref pc, bitmapData, width, height, 0, 1, IntPtr.Zero);

            //Ref: https://github.com/nothings/stb/blob/bdef693b7cc89efb0c450b96a8ae4aecf27785c8/tests/test_truetype.c
            //allocate packed char buffer
            PackedChar[] pdata = new PackedChar[text.Length];

            using (var pin_pdata = new PinnedArray <PackedChar>(pdata))
            {
                //get pointer of the pdata
                var         ptr_pdata  = pin_pdata.Pointer;
                PackRange[] vPackRange = new PackRange[text.Length];
                for (var i = 0; i < text.Length; ++i)
                {
                    //create a PackRange of one character
                    PackRange pr = new PackRange();
                    pr.chardata_for_range          = IntPtr.Add(ptr_pdata, i * Marshal.SizeOf(typeof(PackedChar)));
                    pr.first_unicode_char_in_range = text[i] & 0xFFFF;
                    pr.num_chars_in_range          = 1;
                    pr.font_size = pixelHeight;
                    //add it to the range list
                    vPackRange[i] = pr;
                }
                STBTrueType.PackSetOversampling(ref pc, 2, 2);
                using (var ttf = new PinnedArray <byte>(ttfFileContent))
                {
                    //get pointer of the ttf file content
                    var ttf_buffer = ttf.Pointer;
                    STBTrueType.PackFontRanges(ref pc, ttf_buffer, 0, vPackRange, vPackRange.Length);
                }
                STBTrueType.PackEnd(ref pc);
            }
            var bitmapPackedCharacters = CreateBitmapFromRawData(bitmapData, width, height);

            //ref
            //https://github.com/nothings/stb/blob/bdef693b7cc89efb0c450b96a8ae4aecf27785c8/tests/oversample/main.c

            //Draw characters to a bitmap by order
            Graphics g = Graphics.FromImage(bmp);

            g.Clear(Color.White);
            float x = 0, y = 0;

            for (var i = 0; i < text.Length; ++i)
            {
                var         character = text[i];
                AlignedQuad aq;
                //get character bitmaps in packed bitmap
                STBTrueType.GetPackedQuad(pdata, width, height, i, ref x, ref y, out aq, 0);
#if DebugOutput
                Debug.WriteLine(i);
                Debug.WriteLine("x: {0}, y: {1}", x, y);
                Debug.WriteLine("src: left-top: ({0}, {1}), right-bottom: ({2}, {3})", aq.s0 * width, aq.t0 * height, aq.s1 * width, aq.t1 * height);
                Debug.WriteLine("dest: left-top: ({0}, {1}), right-bottom: ({2}, {3})", aq.x0, aq.y0, aq.x1, aq.y1);
#endif
                var rectSrc  = RectangleF.FromLTRB(aq.s0 * width, aq.t0 * height, aq.s1 * width, aq.t1 * height);
                var rectDest = RectangleF.FromLTRB(aq.x0, aq.y0, aq.x1, aq.y1);
                rectDest.Offset(x, y + pixelHeight);//ATTENTION! The offset of lineHeight(pixelHeight here) should be appended.
#if DebugOutput
                Debug.WriteLine("rectSrc {0}", rectSrc);
                Debug.WriteLine("rectDest {0}", rectDest);
#endif
                g.DrawImage(bitmapPackedCharacters, rectDest, rectSrc, GraphicsUnit.Pixel);
            }
            g.Flush();
            return(bmp);
        }
Ejemplo n.º 57
0
		// Handle the "apply" button on this dialog.
		private void ApplyButtonClicked(Object sender, EventArgs e)
				{
					// Copy the font details into the dialog object.
					SetFont();

					// Make sure that the font cannot be disposed just
					// in case the surrounding application keeps a copy.
					FontInfo info = new FontInfo(dialog.Font, false);
					info = (FontInfo)(fonts[info]);
					if(info != null)
					{
						info.disposable = false;
					}

					// Emit the "Apply" signal.
					dialog.EmitApply(e);
				}
Ejemplo n.º 58
0
        // generate the strings
        private void generateStringsFromFontInfo(FontInfo fontInfo, ref string resultTextSource, ref string resultTextHeader)
        {
            //
            // Character bitmaps
            //

            // according to config
            if (m_outputConfig.commentVariableName)
            {
                // add source header
                resultTextSource += String.Format("{0}Character bitmaps for {1} {2}pt{3}" + nl,
                                                    m_commentStartString, fontInfo.font.Name,
                                                    Math.Round(fontInfo.font.Size), m_commentEndString);
            }

            // get bitmap name
            string charBitmapVarName = String.Format(m_outputConfig.varNfBitmaps, getFontName(ref fontInfo.font)) + "[]";

            // header var
            resultTextHeader += String.Format("extern {0};" + nl, charBitmapVarName);

            // source var
            resultTextSource += String.Format("{0} = " + nl+"{{" + nl, charBitmapVarName);

            // iterate through letters
            for (int charIdx = 0; charIdx < fontInfo.characters.Length; ++charIdx)
            {
                // skip empty bitmaps
                if (fontInfo.characters[charIdx].bitmapToGenerate == null) continue;

                // according to config
                if (m_outputConfig.commentCharDescriptor)
                {
                    // output character header
                    resultTextSource += String.Format("\t{0}@{1} '{2}' ({3} pixels wide){4}" + nl,
                                                        m_commentStartString,
                                                        fontInfo.characters[charIdx].offsetInBytes,
                                                        fontInfo.characters[charIdx].character,
                                                        fontInfo.characters[charIdx].width,
                                                        m_commentEndString);
                }

                // now add letter array
                var charInfo = fontInfo.characters[charIdx];
                var bitmap = fontInfo.characters[charIdx].bitmapToGenerate;
                resultTextSource += generateStringFromPageArray(bitmap.Width, bitmap.Height, charInfo.pages);

                // space out
                if (charIdx != fontInfo.characters.Length - 1 && m_outputConfig.commentCharDescriptor)
                {
                    // space between chars
                    resultTextSource += nl;
                }
            }

            // space out
            resultTextSource += "};" + nl + nl;

            //
            // Charater descriptor
            //

            // whether or not block lookup was generated
            bool blockLookupGenerated = false;

            // generate the lookup array
            generateCharacterDescriptorArray(fontInfo, ref resultTextSource, ref resultTextHeader, ref blockLookupGenerated);

            //
            // Font descriptor
            //

            // according to config
            if (m_outputConfig.commentVariableName)
            {
                // result string
                resultTextSource += String.Format("{0}Font information for {1} {2}pt{3}" + nl,
                                                    m_commentStartString,
                                                    fontInfo.font.Name, Math.Round(fontInfo.font.Size),
                                                    m_commentEndString);
            }

            // character name
            string fontInfoVarName = String.Format(m_outputConfig.varNfFontInfo, getFontName(ref fontInfo.font));

            // add character array for header
            resultTextHeader += String.Format("extern {0};" + nl, fontInfoVarName);

            // the font character height
            string fontCharHeightString = "", spaceCharacterPixelWidthString = "", fontCharMaxWidthString = "";

            // get character height sstring - displayed according to output configuration
            if (m_outputConfig.descFontHeight != OutputConfiguration.DescriptorFormat.DontDisplay)
            {
                // convert the value
                fontCharHeightString = String.Format("\t{0}, {1} Character height{2}" + nl,
                                              convertValueByDescriptorFormat(m_outputConfig.descFontHeight, fontInfo.charHeight),
                                              m_commentStartString,
                                              m_commentEndString);
            }

            // get space char width, if it is up to driver to generate
            if (!m_outputConfig.generateSpaceCharacterBitmap)
            {
                // convert the value
                spaceCharacterPixelWidthString = String.Format("\t{0}, {1} Width, in pixels, of space character{2}" + nl,
                                                                m_outputConfig.spaceGenerationPixels,
                                                                m_commentStartString,
                                                                m_commentEndString);
            }

            // get max char width
            fontCharMaxWidthString = String.Format("\t{0}, {1} Max width, in pixels, of widest character{2}" + nl,
                                                                fontInfo.charMaxWidth,
                                                                m_commentStartString,
                                                                m_commentEndString);

            // font info
            resultTextSource += String.Format("{2} =" + nl+"{{" + nl +
                                              "{3}" +
                                              "\t{4}, {0} Start character{1}" + nl +
                                              "\t{5}, {0} End character{1}" + nl +
                                              "{6}" +
                                              "{7}" +
                                              "\t{8}, {0} Character bitmap array{1}" + nl +
                                              "{9}" +
                                              "\t{10}, {0} Character spacing{1}" + nl +
                                              "}};" + nl,
                                              m_commentStartString,
                                              m_commentEndString,
                                              fontInfoVarName,
                                              fontCharHeightString,
                                              getCharacterDisplayString(fontInfo.startChar),
                                              getCharacterDisplayString(fontInfo.endChar),
                                              spaceCharacterPixelWidthString,
                                              getFontInfoDescriptorsString(fontInfo, blockLookupGenerated),
                                              getVariableNameFromExpression(String.Format(m_outputConfig.varNfBitmaps, getFontName(ref fontInfo.font))),
                                              fontCharMaxWidthString,
                                              2);

            // add the appropriate entity to the header
            if (blockLookupGenerated)
            {
                // add block lookup to header
                resultTextHeader += String.Format("extern const FONT_CHAR_INFO_LOOKUP {0}[];" + nl, getCharacterDescriptorArrayLookupDisplayString(fontInfo));
            }
            else
            {
                // add block lookup to header
                resultTextHeader += String.Format("extern {0}[];" + nl, String.Format(m_outputConfig.varNfCharInfo, getFontName(ref fontInfo.font)));
            }
        }
Ejemplo n.º 59
0
        public void EnsureInitialized(ContentManager contentManager)
        {
            if (_fontData == null)
            {
                _storage.ZeroFill();

                uint fontOffset = 0;

                FontInfo CreateFont(string name)
                {
                    if (contentManager.TryGetFontTitle(name, out ulong fontTitle) && contentManager.TryGetFontFilename(name, out string fontFilename))
                    {
                        string contentPath = contentManager.GetInstalledContentPath(fontTitle, StorageId.BuiltInSystem, NcaContentType.Data);
                        string fontPath    = _device.FileSystem.SwitchPathToSystemPath(contentPath);

                        if (!string.IsNullOrWhiteSpace(fontPath))
                        {
                            byte[] data;

                            using (IStorage ncaFileStream = new LocalStorage(fontPath, FileAccess.Read, FileMode.Open))
                            {
                                Nca         nca   = new Nca(_device.System.KeySet, ncaFileStream);
                                IFileSystem romfs = nca.OpenFileSystem(NcaSectionType.Data, _device.System.FsIntegrityCheckLevel);

                                using var fontFile = new UniqueRef <IFile>();

                                romfs.OpenFile(ref fontFile.Ref(), ("/" + fontFilename).ToU8Span(), OpenMode.Read).ThrowIfFailure();

                                data = DecryptFont(fontFile.Get.AsStream());
                            }

                            FontInfo info = new FontInfo((int)fontOffset, data.Length);

                            WriteMagicAndSize(fontOffset, data.Length);

                            fontOffset += 8;

                            uint start = fontOffset;

                            for (; fontOffset - start < data.Length; fontOffset++)
                            {
                                _storage.GetRef <byte>(fontOffset) = data[fontOffset - start];
                            }

                            return(info);
                        }
                        else
                        {
                            if (!contentManager.TryGetSystemTitlesName(fontTitle, out string titleName))
                            {
                                titleName = "Unknown";
                            }

                            throw new InvalidSystemResourceException($"{titleName} ({fontTitle:x8}) system title not found! This font will not work, provide the system archive to fix this error. (See https://github.com/Ryujinx/Ryujinx#requirements for more information)");
                        }
                    }
                    else
                    {
                        throw new ArgumentException($"Unknown font \"{name}\"!");
                    }
                }

                _fontData = new Dictionary <SharedFontType, FontInfo>
                {
                    { SharedFontType.JapanUsEurope, CreateFont("FontStandard") },
                    { SharedFontType.SimplifiedChinese, CreateFont("FontChineseSimplified") },
                    { SharedFontType.SimplifiedChineseEx, CreateFont("FontExtendedChineseSimplified") },
                    { SharedFontType.TraditionalChinese, CreateFont("FontChineseTraditional") },
                    { SharedFontType.Korean, CreateFont("FontKorean") },
                    { SharedFontType.NintendoEx, CreateFont("FontNintendoExtended") }
                };

                if (fontOffset > Horizon.FontSize)
                {
                    throw new InvalidSystemResourceException("The sum of all fonts size exceed the shared memory size. " +
                                                             $"Please make sure that the fonts don't exceed {Horizon.FontSize} bytes in total. (actual size: {fontOffset} bytes).");
                }
            }
        }
Ejemplo n.º 60
0
 public Task <ucFont> Create(FontInfo f)
 {
     return(Task.Run(() => new ucFont(f)));
 }