/// <summary>
        /// Set font of homework text.
        /// </summary>
        /// <param name="target">The target of this change. <see cref="FontTarget"/>.</param>
        /// <param name="font">The new font. <see cref="FontGroup"/>.</param>
        /// <param name="save">If true, this change will be saved.</param>
        public static void SetFont(FontTarget target, FontGroup font, bool save = true)
        {
            if (font == null)
            {
                return;
            }

            switch (target)
            {
            case FontTarget.NormalHomeworks:
                Global.userData.settings.fonts.NormalHomeworksFont = font;
                break;

            case FontTarget.Tests:
                Global.userData.settings.fonts.TestsFont = font;
                break;

            case FontTarget.subjects:
                Global.userData.settings.fonts.SubjectsFont = font;
                break;

            default:
                throw new Exception("FontTarget value \"" + target + "\" isn't known (SettingsManager.SetFont)");
            }

            HomeworkManager.RefontViewers();
            EventsManager.Call_FontChanged(target, font);

            if (save)
            {
                Save.SaveData();
            }
        }
Exemple #2
0
 public InstalledFontCollection()
 {
     //-----------------------------------------------------
     //init wellknown subfam
     _normal = CreateNewFontGroup(InstalledFontStyle.Normal, "regular", "normal");
     _italic = CreateNewFontGroup(InstalledFontStyle.Italic, "Italic", "italique");
     //
     _bold = CreateNewFontGroup(InstalledFontStyle.Bold, "bold");
     //
     _bold_italic = CreateNewFontGroup(InstalledFontStyle.Bold | InstalledFontStyle.Italic, "bold italic");
     //
 }
 private FontGroup GetFontGroup(string name, Func<FontDetail, bool> predicate)
 {
     var group = new FontGroup()
     {
         Description = name
     };
     foreach(var f in AllFonts.Where(predicate))
     {
         group.Add(f);
     }
     return group;
 }
Exemple #4
0
        private FontGroup GetFontGroup(string name, Func <FontDetail, bool> predicate)
        {
            var group = new FontGroup()
            {
                Description = name
            };

            foreach (var f in AllFonts.Where(predicate))
            {
                group.Add(f);
            }
            group.HasFonts = group.Count > 0;
            return(group);
        }
Exemple #5
0
        FontGroup CreateNewFontGroup(InstalledFontStyle installedFontStyle, params string[] names)
        {
            //create font group
            var fontGroup = new FontGroup();

            //single dic may be called by many names
            foreach (string name in names)
            {
                string upperCaseName = name.ToUpper();
                //register name
                //should not duplicate
                _subFamToFontGroup.Add(upperCaseName, fontGroup);
            }
            _allFontGroups.Add(fontGroup);
            return(fontGroup);
        }
Exemple #6
0
        bool RegisterFont(InstalledFont newfont)
        {
            FontGroup selectedFontGroup;
            string    fontsubFamUpperCaseName = newfont.FontSubFamily.ToUpper();

            if (!_subFamToFontGroup.TryGetValue(fontsubFamUpperCaseName, out selectedFontGroup))
            {
                //create new group, we don't known this font group before
                //so we add to 'other group' list
                selectedFontGroup = new FontGroup();
                _subFamToFontGroup.Add(fontsubFamUpperCaseName, selectedFontGroup);
                _allFontGroups.Add(selectedFontGroup);
            }

            if (newfont.TypographicFontName != newfont.FontName)
            {
            }

            //
            string fontNameUpper = newfont.FontName.ToUpper();

            if (selectedFontGroup.TryGetValue(fontNameUpper, out InstalledFont found))
            {
                //TODO:
                //we already have this font name
                //(but may be different file
                //we let user to handle it
                switch (fontNameDuplicatedHandler(found, newfont))
                {
                default: throw new NotSupportedException();

                case FontNameDuplicatedDecision.Skip:
                    return(false);

                case FontNameDuplicatedDecision.Replace:
                    selectedFontGroup.Replace(newfont);
                    return(true);
                }
            }
            else
            {
                selectedFontGroup.AddFont(newfont);
                return(true);
            }
        }
        public override async Task LoadAsync()
        {
            await base.LoadAsync();

            if (InstalledFonts == null)
            {
                var installedFonts = AllFonts;

                InstalledFonts = new FontGroup();
                InstalledFonts.Description = "Installed Locally";
                InstalledFonts.HasFonts = true;
                foreach (var f in installedFonts)
                {
                    f.Type = "Installed";
                    InstalledFonts.Add(f);
                }
            }

            if (OnlineFonts == null)
            {
                OnlineFonts = new FontGroup();
                OnlineFonts.Description = "Online";
                OnlineFonts.HasFonts = true;
                foreach (var f in await GetOnlineFonts())
                {
                    f.Type = "Online";
                    OnlineFonts.Add(f);
                }

                // load online fonts
                foreach (var font in OnlineFonts)
                {
                    var codes = font.CharacterCodes.Select(c => new FontChar()
                    {
                        Name = c.Key,
                        Char = (char)c.Value,
                        Family = font.Name,
                        Size = 48
                    });
                }
            }

            AllFonts = OnlineFonts.Union(InstalledFonts).ToList();
        }
Exemple #8
0
        public override async Task LoadAsync()
        {
            await base.LoadAsync();

            if (InstalledFonts == null)
            {
                var installedFonts = AllFonts;

                InstalledFonts             = new FontGroup();
                InstalledFonts.Description = "Installed Locally";
                InstalledFonts.HasFonts    = true;
                foreach (var f in installedFonts)
                {
                    f.Type = "Installed";
                    InstalledFonts.Add(f);
                }
            }

            if (OnlineFonts == null)
            {
                OnlineFonts             = new FontGroup();
                OnlineFonts.Description = "Online";
                OnlineFonts.HasFonts    = true;
                foreach (var f in await GetOnlineFonts())
                {
                    f.Type = "Online";
                    OnlineFonts.Add(f);
                }

                // load online fonts
                foreach (var font in OnlineFonts)
                {
                    var codes = font.CharacterCodes.Select(c => new FontChar()
                    {
                        Name   = c.Key,
                        Char   = (char)c.Value,
                        Family = font.Name,
                        Size   = 48
                    });
                }
            }

            AllFonts = OnlineFonts.Union(InstalledFonts).ToList();
        }
 public override Task RefreshAsync()
 {
     InstalledFonts = null;
     OnlineFonts = null;
     return base.RefreshAsync();
 }
 /// <summary>
 /// Invoke FontChanged event
 /// </summary>
 /// <param name="target">Type of element of this font (homework, test, subject)</param>
 /// <param name="font">New font</param>
 internal static void Call_FontChanged(FontTarget target, FontGroup font)
 {
     FontChanged?.Invoke(target, font);
 }
Exemple #11
0
 public override Task RefreshAsync()
 {
     InstalledFonts = null;
     OnlineFonts    = null;
     return(base.RefreshAsync());
 }
        public FontGroup GetGroupForFont(string fontName)
        {
            // Review Linux: very likely something here is not portable.
            if (FontNameToFiles == null)
            {
                FontNameToFiles = new Dictionary<string, FontGroup>();
            #if __MonoCS__
                using (var lib = new SharpFont.Library())
                {
                    // Find all the font files in the standard system location (/usr/share/font) and $HOME/.font (if it exists)
                    foreach (var fontFile in FindLinuxFonts())
                    {
                        try
                        {
                            using (var face = new SharpFont.Face(lib, fontFile))
                            {
                                var embeddingTypes = face.GetFSTypeFlags();
                                if ((embeddingTypes & EmbeddingTypes.RestrictedLicense) == EmbeddingTypes.RestrictedLicense ||
                                    (embeddingTypes & EmbeddingTypes.BitmapOnly) == EmbeddingTypes.BitmapOnly)
                                {
                                    continue;
                                }
                                var name = face.FamilyName;
                                // If you care about bold, italic, etc, you can filter here.
                                FontGroup files;
                                if (!FontNameToFiles.TryGetValue(name, out files))
                                {
                                    files = new FontGroup();
                                    FontNameToFiles[name] = files;
                                }
                                files.Add(face, fontFile);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            #else
                foreach (var fontFile in Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.Fonts)))
                {
                    // ePUB only understands these types, so skip anything else.
                    switch (Path.GetExtension(fontFile))
                    {
                        case ".ttf":
                        case ".otf":
                        case ".woff":
                            break;
                        default:
                            continue;
                    }
                    GlyphTypeface gtf;
                    try
                    {
                        gtf = new GlyphTypeface(new Uri("file:///" + fontFile));
                    }
                    catch (Exception)
                    {
                        continue; // file is somehow corrupt or not really a font file? Just ignore it.
                    }
                    switch (gtf.EmbeddingRights)
                    {
                        case FontEmbeddingRight.Editable:
                        case FontEmbeddingRight.EditableButNoSubsetting:
                        case FontEmbeddingRight.Installable:
                        case FontEmbeddingRight.InstallableButNoSubsetting:
                        case FontEmbeddingRight.PreviewAndPrint:
                        case FontEmbeddingRight.PreviewAndPrintButNoSubsetting:
                            break;
                        default:
                            continue; // not allowed to embed (enhance: warn user?)
                    }

                    var fc = new PrivateFontCollection();
                    try
                    {
                        fc.AddFontFile(fontFile);
                    }
                    catch (FileNotFoundException)
                    {
                        continue; // not sure how this can happen but I've seen it.
                    }
                    var name = fc.Families[0].Name;
                    // If you care about bold, italic, etc, you can filter here.
                    FontGroup files;
                    if (!FontNameToFiles.TryGetValue(name, out files))
                    {
                        files = new FontGroup();
                        FontNameToFiles[name] = files;
                    }
                    files.Add(gtf, fontFile);
                }
            #endif
            }
            FontGroup result;
            FontNameToFiles.TryGetValue(fontName, out result);
            return result;
        }
        public void EmbedFonts_EmbedsExpectedFontsAndReportsOthers()
        {
            var bookHtml       = @"<html><head>
						<link rel='stylesheet' href='Basic Book.css' type='text/css'></link>
						<link rel='stylesheet' href='Traditional-XMatter.css' type='text/css'></link>
						<link rel='stylesheet' href='CustomBookStyles.css' type='text/css'></link>
						<style type='text/css' title='userModifiedStyles'>
							/*<![CDATA[*/
							.Times-style[lang='tpi'] { font-family: Times New Roman ! important; font-size: 12pt  }
							/*]]>*/
						</style>
					</head><body>
					<div class='bloom-page' id='guid1'></div>
			</body></html>"            ;
            var testBook       = CreateBookWithPhysicalFile(bookHtml, bringBookUpToDate: false);
            var fontFileFinder = new StubFontFinder();

            using (var tempFontFolder = new TemporaryFolder("EmbedFonts_EmbedsExpectedFontsAndReportsOthers"))
            {
                fontFileFinder.NoteFontsWeCantInstall = true;

                // Font called for in HTML
                var timesNewRomanFileName = "Times New Roman R.ttf";
                var tnrPath = Path.Combine(tempFontFolder.Path, timesNewRomanFileName);
                File.WriteAllText(tnrPath, "This is phony TNR");

                // Font called for in custom styles CSS
                var calibreFileName = "Calibre R.ttf";
                var calibrePath     = Path.Combine(tempFontFolder.Path, calibreFileName);
                File.WriteAllBytes(calibrePath, new byte[200008]);                 // we want something with a size greater than zero in megs

                fontFileFinder.FilesForFont["Times New Roman"] = new[] { tnrPath };
                fontFileFinder.FilesForFont["Calibre"]         = new [] { calibrePath };
                fontFileFinder.FontsWeCantInstall.Add("NotAllowed");
                // And "NotFound" just doesn't get a mention anywhere.

                var stubProgress = new StubProgress();

                var customStylesPath = Path.Combine(testBook.FolderPath, "CustomBookStyles.css");
                File.WriteAllText(customStylesPath, ".someStyle {font-family:Calibre} .otherStyle {font-family: NotFound} .yetAnother {font-family:NotAllowed}");

                var tnrGroup = new FontGroup();
                tnrGroup.Normal = tnrPath;
                fontFileFinder.FontGroups["Times New Roman"] = tnrGroup;
                var calibreGroup = new FontGroup();
                calibreGroup.Normal = calibrePath;
                fontFileFinder.FontGroups["Calibre"] = calibreGroup;

                BloomReaderFileMaker.EmbedFonts(testBook, stubProgress, fontFileFinder);

                Assert.That(File.Exists(Path.Combine(testBook.FolderPath, timesNewRomanFileName)));
                Assert.That(File.Exists(Path.Combine(testBook.FolderPath, calibreFileName)));
                Assert.That(stubProgress.MessagesNotLocalized, Has.Member("Checking Times New Roman font: License OK for embedding."));
                Assert.That(stubProgress.MessagesNotLocalized, Has.Member("<span style='color:blue'>Embedding font Times New Roman at a cost of 0.0 megs</span>"));
                Assert.That(stubProgress.MessagesNotLocalized, Has.Member("Checking Calibre font: License OK for embedding."));
                Assert.That(stubProgress.MessagesNotLocalized, Has.Member("<span style='color:blue'>Embedding font Calibre at a cost of 0.2 megs</span>"));

                Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Checking NotAllowed font: License does not permit embedding."));
                Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Substituting \"Andika New Basic\" for \"NotAllowed\""));
                Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Checking NotFound font: No font found to embed."));
                Assert.That(stubProgress.ErrorsNotLocalized, Has.Member("Substituting \"Andika New Basic\" for \"NotFound\""));

                var fontSourceRulesPath = Path.Combine(testBook.FolderPath, "fonts.css");
                var fontSource          = RobustFile.ReadAllText(fontSourceRulesPath);
                // We're OK with these in either order.
                string lineTimes = "@font-face {font-family:'Times New Roman'; font-weight:normal; font-style:normal; src:url(Times New Roman R.ttf) format('opentype');}"
                                   + Environment.NewLine;
                string lineCalibre = "@font-face {font-family:'Calibre'; font-weight:normal; font-style:normal; src:url(Calibre R.ttf) format('opentype');}"
                                     + Environment.NewLine;
                Assert.That(fontSource, Is.EqualTo(lineTimes + lineCalibre).Or.EqualTo(lineCalibre + lineTimes));
                AssertThatXmlIn.Dom(testBook.RawDom).HasSpecifiedNumberOfMatchesForXpath("//link[@href='fonts.css']", 1);
            }
        }