コード例 #1
0
        public CollectionModel(string pathToCollection, CollectionSettings collectionSettings,
                               BookSelection bookSelection,
                               SourceCollectionsList sourceCollectionsList,
                               BookCollection.Factory bookCollectionFactory,
                               EditBookCommand editBookCommand,
                               CreateFromSourceBookCommand createFromSourceBookCommand,
                               BookServer bookServer,
                               CurrentEditableCollectionSelection currentEditableCollectionSelection,
                               BookThumbNailer thumbNailer,
                               TeamCollectionManager tcManager,
                               BloomWebSocketServer webSocketServer,
                               BookCollectionHolder bookCollectionHolder,
                               LocalizationChangedEvent localizationChangedEvent)
        {
            _bookSelection         = bookSelection;
            _pathToCollection      = pathToCollection;
            _collectionSettings    = collectionSettings;
            _sourceCollectionsList = sourceCollectionsList;
            _bookCollectionFactory = bookCollectionFactory;
            _editBookCommand       = editBookCommand;
            _bookServer            = bookServer;
            _currentEditableCollectionSelection = currentEditableCollectionSelection;
            _thumbNailer              = thumbNailer;
            _tcManager                = tcManager;
            _webSocketServer          = webSocketServer;
            _bookCollectionHolder     = bookCollectionHolder;
            _localizationChangedEvent = localizationChangedEvent;

            createFromSourceBookCommand.Subscribe(CreateFromSourceBook);
        }
コード例 #2
0
        public void SynchronizeDataItemsThroughoutDOM_HasOnlyEdoloContributors_CopiesItIntoL2ButNotL1()
        {
            var dom = new HtmlDom(@"<html ><head></head><body>
				<div id='bloomDataDiv'>
					 <div data-book='originalContributions' lang='etr'>the contributions</div>
				</div>
				<div class='bloom-page verso'>
					 <div id='originalContributions' class='bloom-translationGroup'>
						<div class='bloom-copyFromOtherLanguageIfNecessary' data-book='originalContributions' lang='fr'></div>
						<div  class='bloom-copyFromOtherLanguageIfNecessary'  data-book='originalContributions' lang='xyz'></div>
					</div>
				</div>
				</body></html>"                );
            var collectionSettings = new CollectionSettings()
            {
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "fr"
            };
            var data = new BookData(dom, collectionSettings, null);

            data.SynchronizeDataItemsThroughoutDOM();
            XmlElement frenchContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='fr']");

            Assert.AreEqual("the contributions", frenchContributions.InnerText, "Should copy Edolo into French Contributions becuase it's better than just showing nothing");
            XmlElement vernacularContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='xyz']");

            Assert.AreEqual("", vernacularContributions.InnerText, "Should not copy Edolo into Vernacualr Contributions. Only national language fields get this treatment");
        }
コード例 #3
0
        public void BringBookUpToDate_ConvertsTagsToJsonWithExpectedDefaults()
        {
            var    storage = GetInitialStorage();
            var    locator = (FileLocator)storage.GetFileLocator();
            string root    = FileLocator.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot);

            locator.AddPath(root.CombineForPath("bookLayout"));
            var folder   = storage.FolderPath;
            var tagsPath = Path.Combine(folder, "tags.txt");

            File.WriteAllText(tagsPath, "suitableForMakingShells\nexperimental\nfolio\n");
            var collectionSettings =
                new CollectionSettings(new NewCollectionSettings()
            {
                PathToSettingsFile  = CollectionSettings.GetPathForNewSettings(folder, "test"),
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "en",
                Language3Iso639Code = "fr"
            });
            var book = new Bloom.Book.Book(new BookInfo(folder, true), storage, new Mock <ITemplateFinder>().Object,
                                           collectionSettings,
                                           new Mock <PageSelection>().Object, new PageListChangedEvent(), new BookRefreshEvent());

            book.BringBookUpToDate(new NullProgress());

            Assert.That(!File.Exists(tagsPath), "The tags.txt file should have been removed");
            // BL-2163, we are no longer migrating suitableForMakingShells
            Assert.That(storage.MetaData.IsSuitableForMakingShells, Is.False);
            Assert.That(storage.MetaData.IsFolio, Is.True);
            Assert.That(storage.MetaData.IsExperimental, Is.True);
            Assert.That(storage.MetaData.BookletMakingIsAppropriate, Is.True);
            Assert.That(storage.MetaData.AllowUploading, Is.True);
        }
コード例 #4
0
        public void UpdateFieldsAndVariables_BookTitleInSpanOnSecondPage_UpdatesH2OnFirstWithCurrentNationalLang()
        {
            var dom = new HtmlDom(@"<html ><head></head><body>
				<div class='bloom-page titlePage'>
						<div class='pageContent'>
							<h2 data-book='bookTitle' lang='N1'>{national book title}</h2>
						</div>
					</div>
				<div class='bloom-page verso'>
					<div class='pageContent'>
						(<span lang='en' data-book='bookTitle'>Vaccinations</span><span lang='tpi' data-book='bookTitle'>Tambu Sut</span>)
						<br />
					</div>
				</div>
				</body></html>"                );
            var collectionSettings = new CollectionSettings()
            {
                Language1Iso639Code = "etr"
            };
            var data = new BookData(dom, collectionSettings, null);

            data.SynchronizeDataItemsThroughoutDOM();
            XmlElement nationalTitle = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//h2[@data-book='bookTitle']");

            Assert.AreEqual("Vaccinations", nationalTitle.InnerText);

            //now switch the national language to Tok Pisin

            collectionSettings.Language2Iso639Code = "tpi";
            data.SynchronizeDataItemsThroughoutDOM();
            nationalTitle = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//h2[@data-book='bookTitle']");
            Assert.AreEqual("Tambu Sut", nationalTitle.InnerText);
        }
コード例 #5
0
        public void SynchronizeDataItemsThroughoutDOM_HasOnlyEnglishContributorsInDataDivButFrenchInBody_DoesNotCopyEnglishIntoFrenchSlot()
        {
            var dom = new HtmlDom(@"<html ><head></head><body>
				<div id='bloomDataDiv'>
					 <div data-book='originalContributions' lang='en'>the contributions</div>
				</div>
				<div class='bloom-page verso'>
					 <div id='originalContributions' class='bloom-translationGroup'>
						<div data-book='originalContributions' lang='fr'>les contributeurs</div>
						<div data-book='originalContributions' lang='xyz'></div>
					</div>
				</div>
				</body></html>"                );
            var collectionSettings = new CollectionSettings()
            {
                Language1Iso639Code = "etr",
                Language2Iso639Code = "fr"
            };
            var data = new BookData(dom, collectionSettings, null);

            data.SynchronizeDataItemsThroughoutDOM();
            XmlElement frenchContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='fr']");

            Assert.AreEqual("les contributeurs", frenchContributions.InnerText, "Should not touch existing French Contributions");
            //Assert.IsFalse(frenchContributions.HasAttribute("bloom-languageBloomHadToCopyFrom"));
        }
コード例 #6
0
        public LibraryModel(string pathToLibrary, CollectionSettings collectionSettings,
                            //SendReceiver sendReceiver,
                            BookSelection bookSelection,
                            SourceCollectionsList sourceCollectionsList,
                            BookCollection.Factory bookCollectionFactory,
                            EditBookCommand editBookCommand,
                            CreateFromSourceBookCommand createFromSourceBookCommand,
                            BookServer bookServer,
                            CurrentEditableCollectionSelection currentEditableCollectionSelection,
                            BookThumbNailer thumbNailer,
                            TeamCollectionManager tcManager)
        {
            _bookSelection      = bookSelection;
            _pathToLibrary      = pathToLibrary;
            _collectionSettings = collectionSettings;
            //_sendReceiver = sendReceiver;
            _sourceCollectionsList = sourceCollectionsList;
            _bookCollectionFactory = bookCollectionFactory;
            _editBookCommand       = editBookCommand;
            _bookServer            = bookServer;
            _currentEditableCollectionSelection = currentEditableCollectionSelection;
            _thumbNailer = thumbNailer;
            _tcManager   = tcManager;

            createFromSourceBookCommand.Subscribe(CreateFromSourceBook);
        }
コード例 #7
0
        private Metadata GetMetadata(string dataDivContent, CollectionSettings collectionSettings = null)
        {
            var dom      = MakeDom(dataDivContent);
            var bookData = new BookData(dom, collectionSettings ?? _collectionSettings, null);

            return(BookCopyrightAndLicense.GetMetadata(dom, bookData));
        }
コード例 #8
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");
        }
コード例 #9
0
        private void LoadFontCombo()
        {
            // Display the fonts in sorted order.
            var fontNames = new List <string>();

            fontNames.AddRange(Browser.NamesOfFontsThatBrowserCanRender());
            fontNames.Sort();
            var defaultFont = CollectionSettings.GetDefaultFontName();

            foreach (var font in fontNames)
            {
                _fontCombo.Items.Add(font);
                if (font == defaultFont)
                {
                    _fontCombo.SelectedItem = font;
                }
            }

            // Make the font combobox wide enough to display the longest value.
            int width = _fontCombo.DropDownWidth;

            using (Graphics g = _fontCombo.CreateGraphics())
            {
                Font font = _fontCombo.Font;
                int  vertScrollBarWidth = (_fontCombo.Items.Count > _fontCombo.MaxDropDownItems) ? SystemInformation.VerticalScrollBarWidth : 0;

                width = (from string s in _fontCombo.Items select(int) g.MeasureString(s, font).Width).Concat(new[] { width }).Max() + vertScrollBarWidth;
            }
            _fontCombo.DropDownWidth = width;
        }
コード例 #10
0
        public void SetNextButtonState(UserControl caller, bool enabled)
        {
            wizardControl1.SelectedPage.AllowNext = enabled;

            if (caller is KindOfCollectionControl)
            {
                _kindOfCollectionPage.NextPage = _collectionInfo.IsSourceCollection
                                                                                                        ? _collectionNamePage
                                                                                                        : _vernacularLanguagePage;

                if (_collectionInfo.IsSourceCollection)
                {
                    _collectionInfo.Language1Iso639Code = "en";
                }
            }

            if (caller is LanguageIdControl)
            {
                var pattern = L10NSharp.LocalizationManager.GetString("NewCollectionWizard.NewBookPattern", "{0} Books", "The {0} is replaced by the name of the language.");
                _collectionInfo.PathToSettingsFile = CollectionSettings.GetPathForNewSettings(DefaultParentDirectoryForCollections, string.Format(pattern, _collectionInfo.Language1Name));
                //_collectionInfo.CollectionName = ;


                _languageLocationPage.NextPage = DefaultCollectionPathWouldHaveProblems
                                                                                                        ? _collectionNamePage //go ahead to the language location page for now, but then divert to the page
                                                                                                                              //we use for fixing up the name
                                                                                                        : _finishPage;
            }
        }
コード例 #11
0
 private void PopulateUI(CollectionSettings settings)
 {
     this.textMusicDirectory.Text        = settings.MusicDirectory;
     this.textFileNamingPattern.Text     = settings.FileNamingPattern;
     this.checkNetworkEncoding.IsChecked = settings.NetworkEncoding;
     this.textLocalThreads.Text          = this.SettingsManager.Settings.LocalConcurrencyLevel.ToString();
 }
コード例 #12
0
        public delegate EditingModel Factory();        //autofac uses this

        public EditingModel(BookSelection bookSelection, PageSelection pageSelection,
                            LanguageSettings languageSettings,
                            TemplateInsertionCommand templateInsertionCommand,
                            PageListChangedEvent pageListChangedEvent,
                            RelocatePageEvent relocatePageEvent,
                            BookRefreshEvent bookRefreshEvent,
                            DuplicatePageCommand duplicatePageCommand,
                            DeletePageCommand deletePageCommand,
                            SelectedTabChangedEvent selectedTabChangedEvent,
                            SelectedTabAboutToChangeEvent selectedTabAboutToChangeEvent,
                            LibraryClosing libraryClosingEvent,
                            LocalizationChangedEvent localizationChangedEvent,
                            CollectionSettings collectionSettings,
                            SendReceiver sendReceiver,
                            EnhancedImageServer server)
        {
            _bookSelection        = bookSelection;
            _pageSelection        = pageSelection;
            _languageSettings     = languageSettings;
            _duplicatePageCommand = duplicatePageCommand;
            _deletePageCommand    = deletePageCommand;
            _collectionSettings   = collectionSettings;
            _sendReceiver         = sendReceiver;
            _server = server;

            bookSelection.SelectionChanged      += new EventHandler(OnBookSelectionChanged);
            pageSelection.SelectionChanged      += new EventHandler(OnPageSelectionChanged);
            templateInsertionCommand.InsertPage += new EventHandler(OnInsertTemplatePage);

            bookRefreshEvent.Subscribe((book) => OnBookSelectionChanged(null, null));
            selectedTabChangedEvent.Subscribe(OnTabChanged);
            selectedTabAboutToChangeEvent.Subscribe(OnTabAboutToChange);
            duplicatePageCommand.Implementer = OnDuplicatePage;
            deletePageCommand.Implementer    = OnDeletePage;
            pageListChangedEvent.Subscribe(x => _view.UpdatePageList(false));
            relocatePageEvent.Subscribe(OnRelocatePage);
            libraryClosingEvent.Subscribe(o => SaveNow());
            localizationChangedEvent.Subscribe(o =>
            {
                //this is visible was added for https://jira.sil.org/browse/BL-267, where the edit tab has never been
                //shown so the view has never been full constructed, so we're not in a good state to do a refresh
                if (Visible)
                {
                    SaveNow();
                    _view.UpdateButtonLocalizations();
                    RefreshDisplayOfCurrentPage();
                    //_view.UpdateDisplay();
                    _view.UpdatePageList(false);
                    _view.UpdateTemplateList();
                }
                else if (_view != null)
                {
                    // otherwise changing UI language in Publish tab (for instance) won't update these localizations
                    _view.UpdateButtonLocalizations();
                }
            });
            _contentLanguages = new List <ContentLanguage>();
            _server.CurrentCollectionSettings = _collectionSettings;
            _server.CurrentBook = CurrentBook;
        }
コード例 #13
0
ファイル: ApiRequest.cs プロジェクト: gmartin7/myBloomFork
 public ApiRequest(IRequestInfo requestinfo, CollectionSettings currentCollectionSettings, Book.Book currentBook)
 {
     _requestInfo = requestinfo;
     CurrentCollectionSettings = currentCollectionSettings;
     CurrentBook = currentBook;
     Parameters  = requestinfo.GetQueryParameters();
 }
コード例 #14
0
 public FakeLibraryModel(TemporaryFolder testFolder, CollectionSettings collectionSettings = null)
     : base(testFolder.Path, collectionSettings ?? new CollectionSettings(), new BookSelection(), GetDefaultSourceCollectionsList(),
            BookCollectionFactory, null, new CreateFromSourceBookCommand(), new FakeBookServer(), new CurrentEditableCollectionSelection(), null,
            new TeamCollectionManager(testFolder.FolderPath, null, new BookRenamedEvent(), new BookStatusChangeEvent(), new BookSelection(), null))
 {
     TestFolderPath = testFolder.Path;
 }
コード例 #15
0
 protected Bloom.Book.Book CreateBook(CollectionSettings collectionSettings)
 {
     _collectionSettings = collectionSettings;
     return(new Bloom.Book.Book(_metadata, _storage.Object, _templateFinder.Object,
                                _collectionSettings,
                                _pageSelection.Object, _pageListChangedEvent, new BookRefreshEvent()));
 }
コード例 #16
0
        public static void AddUIDictionaryToDom(HtmlDom pageDom, CollectionSettings collectionSettings)
        {
            XmlElement dictionaryScriptElement = pageDom.RawDom.SelectSingleNode("//script[@id='ui-dictionary']") as XmlElement;

            if (dictionaryScriptElement != null)
            {
                dictionaryScriptElement.ParentNode.RemoveChild(dictionaryScriptElement);
            }

            dictionaryScriptElement = pageDom.RawDom.CreateElement("script");
            dictionaryScriptElement.SetAttribute("type", "text/javascript");
            dictionaryScriptElement.SetAttribute("id", "ui-dictionary");
            var d = new Dictionary <string, string>();

            d.Add(collectionSettings.Language1Iso639Code, collectionSettings.Language1Name);
            if (!String.IsNullOrEmpty(collectionSettings.Language2Iso639Code) && !d.ContainsKey(collectionSettings.Language2Iso639Code))
            {
                d.Add(collectionSettings.Language2Iso639Code, collectionSettings.GetLanguage2Name(collectionSettings.Language2Iso639Code));
            }
            if (!String.IsNullOrEmpty(collectionSettings.Language3Iso639Code) && !d.ContainsKey(collectionSettings.Language3Iso639Code))
            {
                d.Add(collectionSettings.Language3Iso639Code, collectionSettings.GetLanguage3Name(collectionSettings.Language3Iso639Code));
            }

            d.Add("vernacularLang", collectionSettings.Language1Iso639Code);            //use for making the vernacular the first tab
            d.Add("{V}", collectionSettings.Language1Name);
            d.Add("{N1}", collectionSettings.GetLanguage2Name(collectionSettings.Language2Iso639Code));
            d.Add("{N2}", collectionSettings.GetLanguage3Name(collectionSettings.Language3Iso639Code));

            AddLocalizedHintContentsToDictionary(pageDom, d, collectionSettings);

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

            pageDom.Head.InsertAfter(dictionaryScriptElement, pageDom.Head.LastChild);
        }
コード例 #17
0
        public BookServer CreateBookServer()
        {
            _collectionSettings = CreateDefaultCollectionsSettings();
            var xmatterFinder = new XMatterPackFinder(new[] { BloomFileLocator.GetInstalledXMatterDirectory() });
            var fileLocator   = new BloomFileLocator(_collectionSettings, xmatterFinder, ProjectContext.GetFactoryFileLocations(), ProjectContext.GetFoundFileLocations(), ProjectContext.GetAfterXMatterFileLocations());
            var starter       = new BookStarter(fileLocator, (dir, forSelectedBook) => new BookStorage(dir, fileLocator, new BookRenamedEvent(), _collectionSettings), _collectionSettings);

            return(new BookServer(
                       //book factory
                       (bookInfo, storage) =>
            {
                return new Bloom.Book.Book(bookInfo, storage, null, _collectionSettings,
                                           new PageSelection(),
                                           new PageListChangedEvent(), new BookRefreshEvent());
            },

                       // storage factory
                       (path, forSelectedBook) =>
            {
                var storage = new BookStorage(path, fileLocator, new BookRenamedEvent(), _collectionSettings);
                storage.BookInfo = new BookInfo(path, true);
                return storage;
            },

                       // book starter factory
                       () => starter,

                       // configurator factory
                       null));
        }
コード例 #18
0
        private static string GetReaderSettings(CollectionSettings currentCollectionSettings)
        {
            var settingsPath = DecodableReaderTool.GetReaderToolsSettingsFilePath(currentCollectionSettings);

            // if file exists, return current settings
            if (RobustFile.Exists(settingsPath))
            {
                var result = RobustFile.ReadAllText(settingsPath, Encoding.UTF8);
                if (!string.IsNullOrWhiteSpace(result))
                {
                    return(result);
                }
            }

            // file does not exist, so make a new one
            // The literal string here defines our default reader settings for a collection.
            var settingsString = "{\"letters\":\"a b c d e f g h i j k l m n o p q r s t u v w x y z\","
                                 + "\"moreWords\":\"\","
                                 + "\"stages\":[{\"letters\":\"\",\"sightWords\":\"\"}],"
                                 + "\"levels\":[{\"maxWordsPerSentence\":2,\"maxWordsPerPage\":2,\"maxWordsPerBook\":20,\"maxUniqueWordsPerBook\":0,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":5,\"maxWordsPerPage\":5,\"maxWordsPerBook\":23,\"maxUniqueWordsPerBook\":8,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":7,\"maxWordsPerPage\":10,\"maxWordsPerBook\":72,\"maxUniqueWordsPerBook\":16,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":8,\"maxWordsPerPage\":18,\"maxWordsPerBook\":206,\"maxUniqueWordsPerBook\":32,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":12,\"maxWordsPerPage\":25,\"maxWordsPerBook\":500,\"maxUniqueWordsPerBook\":64,\"thingsToRemember\":[]},"
                                 + "{\"maxWordsPerSentence\":20,\"maxWordsPerPage\":50,\"maxWordsPerBook\":1000,\"maxUniqueWordsPerBook\":0,\"thingsToRemember\":[]}]}";

            RobustFile.WriteAllText(settingsPath, settingsString);

            return(settingsString);
        }
コード例 #19
0
        public void SetNextButtonState(UserControl caller, bool enabled)
        {
            _wizardControl.SelectedPage.AllowNext = enabled;

            if (caller is KindOfCollectionControl)
            {
                _kindOfCollectionPage.NextPage = _collectionInfo.IsSourceCollection
                                                                                                        ? _collectionNamePage
                                                                                                        : _vernacularLanguagePage;

                if (_collectionInfo.IsSourceCollection)
                {
                    _collectionInfo.Language1Iso639Code = "en";
                }
            }

            if (caller is LanguageIdControl)
            {
                var pattern = LocalizationManager.GetString("NewCollectionWizard.NewBookPattern", "{0} Books", "The {0} is replaced by the name of the language.");
                // GetPathForNewSettings uses Path.Combine which can fail with certain characters that are illegal in paths, but not in language names.
                // The characters we ran into were two pipe characters ("|") at the front of the language name.
                var tentativeCollectionName = string.Format(pattern, _collectionInfo.Language1.Name);
                var sanitizedCollectionName = tentativeCollectionName.SanitizePath('.');
                _collectionInfo.PathToSettingsFile = CollectionSettings.GetPathForNewSettings(DefaultParentDirectoryForCollections, sanitizedCollectionName);

                // An earlier version went direct to finish if the proposed name was OK (unless DefaultCollectionPathWouldHaveProblems || (tentativeCollectionName != sanitizedCollectionName))
                // but per BL-2649 we now want to always let the user check the name.
                _languageLocationPage.NextPage = _collectionNamePage;
            }
        }
コード例 #20
0
        public void SetNextButtonState(UserControl caller, bool enabled)
        {
            wizardControl1.SelectedPage.AllowNext = enabled;

            if (caller is KindOfCollectionControl)
            {
                _kindOfCollectionPage.NextPage = _collectionInfo.IsSourceCollection
                                                                                                        ? _collectionNamePage
                                                                                                        : _vernacularLanguagePage;

                if (_collectionInfo.IsSourceCollection)
                {
                    _collectionInfo.Language1Iso639Code = "en";
                }
            }

            if (caller is LanguageIdControl)
            {
                var pattern = L10NSharp.LocalizationManager.GetString("NewCollectionWizard.NewBookPattern", "{0} Books", "The {0} is replaced by the name of the language.");
                // GetPathForNewSettings uses Path.Combine which can fail with certain characters that are illegal in paths, but not in language names.
                // The characters we ran into were two pipe characters ("|") at the front of the language name.
                var tentativeCollectionName = string.Format(pattern, _collectionInfo.Language1Name);
                var sanitizedCollectionName = tentativeCollectionName.SanitizePath('.');
                _collectionInfo.PathToSettingsFile = CollectionSettings.GetPathForNewSettings(DefaultParentDirectoryForCollections, sanitizedCollectionName);

                _languageLocationPage.NextPage = DefaultCollectionPathWouldHaveProblems || (tentativeCollectionName != sanitizedCollectionName)
                                                 //go ahead to the language location page for now,
                                                 //but then divert to the page we use for fixing up the name
                                        ? _collectionNamePage
                                        : _finishPage;
            }
        }
コード例 #21
0
        public void Start(Book.Book book, CollectionSettings collectionSettings, Color backColor)
        {
            if (_wifiAdvertiser != null)
            {
                Stop();
            }

            // This listens for a BloomReader to request a book.
            // It requires a firewall hole allowing Bloom to receive messages on _portToListen.
            // We initialize it before starting the Advertiser to avoid any chance of a race condition
            // where a BloomReader manages to request an advertised book before we start the listener.
            _wifiListener = new BloomReaderUDPListener();
            _wifiListener.NewMessageReceived += (sender, args) =>
            {
                var json = Encoding.UTF8.GetString(args.Data);
                try
                {
                    dynamic settings = JsonConvert.DeserializeObject(json);
                    // The property names used here must match the ones in BloomReader, doInBackground method of SendMessage,
                    // a private class of NewBookListenerService.
                    var androidIpAddress = (string)settings.deviceAddress;

                    var androidName = (string)settings.deviceName;
                    // This prevents the device (or other devices) from queuing up requests while we're busy with this one.
                    // In effect, the Android is only allowed to request a retry after we've given up this try at sending.
                    // Of course, there are async effects from network latency. But if we do get another request while
                    // handling this one, we will ignore it, since StartSendBook checks for a transfer in progress.
                    _wifiAdvertiser.Paused = true;
                    StartSendBookOverWiFi(book, androidIpAddress, androidName, backColor);
                    // Returns immediately. But we don't resume advertisements until the async send completes.
                }
                // If there's something wrong with the JSON (maybe an obsolete or newer version of reader?)
                // just ignore the request.
                catch (Exception ex) when(ex is JsonReaderException || ex is JsonSerializationException)
                {
                    _progress.Error(id: "BadBookRequest",
                                    message: "Got a book request we could not process. Possibly the device is running an incompatible version of BloomReader?");

                    //this is too technical/hard to translate
                    _progress.ErrorWithoutLocalizing($" Request contains {json}; trying to interpret as JSON we got {ex.Message}");
                }
            };

            var pathHtmlFile = book.GetPathHtmlFile();

            _wifiAdvertiser = new WiFiAdvertiser(_progress)
            {
                BookTitle     = BookStorage.SanitizeNameForFileSystem(book.Title),             // must be the exact same name as the file we will send if requested
                TitleLanguage = collectionSettings.Language1Iso639Code,
                BookVersion   = Book.Book.MakeVersionCode(File.ReadAllText(pathHtmlFile), pathHtmlFile)
            };

            AndroidView.CheckBookLayout(book, _progress);
            _wifiAdvertiser.Start();

            _progress.Message(id: "WifiInstructions1",
                              message: "On the Android, run Bloom Reader, open the menu and choose 'Receive Books from computer'.");
            _progress.Message(id: "WifiInstructions2",
                              message: "You can do this on as many devices as you like. Make sure each device is connected to the same network as this computer.");
        }
コード例 #22
0
        /// <summary>
        /// Here, "normally" means unless the user overrides via a .bloom-visibility-user-on/off
        /// </summary>
        internal static bool ShouldNormallyShowEditable(string lang, string[] dataDefaultLanguages,
                                                        string contentLanguageIso2, string contentLanguageIso3, // these are effected by the multilingual settings for this book
                                                        CollectionSettings settings)                            // use to get the collection's current N1 and N2 in xmatter or other template pages that specify default languages
        {
            if (dataDefaultLanguages == null || dataDefaultLanguages.Length == 0 ||
                string.IsNullOrWhiteSpace(dataDefaultLanguages[0]) ||
                dataDefaultLanguages[0].Equals("auto", StringComparison.InvariantCultureIgnoreCase))
            {
                return(lang == settings.Language1Iso639Code || lang == contentLanguageIso2 || lang == contentLanguageIso3);
            }
            else
            {
                // Hote there are (perhaps unfortunately) two different labelling systems, but they have a 1-to-1 correspondence:
                // The V/N1/N2 system feels natural in vernacular book contexts
                // The L1/L2/L3 system is more natural in source book contexts.
                return((lang == settings.Language1Iso639Code && dataDefaultLanguages.Contains("V")) ||
                       (lang == settings.Language1Iso639Code && dataDefaultLanguages.Contains("L1")) ||

                       (lang == settings.Language2Iso639Code && dataDefaultLanguages.Contains("N1")) ||
                       (lang == settings.Language2Iso639Code && dataDefaultLanguages.Contains("L2")) ||

                       (lang == settings.Language3Iso639Code && dataDefaultLanguages.Contains("N2")) ||
                       (lang == settings.Language3Iso639Code && dataDefaultLanguages.Contains("L3")) ||

                       dataDefaultLanguages.Contains(lang));            // a literal language id, e.g. "en" (used by template starter)
            }
        }
コード例 #23
0
        public void SynchronizeDataItemsThroughoutDOM_HasOnlyEnglishContributorsButEnglishIsLang3_CopiesEnglishIntoNationalLanguageSlot()
        {
            var dom = new HtmlDom(@"<html ><head></head><body>
				<div id='bloomDataDiv'>
					 <div data-book='originalContributions' lang='en'>the contributions</div>
				</div>
				<div class='bloom-page verso'>
					 <div id='originalContributions' class='bloom-translationGroup'>
						<div  class='bloom-copyFromOtherLanguageIfNecessary'  data-book='originalContributions' lang='fr'></div>
						<div  class='bloom-copyFromOtherLanguageIfNecessary'  data-book='originalContributions' lang='en'></div>
					</div>
				</div>
				</body></html>"                );
            var collectionSettings = new CollectionSettings()
            {
                Language1Iso639Code = "etr",
                Language2Iso639Code = "fr"
            };
            var data = new BookData(dom, collectionSettings, null);

            data.SynchronizeDataItemsThroughoutDOM();
            XmlElement englishContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='en']");

            Assert.AreEqual("the contributions", englishContributions.InnerText, "Should copy English into body of course, as normal");
            XmlElement frenchContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='fr']");

            Assert.AreEqual("the contributions", frenchContributions.InnerText, "Should copy English into French Contributions becuase it's better than just showing nothing");
            //Assert.AreEqual("en",frenchContributions.GetAttribute("bloom-languageBloomHadToCopyFrom"),"Should have left a record that we did this dubious 'borrowing' from English");
        }
コード例 #24
0
        /// <summary>
        /// This is used when a book is first created from a source; without it, if the shell maker left the book as trilingual when working on it,
        /// then every time someone created a new book based on it, it too would be trilingual.
        /// </summary>
        public static void SetInitialMultilingualSetting(BookData bookData, int oneTwoOrThreeContentLanguages,
                                                         CollectionSettings collectionSettings)
        {
            //var multilingualClass =  new string[]{"bloom-monolingual", "bloom-bilingual","bloom-trilingual"}[oneTwoOrThreeContentLanguages-1];

            if (oneTwoOrThreeContentLanguages < 3)
            {
                bookData.RemoveAllForms("contentLanguage3");
            }
            if (oneTwoOrThreeContentLanguages < 2)
            {
                bookData.RemoveAllForms("contentLanguage2");
            }

            bookData.Set("contentLanguage1", collectionSettings.Language1Iso639Code, false);
            bookData.Set("contentLanguage1Rtl", collectionSettings.IsLanguage1Rtl.ToString(), false);
            if (oneTwoOrThreeContentLanguages > 1)
            {
                bookData.Set("contentLanguage2", collectionSettings.Language2Iso639Code, false);
                bookData.Set("contentLanguage2Rtl", collectionSettings.IsLanguage2Rtl.ToString(), false);
            }
            if (oneTwoOrThreeContentLanguages > 2 && !string.IsNullOrEmpty(collectionSettings.Language3Iso639Code))
            {
                bookData.Set("contentLanguage3", collectionSettings.Language3Iso639Code, false);
                bookData.Set("contentLanguage3Rtl", collectionSettings.IsLanguage3Rtl.ToString(), false);
            }
        }
コード例 #25
0
        public void SynchronizeDataItemsThroughoutDOM_HasFrenchAndEnglishContributorsInDataDiv_DoesNotCopyEnglishIntoFrenchSlot()
        {
            var dom = new HtmlDom(@"<html ><head></head><body>
				<div id='bloomDataDiv'>
					 <div data-book='originalContributions' lang='en'>the contributions</div>
					<div data-book='originalContributions' lang='fr'>les contributeurs</div>
				</div>
				<div class='bloom-page verso'>
					 <div id='originalContributions' class='bloom-translationGroup'>
						<div data-book='originalContributions' lang='fr'></div>
						<div data-book='originalContributions' lang='xyz'></div>
					</div>
				</div>
				</body></html>"                );
            var collectionSettings = new CollectionSettings()
            {
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "fr"
            };
            var data = new BookData(dom, collectionSettings, null);

            data.SynchronizeDataItemsThroughoutDOM();
            XmlElement frenchContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='fr']");

            Assert.AreEqual("les contributeurs", frenchContributions.InnerText, "Should use the French, not the English even though the French in the body was empty");
            XmlElement vernacularContributions = (XmlElement)dom.SelectSingleNodeHonoringDefaultNS("//*[@data-book='originalContributions' and @lang='xyz']");

            Assert.AreEqual("", vernacularContributions.InnerText, "Should not copy Edolo into Vernacualr Contributions. Only national language fields get this treatment");
        }
コード例 #26
0
 protected CollectionSettings CreateDefaultCollectionsSettings()
 {
     return(new CollectionSettings(new NewCollectionSettings()
     {
         PathToSettingsFile = CollectionSettings.GetPathForNewSettings(_testFolder.Path, "test"), Language1Iso639Code = "xyz", Language2Iso639Code = "en", Language3Iso639Code = "fr"
     }));
 }
コード例 #27
0
        public delegate BookStarter Factory();        //autofac uses this

        public BookStarter(IChangeableFileLocator fileLocator, BookStorage.Factory bookStorageFactory, CollectionSettings collectionSettings)
        {
            _fileLocator        = fileLocator;
            _bookStorageFactory = bookStorageFactory;
            _collectionSettings = collectionSettings;
            _isSourceCollection = collectionSettings.IsSourceCollection;
        }
コード例 #28
0
        public BookDownloadSupport()
        {
            // We need the download folder to exist if we are asked to download a book.
            // We also want it to exist, to show the (planned) link that offers to launch the web site.
            // Another advantage of creating it early is that we don't have to create it in the UI when we want to add
            // a downloaded book to the UI.
            // So, we just make sure it exists here at startup.
            string downloadFolder = BookTransfer.DownloadFolder;

            if (!Directory.Exists(downloadFolder))
            {
                var pathToSettingsFile = CollectionSettings.GetPathForNewSettings(Path.GetDirectoryName(downloadFolder),
                                                                                  Path.GetFileName(downloadFolder));
                var settings = new NewCollectionSettings()
                {
                    Language1Iso639Code = "en",
                    Language1Name       = "English",
                    IsSourceCollection  = true,
                    PathToSettingsFile  = pathToSettingsFile
                                          // All other defaults are fine
                };
                CollectionSettings.CreateNewCollection(settings);
            }

            // Make the OS run Bloom when it sees bloom://somebooktodownload
            RegisterForBloomUrlProtocol();
        }
コード例 #29
0
        public void BringBookUpToDate_MigratesReaderToolsAvailableToToolboxIsOpen()
        {
            var oldMetaData =
                "{\"bookInstanceId\":\"3328aa4a - 2ef3 - 43a8 - a656 - 1d7c6f00444c\",\"folio\":false,\"title\":\"Landscape basic book\",\"baseUrl\":null,\"bookOrder\":null,\"isbn\":\"\",\"bookLineage\":\"056B6F11-4A6C-4942-B2BC-8861E62B03B3\",\"downloadSource\":null,\"license\":\"cc-by\",\"formatVersion\":\"2.0\",\"licenseNotes\":null,\"copyright\":null,\"authors\":null,\"credits\":\"\",\"tags\":[\"<p>\r\n</p>\"],\"pageCount\":0,\"languages\":[],\"langPointers\":null,\"summary\":null,\"allowUploadingToBloomLibrary\":true,\"bookletMakingIsAppropriate\":true,\"uploader\":null,\"tools\":null,\"readerToolsAvailable\":true}";
            var storage = GetInitialStorage();

            // This seems to be needed to let it locate some kind of collection settings.
            var    folder  = storage.FolderPath;
            var    locator = (FileLocator)storage.GetFileLocator();
            string root    = FileLocator.GetDirectoryDistributedWithApplication(BloomFileLocator.BrowserRoot);

            locator.AddPath(root.CombineForPath("bookLayout"));
            var collectionSettings =
                new CollectionSettings(new NewCollectionSettings()
            {
                PathToSettingsFile  = CollectionSettings.GetPathForNewSettings(folder, "test"),
                Language1Iso639Code = "xyz",
                Language2Iso639Code = "en",
                Language3Iso639Code = "fr"
            });
            var book = new Bloom.Book.Book(new BookInfo(folder, true), storage, new Mock <ITemplateFinder>().Object,
                                           collectionSettings,
                                           new Mock <PageSelection>().Object, new PageListChangedEvent(), new BookRefreshEvent());
            var jsonPath = book.BookInfo.MetaDataPath;

            File.WriteAllText(jsonPath, oldMetaData);

            book.BringBookUpToDate(new NullProgress());

            Assert.That(book.BookInfo.ToolboxIsOpen, Is.True);
        }
コード例 #30
0
        public delegate EditingModel Factory();        //autofac uses this

        public EditingModel(BookSelection bookSelection, PageSelection pageSelection,
                            LanguageSettings languageSettings,
                            TemplateInsertionCommand templateInsertionCommand,
                            PageListChangedEvent pageListChangedEvent,
                            RelocatePageEvent relocatePageEvent,
                            BookRefreshEvent bookRefreshEvent,
                            DeletePageCommand deletePageCommand,
                            SelectedTabChangedEvent selectedTabChangedEvent,
                            SelectedTabAboutToChangeEvent selectedTabAboutToChangeEvent,
                            LibraryClosing libraryClosingEvent,
                            CollectionSettings collectionSettings,
                            SendReceiver sendReceiver)
        {
            _bookSelection      = bookSelection;
            _pageSelection      = pageSelection;
            _languageSettings   = languageSettings;
            _deletePageCommand  = deletePageCommand;
            _collectionSettings = collectionSettings;
            _sendReceiver       = sendReceiver;

            bookSelection.SelectionChanged      += new EventHandler(OnBookSelectionChanged);
            pageSelection.SelectionChanged      += new EventHandler(OnPageSelectionChanged);
            templateInsertionCommand.InsertPage += new EventHandler(OnInsertTemplatePage);

            bookRefreshEvent.Subscribe((book) => OnBookSelectionChanged(null, null));
            selectedTabChangedEvent.Subscribe(OnTabChanged);
            selectedTabAboutToChangeEvent.Subscribe(OnTabAboutToChange);
            deletePageCommand.Implementer = OnDeletePage;
            pageListChangedEvent.Subscribe(x => _view.UpdatePageList(false));
            relocatePageEvent.Subscribe(OnRelocatePage);
            libraryClosingEvent.Subscribe(o => SaveNow());
            _contentLanguages = new List <ContentLanguage>();
        }