Bloom.Browser.SetUpXulRunner C# (CSharp) Method

SetUpXulRunner() public static method

public static SetUpXulRunner ( ) : void
return void
        public static void SetUpXulRunner()
        {
            if (Xpcom.IsInitialized)
                return;
            string xulRunnerPath = Environment.GetEnvironmentVariable("XULRUNNER");
            if (String.IsNullOrEmpty(xulRunnerPath) || !Directory.Exists(xulRunnerPath))
            {
                var asm = Assembly.GetExecutingAssembly();
                var file = asm.CodeBase.Replace("file://", String.Empty);
                if (SIL.PlatformUtilities.Platform.IsWindows)
                    file = file.TrimStart('/');
                var folder = Path.GetDirectoryName(file);
                xulRunnerPath = Path.Combine(folder, "Firefox");
            }
            Xpcom.Initialize(xulRunnerPath);

            var errorsToHide = new List<string>
            {
                "['Shockwave Flash'] is undefined", // can happen when mootools (used by calendar) is loaded
                "mootools", // can happen when mootools (used by calendar) is loaded
                "PlacesCategoriesStarter.js", // happens if you let bloom sit there long enough
                "PlacesDBUtils", // happens if you let bloom sit there long enough
                "privatebrowsing", // no idea why it shows this error sometimes
                "xulrunner", // can happen when mootools (used by calendar) is loaded
                "FrameExports", // this can happen while switching pages quickly, when the page unloads after the script starts executing.
                "resource://", // these errors/warnings are coming from internal firefox files
                "chrome://",   // these errors/warnings are coming from internal firefox files
                "jar:",        // these errors/warnings are coming from internal firefox files

                //This one started appearing, only on the ImageOnTop pages, when I introduced jquery.resize.js
                //and then added the ResetRememberedSize() function to it. So it's my fault somehow, but I haven't tracked it down yet.
                //it will continue to show in firebug, so i won't forget about it
                "jquery.js at line 622",

                // Warnings began popping up when we started using http rather than file urls for script tags.
                // 21 JUL 2014, PH: This is a confirmed bug in firefox (https://bugzilla.mozilla.org/show_bug.cgi?id=1020846)
                //   and is supposed to be fixed in firefox 33.
                "is being assigned a //# sourceMappingURL, but already has one"
            };

            // BL-535: 404 error if system proxy settings not configured to bypass proxy for localhost
            // See: https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Mozilla_networking_preferences
            GeckoPreferences.User["network.proxy.http"] = string.Empty;
            GeckoPreferences.User["network.proxy.http_port"] = 80;
            GeckoPreferences.User["network.proxy.type"] = 1; // 0 = direct (uses system settings on Windows), 1 = manual configuration
            // Try some settings to reduce memory consumption by the mozilla browser engine.
            // Testing on Linux showed eventual substantial savings after several cycles of viewing
            // all the pages and then going to the publish tab and producing PDF files for several
            // books with embedded jpeg files.  (physical memory 1,153,864K, managed heap 37,789K
            // instead of physical memory 1,952,380K, managed heap 37,723K for stepping through the
            // same operations on the same books in the same order.  I don't know why managed heap
            // changed although it didn't change much.)
            // See http://kb.mozillazine.org/About:config_entries, http://www.davidtan.org/tips-reduce-firefox-memory-cache-usage
            // and http://forums.macrumors.com/showthread.php?t=1838393.
            GeckoPreferences.User["memory.free_dirty_pages"] = true;
            GeckoPreferences.User["browser.sessionhistory.max_entries"] = 0;
            GeckoPreferences.User["browser.sessionhistory.max_total_viewers"] = 0;
            GeckoPreferences.User["browser.cache.memory.enable"] = false;

            // Some more settings that can help to reduce memory consumption.
            // (Tested in switching pages in the Edit tool.  These definitely reduce consumption in that test.)
            // See http://www.instantfundas.com/2013/03/how-to-keep-firefox-from-using-too-much.html
            // and http://kb.mozillazine.org/Memory_Leak.
            // maximum amount of memory used to cache decoded images
            GeckoPreferences.User["image.mem.max_decoded_image_kb"] = 40960;        // 40MB (default = 256000 == 250MB)
            // maximum amount of memory used by javascript
            GeckoPreferences.User["javascript.options.mem.max"] = 40960;            // 40MB (default = -1 == automatic)
            // memory usage at which javascript starts garbage collecting
            GeckoPreferences.User["javascript.options.mem.high_water_mark"] = 20;   // 20MB (default = 128 == 128MB)
            // SurfaceCache is an imagelib-global service that allows caching of temporary
            // surfaces. Surfaces normally expire from the cache automatically if they go
            // too long without being accessed.
            GeckoPreferences.User["image.mem.surfacecache.max_size_kb"] = 40960;    // 40MB (default = 102400 == 100MB)
            GeckoPreferences.User["image.mem.surfacecache.min_expiration_ms"] = 500;    // 500ms (default = 60000 == 60sec)

            // maximum amount of memory for the browser cache (probably redundant with browser.cache.memory.enable above, but doesn't hurt)
            GeckoPreferences.User["browser.cache.memory.capacity"] = 0;             // 0 disables feature

            // do these do anything?
            //GeckoPreferences.User["javascript.options.mem.gc_frequency"] = 5;	// seconds?
            //GeckoPreferences.User["dom.caches.enabled"] = false;
            //GeckoPreferences.User["browser.sessionstore.max_tabs_undo"] = 0;	// (default = 10)
            //GeckoPreferences.User["network.http.use-cache"] = false;

            // These settings prevent a problem where the gecko instance running the add page dialog
            // would request several images at once, but we were not able to generate the image
            // because we could not make additional requests of the localhost server, since some limit
            // had been reached. I'm not sure all of them are needed, but since in this program we
            // only talk to our own local server, there is no reason to limit any requests to the server,
            // so increasing all the ones that look at all relevant seems like a good idea.
            GeckoPreferences.User["network.http.max-persistent-connections-per-server"] = 200;
            GeckoPreferences.User["network.http.pipelining.maxrequests"] = 200;
            GeckoPreferences.User["network.http.pipelining.max-optimistic-requests"] = 200;

            // This suppresses the normal zoom-whole-window behavior that Gecko normally does when using the mouse while
            // while holding crtl. Code in bloomEditing.js provides a more controlled zoom of just the body.
            GeckoPreferences.User["mousewheel.with_control.action"] = 0;
        }

Usage Example

Example #1
0
        static void Main(string[] args)
        {
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                if (Palaso.PlatformUtilities.Platform.IsWindows)
                {
                    OldVersionCheck();
                }
                //bring in settings from any previous version
                if (Settings.Default.NeedUpgrade)
                {
                    //see http://stackoverflow.com/questions/3498561/net-applicationsettingsbase-should-i-call-upgrade-every-time-i-load
                    Settings.Default.Upgrade();
                    Settings.Default.Reload();
                    Settings.Default.NeedUpgrade = false;
                    Settings.Default.Save();
                    StartUpWithFirstOrNewVersionBehavior = true;
                }
#if !USING_CHORUS
                Settings.Default.ShowSendReceive = false;                 // in case someone turned it on before we disabled
#endif
#if DEBUG
                if (args.Length > 0)
                {
                    // This allows us to debug things like  interpreting a URL.
                    MessageBox.Show("Attach debugger now");
                }
#endif

#if DEBUG
                using (new DesktopAnalytics.Analytics("sje2fq26wnnk8c2kzflf", RegistrationDialog.GetAnalyticsUserInfo(), true))
#else
                string feedbackSetting = System.Environment.GetEnvironmentVariable("FEEDBACK");

                //default is to allow tracking
                var allowTracking = string.IsNullOrEmpty(feedbackSetting) || feedbackSetting.ToLower() == "yes" || feedbackSetting.ToLower() == "true";

                using (new Analytics("c8ndqrrl7f0twbf2s6cv", RegistrationDialog.GetAnalyticsUserInfo(), allowTracking))
#endif

                {
                    if (args.Length == 1 && args[0].ToLower().EndsWith(".bloompack"))
                    {
                        SetUpErrorHandling();
                        _applicationContainer = new ApplicationContainer();
                        SetUpLocalization();
                        var path = args[0];
                        // This allows local links to bloom packs.
                        if (path.ToLowerInvariant().StartsWith("bloom://"))
                        {
                            path = path.Substring("bloom://".Length);
                            if (!File.Exists(path))
                            {
                                path = FileLocator.GetFileDistributedWithApplication(true, path);
                                if (!File.Exists(path))
                                {
                                    return;
                                }
                            }
                        }
                        using (var dlg = new BloomPackInstallDialog(path))
                        {
                            dlg.ShowDialog();
                        }
                        return;
                    }
                    if (IsBloomBookOrder(args))
                    {
                        // We will start up just enough to download the book. This avoids the code that normally tries to keep only a single instance running.
                        // There is probably a pathological case here where we are overwriting an existing template just as the main instance is trying to
                        // do something with it. The time interval would be very short, because download uses a temp folder until it has the whole thing
                        // and then copies (or more commonly moves) it over in one step, and making a book from a template involves a similarly short
                        // step of copying the template to the new book. Hopefully users have (or will soon learn) enough sense not to
                        // try to use a template while in the middle of downloading a new version.
                        SetUpErrorHandling();
                        _applicationContainer = new ApplicationContainer();
                        SetUpLocalization();
                        Logger.Init();
                        new BookDownloadSupport();
                        Browser.SetUpXulRunner();
                        L10NSharp.LocalizationManager.SetUILanguage(Settings.Default.UserInterfaceLanguage, false);
                        var transfer = new BookTransfer(new BloomParseClient(), ProjectContext.CreateBloomS3Client(),
                                                        _applicationContainer.HtmlThumbnailer, new BookDownloadStartingEvent()) /*not hooked to anything*/;
                        transfer.HandleBloomBookOrder(args[0]);
                        PathToBookDownloadedAtStartup = transfer.LastBookDownloadedPath;
                        // If another instance is running, this one has served its purpose and can exit right away.
                        // Otherwise, carry on with starting up normally.
                        if (TryToGrabMutexForBloom())
                        {
                            FinishStartup();
                        }
                        else
                        {
                            _onlyOneBloomMutex = null;                             // we don't own it, so ReleaseMutexForBloom must not try to release it.
                            string caption = LocalizationManager.GetString("Download.CompletedCaption", "Download complete");
                            string message = LocalizationManager.GetString("Download.Completed",
                                                                           @"Your download ({0}) is complete. You can see it in the 'Books from BloomLibrary.org' section of your Collections. "
                                                                           + "If you don't seem to be in the middle of doing something, Bloom will select it for you.");
                            message = string.Format(message, Path.GetFileName(PathToBookDownloadedAtStartup));
                            MessageBox.Show(message, caption);
                        }
                        return;
                    }

                    if (!GrabMutexForBloom())
                    {
                        return;
                    }

                    OldVersionCheck();

                    SetUpErrorHandling();

                    _applicationContainer = new ApplicationContainer();

                    if (args.Length == 2 && args[0].ToLowerInvariant() == "--upload")
                    {
                        // A special path to upload chunks of stuff. This is not currently documented and is not very robust.
                        // - User must log in before running this
                        // - For best results each bloom book needs to be part of a collection in its parent folder
                        // - little error checking (e.g., we don't apply the usual constaints that a book must have title and licence info)
                        SetUpLocalization();
                        Browser.SetUpXulRunner();
                        var transfer = new BookTransfer(new BloomParseClient(), ProjectContext.CreateBloomS3Client(),
                                                        _applicationContainer.HtmlThumbnailer, new BookDownloadStartingEvent()) /*not hooked to anything*/;
                        transfer.UploadFolder(args[1], _applicationContainer);
                        return;
                    }

                    new BookDownloadSupport();                     // creating this sets some things up so we can download.

                    SetUpLocalization();
                    Logger.Init();


                    if (args.Length == 1)
                    {
                        Debug.Assert(args[0].ToLower().EndsWith(".bloomcollection"));                         // Anything else handled above.
                        Settings.Default.MruProjects.AddNewPath(args[0]);
                    }

                    if (args.Length > 0 && args[0] == "--rename")
                    {
                        try
                        {
                            var pathToNewCollection = CollectionSettings.RenameCollection(args[1], args[2]);
                            //MessageBox.Show("Your collection has been renamed.");
                            Settings.Default.MruProjects.AddNewPath(pathToNewCollection);
                        }
                        catch (ApplicationException error)
                        {
                            Palaso.Reporting.ErrorReport.NotifyUserOfProblem(error, error.Message);
                            Environment.Exit(-1);
                        }
                        catch (Exception error)
                        {
                            Palaso.Reporting.ErrorReport.NotifyUserOfProblem(error,
                                                                             "Bloom could not finish renaming your collection folder. Restart your computer and try again.");
                            Environment.Exit(-1);
                        }
                    }
                    Browser.SetUpXulRunner();
#if DEBUG
                    StartDebugServer();
#endif
                    L10NSharp.LocalizationManager.SetUILanguage(Settings.Default.UserInterfaceLanguage, false);

                    FinishStartup();
                }
            }
            finally
            {
                ReleaseMutexForBloom();
            }
        }
All Usage Examples Of Bloom.Browser::SetUpXulRunner