Пример #1
0
        public void Setup()
        {
            var library = new Moq.Mock <CollectionSettings>();

            library.SetupGet(x => x.IsSourceCollection).Returns(false);
            library.SetupGet(x => x.Language2Iso639Code).Returns("en");
            library.SetupGet(x => x.Language1Iso639Code).Returns("xyz");
            library.SetupGet(x => x.XMatterPackName).Returns("Factory");

            ErrorReport.IsOkToInteractWithUser = false;
            _fileLocator = new FileLocator(new string[]
            {
                //FileLocationUtilities.GetDirectoryDistributedWithApplication( "factoryCollections"),
                BloomFileLocator.GetFactoryBookTemplateDirectory("Basic Book"),
                BloomFileLocator.GetFactoryBookTemplateDirectory("Wall Calendar"),
                FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot),
                BloomFileLocator.GetBrowserDirectory("bookLayout"),
                BloomFileLocator.GetBrowserDirectory("bookEdit", "css"),
                BloomFileLocator.GetInstalledXMatterDirectory()
            });

            var projectFolder      = new TemporaryFolder("BookStarterTests_ProjectCollection");
            var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));

            _starter = new BookStarter(_fileLocator, (dir, forSelectedBook) => new BookStorage(dir, _fileLocator, new BookRenamedEvent(), collectionSettings), library.Object);
            _shellCollectionFolder = new TemporaryFolder("BookStarterTests_ShellCollection");
            _libraryFolder         = new TemporaryFolder("BookStarterTests_LibraryCollection");
        }
Пример #2
0
        private static void SetUpLocalization()
        {
            string installedStringFileFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication("localization");
            string targetTmxFilePath         = Path.Combine(GlyssenInfo.kCompany, GlyssenInfo.kProduct);
            string desiredUiLangId           = Settings.Default.UserInterfaceLanguage;

            PrimaryLocalizationManager = LocalizationManager.Create(TranslationMemory.Tmx, desiredUiLangId, GlyssenInfo.kApplicationId, Application.ProductName, Application.ProductVersion,
                                                                    installedStringFileFolder, targetTmxFilePath, Resources.glyssenIcon, IssuesEmailAddress, "Glyssen");

            if (string.IsNullOrEmpty(desiredUiLangId))
            {
                if (LocalizationManager.GetUILanguages(true).Count() > 1)
                {
                    using (var dlg = new LanguageChoosingSimpleDialog(Resources.glyssenIcon))
                        if (DialogResult.OK == dlg.ShowDialog())
                        {
                            Analytics.Track("SetUiLanguage", new Dictionary <string, string> {
                                { "uiLanguage", dlg.SelectedLanguage }, { "initialStartup", "true" }
                            });

                            LocalizationManager.SetUILanguage(dlg.SelectedLanguage, true);
                            Settings.Default.UserInterfaceLanguage = dlg.SelectedLanguage;
                        }
                }
            }

            var uiLanguage = LocalizationManager.UILanguageId;

            LocalizationManager.Create(TranslationMemory.Tmx, uiLanguage, "Palaso", "Palaso", Application.ProductVersion,
                                       installedStringFileFolder, targetTmxFilePath, Resources.glyssenIcon, IssuesEmailAddress,
                                       "SIL.Windows.Forms.WritingSystems", "SIL.DblBundle", "SIL.Windows.Forms.DblBundle", "SIL.Windows.Forms.Miscellaneous");
        }
Пример #3
0
        public void Setup()
        {
            var collection = new CollectionSettings
            {
                IsSourceCollection  = false,
                Language2Iso639Code = "en",
                Language1Iso639Code = "xyz",
                XMatterPackName     = "Factory"
            };

            ErrorReport.IsOkToInteractWithUser = false;
            _fileLocator = new FileLocator(new string[]
            {
                //FileLocationUtilities.GetDirectoryDistributedWithApplication( "factoryCollections"),
                BloomFileLocator.GetFactoryBookTemplateDirectory("Basic Book"),
                BloomFileLocator.GetFactoryBookTemplateDirectory("Wall Calendar"),
                FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot),
                BloomFileLocator.GetBrowserDirectory("bookLayout"),
                BloomFileLocator.GetBrowserDirectory("bookEdit", "css"),
                BloomFileLocator.GetFactoryXMatterDirectory()
            });

            var projectFolder      = new TemporaryFolder("BookStarterTests_ProjectCollection");
            var collectionSettings = new CollectionSettings(Path.Combine(projectFolder.Path, "test.bloomCollection"));

            _starter = new BookStarter(_fileLocator, (dir, fullyUpdateBookFiles) => new BookStorage(dir, _fileLocator, new BookRenamedEvent(), collectionSettings), collection);
            _shellCollectionFolder = new TemporaryFolder("BookStarterTests_ShellCollection");
            _collectionFolder      = new TemporaryFolder("BookStarterTests_Collection");
        }
Пример #4
0
        /// <summary>
        /// Give the locations of the bedrock files/folders that come with Bloom. These will have priority.
        /// (But compare GetAfterXMatterFileLocations, for further paths that are searched after factory XMatter).
        /// </summary>
        public static IEnumerable <string> GetFactoryFileLocations()
        {
            //bookLayout has basepage.css. We have it first because it will find its way to many other folders, but this is the authoritative one
            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot, "bookLayout"));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot));

            //hack to get the distfiles folder itself
            yield return(Path.GetDirectoryName(FileLocationUtilities.GetDirectoryDistributedWithApplication("localization")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/js")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/js/toolbar")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/css")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/html")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/html/font-awesome/css")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/img")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "images")));

            foreach (var dir in ToolboxView.GetToolboxServerDirectories())
            {
                yield return(dir);
            }
            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/StyleEditor")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/TopicChooser")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "collection")));

            var x = FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "performance"));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "performance")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "themes/bloom-jqueryui-theme")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "lib")));

            // not needed: yield return FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot,"lib/localizationManager"));
            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "lib/long-press")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "lib/split-pane")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "lib/ckeditor/skins/icy_orange")));

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "bookEdit/toolbox/talkingBook")));

            yield return(BloomFileLocator.GetInstalledXMatterDirectory());

            yield return(FileLocationUtilities.GetDirectoryDistributedWithApplication(Path.Combine(BloomFileLocator.BrowserRoot, "publish/ePUBPublish")));
        }
Пример #5
0
        private static string TryToGetLegacyArtOfReadingImagesPath()
        {
            const string kImages            = "Images";
            var          distributedWithApp = FileLocationUtilities.GetDirectoryDistributedWithApplication(true, "Art Of Reading", kImages);

            if (!string.IsNullOrEmpty(distributedWithApp) && Directory.Exists(distributedWithApp))
            {
                return(distributedWithApp);
            }

            //look for it in a hard-coded location
            if (Environment.OSVersion.Platform == PlatformID.Unix)
            {
                var unixPaths = new[]
                {
                    @"/usr/share/ArtOfReading/images",     // new package location (standard LSB/FHS location)
                    @"/usr/share/SIL/ArtOfReading/images", // old (lost) package location
                    @"/var/share/ArtOfReading/images"      // obsolete test location (?)
                };

                foreach (var path in unixPaths)
                {
                    if (Directory.Exists(path))
                    {
                        return(path);
                    }
                }
            }
            else
            {
                //look for the folder created by the ArtOfReadingFree installer before 3.3, the first version to put it in the ImageCollections folder.
                var aorInstallerTarget =
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
                    .CombineForPath("SIL", "Art Of Reading", kImages);

                //the rest of these are for before we had an installer for AOR
                var appData =
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
                    .CombineForPath("Art Of Reading", kImages);
                var appDataNoSpace =
                    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
                    .CombineForPath("ArtOfReading", kImages);
                var winPaths = new[]
                {
                    aorInstallerTarget, @"c:\art of reading\images", @"c:/ArtOfReading/images", appData, appDataNoSpace
                };

                foreach (var path in winPaths)
                {
                    if (Directory.Exists(path))
                    {
                        return(path);
                    }
                }
            }
            return(null);
        }
Пример #6
0
        /// <summary>
        /// Make the registry entries Bloom requires.
        /// We do this every time a version of Bloom runs, so that if more than one is installed the latest wins.
        /// </summary>
        internal static void MakeBloomRegistryEntries(string[] programArgs)
        {
            if (Program.RunningUnitTests)
            {
                return;                 // unit testing.
            }
            // When installed in program files we only do registry entries when we are first installed,
            // thus keeping them consistent for all users, stored in HKLM.
            if (SharedByAllUsers() && !IsFirstTimeInstall(programArgs))
            {
                return;
            }
            _installInLocalMachine = SharedByAllUsers();
            if (Platform.IsLinux)
            {
                // This will be done by the package installer.
                return;
            }

            var iconDir = FileLocationUtilities.GetDirectoryDistributedWithApplication(true, "icons");

            if (iconDir == null)
            {
                // Note: if this happens a lot we'd want to make it localizable. I think that's unlikely, so it may not be worth the
                // burden on localizers.
                var exception =
                    new FileNotFoundException(
                        "Bloom was not able to find some of its files. The shortcut icon you clicked on may be out of date. Try deleting it and reinstalling Bloom");
                ProblemReportApi.ShowProblemDialog(null, exception, "", "fatal");
                // Not sure these lines are reachable. Just making sure.
                Application.Exit();
                return;
            }

            // BloomCollection icon
            CreateIconRegistrySettings("BloomCollection", iconDir, "BloomCollectionIcon.ico", "Bloom Book Collection");
            // BloomPack icon
            CreateIconRegistrySettings("BloomPack", iconDir, "BloomPack.ico", "Bloom Book Pack", "FriendlyTypeName");
            // JoinBloomTC icon
            CreateIconRegistrySettings("JoinBloomTC", iconDir, "JoinBloomTC.ico", "Join Bloom Team Collection");

            // This might be part of registering as the executable for various file types?
            // I don't know what does it in wix but it's one of the things the old wix installer created.
            var exe = Assembly.GetExecutingAssembly().Location;

            EnsureRegistryValue(@"bloom\shell\open\command", "\"" + exe + "\" \"%1\"");

            BeTheExecutableFor(".BloomCollection", "BloomCollection file");
            BeTheExecutableFor(".BloomPack", "BloomPack file");
            BeTheExecutableFor(".JoinBloomTC", "JoinBloom file");
            // Make the OS run Bloom when it sees bloom://somebooktodownload
            BookDownloadSupport.RegisterForBloomUrlProtocol(_installInLocalMachine);
        }
Пример #7
0
        private static void SetUpLocalization(string desiredUiLangId)
        {
            var assembly   = Assembly.GetExecutingAssembly();
            var attributes = assembly.GetCustomAttributes(typeof(AssemblyCompanyAttribute), false);
            var company    = attributes.Length == 0 ? "SIL" : ((AssemblyCompanyAttribute)attributes[0]).Company;
            var installedStringFileFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication("localization");
            var relativeSettingPathForLocalizationFolder = Path.Combine(company, pluginName);
            var version = assembly.GetName().Version.ToString();

            LocalizationManager.Create(TranslationMemory.XLiff, desiredUiLangId, pluginName, pluginName, version,
                                       installedStringFileFolder, relativeSettingPathForLocalizationFolder, new Icon(FileLocationUtilities.GetFileDistributedWithApplication("TXL no TXL.ico")), emailAddress,
                                       "SIL.Transcelerator", "SIL.Utils");
        }
Пример #8
0
 public void GetDirectoryDistributedWithApplication_WhenFails_ReportsAllTried()
 {
     try
     {
         FileLocationUtilities.GetDirectoryDistributedWithApplication("LookHere", "ThisWillNotExist");
     }
     catch (ArgumentException ex)
     {
         Assert.That(ex.Message, Is.StringContaining(Path.Combine("LookHere", "ThisWillNotExist")));
         Assert.That(ex.Message, Is.StringContaining(FileLocationUtilities.DirectoryOfApplicationOrSolution));
         Assert.That(ex.Message, Is.StringContaining("DistFiles"));
         Assert.That(ex.Message, Is.StringContaining("src"));
     }
 }
Пример #9
0
        /// ------------------------------------------------------------------------------------
        public static void WriteMetadata(XmlWriter writer, PaProject project, bool closeDiv)
        {
            writer.WriteStartElement("div");
            writer.WriteAttributeString("id", "metadata");

            // Open ul and div
            writer.WriteStartElement("ul");
            writer.WriteAttributeString("class", "settings");

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "programConfigurationFolder");

            var path = FileLocationUtilities.GetDirectoryDistributedWithApplication(App.ConfigFolderName);

            writer.WriteString(TerminateFolderPath(path));
            writer.WriteEndElement();

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "programPhoneticInventoryFile");
            writer.WriteString(App.kDefaultInventoryFileName);
            writer.WriteEndElement();

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "programDistinctiveFeaturesName");
            writer.WriteString(project.DistinctiveFeatureSet);
            writer.WriteEndElement();

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "userFolder");
            writer.WriteString(TerminateFolderPath(App.ProjectFolder));
            writer.WriteEndElement();

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "projectFolder");
            writer.WriteString(TerminateFolderPath(project.Folder));
            writer.WriteEndElement();

            writer.WriteStartElement("li");
            writer.WriteAttributeString("class", "projectPhoneticInventoryFile");
            writer.WriteString(Path.GetFileName(project.ProjectInventoryFileName));
            writer.WriteEndElement();

            // Close ul
            writer.WriteEndElement();

            if (closeDiv)
            {
                writer.WriteEndElement();
            }
        }
Пример #10
0
        public static bool InstallFont(string sourceFolder, bool needsRestart = true)
        {
            // This is not needed on Linux - fonts should be installed by adding a package
            // dependency, in this case fonts-sil-andika, or by installing that particular
            // package.
            if (!SIL.PlatformUtilities.Platform.IsWindows)
            {
                return(false);
            }

            var sourcePath = FileLocationUtilities.GetDirectoryDistributedWithApplication(sourceFolder);

            if (AllFontsExist(sourcePath))
            {
                return(false);                // already installed (Enhance: maybe one day we want to check version?)
            }
            var info = new ProcessStartInfo
            {
                // Renamed to make the UAC dialog less mysterious.
                // Originally it is FontReg.exe (http://code.kliu.org/misc/fontreg/).
                // Eventually we will probably have to get our version signed.
                FileName         = "Install Bloom Literacy Fonts.exe",
                Arguments        = "/copy",
                WorkingDirectory = sourcePath,
                UseShellExecute  = true,       // required for runas to achieve privilege elevation
                WindowStyle      = ProcessWindowStyle.Hidden,
                Verb             = "runas"     // that is, run as admin (required to install fonts)
            };

            try
            {
                Process.Start(info);
                if (needsRestart)
                {
                    Program.RestartBloom(true);
                }
                return(true);
            }
            // I hate catching 'Exception' but the one that is likely to happen, the user refused the privilege escalation
            // or is not authorized to do it, comes out as Win32Exception, which is not much more helpful.
            // We probably want to ignore anything else that can go wrong with trying to install the fonts.
            catch (Exception e)
            {
                SIL.Reporting.Logger.WriteEvent("**** Error trying to install font: " + e.Message);
                Debug.Fail(e.Message);
            }

            return(false);
        }
        /// <summary>
        /// stick in a json with various settings we want to make available to the javascript
        /// </summary>
        public static void AddUISettingsToDom(HtmlDom pageDom, BookData bookData, IFileLocator fileLocator)
        {
            CheckDynamicStrings();

            XmlElement existingElement = pageDom.RawDom.SelectSingleNode("//script[@id='ui-settings']") as XmlElement;

            XmlElement element = pageDom.RawDom.CreateElement("script");

            element.SetAttribute("type", "text/javascript");
            element.SetAttribute("id", "ui-settings");
            var d = new Dictionary <string, string>();

            //d.Add("urlOfUIFiles", "file:///" + fileLocator.LocateDirectory("ui", "ui files directory"));
            if (!String.IsNullOrEmpty(Settings.Default.LastSourceLanguageViewed))
            {
                d.Add("defaultSourceLanguage", Settings.Default.LastSourceLanguageViewed);
            }

            d.Add("languageForNewTextBoxes", bookData.Language1.Iso639Code);
            d.Add("isSourceCollection", bookData.CollectionSettings.IsSourceCollection.ToString());

            // BL-2357 To aid in smart ordering of source languages in source bubble
            if (!String.IsNullOrEmpty(bookData.Language2IsoCode))
            {
                d.Add("currentCollectionLanguage2", bookData.Language2IsoCode);
            }
            if (!String.IsNullOrEmpty(bookData.Language3IsoCode))
            {
                d.Add("currentCollectionLanguage3", bookData.Language3IsoCode);
            }

            d.Add("browserRoot", FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot).ToLocalhost());


            element.InnerText = String.Format("function GetSettings() {{ return {0};}}", JsonConvert.SerializeObject(d));

            var head = pageDom.RawDom.SelectSingleNode("//head");

            if (existingElement != null)
            {
                head.ReplaceChild(element, existingElement);
            }
            else
            {
                head.InsertAfter(element, head.LastChild);
            }

            _collectDynamicStrings = false;
        }
        public void Setup()
        {
            _collectionSettings = new Mock <CollectionSettings>();
            _collectionSettings.SetupGet(x => x.IsSourceCollection).Returns(false);
            _collectionSettings.SetupGet(x => x.Language1Iso639Code).Returns("xyz");
            _collectionSettings.SetupGet(x => x.Language2Iso639Code).Returns("fr");
            _collectionSettings.SetupGet(x => x.Language3Iso639Code).Returns("es");
            _collectionSettings.SetupGet(x => x.XMatterPackName).Returns("Factory");
            ErrorReport.IsOkToInteractWithUser = false;

            LocalizationManager.UseLanguageCodeFolders = true;
            var localizationDirectory = FileLocationUtilities.GetDirectoryDistributedWithApplication("src/BloomTests/TestLocalization");

            _localizationManager = LocalizationManager.Create(TranslationMemory.XLiff, "en", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/BloomTests", null, "");
        }
Пример #13
0
        public void Setup()
        {
            Logger.Init();
            _folder = new TemporaryFolder("BloomServerTests");
            LocalizationManager.UseLanguageCodeFolders = true;
            var localizationDirectory = FileLocationUtilities.GetDirectoryDistributedWithApplication("localization");

            _localizationManager = LocalizationManager.Create(TranslationMemory.XLiff, "fr", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/Bloom", null, "", new string[] { });


            ErrorReport.IsOkToInteractWithUser = false;
            _collectionPath = Path.Combine(_folder.Path, "TestCollection");
            var cs = new CollectionSettings(Path.Combine(_folder.Path, "TestCollection.bloomCollection"));

            _fileLocator = new BloomFileLocator(cs, new XMatterPackFinder(new string[] { BloomFileLocator.GetFactoryXMatterDirectory() }), ProjectContext.GetFactoryFileLocations(),
                                                ProjectContext.GetFoundFileLocations(), ProjectContext.GetAfterXMatterFileLocations());
        }
        public void Setup()
        {
            _collectionSettings = new CollectionSettings
            {
                IsSourceCollection  = false,
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "fr",
                Language3Iso639Code = "es",
                XMatterPackName     = "Factory"
            };
            ErrorReport.IsOkToInteractWithUser = false;

            LocalizationManager.UseLanguageCodeFolders = true;
            var localizationDirectory = FileLocationUtilities.GetDirectoryDistributedWithApplication("src/BloomTests/TestLocalization");

            _localizationManager = LocalizationManager.Create(TranslationMemory.XLiff, "en", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/BloomTests", null, "");
        }
Пример #15
0
        public void Setup()
        {
            _collectionSettings = new CollectionSettings(new NewCollectionSettings()
            {
                PathToSettingsFile  = CollectionSettings.GetPathForNewSettings(new TemporaryFolder("BookDataTests").Path, "test"),
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "en",
                Language3Iso639Code = "fr"
            });
            ErrorReport.IsOkToInteractWithUser = false;

            LocalizationManager.UseLanguageCodeFolders = true;
            var localizationDirectory = FileLocationUtilities.GetDirectoryDistributedWithApplication("localization");

            _localizationManager = LocalizationManager.Create(TranslationMemory.XLiff, "fr", "Bloom", "Bloom", "1.0.0", localizationDirectory, "SIL/Bloom",
                                                              null, "", new string[] { });
            _palasoLocalizationManager = LocalizationManager.Create(TranslationMemory.XLiff, "fr", "Palaso", "Palaso", "1.0.0", localizationDirectory, "SIL/Bloom",
                                                                    null, "", new string[] { });
        }
Пример #16
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            var installedStringFileFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication(false, "localization");

            LocalizationManager.UseLanguageCodeFolders    = true;
            LocalizationManager.ReturnOnlyApprovedStrings = true;

            // we start with the language of their Operating System
            var uiLanguage = CultureInfo.CurrentUICulture.TwoLetterISOLanguageName;

            // then if they've chosen a language in the past, use that
            if (Settings.Default.UserInterfaceLanguageSetExplicitly)
            {
                uiLanguage = Settings.Default.UserInterfaceLanguage;
            }

            using (var lm = LocalizationManager.Create(TranslationMemory.XLiff,
                                                       uiLanguage,
                                                       "Palaso", "Palaso", "1.0.0" /*product version*/, installedStringFileFolder, "SIL/Palaso",
                                                       null /*icon*/, ""))
            {
                // if the language we asked for wasn't available, the LocalizationManager will ask the user
                // to choose a different one. If that happens, let's remember their choice for next time
                if (uiLanguage != LocalizationManager.UILanguageId)
                {
                    Settings.Default.UserInterfaceLanguage = LocalizationManager.UILanguageId;
                    Settings.Default.UserInterfaceLanguageSetExplicitly = true;
                    Settings.Default.Save();
                }
                Application.Run(new Form1());
            }

            /*
             * LocalizationManager.SetUILanguage(tag.IsoCode, true);
             * Settings.Default.UserInterfaceLanguage = tag.IsoCode;
             * Settings.Default.UserInterfaceLanguageSetExplicitly = true;
             * Settings.Default.Save();
             */
        }
Пример #17
0
        private static void UpdateExtensions()
        {
            var extensions = new Dictionary <string, string>();

            if (!Platform.IsMono)
            {
                extensions.Add("eol", "");             //for converting line endings on windows machines
            }
            extensions.Add("hgext.graphlog", "");      //for more easily readable diagnostic logs
            extensions.Add("convert", "");             //for catastrophic repair in case of repo corruption
            string fixUtfFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication(false, "MercurialExtensions", "fixutf8");

            if (!string.IsNullOrEmpty(fixUtfFolder))
            {
                extensions.Add("fixutf8", Path.Combine(fixUtfFolder, "fixutf8.py"));
            }

            var doc = HgRepository.GetMercurialConfigInMercurialFolder();

            SetExtensions(doc, extensions);
            doc.SaveAndThrowIfCannot();
        }
Пример #18
0
        /// ------------------------------------------------------------------------------------
        private static void IfNecessaryUpgradeFilesThatMakePrettyHTMLExports(string fileTypeExtension)
        {
            var processingFolder =
                FileLocationUtilities.GetDirectoryDistributedWithApplication(App.ProcessingFolderName);

            foreach (var filename in Directory.GetFiles(processingFolder, fileTypeExtension))
            {
                try
                {
                    var dst = Path.Combine(App.ProjectFolder, Path.GetFileName(filename));

                    if (File.Exists(dst))
                    {
                        var srcfi = new FileInfo(filename);
                        var dstfi = new FileInfo(dst);

                        if (srcfi.LastWriteTime != dstfi.LastWriteTime || srcfi.Length != dstfi.Length)
                        {
                            File.Delete(dst);
                        }
                    }

                    if (!File.Exists(dst))
                    {
                        File.Copy(filename, dst);
                    }
                }
                catch (Exception e)
                {
                    var msg = LocalizationManager.GetString("Miscellaneous.Messages.UpgradingProcessFileErrorMsg",
                                                            "There was an error copying the file '{0}' to '{1}'. Make sure the file is not in use by another program.");

                    App.NotifyUserOfProblem(e, msg, filename, App.ProjectFolder);
                }
            }
        }
Пример #19
0
        /// <summary>
        /// We've had a number of user reports that suggest that files were either missing or inaccessible.
        /// The idea here is to check a set of files and folders at the start of each launch, and generate
        /// a useful report if anything is missing.
        /// </summary>
        /// <returns>true if all is well. Application should exit if this returns false.</returns>
        public static bool CheckIntegrity()
        {
            var errors = new StringBuilder();
            var files  = new[] { "Bloom.chm", "PdfDroplet.exe", "BloomPdfMaker.exe" };

            string[] dirs;
            if (Platform.IsWindows)
            {
                dirs = new[] { "AndikaNewBasic", "localization", "xslts", "icons" }
            }
            ;
            else
            {
                dirs = new[] { "localization", "xslts", "icons" }
            };

            foreach (var fileName in files)
            {
                if (FileLocationUtilities.GetFileDistributedWithApplication(true, fileName) == null)
                {
                    //In a code directory, the FileLocator considers the solution the root, so it can't find files in output\debug
                    if (!RobustFile.Exists(Path.Combine(FileLocationUtilities.DirectoryOfTheApplicationExecutable, fileName)))
                    {
                        //maybe it's an exe in distfiles?
                        if (fileName.EndsWith(".exe") && RobustFile.Exists(Path.Combine(FileLocationUtilities.DirectoryOfApplicationOrSolution, "DistFiles")))
                        {
                            continue;
                        }
                        errors.AppendFormat("<p>Missing File: {0}</p>{1}", fileName, Environment.NewLine);
                    }
                }
            }
            foreach (var directory in dirs)
            {
                if (FileLocationUtilities.GetDirectoryDistributedWithApplication(true, directory) == null)
                {
                    errors.AppendFormat("<p>Missing Directory: {0}</p>{1}", directory, Environment.NewLine);
                }
            }
            if (errors.Length == 0)
            {
                return(true);
            }

            using (var dlg = new BloomIntegrityDialog())
            {
                const string nonHtmlMessage = "Bloom cannot find some of its own files, and cannot continue. After you submit this report, we will contact you and help you work this out. In the meantime, you can run the Bloom installer again.";
                var          messagePath    = BloomFileLocator.GetBestLocalizableFileDistributedWithApplication(false, "help", "IntegrityFailureAdvice-en.htm");
                string       message;
                if (messagePath == null)                // maybe we can't even get at this file we need for a good description of the problem
                {
                    message = nonHtmlMessage;
                }
                else
                {
                    var installFolder = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData)
                                        .CombineForPath(Application.ProductName);
                    message = RobustFile.ReadAllText(messagePath).Replace("{{installFolder}}", installFolder); //new
                    message = message.Replace("{installFolder}", installFolder);                               //old
                }

                message = message + Environment.NewLine + Environment.NewLine + errors;
                dlg.htmlTextBox1.HtmlText = message;
                dlg.ShowDialog();
                Logger.WriteEvent("Bloom Integrity Check Failed: " + message);
                // We would like to do this:
                // ProblemReportApi.ShowProblemDialog(null, "fatal");
                // But that can't work because BloomServer isn't running yet.
            }

            return(false);            //Force termination of the current process.
        }
Пример #20
0
 public MercurialExtensionHider()
 {
     _extensionPath        = FileLocationUtilities.GetDirectoryDistributedWithApplication(false, "MercurialExtensions", "fixutf8");
     _extensionPathRenamed = _extensionPath + "-HidingForTest";
     Directory.Move(_extensionPath, _extensionPathRenamed);
 }
Пример #21
0
        public virtual void Setup()
        {
            _testFolder = new TemporaryFolder(GetTestFolderName());
            _tempFolder = new TemporaryFolder(_testFolder, "book");

            _bookDom = new HtmlDom(GetThreePageDom());             // a default, many tests replace this
            // Note that we're passing a function which returns the _bookDom member variable. By the time we return it,
            // it may have a different value than the _bookDom created on the previous line.
            // Thus, we are making a mock storage which, unlike a real one, doesn't itself
            // store a DOM set at creation; many tests update _bookDom to something else AFTER
            // this setup routine makes the Storage they use in their books.
            _storage  = MakeMockStorage(_tempFolder.Path, () => _bookDom);
            _bookDom  = _storage.Object.Dom;
            _metadata = _storage.Object.BookInfo;

            _templateFinder = new Moq.Mock <ITemplateFinder>();
            _fileLocator    = new Moq.Mock <IFileLocator>();
            string root    = FileLocationUtilities.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot);
            string xMatter = BloomFileLocator.GetInstalledXMatterDirectory();

            _fileLocator.Setup(x => x.LocateFileWithThrow("langVisibility.css")).Returns("../notareallocation/langVisibility.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("previewMode.css")).Returns("../notareallocation/previewMode.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("origami.css")).Returns("../notareallocation/origami.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("origamiEditing.css")).Returns("../notareallocation/origamiEditing.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("editMode.css")).Returns("../notareallocation/editMode.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("editTranslationMode.css")).Returns("../notareallocation/editTranslationMode.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("editOriginalMode.css")).Returns("../notareallocation/editOriginalMode.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("editPaneGlobal.css")).Returns("../notareallocation/editPaneGlobal.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("basePage.css")).Returns("../notareallocation/basePage.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("bloomBootstrap.js")).Returns("../notareallocation/bloomBootstrap.js");
            _fileLocator.Setup(x => x.LocateFileWithThrow("bloomPreviewBootstrap.js")).Returns("../notareallocation/bloomPreviewBootstrap.js");
            _fileLocator.Setup(x => x.LocateFileWithThrow("baseEPUB.css")).Returns("../notareallocation/baseEPUB.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("Device-XMatter.css")).Returns("../notareallocation/Device-XMatter.css");
            _fileLocator.Setup(x => x.LocateFileWithThrow("customBookStyles.css")).Returns(Path.Combine(_tempFolder.Path, "customBookStyles.css"));
            _fileLocator.Setup(x => x.LocateFileWithThrow("defaultLangStyles.css")).Returns(Path.Combine(_testFolder.Path, "defaultLangStyles.css"));
            _fileLocator.Setup(x => x.LocateFileWithThrow("customCollectionStyles.css")).Returns(Path.Combine(_testFolder.Path, "customCollectionStyles.css"));
            var basicBookPath = BloomFileLocator.GetCodeBaseFolder() + "/../browser/templates/template books/Basic Book/Basic Book.css";

            _fileLocator.Setup(x => x.LocateFile("Basic Book.css")).Returns(basicBookPath);

            _fileLocator.Setup(x => x.LocateDirectory("Factory-XMatter")).Returns(xMatter.CombineForPath("Factory-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectoryWithThrow("Factory-XMatter")).Returns(xMatter.CombineForPath("Factory-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectory("Factory-XMatter", It.IsAny <string>())).Returns(xMatter.CombineForPath("Factory-XMatter"));
            _fileLocator.Setup(x => x.LocateFileWithThrow("Factory-XMatter".CombineForPath("Factory-XMatter.htm"))).Returns(xMatter.CombineForPath("Factory-XMatter", "Factory-XMatter.htm"));

            _fileLocator.Setup(x => x.LocateDirectory("Traditional-XMatter")).Returns(xMatter.CombineForPath("Traditional-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectoryWithThrow("Traditional-XMatter")).Returns(xMatter.CombineForPath("Traditional-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectory("Traditional-XMatter", It.IsAny <string>())).Returns(xMatter.CombineForPath("Traditional-XMatter"));
            _fileLocator.Setup(x => x.LocateFileWithThrow("Traditional-XMatter".CombineForPath("Traditional-XMatter.htm"))).Returns(xMatter.CombineForPath("Traditional-XMatter", "Factory-XMatter.htm"));


            _fileLocator.Setup(x => x.LocateDirectory("BigBook-XMatter")).Returns(xMatter.CombineForPath("BigBook-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectoryWithThrow("BigBook-XMatter")).Returns(xMatter.CombineForPath("BigBook-XMatter"));
            _fileLocator.Setup(x => x.LocateDirectory("BigBook-XMatter", It.IsAny <string>())).Returns(xMatter.CombineForPath("BigBook-XMatter"));
            _fileLocator.Setup(x => x.LocateFileWithThrow("BigBook-XMatter".CombineForPath("BigBook-XMatter.htm"))).Returns(xMatter.CombineForPath("BigBook-XMatter", "BigBook-XMatter.htm"));

            //warning: we're neutering part of what the code under test is trying to do here:
            _fileLocator.Setup(x => x.CloneAndCustomize(It.IsAny <IEnumerable <string> >())).Returns(_fileLocator.Object);

            _thumbnailer          = new Moq.Mock <HtmlThumbNailer>(new object[] { NavigationIsolator.GetOrCreateTheOneNavigationIsolator() });
            _pageSelection        = new Mock <PageSelection>();
            _pageListChangedEvent = new PageListChangedEvent();
        }
Пример #22
0
        private void OnPrint_Click(object sender, EventArgs e)
        {
            var printSettingsPreviewFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication("printer settings images");
            var printSettingsSamplePrefix  = Path.Combine(printSettingsPreviewFolder,
                                                          _model.PageLayout.SizeAndOrientation + "-" + (isBooklet() ? "Booklet-" : ""));
            string printSettingsSampleName = null;

            if (SIL.PlatformUtilities.Platform.IsLinux)
            {
                printSettingsSampleName = printSettingsSamplePrefix + "Linux-" + LocalizationManager.UILanguageId + ".png";
                if (!RobustFile.Exists(printSettingsSampleName))
                {
                    printSettingsSampleName = printSettingsSamplePrefix + "Linux-en.png";
                }
            }
            if (printSettingsSampleName == null || !RobustFile.Exists(printSettingsSampleName))
            {
                printSettingsSampleName = printSettingsSamplePrefix + LocalizationManager.UILanguageId + ".png";
            }
            if (!RobustFile.Exists(printSettingsSampleName))
            {
                printSettingsSampleName = printSettingsSamplePrefix + "en" + ".png";
            }
            if (RobustFile.Exists(printSettingsSampleName))
            {
                // We display the _previewBox to show sample print settings. We need to get rid of it when the
                // print dialog goes away. For Windows, the only way I've found to know when that happens is
                // that the main Bloom form gets activated again.  For Linux, waiting for process spawned off
                // to print the pdf file to finish seems to be the only way to know it's safe to hide the
                // sample print settings.  (On Linux/Mono, the form activates almost as soon as the print
                // dialog appears.)
#if __MonoCS__
                _pdfViewer.PrintFinished += FormActivatedAfterPrintDialog;
#else
                var form = FindForm();
                form.Activated += FormActivatedAfterPrintDialog;
#endif
                _previewBox.Image    = Image.FromFile(printSettingsSampleName);
                _previewBox.Bounds   = GetPreviewBounds();
                _previewBox.SizeMode = PictureBoxSizeMode.Zoom;
                _previewBox.BringToFront();                 // prevents BL-6001
                _previewBox.Show();
                if (!Settings.Default.DontShowPrintNotification)
                {
                    using (var dlg = new SamplePrintNotification())
                    {
                        dlg.StartPosition = FormStartPosition.CenterParent;
#if __MonoCS__
                        _pdfViewer.PrintFinished -= FormActivatedAfterPrintDialog;
                        dlg.ShowDialog(this);
                        _pdfViewer.PrintFinished += FormActivatedAfterPrintDialog;
#else
                        form.Activated -= FormActivatedAfterPrintDialog;                         // not wanted when we close the dialog.
                        dlg.ShowDialog(this);
                        form.Activated += FormActivatedAfterPrintDialog;
#endif
                        if (dlg.StopShowing)
                        {
                            Settings.Default.DontShowPrintNotification = true;
                            Settings.Default.Save();
                        }
                    }
                }
            }
            _pdfViewer.Print();
            Logger.WriteEvent("Calling Print on PDF Viewer");
            _model.ReportAnalytics("Print PDF");
        }
Пример #23
0
 public static string GetBrowserDirectory(params string[] parts)
 {
     parts[0] = Path.Combine(BrowserRoot, parts[0]);
     return(FileLocationUtilities.GetDirectoryDistributedWithApplication(false, parts));
 }
Пример #24
0
        public void GetDirectoryDistributedWithApplication_MultipleParts_FindsCorrectly()
        {
            var path = FileLocationUtilities.GetDirectoryDistributedWithApplication("DirectoryForTests");

            Assert.That(Directory.Exists(path));
        }
Пример #25
0
        /// ------------------------------------------------------------------------------------
        public static Pipeline CreatePipeline(Pipeline.ProcessType prsType)
        {
            var processingFolder = FileLocationUtilities.GetDirectoryDistributedWithApplication(App.ProcessingFolderName);

            return(Pipeline.Create(prsType, ProcessFile, processingFolder));
        }