Пример #1
0
        public static void Save(Book.Book book, BookServer bookServer, Color backColor, WebSocketProgress progress, AndroidPublishSettings settings = null)
        {
            var progressWithL10N = progress.WithL10NPrefix("PublishTab.Android.File.Progress.");

            using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
            {
                dlg.DefaultExt = BookCompressor.ExtensionForDeviceBloomBook;
                var bloomdFileDescription = LocalizationManager.GetString("PublishTab.Android.bloomdFileFormatLabel", "Bloom Book for Devices", "This is shown in the 'Save' dialog when you save a bloom book in the format that works with the Bloom Reader Android App");
                dlg.Filter   = $"{bloomdFileDescription}|*{BookCompressor.ExtensionForDeviceBloomBook}";
                dlg.FileName = Path.GetFileName(book.FolderPath) + BookCompressor.ExtensionForDeviceBloomBook;
                if (!string.IsNullOrWhiteSpace(Settings.Default.BloomDeviceFileExportFolder) &&
                    Directory.Exists(Settings.Default.BloomDeviceFileExportFolder))
                {
                    dlg.InitialDirectory = Settings.Default.BloomDeviceFileExportFolder;
                    //(otherwise leave to default save location)
                }
                dlg.OverwritePrompt = true;
                if (DialogResult.OK == dlg.ShowDialog())
                {
                    Settings.Default.BloomDeviceFileExportFolder = Path.GetDirectoryName(dlg.FileName);
                    PublishToAndroidApi.CheckBookLayout(book, progress);
                    PublishToAndroidApi.SendBook(book, bookServer, dlg.FileName, null,
                                                 progressWithL10N,
                                                 (publishedFileName, bookTitle) => progressWithL10N.GetMessageWithParams("Saving", "{0} is a file path", "Saving as {0}", dlg.FileName),
                                                 null,
                                                 backColor,
                                                 settings: settings);
                    PublishToAndroidApi.ReportAnalytics("file", book);
                }
            }
        }
Пример #2
0
        /// <summary>
        /// Respond to an export UI button push by letting the user specify what file to export to, and starting the export process.
        /// </summary>
        private void OnExportConfiguration(object sender, EventArgs e)
        {
            // Not capable of exporting new configurations yet.
            if (IsDirty)
            {
                MessageBox.Show(_view, xWorksStrings.kstidConfigsChanged);
                return;
            }

            if (string.IsNullOrEmpty(SelectedConfiguration.FilePath))
            {
                throw new ArgumentNullException("The configuration selected for export has an empty file path.");
            }
            if (Path.GetDirectoryName(SelectedConfiguration.FilePath) == _defaultConfigDir)
            {
                SelectedConfiguration.FilePath = Path.Combine(_projectConfigDir,
                                                              Path.GetFileName(SelectedConfiguration.FilePath));
                SelectedConfiguration.Save();
            }

            var    disallowedCharacters = MiscUtils.GetInvalidProjectNameChars(MiscUtils.FilenameFilterStrength.kFilterBackup) + " $%";
            string outputPath;

            using (var saveDialog = new DialogAdapters.SaveFileDialogAdapter())
            {
                saveDialog.Title            = xWorksStrings.kstidChooseExportFile;
                saveDialog.FileName         = StringUtils.FilterForFileName(SelectedConfiguration + "_FLEx-Dictionary-Configuration_" + DateTime.Now.ToString("yyyy-MM-dd"), disallowedCharacters);
                saveDialog.DefaultExt       = "zip";
                saveDialog.AddExtension     = true;
                saveDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                var result = saveDialog.ShowDialog(_view);
                if (result != DialogResult.OK)
                {
                    return;
                }
                outputPath = saveDialog.FileName;
            }

            // Append ".zip" if user entered something like "foo.gif", which loses the hidden ".zip" extension.
            if (!outputPath.EndsWith(".zip", StringComparison.InvariantCultureIgnoreCase))
            {
                outputPath += ".zip";
            }

            ExportConfiguration(SelectedConfiguration, outputPath, _cache);
        }
Пример #3
0
        /// <summary>
        /// Wrap a "Save File" dialog to prevent saving files inside the book's collection folder.
        /// </summary>
        /// <returns>The output file path, or null if canceled.</returns>
        public static string GetOutputFilePathOutsideCollectionFolder(string initialPath, string filter)
        {
            string initialFolder    = Path.GetDirectoryName(initialPath);
            string initialFilename  = Path.GetFileName(initialPath);
            string defaultExtension = Path.GetExtension(initialPath);
            var    destFileName     = String.Empty;
            var    repeat           = false;

            do
            {
                using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
                {
                    dlg.AddExtension     = true;
                    dlg.DefaultExt       = defaultExtension;
                    dlg.FileName         = initialFilename;
                    dlg.Filter           = filter;
                    dlg.RestoreDirectory = false;
                    dlg.OverwritePrompt  = true;
                    dlg.InitialDirectory = initialFolder;
                    if (DialogResult.Cancel == dlg.ShowDialog())
                    {
                        return(null);
                    }
                    destFileName = dlg.FileName;
                }
                string collectionFolder;
                repeat = IsFolderInsideBloomCollection(Path.GetDirectoryName(destFileName), out collectionFolder);
                if (repeat)
                {
                    WarnUserOfInvalidFolderChoice(collectionFolder, destFileName);
                    // Change the initialFolder to just above the collection folder, or to the documents folder
                    // if that ends up empty.
                    initialFolder = Path.GetDirectoryName(collectionFolder);
                    if (String.IsNullOrEmpty(initialFolder))
                    {
                        initialFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                    }
                }
            } while (repeat);
            return(destFileName);
        }
Пример #4
0
        internal void SaveAsEpub()
        {
            using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
            {
                if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                {
                    dlg.InitialDirectory = _lastDirectory;
                }

                string suggestedName = string.Format("{0}-{1}.epub", Path.GetFileName(BookSelection.CurrentSelection.FolderPath),
                                                     _collectionSettings.GetLanguage1Name("en"));
                dlg.FileName = suggestedName;
                dlg.Filter   = "EPUB|*.epub";
                if (DialogResult.OK == dlg.ShowDialog())
                {
                    _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                    EpubMaker.FinishEpub(dlg.FileName);
                    ReportAnalytics("Save ePUB");
                }
            }
        }
Пример #5
0
        public void RegisterWithApiHandler(BloomApiHandler apiHandler)
        {
            apiHandler.RegisterEndpointHandler(kApiUrlPart + "save", request =>
            {
                {
                    string suggestedName = string.Format("{0}-{1}.epub", Path.GetFileName(_bookSelection.CurrentSelection.FolderPath),
                                                         _bookSelection.CurrentSelection.BookData.Language1.GetNameInLanguage("en"));
                    using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
                    {
                        if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                        {
                            dlg.InitialDirectory = _lastDirectory;
                        }
                        dlg.FileName        = suggestedName;
                        dlg.Filter          = "EPUB|*.epub";
                        dlg.OverwritePrompt = true;
                        if (DialogResult.OK == dlg.ShowDialog())
                        {
                            _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                            lock (_epubMakerLock)
                            {
                                _pendingSaveAsPath = dlg.FileName;
                                if (!_stagingEpub)
                                {
                                    // we can do it right now. No need to check version etc., because anything
                                    // that will change the epub we want to save will immediately trigger a new
                                    // preview, and we will be staging it until we have it.
                                    SaveAsEpub();
                                }
                                // If we ARE in the middle of staging the epub...quite possible since this
                                // handler is registered with permission to execute in parallel with other
                                // API handlers, the user just has to click Save before the preview is finished...
                                // then we need not do any more here. A call to SaveAsEpub at the end of the
                                // preview generation process will pick up the pending request in _pendingSaveAsPath
                                // and complete the Save.
                            }

                            ReportProgress(LocalizationManager.GetString("PublishTab.Epub.Done", "Done"));
                            ReportAnalytics("Save ePUB");
                        }
                    }

                    request.PostSucceeded();
                }
            }, true, false);

            apiHandler.RegisterEndpointHandler(kApiUrlPart + "epubSettings", request =>
            {
                if (request.HttpMethod == HttpMethods.Get)
                {
                    request.ReplyWithJson(GetEpubSettings());
                }
                else
                {
                    // post is deprecated.
                    throw new ApplicationException("epubSettings POST is deprecated");
                }
            }, false);

            // The backend here was written with an enum that had two choices for how to publish descriptions, but we only ever
            // have used one of them so far in the UI. So this is a boolean api that converts to an enum underlying value.
            apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "imageDescriptionSetting",
                                                      request => request.CurrentBook.BookInfo.MetaData.Epub_HowToPublishImageDescriptions == BookInfo.HowToPublishImageDescriptions.OnPage,
                                                      (request, onPage) =>
            {
                request.CurrentBook.BookInfo.MetaData.Epub_HowToPublishImageDescriptions = onPage
                                                ? BookInfo.HowToPublishImageDescriptions.OnPage
                                                : BookInfo.HowToPublishImageDescriptions.None;
                request.CurrentBook.BookInfo.Save();
                var newSettings = _desiredEpubSettings.Clone();
                newSettings.howToPublishImageDescriptions = request.CurrentBook.BookInfo.MetaData.Epub_HowToPublishImageDescriptions;
                RefreshPreview(newSettings);
            },
                                                      false);

            // Saving a checkbox setting that the user ticks to say "Use my E-reader's font sizes"
            apiHandler.RegisterBooleanEndpointHandler(kApiUrlPart + "removeFontSizesSetting",
                                                      request => request.CurrentBook.BookInfo.MetaData.Epub_RemoveFontSizes,
                                                      (request, booleanSetting) => {
                request.CurrentBook.BookInfo.MetaData.Epub_RemoveFontSizes = booleanSetting;
                request.CurrentBook.BookInfo.Save();
                var newSettings             = _desiredEpubSettings.Clone();
                newSettings.removeFontSizes = booleanSetting;
                RefreshPreview(newSettings);
            },
                                                      false);

            apiHandler.RegisterEndpointHandler(kApiUrlPart + "updatePreview", request =>
            {
                RefreshPreview(_desiredEpubSettings);
                request.PostSucceeded();
            }, false);             // in fact, must NOT be on UI thread

            apiHandler.RegisterEndpointHandler(kApiUrlPart + "abortPreview", request =>
            {
                AbortMakingEpub();

                request.PostSucceeded();
            }, false, false);
        }
Пример #6
0
        public void Save()
        {
            try
            {
                // Give a slight preference to USB keys, though if they used a different directory last time, we favor that.

                if (string.IsNullOrEmpty(_lastDirectory) || !Directory.Exists(_lastDirectory))
                {
                    var drives = SIL.UsbDrive.UsbDriveInfo.GetDrives();
                    if (drives != null && drives.Count > 0)
                    {
                        _lastDirectory = drives[0].RootDirectory.FullName;
                    }
                }

                using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
                {
                    if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                    {
                        dlg.InitialDirectory = _lastDirectory;
                    }
                    var portion = "";
                    switch (BookletPortion)
                    {
                    case BookletPortions.None:
                        Debug.Fail("Save should not be enabled");
                        return;

                    case BookletPortions.AllPagesNoBooklet:
                        portion = "Pages";
                        break;

                    case BookletPortions.BookletCover:
                        portion = "Cover";
                        break;

                    case BookletPortions.BookletPages:
                        portion = "Inside";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    string forPrintShop =
                        _currentlyLoadedBook.UserPrefs.CmykPdf || _currentlyLoadedBook.UserPrefs.FullBleed
                                                        ? "-printshop"
                                                        : "";
                    string suggestedName = string.Format($"{Path.GetFileName(_currentlyLoadedBook.FolderPath)}-{_currentlyLoadedBook.GetFilesafeLanguage1Name("en")}-{portion}{forPrintShop}.pdf");
                    dlg.FileName = suggestedName;
                    var pdfFileLabel = L10NSharp.LocalizationManager.GetString(@"PublishTab.PdfMaker.PdfFile",
                                                                               "PDF File",
                                                                               @"displayed as file type for Save File dialog.");

                    pdfFileLabel        = pdfFileLabel.Replace("|", "");
                    dlg.Filter          = String.Format("{0}|*.pdf", pdfFileLabel);
                    dlg.OverwritePrompt = true;
                    if (DialogResult.OK == dlg.ShowDialog())
                    {
                        _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                        if (_currentlyLoadedBook.UserPrefs.CmykPdf)
                        {
                            // PDF for Printshop (CMYK US Web Coated V2)
                            ProcessPdfFurtherAndSave(ProcessPdfWithGhostscript.OutputType.Printshop, dlg.FileName);
                        }
                        else
                        {
                            // we want the simple PDF we already made.
                            RobustFile.Copy(PdfFilePath, dlg.FileName, true);
                        }
                        Analytics.Track("Save PDF", new Dictionary <string, string>()
                        {
                            { "Portion", Enum.GetName(typeof(BookletPortions), BookletPortion) },
                            { "Layout", PageLayout.ToString() },
                            { "BookId", BookSelection.CurrentSelection.ID },
                            { "Country", _collectionSettings.Country }
                        });
                    }
                }
            }
            catch (Exception err)
            {
                SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the PDF.  {0}", err.Message);
            }
        }
Пример #7
0
        public void Save()
        {
            if (EpubMode)
            {
                try
                {
                    SaveAsEpub();
                }
                catch (Exception err)
                {
                    SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the ePUB.  {0}", err.Message);
                }
                return;
            }
            try
            {
                // Give a slight preference to USB keys, though if they used a different directory last time, we favor that.

                if (string.IsNullOrEmpty(_lastDirectory) || !Directory.Exists(_lastDirectory))
                {
                    var drives = SIL.UsbDrive.UsbDriveInfo.GetDrives();
                    if (drives != null && drives.Count > 0)
                    {
                        _lastDirectory = drives[0].RootDirectory.FullName;
                    }
                }

                using (var dlg = new DialogAdapters.SaveFileDialogAdapter())
                {
                    if (!string.IsNullOrEmpty(_lastDirectory) && Directory.Exists(_lastDirectory))
                    {
                        dlg.InitialDirectory = _lastDirectory;
                    }
                    var portion = "";
                    switch (BookletPortion)
                    {
                    case BookletPortions.None:
                        Debug.Fail("Save should not be enabled");
                        return;

                    case BookletPortions.AllPagesNoBooklet:
                        portion = "Pages";
                        break;

                    case BookletPortions.BookletCover:
                        portion = "Cover";
                        break;

                    case BookletPortions.BookletPages:
                        portion = "Inside";
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }
                    string suggestedName = string.Format("{0}-{1}-{2}.pdf", Path.GetFileName(_currentlyLoadedBook.FolderPath),
                                                         _collectionSettings.GetFilesafeLanguage1Name("en"), portion);
                    dlg.FileName = suggestedName;
                    var rgb = L10NSharp.LocalizationManager.GetString(@"PublishTab.PdfMaker.PdfWithRGB",
                                                                      "PDF with RGB color",
                                                                      @"displayed as file type for Save File dialog. 'RGB' may not be translatable, it is a standard.");
                    var swopv2 = L10NSharp.LocalizationManager.GetString(@"PublishTab.PdfMaker.PdfWithCmykSwopV2",
                                                                         "PDF with CMYK color (U.S. Web Coated (SWOP) v2)",
                                                                         @"displayed as file type for Save File dialog, the content in parentheses may not be translatable. 'CMYK' may not be translatable, it is a print shop standard.");

                    rgb        = rgb.Replace("|", "");
                    swopv2     = swopv2.Replace("|", "");
                    dlg.Filter = String.Format("{0}|*.pdf|{1}|*.pdf", rgb, swopv2);
                    if (DialogResult.OK == dlg.ShowDialog())
                    {
                        _lastDirectory = Path.GetDirectoryName(dlg.FileName);
                        switch (dlg.FilterIndex)
                        {
                        case 1:                         // PDF for Desktop Printing
                            RobustFile.Copy(PdfFilePath, dlg.FileName, true);
                            break;

                        case 2:                         // PDF for Printshop (CMYK US Web Coated V2)
                            ProcessPdfFurtherAndSave(ProcessPdfWithGhostscript.OutputType.Printshop, dlg.FileName);
                            break;
                        }
                        Analytics.Track("Save PDF", new Dictionary <string, string>()
                        {
                            { "Portion", Enum.GetName(typeof(BookletPortions), BookletPortion) },
                            { "Layout", PageLayout.ToString() },
                            { "BookId", BookSelection.CurrentSelection.ID },
                            { "Country", _collectionSettings.Country }
                        });
                    }
                }
            }
            catch (Exception err)
            {
                SIL.Reporting.ErrorReport.NotifyUserOfProblem("Bloom was not able to save the PDF.  {0}", err.Message);
            }
        }