diff --git a/CHANGELOG.md b/CHANGELOG.md index 16bb1b32..f987594b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,147 @@ # novelWriter Changelog +## Version 2.0 RC 1 [2022-10-17] + +### Release Notes + +This is a release candidate of the next release version, and is intended for testing purposes. +Please be careful when using this version on live writing projects, and make sure you take frequent +backups. + +Please check the changelog for an overview of changes. The full release notes will be added to the +final release. + +**Note:** As of the 2.0 release, novelWriter requires Qt 5.10 or higher and Python 3.7 or higher. + +### Detailed Changelog + +**Note:** This will no longer be release 1.7, but 2.0 instead due to the major changes to the User +Interface. PR #1146. + +**Features** + +* The add new documents feature has been made a little smarter and now tries to choose whether the + added document should be a sibling or a child to the selected document. Issue #1107. PR #1110. +* A folder in the Project Tree can now be converted to a Novel Document or Project Note from the + item's context menu. This makes sense now that documents can have child items. Issue #1071. + PR #1128. +* All child elements of an item in the Project Tree can now be collectively expanded or collapsed + from the context menu. The same action can be triggered on the entire tree from the menu button + at the top. Issue #1122. PR #1129. +* If using the auto-insert feature for spaces next to punctuation designed for for instance French, + any existing spaces are first stripped before the correct space character is added. Some users + find it hard to unlearn the reflex to type the space. Issue #1061. PR #1131. +* The Project Tree now has Quick Links for navigating directly between root folders. This is + convenient for very large projects. Issue #1137. PR #1165. +* It is now possible to filter out entire root folders on the Build Tool. Issue #1138. PR #1168. + +**Bugfixes** + +* Fix a typo in the Lorem Ipsum tool and set a max width for the views bar. PR #1065. +* The language set in the Build Tool is now properly exported to Open Document files. Previously, + it would be set to English regardless of the user's selection. Issue #1073. PR #1077. +* Since the text editor cursor extends to the right of its position in the window, it would + disappear under the right-hand margin if it reached the edge. A minimum margin of the width of + the cursor has been added to the editor, and the same value subtracted from the margin of the + viewbox. Thus, the cursor no longer disappears. Issue #1112. PR #1113. +* The `Shift+Enter` key combination no longer inserts a Unicode line separator in the text editor. + Issue #1150. PR #1151. +* Fixed an issue where idle time would not be properly reset when a new project was created. + Issue #1149. PR #1153. +* Removed the context menu that would appear on the Views Bar, from which the bar could be hidden. + This is some feature imposed by the Qt library, and it is not wanted. Issue #1147. PR #1153. + +**Known Issues** + +* An attempt has been made to fix the missing mime icon for novelWriter projects on Linux. The + newer versions of Nautilus don't seem to display the correct icon due to some changes in the way + icons are extracted from the theme. The icon displays fine in other places. PR #1068. + +**Internationalisation** + +* Norwegian and US English translations have been updated. PR #1170. + +**User Interface** + +* The New Project Wizard has been updated based on user feedback. The "Working Title" setting is + now called "Project Name". The number of root folders one can create on the options page has been + reduced to the standard ones. An option to add sample notes has been added, and the option to + generate chapter folders has been removed. The "Minimal Project" option also no longer creates + folders. An Archive root folder is automatically added to all new projects, and a Trash folder is + added to custom projects. PR #1067. +* The border around a lot of Widgets on the main GUI have been removed. PR #1069. +* The Views Bar has been updated since the beta re;ease with better icons, tooltips, and an + expanding menu on the Settings button. The Build Tool can now also be accessed from the Views + Bar. PR #1069. +* The editor theme setting in Preferences has been moved back to the General tab where users seem + to expect to find it. PR #1069. +* A toolbar has been added to the Outline View where the user can select which Novel folder to + view. A refresh button for a forced reload of the selected Novel folder has been added, and the + menu to select which columns to show has been added to a new button. This makes it easier to find + for users instead of having to right-click the table header. Issue #1105. PRs #1063, #1094, and + #1111. +* The Rebuild Outline and Auto-Update Outline options have been removed from the Main Menu. + PR #1063. +* The Project Tree has been redesigned. The header is now hidden, and the columns resize + automatically. A toolbar has been added with buttons for moving items up and down in the tree, a + button for adding new files, folders and root folders, and a menu button for further options + affecting the whole tree. These features have mostly bee removed from the Main Menu. PR #1079. +* The context menu of the Project Tree has been rewritten completely. It is now possible to set + importance and status directly from this menu. Part of issue #973. PRs #1079 and #1105. +* The Edit Item dialog has been replaced with a simple Edit Label dialog. Most of the features + handled by the old dialog have been moved to the Project Tree context menu. PR #1082. +* The Novel View has been redesigned to match the new Outline View and Project Tree. The header is + now hidden, and the columns auto-size. The third column can be selected from a set of options, or + be hidden entirely. A button with a menu can be used to select which Novel folder to show. + Issue #1041. PR #1084. +* An arrow icon has been added behind each item in the Novel View. Clicking it, will pop up a + tooltip showing the collected meta data for the heading the item represents. PR #1088. +* The Project Details dialog now supports multiple novel folders. Issue #1078. PRs #1130 and #1167. +* The Split and Merge tools have been rewritten to work with the new feature of allowing documents + to have child documents. The tools have also had more options added to them. The feature is now + accessible through the Project Tree item's context menu, and is no longer available from the Main + Menu. Issues #1072 and #1032. PRs #1148 and #1154. + +**Installation and Packaging** + +* AppImage distribution has been added by @Ryex. Issue #1091. PR #1092. + +**Code Improvements** + +* A new test project generator function has been added to replace the dependency on the New Project + tools in the app itself. This ensures that changing the in-app feature doesn't affect the entire + test suite. Over time, this generator function should also replace the minimal sample project + saved in the test suite. PR #1067. +* The index class has been rewritten. The index data is now stored in a hierarchy of objects rather + than a set of nested dictionaries. The `itemIndex` holds all the data collected from the project, + and the `tagsIndex` is a reverse lookup index for linking tags back to where they are used. The + reading/writing of the index to disk between sessions is now handled by pack/unpack functions in + each object. The index will be regenerated when the user first opens a project as it has been + completely restructured. PR #1074. +* The index instance is now an instance of the project class, not the main GUI. PR #1074. +* The Outline View has been restructured into a single parent widget in the same manner as the + Novel View was in the previous pre-release. Related to #1041. PR #1063. +* A lot of main GUI objects have been given new names in the code to better represent what they do. + PR #1081. +* The converter for the old 1.0 project structure has been simplified. Mostly to reduce the amount + of code and number of translation labels needed for it. It now produces a single error if + something went wrong. PR #1083. +* A number of unused icons have been removed from the code base. PR #1164. +* All checks for Qt versions below 5.10 have been removed. PR #1174. + +**Not Implemented** + +* An idea to make the indexer run in the global thread pool was not implemented. Issue #1076. +* Feature #997 is now obsolete due to the changes made to the Edit Item dialog in #1082. +* Feature #1106 is not implemented. It proposes to hide the option to select Novel folder if there + is only one. We will see if this is really needed based on user feedback. + +---- + ## Version 1.7 Beta 1 [2022-05-17] +**Note:** The 1.7 release cycle was renamed 2.0 on 2022-10-06. See #1144. + ### Release Notes This is a beta release of the next release version, and is intended for testing purposes. Please be @@ -89,6 +229,39 @@ final release. ---- +## Version 1.6.5 [2022-10-13] + +### Release Notes + +This is a bugfix release that fixes a a few minor issues. The idle time for new projects would be +artificially inflated as the clock was not reset when the project was first created. This only +affects the first entry in the writing statistics. A scaling issue for the Preferences dialog has +also been fixed. It only affected screens with UI scaling enabled. Lastly, typing `Shift+Enter` in +the text editor now creates a regular line break instead of a special line separator. The line +separator serves no purpose in plain text, and was producing inconsistencies in how text is +processed and displayed. + +### Detailed Changelog + +**Bugfixes** + +* Fixed a bug where the idle time was not properly zeroed when a new project was generated after + the wizard was closed. The idle time would be calculated from the time the previous project + closed, thus inflating the value. Issue #1149. PR #1159. +* Fixes an issue where the window size of the Preferences dialog would have the GUI scaling factor + applied twice when the dialog was closed, resulting in the dialog growing in size each time it is + opened. Issue #989. PR #1159. + +**Other Changes** + +* The text editor no longer creates a Unicode line separator (U+2028) when the user presses + `Shift+Enter`. The line separator serves no purpose in a plain text editor, and the code in + general treats them as regular line break. This caused the line separator to display differently + before and after saving. The line separator character is now automatically replaced by a + paragraph separator. Issue #1150. PR #1159. + +---- + ## Version 1.6.4 [2022-09-29] ### Release Notes diff --git a/README.md b/README.md index 7b0a9965..d0e13b6f 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ You can also follow novelWriter on Mastodon at [fosstodon.org/@novelwriter](http ## Implementation -The application is written with Python 3 (3.7+) using Qt5 and PyQt5 (5.3+). It is developed on +The application is written with Python 3 (3.7+) using Qt5 and PyQt5 (5.10+). It is developed on Linux, but should in principle work fine on other operating systems as well as long as dependencies are met. It is regularly tested on Debian and Ubuntu Linux, Windows, and macOS. diff --git a/docs/source/images/screenshot_dark.png b/docs/source/images/screenshot_dark.png index 4555806f..8fb3d728 100644 Binary files a/docs/source/images/screenshot_dark.png and b/docs/source/images/screenshot_dark.png differ diff --git a/docs/source/images/screenshot_default.png b/docs/source/images/screenshot_default.png index d6bd2769..f3ce1e59 100644 Binary files a/docs/source/images/screenshot_default.png and b/docs/source/images/screenshot_default.png differ diff --git a/docs/source/images/screenshot_multi.png b/docs/source/images/screenshot_multi.png index a06922fd..cbbcae21 100644 Binary files a/docs/source/images/screenshot_multi.png and b/docs/source/images/screenshot_multi.png differ diff --git a/docs/source/int_customise.rst b/docs/source/int_customise.rst index c5c26e3b..f77cc9cc 100644 --- a/docs/source/int_customise.rst +++ b/docs/source/int_customise.rst @@ -71,5 +71,5 @@ On Windows, file extensions may not be visible by default, so make sure you only extension, and don't end up with two. The QSS files are Qt Style Sheet files. See Qt's -`The Style Sheet Syntax `_` documentation for more +`The Style Sheet Syntax `_ documentation for more details. diff --git a/docs/source/int_source.rst b/docs/source/int_source.rst index 86fb3b1e..879700a5 100644 --- a/docs/source/int_source.rst +++ b/docs/source/int_source.rst @@ -34,7 +34,7 @@ The following Python packages are needed to run novelWriter: * ``lxml`` – needed for full XML support. * ``PyEnchant`` – needed for spell checking (optional). -PyQt/Qt should be at least 5.3, but ideally 5.10 or higher for nearly all features to work. For +PyQt/Qt should be at least 5.10, but ideally 5.13 or higher for nearly all features to work. For instance, searching using regular expressions with full Unicode support requires 5.13. There is no known minimum version requirement for package ``lxml``, but the code was originally written with 4.2, which is therefore set as the minimum. It may work on lower versions. You have to test it. diff --git a/docs/source/tech_locations.rst b/docs/source/tech_locations.rst index 8f1d4db6..f3003e37 100644 --- a/docs/source/tech_locations.rst +++ b/docs/source/tech_locations.rst @@ -40,8 +40,7 @@ Application Data novelWriter also stores a bit of data that is generated by the user's actions. This includes the list of recent projects form the :guilabel:`Open Project` dialog. Custom themes are also saved -here. The system paths are provided by the Qt QStandardPaths_ class and its AppDataLocation value -on Qt 5.4 or greater, or DataLocation for earlier versions. +here. The system paths are provided by the Qt QStandardPaths_ class and its AppDataLocation. The standard paths are: diff --git a/docs/source/usage_shortcuts.rst b/docs/source/usage_shortcuts.rst index e9e7bb36..7a321bcc 100644 --- a/docs/source/usage_shortcuts.rst +++ b/docs/source/usage_shortcuts.rst @@ -47,6 +47,7 @@ The main shorcuts are as follows: ":kbd:`Ctrl`:kbd:`H`", "Open the search and replace bar and search for the selected word, if any is selected. (On Mac, this is :kbd:`Cmd`:kbd:`=`.)" ":kbd:`Ctrl`:kbd:`I`", "Format selected text, or word under cursor, with emphasis (italic)." ":kbd:`Ctrl`:kbd:`K`", "Activate the insert commands. The commands are listed in :ref:`a_kb_ins`." + ":kbd:`Ctrl`:kbd:`L`", "Open the :guilabel:`Quick Links` menu in the Project Tree." ":kbd:`Ctrl`:kbd:`N`", "Create new project item." ":kbd:`Ctrl`:kbd:`O`", "Open selected document." ":kbd:`Ctrl`:kbd:`Q`", "Exit novelWriter." diff --git a/i18n/nw_base.ts b/i18n/nw_base.ts index 8d7e2940..58a4c7e2 100644 --- a/i18n/nw_base.ts +++ b/i18n/nw_base.ts @@ -77,259 +77,264 @@ Constant - - - + + + None - + Novel - - + + Plot - - + + Characters - - + + Locations - - + + Timeline - - + + Objects - - + + Entities - - + + Custom - + Archive - + Trash - - + + Novel Document - - + + Project Note - + Root Folder - + Folder - + Novel Title Page - + Novel Chapter - + Novel Scene - + + Novel Section + + + + Tag - + Point of View - - + + Focus - + Title - + Level - + Document - + Line - + Chars - + Words - + Pars - + POV - + Synopsis - + Straight single quotation mark - + Straight double quotation mark - + Left single quotation mark - + Right single quotation mark - + Single low-9 quotation mark - + Single high-reversed-9 quotation mark - + Left double quotation mark - + Right double quotation mark - + Double low-9 quotation mark - + Double high-reversed-9 quotation mark - + Double low-reversed-9 quotation mark - + Single left-pointing angle quotation mark - + Single right-pointing angle quotation mark - + Double left-pointing angle quotation mark - + Double right-pointing angle quotation mark - + Left corner bracket - + Right corner bracket - + Left white corner bracket - + Right white corner bracket @@ -443,7 +448,7 @@ GuiBuildNovel - + Build Novel Project @@ -604,176 +609,181 @@ + Root Filter Options + + + + File Filter Options - + Include novel files - + Include note files - + Ignore export flag - + Export Options - + Replace tabs with spaces - + Replace Unicode in HTML - + Build Preview - + Print - + Print Preview - + Print to PDF - + Save As - + Open Document (.odt) - + Flat Open Document (.fodt) - + novelWriter HTML (.htm) - + novelWriter Markdown (.nwd) - + Standard Markdown (.md) - + GitHub Markdown (.md) - + JSON + novelWriter HTML (.json) - + JSON + novelWriter Markdown (.json) - + Close - + Failed to generate preview. The result is too big. - + There were problems when building the project: - + Open Document - + Flat Open Document - + Plain HTML - + novelWriter Markdown - + Standard Markdown - + GitHub Markdown - + JSON + novelWriter HTML - + JSON + novelWriter Markdown - + PDF - + Save Document As - + {0} file successfully written to: - + Failed to write {0} file. {1} @@ -781,17 +791,17 @@ GuiBuildNovelDocView - + This area will show the content of the document to be exported or printed. Press the "Build Preview" button to generate content. - + Unknown - + Build Time: @@ -799,32 +809,32 @@ GuiDocEditFooter - + Status - + Line: {0} ({1}) - + Words: {0} ({1}) - + Document size is {0} bytes - + Words: {0} selected - + Character count: {0} @@ -832,22 +842,22 @@ GuiDocEditHeader - - Edit document meta + + Edit document label - + Search document - + Toggle Focus Mode - + Close the document @@ -855,58 +865,58 @@ GuiDocEditSearch - - + + Search - + Replace - + Case Sensitive - + Whole Words Only - + RegEx Mode - + Loop Search - + Search Next File - + Preserve Case - + Close Search - + Find in current document - + Find and replace in current document @@ -914,117 +924,117 @@ GuiDocEditor - + The document you are trying to open is too big. The document size is {0} MB. The maximum size allowed is {1} MB. - + Opened Document: {0} - + The text you are trying to add is too big. The text size is {0} MB. The maximum size allowed is {1} MB. - + File Changed on Disk - + This document has been changed outside of novelWriter while it was open. Overwrite the file on disk? - + Could not save document. - + Saved Document: {0} - + Spell checking requires the package PyEnchant. It does not appear to be installed. - + Spell check complete - + File Location - + The currently open file is saved in: - + The document has grown too big and you cannot add more text to it. The maximum size of a single novelWriter document is {0} MB. - + Follow Tag - + Cut - + Copy - + Paste - + Select All - + Select Word - + Select Paragraph - + Spelling Suggestion(s) - + No Suggestions - + Add Word to Dictionary - + Please select some text before calling replace quotes. @@ -1042,159 +1052,103 @@ - - Drag and drop items to change the order. + + Drag and drop items to change the order, or uncheck to exclude. - - No source documents found. Nothing to do. - - - - - Failed to open document file. - - - - - No source folder selected. Nothing to do. - - - - - Internal error. - - - - - Could not save document. - - - - - Element selected in the project tree must be a folder. + + Move merged items to Trash GuiDocSplit - - + Split Document - + Document Headers - + Select the maximum level to split into files. - + Split on Header Level 1 (Title) - + Split up to Header Level 2 (Chapter) - + Split up to Header Level 3 (Scene) - + Split up to Header Level 4 (Section) - - No source document selected. Nothing to do. + + Split into a new folder - - Could not parse source document. - - - - - Failed to open document file. - - - - - No headers found. Nothing to do. - - - - - The document will be split into {0} file(s) in a new folder. The original document will remain intact. - - - - - Continue with the splitting process? - - - - - Could not save document. - - - - - Element selected in the project tree must be a file. + + Create document hierarchy GuiDocViewFooter - + Show/hide the references panel - + Activate to freeze the content of the references panel when changing document - + Show comments - + Show synopsis comments - + References - + Sticky - + Comments - + Synopsis @@ -1202,22 +1156,22 @@ GuiDocViewHeader - + Go backward - + Go forward - + Reload the document - + Close the document @@ -1225,102 +1179,82 @@ GuiDocViewer - + An error occurred while generating the preview. - - Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. - - - - + Copy - + Select All - + Select Word - + Select Paragraph + + GuiEditLabel + + + Item Label + + + + + Label + + + GuiItemDetails - + Label - + Status - + Class - + Usage - + Characters - + Words - + Paragraphs - - GuiItemEditor - - - Item Settings - - - - - Include when building project - - - - - Label - - - - - Status - - - - - Layout - - - GuiLipsum @@ -1352,862 +1286,761 @@ GuiMain - + You are running an untested development version of novelWriter. Please be careful when working on a live project and make sure you take regular backups. - + novelWriter is ready ... - + Cannot create a new project when another project is open. - + A project already exists in that location. Please choose another folder. - + New project created ... - + Close Project - + Close the current project? - - + + Changes are saved automatically. - + Backup Project - + Backup the current project? - + The project was locked by the computer '{0}' ({1} {2}), last active on {3}. - + Project Locked - + The project is already open by another instance of novelWriter, and is therefore locked. Override lock and continue anyway? - + Note: If the program or the computer previously crashed, the lock can safely be overridden. However, overriding it is not recommended if the project is open in another instance of novelWriter. Doing so may corrupt the project. - + The project index is outdated or broken. Rebuilding index. - + Text files ({0}) - + Markdown files ({0}) - + novelWriter files ({0}) - + All files ({0}) - + Import File - + Could not read file. The file must be an existing text file. - + Please open a document to import the text file into. - + Import Document - + Importing the file will overwrite the current content of the document. Do you want to proceed? - - - Indexing: '{0}' - - - - - Unknown item - - - - + Indexing completed in {0} ms - + The project index has been successfully rebuilt. - + Information - + Warning - + Error - + This is a bug! - + Internal Error - + Exit - + Do you want to exit novelWriter? + + + Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. + + GuiMainMenu - + &Project - + New Project - + Open Project - + Save Project - + Close Project - + Project Settings - + Project Details - - Create Root Folder + + Rename Item - - Novel Root - - - - - Plot Root - - - - - Character Root - - - - - Location Root - - - - - Timeline Root - - - - - Object Root - - - - - Entity Root - - - - - Custom Root - - - - - Archive Root - - - - - Create Folder - - - - - Edit Item - - - - + Delete Item - - Move Item Up - - - - - Move Item Down - - - - - Undo Last Move - - - - + Empty Trash - + Exit - + &Document - - New Document - - - - + Open Document - + Save Document - + Close Document - + View Document - + Close Document View - + Show File Details - + Import Text from File - - Merge Folder to Document - - - - - Split Document to Folder - - - - + &Edit - + Undo - + Redo - + Cut - + Copy - + Paste - + Select All - + Select Paragraph - + &View - + Go to Project Tree - + Go to Document Editor - + Go to Document Viewer - + Go to Outline - + Navigate Backward - + Navigate Forward - + Focus Mode - + Full Screen Mode - + &Insert - + Dashes - + Short Dash - + Long Dash - + Horizontal Bar - + Figure Dash - + Quote Marks - + Left Single Quote - + Right Single Quote - + Left Double Quote - + Right Double Quote - + Alternative Apostrophe - + General Punctuation - + Ellipsis - + Prime - + Double Prime - + White Spaces - + Non-Breaking Space - + Thin Space - + Thin Non-Breaking Space - + Other Symbols - + List Bullet - + Hyphen Bullet - + Flower Mark - + Per Mille - + Degree Symbol - + Minus Sign - + Times Sign - + Division Sign - + Tags and References - + Page Break and Space - + Page Break - + Vertical Space (Single) - + Vertical Space (Multi) - + Placeholder Text - + &Format - + Emphasis - + Strong Emphasis - + Strikethrough - + Wrap Double Quotes - + Wrap Single Quotes - + Header 1 (Partition) - + Header 2 (Chapter) - + Header 3 (Scene) - + Header 4 (Section) - + Novel Title - + Unnumbered Chapter - + Align Left - + Align Centre - + Align Right - + Indent Left - + Indent Right - + Toggle Comment - + Remove Block Format - + Convert Single Quotes - + Convert Double Quotes - + Remove In-Paragraph Breaks - + &Search - + Find - + Replace - + Find Next - + Find Previous - + Replace Next - + &Tools - + Check Spelling - + Re-Run Spell Check - + Project Word List - + Rebuild Index - - Rebuild Outline - - - - - Auto-Update Outline - - - - + Backup Project - + Build Novel Project - + Writing Statistics - + Preferences - + &Help - + About novelWriter - + About Qt5 - + User Manual (Online) - + User Manual (PDF) - + Report an Issue (GitHub) - + Ask a Question (GitHub) - + The novelWriter Website - + Check for New Release @@ -2252,100 +2085,123 @@ - GuiNovelTree + GuiNovelToolBar - + Novel Outline - - Words + + Refresh - - POV + + Novel Root - - Section title + + Last Column - - Word count + + Hidden - - Point-of-view character + + Point of View Character + + + + + Focus Character + + + + + Novel Plot + + + + + More Options + + + + + GuiNovelTree + + + No meta data GuiOutlineDetails - - - - + + + + Title - + Chapter - + Scene - + Section - + Document - + Status - + Characters - + Words - + Paragraphs - + Synopsis - + Title Details - + Reference Tags @@ -2353,11 +2209,29 @@ GuiOutlineHeaderMenu - + Select Columns + + GuiOutlineToolBar + + + Outline of + + + + + Refresh + + + + + All Novel Folders + + + GuiPreferences @@ -2409,103 +2283,103 @@ GuiPreferencesAutomation - + Automatic Features - + Auto-select word under cursor - + Apply formatting to word under cursor if no selection is made. - + Auto-replace text as you type - + Allow the editor to replace symbols as you type. - + Replace as You Type - + Auto-replace single quotes - - + + Try to guess which is an opening or a closing quote. - + Auto-replace double quotes - + Auto-replace dashes - + Double and triple hyphens become short and long dashes. - + Auto-replace dots - + Three consecutive dots become ellipsis. - + Automatic Padding - + Insert non-breaking space before - + Automatically add space before any of these symbols. - + Insert non-breaking space after - + Automatically add space after any of these symbols. - + Use thin space instead - + Inserts a thin space instead of a regular space. @@ -2513,93 +2387,93 @@ GuiPreferencesDocuments - + Text Style - + Font family - - - - + + + + Applies to both document editor and viewer. - + Font size - + pt - + Text Flow - + Maximum text width in "Normal Mode" - + Set to 0 to disable this feature. - - - - + + + + px - + Maximum text width in "Focus Mode" - + The maximum width cannot be disabled. - + Hide document footer in "Focus Mode" - + Hide the information bar in the document editor. - + Justify the text margins - + Minimum text margin - + Tab width - + The width of a tab key press in the editor and viewer. @@ -2607,117 +2481,117 @@ GuiPreferencesEditor - + Spell Checking - + None - + Not installed - + Spell check language - + Available languages are determined by your system. - + Big document limit - + Full spell checking is disabled above this limit. - + kB - + Word Count - + Word count interval - + seconds - + Include project notes in status bar word count - + Writing Guides - + Show tabs and spaces - + Show line endings - + Scroll Behaviour - + Scroll past end of the document - + Set to 0 to disable this feature. - + lines - + Typewriter style scrolling when you type - + Keeps the cursor at a fixed vertical position. - + Minimum position for Typewriter scrolling - + Percentage of the editor height from the top. @@ -2725,87 +2599,97 @@ GuiPreferencesGeneral - + Look and Feel - + Main GUI language - - - - - + + + + + Requires restart. - + Main GUI theme - + Main icon theme + Editor theme + + + + + Colour theme for the editor and viewer. + + + + Font family - + Font size - + pt - + GUI Settings - + Emphasise partition and chapter labels - + Makes them stand out in the project tree. - + Show full path in document header - + Add the parent folder names to the header. - + Hide vertical scroll bars in main windows - - + + Scrolling available with mouse wheel and keys only. - + Hide horizontal scroll bars in main windows @@ -2813,109 +2697,109 @@ GuiPreferencesProjects - + Automatic Save - + Save document interval - + How often the document is automatically saved. - - + + seconds - + Save project interval - + How often the project is automatically saved. - + Project Backup - + Browse - + Backup storage location - - + + Path: {0} - + Run backup when the project is closed - + Can be overridden for individual projects in Project Settings. - + Ask before running backup - + If off, backups will run in the background. - + Session Timer - + Pause the session timer when not writing - + Also pauses when the application window does not have focus. - + Editor inactive time before pausing timer - + User activity includes typing and changing the content. - + minutes - + Backup Directory @@ -2923,47 +2807,47 @@ GuiPreferencesQuotes - + Quotation Style - + Single quote open style - + The symbol to use for a leading single quote. - + Single quote close style - + The symbol to use for a trailing single quote. - + Double quote open style - + The symbol to use for a leading double quote. - + Double quote close style - + The symbol to use for a trailing double quote. @@ -2971,74 +2855,59 @@ GuiPreferencesSyntax - - Highlighting Theme - - - - - Highlighting theme - - - - - Colour theme for the editor and viewer. - - - - + Quotes & Dialogue - + Highlight text wrapped in quotes - - - + + + Applies to the document editor only. - + Allow open-ended single quotes - + Highlight single-quoted line with no closing quote. - + Allow open-ended double quotes - + Highlight double-quoted line with no closing quote. - + Text Emphasis - + Add highlight colour to emphasised text - + Text Errors - + Highlight multiple or trailing spaces @@ -3046,17 +2915,17 @@ GuiProjectDetails - + Project Details - + Overview - + Contents @@ -3064,72 +2933,72 @@ GuiProjectDetailsContents - - Title - - - - - Words - - - - - Pages - - - - - Page - - - - - Progress - - - - - Typical word count for a 5 by 8 inch book page with 11 pt font is 350. - - - - - Start counting page numbers from this page. - - - - - Assume a new chapter or partition always start on an odd numbered page. - - - - - Words per page - - - - - Count pages from - - - - - Clear double pages - - - - + Table of Contents - + + Title + + + + + Words + + + + + Pages + + + + + Page + + + + + Progress + + + + + Typical word count for a 5 by 8 inch book page with 11 pt font is 350. + + + + + Start counting page numbers from this page. + + + + + Assume a new chapter or partition always start on an odd numbered page. + + + + + Words per page + + + + + Count pages from + + + + + Clear double pages + + + + END - + Untitled @@ -3137,42 +3006,42 @@ GuiProjectDetailsMain - + Working Title: {0} - + By {0} - + Words - + Chapters - + Scenes - + Revisions - + Editing Time - + Path @@ -3180,58 +3049,58 @@ GuiProjectEditMain - + Project Settings - - Working title + + Project name - + Should be set only once. - + Novel title - + Change whenever you want! - + Author(s) - + One name per line. - + Default - + Spell check language - - + + Overrides main preferences. - + No backup on close @@ -3239,27 +3108,27 @@ GuiProjectEditReplace - + Text Replace List for Preview and Export - + Keyword - + Replace With - + Select item to edit - + Save @@ -3399,7 +3268,7 @@ GuiProjectSettings - + Project Settings @@ -3425,164 +3294,247 @@ - GuiProjectTree + GuiProjectToolBar - - Project Tree + + Project Content - - Words + + Quick Links - - Item label + + Move Up - - Word count + + Move Down - - Include in build + + Add Item - - Item status + + Expand All - - Did not find anywhere to add the file or folder! + + Collapse All - - Cannot add new files or folders to the Trash folder. + + Undo Move - - New Document - - - - - New Note - - - - - New Folder - - - - - There is currently no Trash folder in this project. - - - - - The Trash folder is already empty. - - - - + Empty Trash - - Permanently delete {0} file(s) from Trash? - - - - - Cannot delete root folder. It is not empty. Recursive deletion is not supported. Please delete the content first. - - - - - - Delete - - - - - Permanently delete '{0}'? - - - - - Move '{0}' to Trash? - - - - - Could not delete document file. - - - - - There is nowhere to add item with name '{0}'. + + More Options - GuiProjectTreeMenu + GuiProjectTree - - Edit Project Item + + Did not find anywhere to add the file or folder! - - Open Document + + Cannot add new files or folders to the Trash folder. - - View Document + + New Note - - Toggle Included Flag + + New Chapter - - New File + + New Scene - + + New Document + + + + New Folder - - Delete Item + + There is currently no Trash folder in this project. - + + The Trash folder is already empty. + + + + + Empty Trash - - Move Item Up + + Permanently delete {0} file(s) from Trash? - - Move Item Down + + + Delete + + + + + Move '{0}' to Trash? + + + + + Root folders can only be deleted when they are empty. + + + + + Permanently delete '{0}'? + + + + + Open Document + + + + + View Document + + + + + Change Label + + + + + Toggle Exported + + + + + Set Status to ... + + + + + Set Importance to ... + + + + + Transform + + + + + + Convert to {0} + + + + + Merge Child Items into Self + + + + + Merge Child Items into New + + + + + Combine Documents in Folder + + + + + Split Document by Header + + + + + Expand All + + + + + Collapse All + + + + + Delete Permanently + + + + + Move to Trash + + + + + Convert Folder + + + + + Do you want to convert the folder to a {0}? This action cannot be reversed. + + + + + No documents selected for merging. + + + + + Merged + + + + + + Could not write document content. + + + + + There is nowhere to add item with name '{0}'. @@ -3623,32 +3575,67 @@ GuiViewsBar - + Project - + + Project Tree View + + + + Novel - - - Outline - - - Details + Novel Tree View + Outline + + + + + Novel Outline View + + + + + Build + + + + + Build Novel Project + + + + + Details + + + + + Project Details + + + + Stats - + + Writing Statistics + + + + Settings @@ -3657,7 +3644,7 @@ GuiWordList - + Project Word List @@ -3675,152 +3662,152 @@ GuiWritingStats - + Writing Statistics - + Session Start - + Length - + Idle - + Words - + Histogram - + Sum Totals - + Total Time: - + Idle Time: - + Filtered Time: - + Novel Word Count: - + Notes Word Count: - + Total Word Count: - + Filters - + Count novel files - + Count note files - + Hide zero word count - + Hide negative word count - + Group entries by day - + Show idle time - + Word count cap for the histogram - + Save As - + JSON Data File (.json) - + CSV Data File (.csv) - + JSON Data File - + CSV Data File - + Save Data As - + {0} file successfully written to: - + Failed to write {0} file. - + Failed to read session log file. @@ -3828,385 +3815,421 @@ NWProject - - + + Could not delete document file. + + + + + New - + Note - + Draft - + Finished - + Minor - + Major - + Main - + New Project - - By - - - - - - Novel - - - - - Plot - - - - - Characters - - - - - World - - - - - + Title Page - - - + + By + + + + + New Chapter - - + + New Scene - + + Summary of the chapter. + + + + + Summary of the scene. + + + + Chapter {0} - - + + Scene {0} - + + Main Plot + + + + + Protagonist + + + + + Main Location + + + + File not found: {0} - - + + Failed to parse project xml. - + Attempting to open backup project file instead. - - + + Unknown - + Project file does not appear to be a novelWriterXML file. - + Unknown or unsupported novelWriter project file format. The project cannot be opened by this version of novelWriter. The file was saved with novelWriter version {0}. - + File Version - + The file format of your project is about to be updated. If you proceed, older versions of novelWriter will no longer be able to open this project. Continue? - + Version Conflict - + This project was saved by a newer version of novelWriter, version {0}. This is version {1}. If you continue to open the project, some attributes and settings may not be preserved, but the overall project should be fine. Continue opening the project? - + + There was an error updating the project. Some data may not have been preserved. + + + + Opened Project: {0} - + Project path not set, cannot save project. - - + + Failed to save project. - + Saved Project: {0} - + Backing up project ... - + Cannot backup project because no valid backup path is set. Please set a valid backup location in Preferences. - + Cannot backup project because no project name is set. Please set a Working Title in Project Settings. - + Could not create backup folder. - + Cannot backup project because the backup path is within the project folder to be backed up. Please choose a different backup path in Preferences. - + Backup from {0} - + Backup archive file written to: {0} - + Could not write backup archive. - + Project backed up to '{0}' - - + + Failed to create a new example project. - + Failed to create a new example project. Could not find the necessary files. They seem to be missing from this installation. - + Could not create new project folder. - + New project folder is not empty. Each project requires a dedicated project folder. - + You must set a valid backup path in Preferences to use the automatic project backup feature. - + You must set a valid project name in Project Settings to use the automatic project backup feature. - + and - + Could not create folder. - + Found {0} orphaned file(s) in project folder. - + Recovered - + [{0}] {1} - + Recovered File {0} - + One or more orphaned files could not be added back into the project. Make sure at least a Novel root folder exists. - - - Not a folder: {0} - - - - - Could not move: {0} - - - - - - Could not delete: {0} - - - - - Could not make folder: {0} - - - - - Could not move item {0} to {1}. - - ProjWizardCustomPage - + Custom Project Options - - Select which additional root folders to make, and how to populate the Novel folder. If you don't want to add chapters or scenes, set the values to 0. You can add scenes without chapters. + + Select which additional elements to populate the project with. You can skip making chapters and add only scenes by setting the number of chapters to 0. - - Additional Root Folders + + Add a folder for plot notes - - - - - - - {0} folder + + Add a folder for character notes - - Populate Novel Folder + + Add a folder for location notes - - Add chapters + + Add example notes to the above - - Scenes (per chapter) + + Add chapters to the novel folder - - Add chapter folders + + Add scenes to each chapter ProjWizardFinalPage - - Finished + + Summary - - All done. + + Project Name: {0} - + + Project Path: {0} + + + + + Fill the project with a minimal set of items + + + + + Fill the project with example files + + + + + Add a folder for plot notes + + + + + Add a folder for character notes + + + + + Add a folder for location notes + + + + + Add example notes to the above + + + + + Add {0} chapters to the novel folder + + + + + Add {0} scenes to each chapter + + + + + Add {0} scenes + + + + + You have selected the following: + + + + Press '{0}' to create the new project. - + Done - + Finish @@ -4214,33 +4237,33 @@ ProjWizardFolderPage - - + + Select Project Folder - + Select a location to store the project. A new project folder will be created in the selected location. - + Required - + Project Path - + Error: A project folder cannot be created using this path. - + Error: The selected path already exists. @@ -4248,47 +4271,47 @@ ProjWizardIntroPage - + Create New Project - - Provide at least a working title. The working title should not be change beyond this point as it is used by the application for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. + + Provide at least a project name. The project name should not be changed beyond this point as it is used for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. - + Side image by {0}, {1} - + Required - + Optional - + Optional. One name per line. - - Working Title + + Project Name - + Novel Title - + Author(s) @@ -4296,27 +4319,27 @@ ProjWizardPopulatePage - + Populate Project - + Choose how to pre-fill the project. Either with a minimal set of starter items, an example project explaining and showing many of the features, or show further custom options on the next page. - + Fill the project with a minimal set of items - + Fill the project with example files - + Show detailed options for filling the project @@ -4512,17 +4535,17 @@ Tokenizer - + Synopsis - + Document '{0}' is too big ({1} MB). Skipping. - + ERROR diff --git a/i18n/nw_en_US.ts b/i18n/nw_en_US.ts index 75aee812..74c20d80 100644 --- a/i18n/nw_en_US.ts +++ b/i18n/nw_en_US.ts @@ -77,259 +77,264 @@ Constant - - - + + + None None - + Novel Novel - - + + Plot Plot - - + + Characters Characters - - + + Locations Locations - - + + Timeline Timeline - - + + Objects Objects - - + + Entities Entities - - + + Custom Custom - + Archive Archive - + Trash Trash - - + + Novel Document Novel Document - - + + Project Note Project Note - + Root Folder Root Folder - + Folder Folder - + Novel Title Page Novel Title Page - + Novel Chapter Novel Chapter - + Novel Scene Novel Scene - + + Novel Section + Novel Section + + + Tag Tag - + Point of View Point of View - - + + Focus Focus - + Title Title - + Level Level - + Document Document - + Line Line - + Chars Chars - + Words Words - + Pars Pars - + POV POV - + Synopsis Synopsis - + Straight single quotation mark Straight single quotation mark - + Straight double quotation mark Straight double quotation mark - + Left single quotation mark Left single quotation mark - + Right single quotation mark Right single quotation mark - + Single low-9 quotation mark Single low-9 quotation mark - + Single high-reversed-9 quotation mark Single high-reversed-9 quotation mark - + Left double quotation mark Left double quotation mark - + Right double quotation mark Right double quotation mark - + Double low-9 quotation mark Double low-9 quotation mark - + Double high-reversed-9 quotation mark Double high-reversed-9 quotation mark - + Double low-reversed-9 quotation mark Double low-reversed-9 quotation mark - + Single left-pointing angle quotation mark Single left-pointing angle quotation mark - + Single right-pointing angle quotation mark Single right-pointing angle quotation mark - + Double left-pointing angle quotation mark Double left-pointing angle quotation mark - + Double right-pointing angle quotation mark Double right-pointing angle quotation mark - + Left corner bracket Left corner bracket - + Right corner bracket Right corner bracket - + Left white corner bracket Left white corner bracket - + Right white corner bracket Right white corner bracket @@ -443,7 +448,7 @@ GuiBuildNovel - + Build Novel Project Build Novel Project @@ -604,176 +609,181 @@ + Root Filter Options + Root Filter Options + + + File Filter Options File Filter Options - + Include novel files Include novel files - + Include note files Include note files - + Ignore export flag Ignore export flag - + Export Options Export Options - + Replace tabs with spaces Replace tabs with spaces - + Replace Unicode in HTML Replace Unicode in HTML - + Build Preview Build Preview - + Print Print - + Print Preview Print Preview - + Print to PDF Print to PDF - + Save As Save As - + Open Document (.odt) Open Document (.odt) - + Flat Open Document (.fodt) Flat Open Document (.fodt) - + novelWriter HTML (.htm) novelWriter HTML (.htm) - + novelWriter Markdown (.nwd) novelWriter Markdown (.nwd) - + Standard Markdown (.md) Standard Markdown (.md) - + GitHub Markdown (.md) GitHub Markdown (.md) - + JSON + novelWriter HTML (.json) JSON + novelWriter HTML (.json) - + JSON + novelWriter Markdown (.json) JSON + novelWriter Markdown (.json) - + Close Close - + Failed to generate preview. The result is too big. Failed to generate preview. The result is too big. - + There were problems when building the project: There were problems when building the project: - + Open Document Open Document - + Flat Open Document Flat Open Document - + Plain HTML Plain HTML - + novelWriter Markdown novelWriter Markdown - + Standard Markdown Standard Markdown - + GitHub Markdown GitHub Markdown - + JSON + novelWriter HTML JSON + novelWriter HTML - + JSON + novelWriter Markdown JSON + novelWriter Markdown - + PDF PDF - + Save Document As Save Document As - + {0} file successfully written to: {0} file successfully written to: - + Failed to write {0} file. {1} Failed to write {0} file. {1} @@ -781,17 +791,17 @@ GuiBuildNovelDocView - + This area will show the content of the document to be exported or printed. Press the "Build Preview" button to generate content. This area will show the content of the document to be exported or printed. Press the "Build Preview" button to generate content. - + Unknown Unknown - + Build Time: Build Time: @@ -799,32 +809,32 @@ GuiDocEditFooter - + Status Status - + Line: {0} ({1}) Line: {0} ({1}) - + Words: {0} ({1}) Words: {0} ({1}) - + Document size is {0} bytes Document size is {0} bytes - + Words: {0} selected Words: {0} selected - + Character count: {0} Character count: {0} @@ -832,22 +842,22 @@ GuiDocEditHeader - - Edit document meta - Edit document meta + + Edit document label + Edit document label - + Search document Search document - + Toggle Focus Mode Toggle Focus Mode - + Close the document Close the document @@ -855,58 +865,58 @@ GuiDocEditSearch - - + + Search Search - + Replace Replace - + Case Sensitive Case Sensitive - + Whole Words Only Whole Words Only - + RegEx Mode RegEx Mode - + Loop Search Loop Search - + Search Next File Search Next File - + Preserve Case Preserve Case - + Close Search Close Search - + Find in current document Find in current document - + Find and replace in current document Find and replace in current document @@ -914,117 +924,117 @@ GuiDocEditor - + The document you are trying to open is too big. The document size is {0} MB. The maximum size allowed is {1} MB. The document you are trying to open is too big. The document size is {0} MB. The maximum size allowed is {1} MB. - + Opened Document: {0} Opened Document: {0} - + The text you are trying to add is too big. The text size is {0} MB. The maximum size allowed is {1} MB. The text you are trying to add is too big. The text size is {0} MB. The maximum size allowed is {1} MB. - + File Changed on Disk File Changed on Disk - + This document has been changed outside of novelWriter while it was open. Overwrite the file on disk? This document has been changed outside of novelWriter while it was open. Overwrite the file on disk? - + Could not save document. Could not save document. - + Saved Document: {0} Saved Document: {0} - + Spell checking requires the package PyEnchant. It does not appear to be installed. Spell checking requires the package PyEnchant. It does not appear to be installed. - + Spell check complete Spell check complete - + File Location File Location - + The currently open file is saved in: The currently open file is saved in: - + The document has grown too big and you cannot add more text to it. The maximum size of a single novelWriter document is {0} MB. The document has grown too big and you cannot add more text to it. The maximum size of a single novelWriter document is {0} MB. - + Follow Tag Follow Tag - + Cut Cut - + Copy Copy - + Paste Paste - + Select All Select All - + Select Word Select Word - + Select Paragraph Select Paragraph - + Spelling Suggestion(s) Spelling Suggestion(s) - + No Suggestions No Suggestions - + Add Word to Dictionary Add Word to Dictionary - + Please select some text before calling replace quotes. Please select some text before calling replace quotes. @@ -1042,159 +1052,103 @@ Documents to Merge - - Drag and drop items to change the order. - Drag and drop items to change the order. + + Drag and drop items to change the order, or uncheck to exclude. + Drag and drop items to change the order, or uncheck to exclude. - - No source documents found. Nothing to do. - No source documents found. Nothing to do. - - - - Failed to open document file. - Failed to open document file. - - - - No source folder selected. Nothing to do. - No source folder selected. Nothing to do. - - - - Internal error. - Internal error. - - - - Could not save document. - Could not save document. - - - - Element selected in the project tree must be a folder. - Element selected in the project tree must be a folder. + + Move merged items to Trash + Move merged items to Trash GuiDocSplit - - + Split Document Split Document - + Document Headers Document Headers - + Select the maximum level to split into files. Select the maximum level to split into files. - + Split on Header Level 1 (Title) Split on Header Level 1 (Title) - + Split up to Header Level 2 (Chapter) Split up to Header Level 2 (Chapter) - + Split up to Header Level 3 (Scene) Split up to Header Level 3 (Scene) - + Split up to Header Level 4 (Section) Split up to Header Level 4 (Section) - - No source document selected. Nothing to do. - No source document selected. Nothing to do. + + Split into a new folder + Split into a new folder - - Could not parse source document. - Could not parse source document. - - - - Failed to open document file. - Failed to open document file. - - - - No headers found. Nothing to do. - No headers found. Nothing to do. - - - - The document will be split into {0} file(s) in a new folder. The original document will remain intact. - The document will be split into {0} file(s) in a new folder. The original document will remain intact. - - - - Continue with the splitting process? - Continue with the splitting process? - - - - Could not save document. - Could not save document. - - - - Element selected in the project tree must be a file. - Element selected in the project tree must be a file. + + Create document hierarchy + Create document hierarchy GuiDocViewFooter - + Show/hide the references panel Show/hide the references panel - + Activate to freeze the content of the references panel when changing document Activate to freeze the content of the references panel when changing document - + Show comments Show comments - + Show synopsis comments Show synopsis comments - + References References - + Sticky Sticky - + Comments Comments - + Synopsis Synopsis @@ -1202,22 +1156,22 @@ GuiDocViewHeader - + Go backward Go backward - + Go forward Go forward - + Reload the document Reload the document - + Close the document Close the document @@ -1225,102 +1179,82 @@ GuiDocViewer - + An error occurred while generating the preview. An error occurred while generating the preview. - - Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. - Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. - - - + Copy Copy - + Select All Select All - + Select Word Select Word - + Select Paragraph Select Paragraph + + GuiEditLabel + + + Item Label + Item Label + + + + Label + Label + + GuiItemDetails - + Label Label - + Status Status - + Class Class - + Usage Usage - + Characters Characters - + Words Words - + Paragraphs Paragraphs - - GuiItemEditor - - - Item Settings - Item Settings - - - - Include when building project - Include when building project - - - - Label - Label - - - - Status - Status - - - - Layout - Layout - - GuiLipsum @@ -1352,862 +1286,761 @@ GuiMain - + You are running an untested development version of novelWriter. Please be careful when working on a live project and make sure you take regular backups. You are running an untested development version of novelWriter. Please be careful when working on a live project and make sure you take regular backups. - + novelWriter is ready ... novelWriter is ready ... - + Cannot create a new project when another project is open. Cannot create a new project when another project is open. - + A project already exists in that location. Please choose another folder. A project already exists in that location. Please choose another folder. - + New project created ... New project created ... - + Close Project Close Project - + Close the current project? Close the current project? - - + + Changes are saved automatically. Changes are saved automatically. - + Backup Project Backup Project - + Backup the current project? Backup the current project? - + The project was locked by the computer '{0}' ({1} {2}), last active on {3}. The project was locked by the computer '{0}' ({1} {2}), last active on {3}. - + Project Locked Project Locked - + The project is already open by another instance of novelWriter, and is therefore locked. Override lock and continue anyway? The project is already open by another instance of novelWriter, and is therefore locked. Override lock and continue anyway? - + Note: If the program or the computer previously crashed, the lock can safely be overridden. However, overriding it is not recommended if the project is open in another instance of novelWriter. Doing so may corrupt the project. Note: If the program or the computer previously crashed, the lock can safely be overridden. However, overriding it is not recommended if the project is open in another instance of novelWriter. Doing so may corrupt the project. - + The project index is outdated or broken. Rebuilding index. The project index is outdated or broken. Rebuilding index. - + Text files ({0}) Text files ({0}) - + Markdown files ({0}) Markdown files ({0}) - + novelWriter files ({0}) novelWriter files ({0}) - + All files ({0}) All files ({0}) - + Import File Import File - + Could not read file. The file must be an existing text file. Could not read file. The file must be an existing text file. - + Please open a document to import the text file into. Please open a document to import the text file into. - + Import Document Import Document - + Importing the file will overwrite the current content of the document. Do you want to proceed? Importing the file will overwrite the current content of the document. Do you want to proceed? - - - Indexing: '{0}' - Indexing: '{0}' - - - - Unknown item - Unknown item - - - + Indexing completed in {0} ms Indexing completed in {0} ms - + The project index has been successfully rebuilt. The project index has been successfully rebuilt. - + Information Information - + Warning Warning - + Error Error - + This is a bug! This is a bug! - + Internal Error Internal Error - + Exit Exit - + Do you want to exit novelWriter? Do you want to exit novelWriter? + + + Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. + Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. + GuiMainMenu - + &Project &Project - + New Project New Project - + Open Project Open Project - + Save Project Save Project - + Close Project Close Project - + Project Settings Project Settings - + Project Details Project Details - - Create Root Folder - Create Root Folder + + Rename Item + Rename Item - - Novel Root - Novel Root - - - - Plot Root - Plot Root - - - - Character Root - Character Root - - - - Location Root - Location Root - - - - Timeline Root - Timeline Root - - - - Object Root - Object Root - - - - Entity Root - Entity Root - - - - Custom Root - Custom Root - - - - Archive Root - Archive Root - - - - Create Folder - Create Folder - - - - Edit Item - Edit Item - - - + Delete Item Delete Item - - Move Item Up - Move Item Up - - - - Move Item Down - Move Item Down - - - - Undo Last Move - Undo Last Move - - - + Empty Trash Empty Trash - + Exit Exit - + &Document &Document - - New Document - New Document - - - + Open Document Open Document - + Save Document Save Document - + Close Document Close Document - + View Document View Document - + Close Document View Close Document View - + Show File Details Show File Details - + Import Text from File Import Text from File - - Merge Folder to Document - Merge Folder to Document - - - - Split Document to Folder - Split Document to Folder - - - + &Edit &Edit - + Undo Undo - + Redo Redo - + Cut Cut - + Copy Copy - + Paste Paste - + Select All Select All - + Select Paragraph Select Paragraph - + &View &View - + Go to Project Tree Go to Project Tree - + Go to Document Editor Go to Document Editor - + Go to Document Viewer Go to Document Viewer - + Go to Outline Go to Outline - + Navigate Backward Navigate Backward - + Navigate Forward Navigate Forward - + Focus Mode Focus Mode - + Full Screen Mode Full Screen Mode - + &Insert &Insert - + Dashes Dashes - + Short Dash Short Dash - + Long Dash Long Dash - + Horizontal Bar Horizontal Bar - + Figure Dash Figure Dash - + Quote Marks Quote Marks - + Left Single Quote Left Single Quote - + Right Single Quote Right Single Quote - + Left Double Quote Left Double Quote - + Right Double Quote Right Double Quote - + Alternative Apostrophe Alternative Apostrophe - + General Punctuation General Punctuation - + Ellipsis Ellipsis - + Prime Prime - + Double Prime Double Prime - + White Spaces White Spaces - + Non-Breaking Space Non-Breaking Space - + Thin Space Thin Space - + Thin Non-Breaking Space Thin Non-Breaking Space - + Other Symbols Other Symbols - + List Bullet List Bullet - + Hyphen Bullet Hyphen Bullet - + Flower Mark Flower Mark - + Per Mille Per Mille - + Degree Symbol Degree Symbol - + Minus Sign Minus Sign - + Times Sign Times Sign - + Division Sign Division Sign - + Tags and References Tags and References - + Page Break and Space Page Break and Space - + Page Break Page Break - + Vertical Space (Single) Vertical Space (Single) - + Vertical Space (Multi) Vertical Space (Multi) - + Placeholder Text Placeholder Text - + &Format &Format - + Emphasis Emphasis - + Strong Emphasis Strong Emphasis - + Strikethrough Strikethrough - + Wrap Double Quotes Wrap Double Quotes - + Wrap Single Quotes Wrap Single Quotes - + Header 1 (Partition) Header 1 (Partition) - + Header 2 (Chapter) Header 2 (Chapter) - + Header 3 (Scene) Header 3 (Scene) - + Header 4 (Section) Header 4 (Section) - + Novel Title Novel Title - + Unnumbered Chapter Unnumbered Chapter - + Align Left Align Left - + Align Centre Align Center - + Align Right Align Right - + Indent Left Indent Left - + Indent Right Indent Right - + Toggle Comment Toggle Comment - + Remove Block Format Remove Block Format - + Convert Single Quotes Convert Single Quotes - + Convert Double Quotes Convert Double Quotes - + Remove In-Paragraph Breaks Remove In-Paragraph Breaks - + &Search &Search - + Find Find - + Replace Replace - + Find Next Find Next - + Find Previous Find Previous - + Replace Next Replace Next - + &Tools &Tools - + Check Spelling Check Spelling - + Re-Run Spell Check Re-Run Spell Check - + Project Word List Project Word List - + Rebuild Index Rebuild Index - - Rebuild Outline - Rebuild Outline - - - - Auto-Update Outline - Auto-Update Outline - - - + Backup Project Backup Project - + Build Novel Project Build Novel Project - + Writing Statistics Writing Statistics - + Preferences Preferences - + &Help &Help - + About novelWriter About novelWriter - + About Qt5 About Qt5 - + User Manual (Online) User Manual (Online) - + User Manual (PDF) User Manual (PDF) - + Report an Issue (GitHub) Report an Issue (GitHub) - + Ask a Question (GitHub) Ask a Question (GitHub) - + The novelWriter Website The novelWriter Website - + Check for New Release Check for New Release @@ -2252,100 +2085,123 @@ - GuiNovelTree + GuiNovelToolBar - + Novel Outline Novel Outline - - Words - Words + + Refresh + Refresh - - POV - POV + + Novel Root + Novel Root - - Section title - Section title + + Last Column + Last Column - - Word count - Word count + + Hidden + Hidden - - Point-of-view character - Point-of-view character + + Point of View Character + Point of View Character + + + + Focus Character + Focus Character + + + + Novel Plot + Novel Plot + + + + More Options + More Options + + + + GuiNovelTree + + + No meta data + No meta data GuiOutlineDetails - - - - + + + + Title Title - + Chapter Chapter - + Scene Scene - + Section Section - + Document Document - + Status Status - + Characters Characters - + Words Words - + Paragraphs Paragraphs - + Synopsis Synopsis - + Title Details Title Details - + Reference Tags Reference Tags @@ -2353,11 +2209,29 @@ GuiOutlineHeaderMenu - + Select Columns Select Columns + + GuiOutlineToolBar + + + Outline of + Outline of + + + + Refresh + Refresh + + + + All Novel Folders + All Novel Folders + + GuiPreferences @@ -2409,103 +2283,103 @@ GuiPreferencesAutomation - + Automatic Features Automatic Features - + Auto-select word under cursor Auto-select word under cursor - + Apply formatting to word under cursor if no selection is made. Apply formatting to word under cursor if no selection is made. - + Auto-replace text as you type Auto-replace text as you type - + Allow the editor to replace symbols as you type. Allow the editor to replace symbols as you type. - + Replace as You Type Replace as You Type - + Auto-replace single quotes Auto-replace single quotes - - + + Try to guess which is an opening or a closing quote. Try to guess which is an opening or a closing quote. - + Auto-replace double quotes Auto-replace double quotes - + Auto-replace dashes Auto-replace dashes - + Double and triple hyphens become short and long dashes. Double and triple hyphens become short and long dashes. - + Auto-replace dots Auto-replace dots - + Three consecutive dots become ellipsis. Three consecutive dots become ellipsis. - + Automatic Padding Automatic Padding - + Insert non-breaking space before Insert non-breaking space before - + Automatically add space before any of these symbols. Automatically add space before any of these symbols. - + Insert non-breaking space after Insert non-breaking space after - + Automatically add space after any of these symbols. Automatically add space after any of these symbols. - + Use thin space instead Use thin space instead - + Inserts a thin space instead of a regular space. Inserts a thin space instead of a regular space. @@ -2513,93 +2387,93 @@ GuiPreferencesDocuments - + Text Style Text Style - + Font family Font family - - - - + + + + Applies to both document editor and viewer. Applies to both document editor and viewer. - + Font size Font size - + pt pt - + Text Flow Text Flow - + Maximum text width in "Normal Mode" Maximum text width in "Normal Mode" - + Set to 0 to disable this feature. Set to 0 to disable this feature. - - - - + + + + px px - + Maximum text width in "Focus Mode" Maximum text width in "Focus Mode" - + The maximum width cannot be disabled. The maximum width cannot be disabled. - + Hide document footer in "Focus Mode" Hide document footer in "Focus Mode" - + Hide the information bar in the document editor. Hide the information bar in the document editor. - + Justify the text margins Justify the text margins - + Minimum text margin Minimum text margin - + Tab width Tab width - + The width of a tab key press in the editor and viewer. The width of a tab key press in the editor and viewer. @@ -2607,117 +2481,117 @@ GuiPreferencesEditor - + Spell Checking Spell Checking - + None None - + Not installed Not installed - + Spell check language Spell check language - + Available languages are determined by your system. Available languages are determined by your system. - + Big document limit Big document limit - + Full spell checking is disabled above this limit. Full spell checking is disabled above this limit. - + kB kB - + Word Count Word Count - + Word count interval Word count interval - + seconds seconds - + Include project notes in status bar word count Include project notes in status bar word count - + Writing Guides Writing Guides - + Show tabs and spaces Show tabs and spaces - + Show line endings Show line endings - + Scroll Behaviour Scroll Behavior - + Scroll past end of the document Scroll past end of the document - + Set to 0 to disable this feature. Set to 0 to disable this feature. - + lines lines - + Typewriter style scrolling when you type Typewriter style scrolling when you type - + Keeps the cursor at a fixed vertical position. Keeps the cursor at a fixed vertical position. - + Minimum position for Typewriter scrolling Minimum position for Typewriter scrolling - + Percentage of the editor height from the top. Percentage of the editor height from the top. @@ -2725,87 +2599,97 @@ GuiPreferencesGeneral - + Look and Feel Look and Feel - + Main GUI language Main GUI language - - - - - + + + + + Requires restart. Requires restart. - + Main GUI theme Main GUI theme - + Main icon theme Main icon theme + Editor theme + Editor theme + + + + Colour theme for the editor and viewer. + Color theme for the editor and viewer. + + + Font family Font family - + Font size Font size - + pt pt - + GUI Settings GUI Settings - + Emphasise partition and chapter labels Emphasise partition and chapter labels - + Makes them stand out in the project tree. Makes them stand out in the project tree. - + Show full path in document header Show full path in document header - + Add the parent folder names to the header. Add the parent folder names to the header. - + Hide vertical scroll bars in main windows Hide vertical scroll bars in main windows - - + + Scrolling available with mouse wheel and keys only. Scrolling available with mouse wheel and keys only. - + Hide horizontal scroll bars in main windows Hide horizontal scroll bars in main windows @@ -2813,109 +2697,109 @@ GuiPreferencesProjects - + Automatic Save Automatic Save - + Save document interval Save document interval - + How often the document is automatically saved. How often the document is automatically saved. - - + + seconds seconds - + Save project interval Save project interval - + How often the project is automatically saved. How often the project is automatically saved. - + Project Backup Project Backup - + Browse Browse - + Backup storage location Backup storage location - - + + Path: {0} Path: {0} - + Run backup when the project is closed Run backup when the project is closed - + Can be overridden for individual projects in Project Settings. Can be overridden for individual projects in Project Settings. - + Ask before running backup Ask before running backup - + If off, backups will run in the background. If off, backups will run in the background. - + Session Timer Session Timer - + Pause the session timer when not writing Pause the session timer when not writing - + Also pauses when the application window does not have focus. Also pauses when the application window does not have focus. - + Editor inactive time before pausing timer Editor inactive time before pausing timer - + User activity includes typing and changing the content. User activity includes typing and changing the content. - + minutes minutes - + Backup Directory Backup Directory @@ -2923,47 +2807,47 @@ GuiPreferencesQuotes - + Quotation Style Quotation Style - + Single quote open style Single quote open style - + The symbol to use for a leading single quote. The symbol to use for a leading single quote. - + Single quote close style Single quote close style - + The symbol to use for a trailing single quote. The symbol to use for a trailing single quote. - + Double quote open style Double quote open style - + The symbol to use for a leading double quote. The symbol to use for a leading double quote. - + Double quote close style Double quote close style - + The symbol to use for a trailing double quote. The symbol to use for a trailing double quote. @@ -2971,74 +2855,59 @@ GuiPreferencesSyntax - - Highlighting Theme - Highlighting Theme - - - - Highlighting theme - Highlighting theme - - - - Colour theme for the editor and viewer. - Color theme for the editor and viewer. - - - + Quotes & Dialogue Quotes & Dialogue - + Highlight text wrapped in quotes Highlight text wrapped in quotes - - - + + + Applies to the document editor only. Applies to the document editor only. - + Allow open-ended single quotes Allow open-ended single quotes - + Highlight single-quoted line with no closing quote. Highlight single-quoted line with no closing quote. - + Allow open-ended double quotes Allow open-ended double quotes - + Highlight double-quoted line with no closing quote. Highlight double-quoted line with no closing quote. - + Text Emphasis Text Emphasis - + Add highlight colour to emphasised text Add highlight color to emphasised text - + Text Errors Text Errors - + Highlight multiple or trailing spaces Highlight multiple or trailing spaces @@ -3046,17 +2915,17 @@ GuiProjectDetails - + Project Details Project Details - + Overview Overview - + Contents Contents @@ -3064,72 +2933,72 @@ GuiProjectDetailsContents - - Title - Title - - - - Words - Words - - - - Pages - Pages - - - - Page - Page - - - - Progress - Progress - - - - Typical word count for a 5 by 8 inch book page with 11 pt font is 350. - Typical word count for a 5 by 8 inch book page with 11 pt font is 350. - - - - Start counting page numbers from this page. - Start counting page numbers from this page. - - - - Assume a new chapter or partition always start on an odd numbered page. - Assume a new chapter or partition always start on an odd numbered page. - - - - Words per page - Words per page - - - - Count pages from - Count pages from - - - - Clear double pages - Clear double pages - - - + Table of Contents Table of Contents - + + Title + Title + + + + Words + Words + + + + Pages + Pages + + + + Page + Page + + + + Progress + Progress + + + + Typical word count for a 5 by 8 inch book page with 11 pt font is 350. + Typical word count for a 5 by 8 inch book page with 11 pt font is 350. + + + + Start counting page numbers from this page. + Start counting page numbers from this page. + + + + Assume a new chapter or partition always start on an odd numbered page. + Assume a new chapter or partition always start on an odd numbered page. + + + + Words per page + Words per page + + + + Count pages from + Count pages from + + + + Clear double pages + Clear double pages + + + END END - + Untitled Untitled @@ -3137,42 +3006,42 @@ GuiProjectDetailsMain - + Working Title: {0} Working Title: {0} - + By {0} By {0} - + Words Words - + Chapters Chapters - + Scenes Scenes - + Revisions Revisions - + Editing Time Editing Time - + Path Path @@ -3180,58 +3049,58 @@ GuiProjectEditMain - + Project Settings Project Settings - - Working title - Working title + + Project name + Project name - + Should be set only once. Should be set only once. - + Novel title Novel title - + Change whenever you want! Change whenever you want! - + Author(s) Author(s) - + One name per line. One name per line. - + Default Default - + Spell check language Spell check language - - + + Overrides main preferences. Overrides main preferences. - + No backup on close No backup on close @@ -3239,27 +3108,27 @@ GuiProjectEditReplace - + Text Replace List for Preview and Export Text Replace List for Preview and Export - + Keyword Keyword - + Replace With Replace With - + Select item to edit Select item to edit - + Save Save @@ -3399,7 +3268,7 @@ GuiProjectSettings - + Project Settings Project Settings @@ -3424,166 +3293,249 @@ Auto-Replace + + GuiProjectToolBar + + + Project Content + Project Content + + + + Quick Links + Quick Links + + + + Move Up + Move Up + + + + Move Down + Move Down + + + + Add Item + Add Item + + + + Expand All + Expand All + + + + Collapse All + Collapse All + + + + Undo Move + Undo Move + + + + Empty Trash + Empty Trash + + + + More Options + More Options + + GuiProjectTree - - Project Tree - Project Tree - - - - Words - Words - - - - Item label - Item label - - - - Word count - Word count - - - - Include in build - Include in build - - - - Item status - Item status - - - + Did not find anywhere to add the file or folder! Did not find anywhere to add the file or folder! - + Cannot add new files or folders to the Trash folder. Cannot add new files or folders to the Trash folder. - - New Document - New Document - - - + New Note New Note - + + New Chapter + New Chapter + + + + New Scene + New Scene + + + + New Document + New Document + + + New Folder New Folder - + There is currently no Trash folder in this project. There is currently no Trash folder in this project. - + The Trash folder is already empty. The Trash folder is already empty. - + + Empty Trash Empty Trash - + Permanently delete {0} file(s) from Trash? Permanently delete {0} file(s) from Trash? - - Cannot delete root folder. It is not empty. Recursive deletion is not supported. Please delete the content first. - Cannot delete root folder. It is not empty. Recursive deletion is not supported. Please delete the content first. - - - - + + Delete Delete - - Permanently delete '{0}'? - Permanently delete '{0}'? - - - + Move '{0}' to Trash? Move '{0}' to Trash? - - Could not delete document file. - Could not delete document file. + + Root folders can only be deleted when they are empty. + Root folders can only be deleted when they are empty. - - There is nowhere to add item with name '{0}'. - There is nowhere to add item with name '{0}'. - - - - GuiProjectTreeMenu - - - Edit Project Item - Edit Project Item + + Permanently delete '{0}'? + Permanently delete '{0}'? - + Open Document Open Document - + View Document View Document - - Toggle Included Flag - Toggle Included Flag + + Change Label + Change Label - - New File - New File + + Toggle Exported + Toggle Exported - - New Folder - New Folder + + Set Status to ... + Set Status to ... - - Delete Item - Delete Item + + Set Importance to ... + Set Importance to ... - - Empty Trash - Empty Trash + + Transform + Transform - - Move Item Up - Move Item Up + + + Convert to {0} + Convert to {0} - - Move Item Down - Move Item Down + + Merge Child Items into Self + Merge Child Items into Self + + + + Merge Child Items into New + Merge Child Items into New + + + + Combine Documents in Folder + Combine Documents in Folder + + + + Split Document by Header + Split Document by Header + + + + Expand All + Expand All + + + + Collapse All + Collapse All + + + + Delete Permanently + Delete Permanently + + + + Move to Trash + Move to Trash + + + + Convert Folder + Convert Folder + + + + Do you want to convert the folder to a {0}? This action cannot be reversed. + Do you want to convert the folder to a {0}? This action cannot be reversed. + + + + No documents selected for merging. + No documents selected for merging. + + + + Merged + Merged + + + + + Could not write document content. + Could not write document content. + + + + There is nowhere to add item with name '{0}'. + There is nowhere to add item with name '{0}'. @@ -3623,32 +3575,67 @@ GuiViewsBar - + Project Project - + + Project Tree View + Project Tree View + + + Novel Novel - + + Novel Tree View + Novel Tree View + + + Outline Outline - + + Novel Outline View + Novel Outline View + + + + Build + Build + + + + Build Novel Project + Build Novel Project + + + Details Details - + + Project Details + Project Details + + + Stats Stats - + + Writing Statistics + Writing Statistics + + + Settings Settings @@ -3657,7 +3644,7 @@ GuiWordList - + Project Word List Project Word List @@ -3675,152 +3662,152 @@ GuiWritingStats - + Writing Statistics Writing Statistics - + Session Start Session Start - + Length Length - + Idle Idle - + Words Words - + Histogram Histogram - + Sum Totals Sum Totals - + Total Time: Total Time: - + Idle Time: Idle Time: - + Filtered Time: Filtered Time: - + Novel Word Count: Novel Word Count: - + Notes Word Count: Notes Word Count: - + Total Word Count: Total Word Count: - + Filters Filters - + Count novel files Count novel files - + Count note files Count note files - + Hide zero word count Hide zero word count - + Hide negative word count Hide negative word count - + Group entries by day Group entries by day - + Show idle time Show idle time - + Word count cap for the histogram Word count cap for the histogram - + Save As Save As - + JSON Data File (.json) JSON Data File (.json) - + CSV Data File (.csv) CSV Data File (.csv) - + JSON Data File JSON Data File - + CSV Data File CSV Data File - + Save Data As Save Data As - + {0} file successfully written to: {0} file successfully written to: - + Failed to write {0} file. Failed to write {0} file. - + Failed to read session log file. Failed to read session log file. @@ -3828,385 +3815,421 @@ NWProject - - + + Could not delete document file. + Could not delete document file. + + + + New New - + Note Note - + Draft Draft - + Finished Finished - + Minor Minor - + Major Major - + Main Main - + New Project New Project - - By - By - - - - - Novel - Novel - - - - Plot - Plot - - - - Characters - Characters - - - - World - World - - - - + Title Page Title Page - - - + + By + By + + + + New Chapter New Chapter - - + + New Scene New Scene - + + Summary of the chapter. + Summary of the chapter. + + + + Summary of the scene. + Summary of the scene. + + + Chapter {0} Chapter {0} - - + + Scene {0} Scene {0} - + + Main Plot + Main Plot + + + + Protagonist + Protagonist + + + + Main Location + Main Location + + + File not found: {0} File not found: {0} - - + + Failed to parse project xml. Failed to parse project xml. - + Attempting to open backup project file instead. Attempting to open backup project file instead. - - + + Unknown Unknown - + Project file does not appear to be a novelWriterXML file. Project file does not appear to be a novelWriterXML file. - + Unknown or unsupported novelWriter project file format. The project cannot be opened by this version of novelWriter. The file was saved with novelWriter version {0}. Unknown or unsupported novelWriter project file format. The project cannot be opened by this version of novelWriter. The file was saved with novelWriter version {0}. - + File Version File Version - + The file format of your project is about to be updated. If you proceed, older versions of novelWriter will no longer be able to open this project. Continue? The file format of your project is about to be updated. If you proceed, older versions of novelWriter will no longer be able to open this project. Continue? - + Version Conflict Version Conflict - + This project was saved by a newer version of novelWriter, version {0}. This is version {1}. If you continue to open the project, some attributes and settings may not be preserved, but the overall project should be fine. Continue opening the project? This project was saved by a newer version of novelWriter, version {0}. This is version {1}. If you continue to open the project, some attributes and settings may not be preserved, but the overall project should be fine. Continue opening the project? - + + There was an error updating the project. Some data may not have been preserved. + There was an error updating the project. Some data may not have been preserved. + + + Opened Project: {0} Opened Project: {0} - + Project path not set, cannot save project. Project path not set, cannot save project. - - + + Failed to save project. Failed to save project. - + Saved Project: {0} Saved Project: {0} - + Backing up project ... Backing up project ... - + Cannot backup project because no valid backup path is set. Please set a valid backup location in Preferences. Cannot backup project because no valid backup path is set. Please set a valid backup location in Preferences. - + Cannot backup project because no project name is set. Please set a Working Title in Project Settings. Cannot backup project because no project name is set. Please set a Working Title in Project Settings. - + Could not create backup folder. Could not create backup folder. - + Cannot backup project because the backup path is within the project folder to be backed up. Please choose a different backup path in Preferences. Cannot backup project because the backup path is within the project folder to be backed up. Please choose a different backup path in Preferences. - + Backup from {0} Backup from {0} - + Backup archive file written to: {0} Backup archive file written to: {0} - + Could not write backup archive. Could not write backup archive. - + Project backed up to '{0}' Project backed up to '{0}' - - + + Failed to create a new example project. Failed to create a new example project. - + Failed to create a new example project. Could not find the necessary files. They seem to be missing from this installation. Failed to create a new example project. Could not find the necessary files. They seem to be missing from this installation. - + Could not create new project folder. Could not create new project folder. - + New project folder is not empty. Each project requires a dedicated project folder. New project folder is not empty. Each project requires a dedicated project folder. - + You must set a valid backup path in Preferences to use the automatic project backup feature. You must set a valid backup path in Preferences to use the automatic project backup feature. - + You must set a valid project name in Project Settings to use the automatic project backup feature. You must set a valid project name in Project Settings to use the automatic project backup feature. - + and and - + Could not create folder. Could not create folder. - + Found {0} orphaned file(s) in project folder. Found {0} orphaned file(s) in project folder. - + Recovered Recovered - + [{0}] {1} [{0}] {1} - + Recovered File {0} Recovered File {0} - + One or more orphaned files could not be added back into the project. Make sure at least a Novel root folder exists. One or more orphaned files could not be added back into the project. Make sure at least a Novel root folder exists. - - - Not a folder: {0} - Not a folder: {0} - - - - Could not move: {0} - Could not move: {0} - - - - - Could not delete: {0} - Could not delete: {0} - - - - Could not make folder: {0} - Could not make folder: {0} - - - - Could not move item {0} to {1}. - Could not move item {0} to {1}. - ProjWizardCustomPage - + Custom Project Options Custom Project Options - - Select which additional root folders to make, and how to populate the Novel folder. If you don't want to add chapters or scenes, set the values to 0. You can add scenes without chapters. - Select which additional root folders to make, and how to populate the Novel folder. If you don't want to add chapters or scenes, set the values to 0. You can add scenes without chapters. + + Select which additional elements to populate the project with. You can skip making chapters and add only scenes by setting the number of chapters to 0. + Select which additional elements to populate the project with. You can skip making chapters and add only scenes by setting the number of chapters to 0. - - Additional Root Folders - Additional Root Folders + + Add a folder for plot notes + Add a folder for plot notes - - - - - - - {0} folder - {0} folder + + Add a folder for character notes + Add a folder for character notes - - Populate Novel Folder - Populate Novel Folder + + Add a folder for location notes + Add a folder for location notes - - Add chapters - Add chapters + + Add example notes to the above + Add example notes to the above - - Scenes (per chapter) - Scenes (per chapter) + + Add chapters to the novel folder + Add chapters to the novel folder - - Add chapter folders - Add chapter folders + + Add scenes to each chapter + Add scenes to each chapter ProjWizardFinalPage - - Finished - Finished + + Summary + Summary - - All done. - All done. + + Project Name: {0} + Project Name: {0} - + + Project Path: {0} + Project Path: {0} + + + + Fill the project with a minimal set of items + Fill the project with a minimal set of items + + + + Fill the project with example files + Fill the project with example files + + + + Add a folder for plot notes + Add a folder for plot notes + + + + Add a folder for character notes + Add a folder for character notes + + + + Add a folder for location notes + Add a folder for location notes + + + + Add example notes to the above + Add example notes to the above + + + + Add {0} chapters to the novel folder + Add {0} chapters to the novel folder + + + + Add {0} scenes to each chapter + Add {0} scenes to each chapter + + + + Add {0} scenes + Add {0} scenes + + + + You have selected the following: + You have selected the following: + + + Press '{0}' to create the new project. Press '{0}' to create the new project. - + Done Done - + Finish Finish @@ -4214,33 +4237,33 @@ ProjWizardFolderPage - - + + Select Project Folder Select Project Folder - + Select a location to store the project. A new project folder will be created in the selected location. Select a location to store the project. A new project folder will be created in the selected location. - + Required Required - + Project Path Project Path - + Error: A project folder cannot be created using this path. Error: A project folder cannot be created using this path. - + Error: The selected path already exists. Error: The selected path already exists. @@ -4248,47 +4271,47 @@ ProjWizardIntroPage - + Create New Project Create New Project - - Provide at least a working title. The working title should not be change beyond this point as it is used by the application for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. - Provide at least a working title. The working title should not be change beyond this point as it is used by the application for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. + + Provide at least a project name. The project name should not be changed beyond this point as it is used for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. + Provide at least a project name. The project name should not be changed beyond this point as it is used for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. - + Side image by {0}, {1} Side image by {0}, {1} - + Required Required - + Optional Optional - + Optional. One name per line. Optional. One name per line. - - Working Title - Working Title + + Project Name + Project Name - + Novel Title Novel Title - + Author(s) Author(s) @@ -4296,27 +4319,27 @@ ProjWizardPopulatePage - + Populate Project Populate Project - + Choose how to pre-fill the project. Either with a minimal set of starter items, an example project explaining and showing many of the features, or show further custom options on the next page. Choose how to pre-fill the project. Either with a minimal set of starter items, an example project explaining and showing many of the features, or show further custom options on the next page. - + Fill the project with a minimal set of items Fill the project with a minimal set of items - + Fill the project with example files Fill the project with example files - + Show detailed options for filling the project Show detailed options for filling the project @@ -4512,17 +4535,17 @@ Tokenizer - + Synopsis Synopsis - + Document '{0}' is too big ({1} MB). Skipping. Document '{0}' is too big ({1} MB). Skipping. - + ERROR ERROR diff --git a/i18n/nw_nb_NO.ts b/i18n/nw_nb_NO.ts index 17cb5ddb..8a3a1129 100644 --- a/i18n/nw_nb_NO.ts +++ b/i18n/nw_nb_NO.ts @@ -77,259 +77,264 @@ Constant - - - + + + None Ingen - + Novel Roman - - + + Plot Plott - - + + Characters Karakterer - - + + Locations Lokasjoner - - + + Timeline Tidslinje - - + + Objects Objekter - - + + Entities Enheter - - + + Custom Annet - + Archive Arkiv - + Trash Søppel - - + + Novel Document Romandokument - - + + Project Note Prosjektnotat - + Root Folder Hovedmappe - + Folder Mappe - + Novel Title Page Tittelside - + Novel Chapter Kapittel - + Novel Scene Scene - + + Novel Section + Seksjon + + + Tag Knagg - + Point of View Perspektiv - - + + Focus Fokus - + Title Tittel - + Level Nivå - + Document Dokument - + Line Linje - + Chars Tegn - + Words Ord - + Pars Avsnitt - + POV Persp. - + Synopsis Sammendrag - + Straight single quotation mark Rett, enkelt sitattegn - + Straight double quotation mark Rett, dobbelt sitattegn - + Left single quotation mark Venstre, enkelt sitattegn - + Right single quotation mark Høyre, enkelt sitattegn - + Single low-9 quotation mark Enkelt, lavt-9 sitattegn - + Single high-reversed-9 quotation mark Enkelt, høyt, reversert-9 sitattegn - + Left double quotation mark Venstre, dobbelt sitattegn - + Right double quotation mark Høyre, dobbelt sitattegn - + Double low-9 quotation mark Dobbelt, lavt-9 sitattegn - + Double high-reversed-9 quotation mark Dobbelt, høyt, reversert-9 sitattegn - + Double low-reversed-9 quotation mark Dobbelt, lavt, reversert-9 sitattegn - + Single left-pointing angle quotation mark Enkelt, venstre, angulært sitattegn - + Single right-pointing angle quotation mark Enkelt, høyre, angulært sitattegn - + Double left-pointing angle quotation mark Dobbelt, venstre, angulært sitattegn - + Double right-pointing angle quotation mark Dobbelt, høyre, angulært sitattegn - + Left corner bracket Venstre hjørnevinkel - + Right corner bracket Høyre hjørnevinkel - + Left white corner bracket Venstre, hvit hjørnevinkel - + Right white corner bracket Høyre, hvit hjørnevinkel @@ -443,7 +448,7 @@ GuiBuildNovel - + Build Novel Project Bygg prosjektet @@ -604,176 +609,181 @@ + Root Filter Options + Filtrer rotmapper + + + File Filter Options Fil-filtre - + Include novel files Inkluder romanfiler - + Include note files Inkluder notatfiler - + Ignore export flag Ignorer 'ta med'-flagg - + Export Options Eksportvalg - + Replace tabs with spaces Erstatt tab med mellomrom - + Replace Unicode in HTML Erstatt Unicode med HTML - + Build Preview Lag forhåndsvisning - + Print Skriv ut - + Print Preview Forhåndsvisning av utskrift - + Print to PDF Skriv ut til PDF - + Save As Lagre som - + Open Document (.odt) Open Document (.odt) - + Flat Open Document (.fodt) Flat Open Document (.fodt) - + novelWriter HTML (.htm) novelWriter HTML (.htm) - + novelWriter Markdown (.nwd) novelWriter Markdown (.nwd) - + Standard Markdown (.md) Standard Markdown (.md) - + GitHub Markdown (.md) GitHub Markdown (.md) - + JSON + novelWriter HTML (.json) JSON + novelWriter HTML (.json) - + JSON + novelWriter Markdown (.json) JSON + novelWriter Markdown (.json) - + Close Lukk - + Failed to generate preview. The result is too big. Kunne ikke generere forhåndsvisning. Resultatet er for stort til å vise. - + There were problems when building the project: Det har oppstått problemer under bygging av prosjektet: - + Open Document Open Document - + Flat Open Document Flat Open Document - + Plain HTML Enkel HTML - + novelWriter Markdown novelWriter Markdown - + Standard Markdown Standard Markdown - + GitHub Markdown GitHub Markdown - + JSON + novelWriter HTML JSON + novelWriter HTML - + JSON + novelWriter Markdown JSON + novelWriter Markdown - + PDF PDF - + Save Document As Lagre dokumentet som - + {0} file successfully written to: Lagring av {0} var vellykket, og filen ble skrevet til: - + Failed to write {0} file. {1} Misslykkes i å skrive {0} til. {1} @@ -781,17 +791,17 @@ GuiBuildNovelDocView - + This area will show the content of the document to be exported or printed. Press the "Build Preview" button to generate content. Dette området vil vise innholdet av dokumentet som skal eksporteres. Trykk på knappen merket med "Lag forhåndsvisning" for å oppdatere innholdet. - + Unknown Ukjent - + Build Time: Bygget: @@ -799,32 +809,32 @@ GuiDocEditFooter - + Status Status - + Line: {0} ({1}) Linje: {0} ({1}) - + Words: {0} ({1}) Ord: {0} ({1}) - + Document size is {0} bytes Dokumentet er {0} byte - + Words: {0} selected Ord: {0} valgt - + Character count: {0} Antall tegn: {0} @@ -832,22 +842,22 @@ GuiDocEditHeader - - Edit document meta - Rediger dokumentinstillinger + + Edit document label + Endre dokumentnavn - + Search document Søk i dokumentet - + Toggle Focus Mode Slå av/på "Fokus-modus" - + Close the document Lukk dokumentet @@ -855,58 +865,58 @@ GuiDocEditSearch - - + + Search Søk - + Replace Erstatt - + Case Sensitive Skill store/små bokstaver - + Whole Words Only Kun hele ord - + RegEx Mode RegEx-modus - + Loop Search Søk rundt - + Search Next File Søk i neste file - + Preserve Case Behold store/små bokstaver - + Close Search Lukk søk - + Find in current document Søk i det åpne dokumentet - + Find and replace in current document Søk og erstatt i det åpne dokumentet @@ -914,117 +924,117 @@ GuiDocEditor - + The document you are trying to open is too big. The document size is {0} MB. The maximum size allowed is {1} MB. Dokumentet du prøver å åpne er for stort. Dokumenter er på {0} MB. Den maksimale størrelsen tillat er {1} MB. - + Opened Document: {0} Åpnet dokument: {0} - + The text you are trying to add is too big. The text size is {0} MB. The maximum size allowed is {1} MB. Teksten du forsøker å legge til er for stor. Teksten er {0} MB. Den maksimale tillatte størrelsen er {1} MB. - + File Changed on Disk Filen er endret på disk - + This document has been changed outside of novelWriter while it was open. Overwrite the file on disk? Dette dokumentet er endret utenfor novelWriter mens det var åpent. Overskrive filen på disken? - + Could not save document. Kunne ikke lagre dokumentet. - + Saved Document: {0} Lagret dokument: {0} - + Spell checking requires the package PyEnchant. It does not appear to be installed. Stavekontroll krever at pakken PyEnchant er installert. Det ser det ikke ut til at den er. - + Spell check complete Stavekontrollen er ferdig - + File Location Filens plassering - + The currently open file is saved in: Det åpne dokumentet er lagret på følgende sted: - + The document has grown too big and you cannot add more text to it. The maximum size of a single novelWriter document is {0} MB. Dokumentet har blitt for stort og du kan ikke legge til mer tekst. Den maksimale tillatte størrelsen for et novelWriter-dokument er {0} MB. - + Follow Tag Følg knagg - + Cut Klipp - + Copy Kopier - + Paste Lim inn - + Select All Velg hele teksten - + Select Word Velg hele ordet - + Select Paragraph Velg hele avsnittet - + Spelling Suggestion(s) Forslag fra stavekontrollen - + No Suggestions Ingen forslag - + Add Word to Dictionary Legg til ord i ordbok - + Please select some text before calling replace quotes. Venligst velg en del av teksten før du velger å erstatte sitattegn. @@ -1042,159 +1052,103 @@ Dokumenter som skal slås sammen - - Drag and drop items to change the order. - Dra og slipp dokumenter for å endre rekkefølge. + + Drag and drop items to change the order, or uncheck to exclude. + Dra og slipp elementer for å endre rekkefølgen, eller fjern merking for å ekskludere. - - No source documents found. Nothing to do. - Ingen kilde-dokument funnet. Det er ingenting å gjøre. - - - - Failed to open document file. - Kunne ikke åpne dokumentets fil. - - - - No source folder selected. Nothing to do. - Ingen kildemappe valgt. Det er ingenting å gjøre. - - - - Internal error. - Intern feil - - - - Could not save document. - Kunne ikke lagre dokumentet. - - - - Element selected in the project tree must be a folder. - Elementet som er valgt i prosjekttreet må være en mappe. + + Move merged items to Trash + Flytt sammenslåtte elementer til papirkurven GuiDocSplit - - + Split Document Del opp dokument - + Document Headers Dokumentets overskrifter - + Select the maximum level to split into files. Velg hvilket nivå av overskrifter å dele opp til. - + Split on Header Level 1 (Title) Del på overskrifter på nivå 1 (titler) - + Split up to Header Level 2 (Chapter) Del på overskrifter opp til nivå 2 (kapitler) - + Split up to Header Level 3 (Scene) Del på overskrifter opp til nivå 3 (scener) - + Split up to Header Level 4 (Section) Del på overskrifter opp til nivå 4 (seksjoner) - - No source document selected. Nothing to do. - Ingen kilde-dokument er valgt. Det er ingenting å gjøre. + + Split into a new folder + Del inn i en ny mappe - - Could not parse source document. - Klarte ikke å lese kilde-dokumentet. - - - - Failed to open document file. - Kunne ikke åpne dokumentets fil. - - - - No headers found. Nothing to do. - Ingen overskrifter ble funnet i dokumentet. Det er ikke noe å gjøre. - - - - The document will be split into {0} file(s) in a new folder. The original document will remain intact. - Dokumentet vil nå bli delt opp i {0} nye filer i en ny mappe. Det originale dokumentet vil ikke bli endret eller fjernet. - - - - Continue with the splitting process? - Fortsette med oppdelingen? - - - - Could not save document. - Kunne ikke lagre dokumentet. - - - - Element selected in the project tree must be a file. - Elementet som er valgt i prosjekttreet må være et dokument. + + Create document hierarchy + Opprett dokumenthierarki GuiDocViewFooter - + Show/hide the references panel Skjul eller vis referanse-panelet - + Activate to freeze the content of the references panel when changing document Aktiver for å fryse innholdet i referanse-panelet ved bytte av vist dokument - + Show comments Vis kommentarer - + Show synopsis comments Vis sammendrag - + References Referanser - + Sticky Hold igjen - + Comments Kommentarer - + Synopsis Sammendrag @@ -1202,22 +1156,22 @@ GuiDocViewHeader - + Go backward Gå bakover - + Go forward Gå fremover - + Reload the document Last dokumentet på nytt - + Close the document Lukk dokumentet @@ -1225,102 +1179,82 @@ GuiDocViewer - + An error occurred while generating the preview. Det har oppstått en feil under genereringen av visningen. - - Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. - Kunne ikke finne referansen til knagg {0}. Enten finnes den ikke, eller så er prosjektets indeks ikke oppdatert. Indeksen kan oppdateres fra Verktøy-menyen eller ved å trykke på {1}. - - - + Copy Kopier - + Select All Velg hele teksten - + Select Word Velg hele ordet - + Select Paragraph Velg hele avsnittet + + GuiEditLabel + + + Item Label + Enhetens navn + + + + Label + Navn + + GuiItemDetails - + Label Navn - + Status Status - + Class Klasse - + Usage Formål - + Characters Tegn - + Words Ord - + Paragraphs Avsnitt - - GuiItemEditor - - - Item Settings - Enhetsinstillinger - - - - Include when building project - Ta med ved eksport - - - - Label - Navn - - - - Status - Status - - - - Layout - Format - - GuiLipsum @@ -1352,862 +1286,761 @@ GuiMain - + You are running an untested development version of novelWriter. Please be careful when working on a live project and make sure you take regular backups. Du kjører nå en utestet versjon av novelWriter. Vær forsiktig om du jobber med et av dine faktiske prosjekter. Husk å ta backup! - + novelWriter is ready ... novelWriter er klar ... - + Cannot create a new project when another project is open. Kan ikke lage et nytt prosjekt mens et annet prosjekt er åpent. - + A project already exists in that location. Please choose another folder. Et prosjekt finnes allerede i den mappen. Vennligst velg et annet sted å lagre prosjektet. - + New project created ... Et nytt prosjekt har blitt opprettet ... - + Close Project Lukk prosjektet - + Close the current project? Ønsker du å lukke dette prosjektet? - - + + Changes are saved automatically. Endringer lagres automatisk. - + Backup Project Sikkerhetskopiering - + Backup the current project? Ønsker du å ta sikkerhetskopi av dette prosjektet? - + The project was locked by the computer '{0}' ({1} {2}), last active on {3}. Prosjektet er låst av datamaskinen {0} ({1} {2}), siste registrerte aktivitet var {3}. - + Project Locked Prosjektlås - + The project is already open by another instance of novelWriter, and is therefore locked. Override lock and continue anyway? Prosjektet er allerede åpent av en annen instans av novelWriter, og er derfor låst. Vil du overstyre denne låsen og fortsette likevel? - + Note: If the program or the computer previously crashed, the lock can safely be overridden. However, overriding it is not recommended if the project is open in another instance of novelWriter. Doing so may corrupt the project. Merk: Hvis programmet eller datamaskinen tidligere krasjet, kan fil-låsen trygt overstyres. Det anbefales imidlertid ikke å overstyre den hvis prosjektet er åpent i en annen instans av novelWriter. Å gjøre det kan skape konflikter i prosjektets filer. - + The project index is outdated or broken. Rebuilding index. Prosjektets indeks er utdatert eller skadet. Bygger indeksen på nytt. - + Text files ({0}) Tekstfiler ({0}) - + Markdown files ({0}) Markdown-filer ({0}) - + novelWriter files ({0}) novelWriter-filer ({0}) - + All files ({0}) Alle filer ({0}) - + Import File Importer fil - + Could not read file. The file must be an existing text file. Kunne ikke lese filen. Filen må eksistere fra før av. - + Please open a document to import the text file into. Vennligst åpne et dokument hvor teksten i filen kan importeres. - + Import Document Importer dokument - + Importing the file will overwrite the current content of the document. Do you want to proceed? Å importere filen vil overskrive all eksisterende tekst i dokumentet. Ønsker du å fortsette? - - - Indexing: '{0}' - Indekserer: '{0}' - - - - Unknown item - Ukjent enhet - - - + Indexing completed in {0} ms Indekseringen tok {0} ms - + The project index has been successfully rebuilt. Prosjektets indeks har blitt bygget på nytt. - + Information Informasjon - + Warning Advarsel - + Error Feil - + This is a bug! Dette er en systemfeil! - + Internal Error Intern feil - + Exit Avslutt - + Do you want to exit novelWriter? Ønsker du å avslutte novelWriter? + + + Could not find the reference for tag '{0}'. It either doesn't exist, or the index is out of date. The index can be updated from the Tools menu, or by pressing {1}. + Kunne ikke finne referansen til knagg {0}. Enten finnes den ikke, eller så er prosjektets indeks ikke oppdatert. Indeksen kan oppdateres fra Verktøy-menyen eller ved å trykke på {1}. + GuiMainMenu - + &Project &Prosjekt - + New Project Nytt prosjekt - + Open Project Åpne prosjekt - + Save Project Lagre prosjektet - + Close Project Lukk prosjektet - + Project Settings Prosjektinnstillinger - + Project Details Prosjektdetaljer - - Create Root Folder - Lag ny hovedmappe + + Rename Item + Endre navn - - Novel Root - Mappe for "Roman" - - - - Plot Root - Mappe for "Plott" - - - - Character Root - Mappe for "Karakterer" - - - - Location Root - Mappe for "Lokasjoner" - - - - Timeline Root - Mappe for "Tidslinjer" - - - - Object Root - Mappe for "Objekter" - - - - Entity Root - Mappe for "Enheter" - - - - Custom Root - Mappe for "Annet" - - - - Archive Root - Mappe for Arkiv - - - - Create Folder - Lag ny mappe - - - - Edit Item - Endre enhet - - - + Delete Item Slett enhet - - Move Item Up - Flytt enhet opp - - - - Move Item Down - Flytt enhet ned - - - - Undo Last Move - Angre siste flytting - - - + Empty Trash Tøm søppel - + Exit Avslutt - + &Document &Dokument - - New Document - Nytt dokument - - - + Open Document Åpne dokument - + Save Document Lagre dokumentet - + Close Document Lukk dokumentet - + View Document Vis dokument - + Close Document View Lukk dokumentvisning - + Show File Details Vis filinformasjon - + Import Text from File Importer tekst fra fil - - Merge Folder to Document - Slå sammen mappe - - - - Split Document to Folder - Del opp dokument - - - + &Edit &Rediger - + Undo Angre - + Redo Gjenopprett - + Cut Klipp - + Copy Kopier - + Paste Lim inn - + Select All Velg hele teksten - + Select Paragraph Velg hele avsnittet - + &View &Vis - + Go to Project Tree Gå til prosjekt-tre - + Go to Document Editor Gå til dokument-editor - + Go to Document Viewer Gå til visningsvindu - + Go to Outline Gå til disposisjon - + Navigate Backward Navigere bakover - + Navigate Forward Navigere fremover - + Focus Mode Focus-modus - + Full Screen Mode Fullskjerm-modus - + &Insert Sett &inn - + Dashes Bindestreker - + Short Dash Kort bindestrek - + Long Dash Lang bindestrek - + Horizontal Bar Horisontal strek - + Figure Dash Tallstrek - + Quote Marks Sitattegn - + Left Single Quote Venstre, enkelt sitattegn - + Right Single Quote Høyre, enkelt sitattegn - + Left Double Quote Venstre, dobbelt sitattegn - + Right Double Quote Høyre, dobbelt sitattegn - + Alternative Apostrophe Alternativ apostrof - + General Punctuation Generell tegnsetting - + Ellipsis Ellipsis - + Prime Primtegn - + Double Prime Dobbelt primtegn - + White Spaces Mellomrom - + Non-Breaking Space Hardt mellomrom - + Thin Space Kort mellomrom - + Thin Non-Breaking Space Hardt, kort mellomrom - + Other Symbols Andre symboler - + List Bullet Kulepunkt - + Hyphen Bullet Bindestrekpunkt - + Flower Mark Blomsterpunkt - + Per Mille Promille - + Degree Symbol Gradertegn - + Minus Sign Minustegn - + Times Sign Gangetegn - + Division Sign Deletegn - + Tags and References Knagger og referanser - + Page Break and Space Sideskift og avstand - + Page Break Sideskift - + Vertical Space (Single) Vertikal avstand (enkel) - + Vertical Space (Multi) Vertikal avstand (flere) - + Placeholder Text Midlertidig tekst - + &Format &Formattering - + Emphasis Kursiv - + Strong Emphasis Uthev - + Strikethrough Gjennomstrek - + Wrap Double Quotes Sett i doble sitattegn - + Wrap Single Quotes Sett i enkle sitattegn - + Header 1 (Partition) Overskrift 1 (inndeling) - + Header 2 (Chapter) Overskrift 2 (kapittel) - + Header 3 (Scene) Overskrift 3 (scene) - + Header 4 (Section) Overskrift 4 (seksjon) - + Novel Title Boktittel - + Unnumbered Chapter Unumrert kapittel - + Align Left Venstrejuster - + Align Centre Sentrer - + Align Right Høyrejuster - + Indent Left Innrykk fra venstre - + Indent Right Innrykk fra høyre - + Toggle Comment Veksle kommentar - + Remove Block Format Fjern formattering - + Convert Single Quotes Konverter enkle sitattegn - + Convert Double Quotes Konverter doble sitattegn - + Remove In-Paragraph Breaks Fjern linjeskift i avsnittet - + &Search &Søk - + Find Søk - + Replace Erstatt - + Find Next Finn neste - + Find Previous Finn forrige - + Replace Next Erstatt neste - + &Tools &Verktøy - + Check Spelling Stavekontroll - + Re-Run Spell Check Kjør stavekontroll - + Project Word List Prosjektets ordliste - + Rebuild Index Bygg indeks - - Rebuild Outline - Bygg disposisjon - - - - Auto-Update Outline - Auto-oppdater disposisjon - - - + Backup Project Lag sikkerhetskopi av prosjektets mappe - + Build Novel Project Bygg prosjektet - + Writing Statistics Statistikk - + Preferences Innstillinger - + &Help &Hjelp - + About novelWriter Om novelWriter - + About Qt5 Om Qt5 - + User Manual (Online) Brukermanual (på nett) - + User Manual (PDF) Brukermanual (PDF) - + Report an Issue (GitHub) Rapporter en feil (GitHub) - + Ask a Question (GitHub) Still et spørsmål (GitHub) - + The novelWriter Website novelWriters nettside - + Check for New Release Sjekk etter oppdateringer @@ -2252,100 +2085,123 @@ - GuiNovelTree + GuiNovelToolBar - + Novel Outline Disposisjon - - Words - Ord + + Refresh + Oppdatér - - POV - Persp. + + Novel Root + Roman-mappe - - Section title - Seksjonens tittel + + Last Column + Siste kolonne - - Word count - Antall ord + + Hidden + Skjult - - Point-of-view character + + Point of View Character Synsvinkel-karakter + + + Focus Character + Fokus-karakter + + + + Novel Plot + Roman-plott + + + + More Options + Flere valg + + + + GuiNovelTree + + + No meta data + Ingen meta-data + GuiOutlineDetails - - - - + + + + Title Tittel - + Chapter Kapittel - + Scene Scene - + Section Seksjon - + Document Dokument - + Status Status - + Characters Tegn - + Words Ord - + Paragraphs Avsnitt - + Synopsis Sammendrag - + Title Details Oversikt - + Reference Tags Referanser @@ -2353,11 +2209,29 @@ GuiOutlineHeaderMenu - + Select Columns Velg kolonner + + GuiOutlineToolBar + + + Outline of + Disposisjon for + + + + Refresh + Oppdatér + + + + All Novel Folders + Alle roman-mapper + + GuiPreferences @@ -2409,103 +2283,103 @@ GuiPreferencesAutomation - + Automatic Features Automatiske funksjoner - + Auto-select word under cursor Auto-velg ord under markør - + Apply formatting to word under cursor if no selection is made. Hvis ingen tekst er valgt, formatter ordet hvor markøren står. - + Auto-replace text as you type Erstatt mens du skriver - + Allow the editor to replace symbols as you type. La editoren erstatte symboler mens du skriver. - + Replace as You Type Erstatt mens du skriver - + Auto-replace single quotes Erstatt enkle sitattegn - - + + Try to guess which is an opening or a closing quote. Prøv å gjette om det er et åpne- eller lukketegn. - + Auto-replace double quotes Erstatt doble sitattegn - + Auto-replace dashes Erstatt bindestreker - + Double and triple hyphens become short and long dashes. To og tre bindestreker erstattes med kort og lang bindestrek. - + Auto-replace dots Erstatt tre punktum - + Three consecutive dots become ellipsis. Tre punktum på rad erstattes med ellipsis. - + Automatic Padding Automatisk mellomrom - + Insert non-breaking space before Sett inn hardt mellomrom foran - + Automatically add space before any of these symbols. Legg til mellomrom automatisk foran disse tegnene. - + Insert non-breaking space after Sett inn hardt mellomrom etter - + Automatically add space after any of these symbols. Legg til mellomrom automatisk etter disse tegnene. - + Use thin space instead Bruk tynt mellomrom istedet - + Inserts a thin space instead of a regular space. Sett inn et tynt mellomrom istedenfor et vanlig et. @@ -2513,93 +2387,93 @@ GuiPreferencesDocuments - + Text Style Tekststil - + Font family Skriftfamilie - - - - + + + + Applies to both document editor and viewer. Gjelder både redigerings- og visningsvindu. - + Font size Skriftstørrelse - + pt pt - + Text Flow Tekstflyt - + Maximum text width in "Normal Mode" Maks tekstbredde i "Normal-modus" - + Set to 0 to disable this feature. Sett til 0 for å deaktivere denne funksjonen. - - - - + + + + px px - + Maximum text width in "Focus Mode" Maks tekstbredde i "Fokus-modus" - + The maximum width cannot be disabled. Denne maks-bredden kan ikke deaktiveres. - + Hide document footer in "Focus Mode" Gjem dokumentets bunnlinje i "Fokus-modus" - + Hide the information bar in the document editor. Skjul informasjonslinjen i dokumenteditoren. - + Justify the text margins Juster tekstmarginer - + Minimum text margin Minimum tekstmargin - + Tab width Tabulatorens bredde - + The width of a tab key press in the editor and viewer. Hvor langt tabulatoren hopper i editor og visning. @@ -2607,117 +2481,117 @@ GuiPreferencesEditor - + Spell Checking Stavekontroll - + None Ingen - + Not installed Ikke installert - + Spell check language Språk for stavekontroll - + Available languages are determined by your system. Tilgjengelige språk hentes fra operativystemet ditt. - + Big document limit Grense for store dokumenter - + Full spell checking is disabled above this limit. Automatisk stavekontroll slås av over grensen. - + kB kB - + Word Count Telling av ord - + Word count interval Telle-intervall - + seconds sekunder - + Include project notes in status bar word count Inkluder prosjektnotater i antallet ord i statuslinjen - + Writing Guides Hjelpesymboler - + Show tabs and spaces Synlige tabulatorer og mellomrom - + Show line endings Synlige linjeender - + Scroll Behaviour Rullefelt - + Scroll past end of the document Tillat å rulle forbi slutten av dokumentet - + Set to 0 to disable this feature. Sett til 0 for å deaktivere denne funksjonen. - + lines linjer - + Typewriter style scrolling when you type Skrivemaskin-liknende rulling mens du skriver - + Keeps the cursor at a fixed vertical position. Holder markøren på samme sted vertikalt. - + Minimum position for Typewriter scrolling Minste avstand for skrivemaskin-rulling - + Percentage of the editor height from the top. I prosent fra toppen av editor-vinduet. @@ -2725,87 +2599,97 @@ GuiPreferencesGeneral - + Look and Feel Utseende - + Main GUI language Programspråk - - - - - + + + + + Requires restart. Krever omstart. - + Main GUI theme Fargetema - + Main icon theme Ikon-tema + Editor theme + Syntaksfremheving + + + + Colour theme for the editor and viewer. + Fargetema for editor og visning. + + + Font family Skriftfamilie - + Font size Skriftstørrelse - + pt pt - + GUI Settings Brukergrensesnitt - + Emphasise partition and chapter labels Fremhev filnavn for inndeling og kapitler - + Makes them stand out in the project tree. Får dem til å skille seg ut i prosjekttreet. - + Show full path in document header Vis full prosjektbane i dokumenthoder - + Add the parent folder names to the header. Legger til mappene foran dokumentets navn. - + Hide vertical scroll bars in main windows Skjul vertikale rullefelt i hovedvinduer - - + + Scrolling available with mouse wheel and keys only. Rulling kan bare gjøres med mus og tastatur. - + Hide horizontal scroll bars in main windows Skjul horisontale rullefelt i hovedvinduer @@ -2813,109 +2697,109 @@ GuiPreferencesProjects - + Automatic Save Automatisk lagring - + Save document interval Interval for lagring av dokument - + How often the document is automatically saved. Hvor ofte dokumentet lagres automatisk. - - + + seconds sekunder - + Save project interval Interval for lagring av prosjekt - + How often the project is automatically saved. Hvor ofte prosjektet lagres automatisk. - + Project Backup Sikkerhetskopi - + Browse Bla - + Backup storage location Filbane for sikkerhetskopi - - + + Path: {0} Filbane: {0} - + Run backup when the project is closed Lag sikkerhetskopi når prosjektet lukkes - + Can be overridden for individual projects in Project Settings. Kan overstyres fra individuelle prosjektinnstillinger. - + Ask before running backup Spør før sikkerhetskopi tas - + If off, backups will run in the background. Hvis avslått, tas sikkerhetskopi automatisk. - + Session Timer Sesjons-klokke - + Pause the session timer when not writing Sett klokka på pause når du er inaktiv - + Also pauses when the application window does not have focus. Pauses også når du ikke jobber i applikasjonens vindu. - + Editor inactive time before pausing timer Tid uten skriving før klokka settes på pause - + User activity includes typing and changing the content. Dette måler kun endringer i teksteditoren. - + minutes minutter - + Backup Directory Mappe for sikkerhetskopi @@ -2923,47 +2807,47 @@ GuiPreferencesQuotes - + Quotation Style Sitattegn - + Single quote open style Enkelt sitat, venstre side - + The symbol to use for a leading single quote. Symbol for enkelt sitattegn før et sitat. - + Single quote close style Enkelt sitat, høyre side - + The symbol to use for a trailing single quote. Symbol for enkelt sitattegn etter et sitat. - + Double quote open style Dobbelt sitat, venstre side - + The symbol to use for a leading double quote. Symbol for dobbelt sitattegn før et sitat. - + Double quote close style Dobbelt sitat, høyre side - + The symbol to use for a trailing double quote. Symbol for dobbelt sitattegn etter et sitat. @@ -2971,74 +2855,59 @@ GuiPreferencesSyntax - - Highlighting Theme - Syntaksfremheving - - - - Highlighting theme - Fremhevingstema - - - - Colour theme for the editor and viewer. - Fargetema for editor og visning. - - - + Quotes & Dialogue Sitattegn & dialog - + Highlight text wrapped in quotes Fremhev tekst mellom sitattegn - - - + + + Applies to the document editor only. Gjelder bare for redigeringsvindu. - + Allow open-ended single quotes Tillat enkle sitattegn som ikke lukkes - + Highlight single-quoted line with no closing quote. Fremhev sitater som ikke er lukket i samme avsnitt. - + Allow open-ended double quotes Tillat doble sitattegn som ikke lukkes - + Highlight double-quoted line with no closing quote. Fremhev sitater som ikke er lukket i samme avsnitt. - + Text Emphasis Fremheving av tekst - + Add highlight colour to emphasised text Fremhev formattert tekst - + Text Errors Feil i tekst - + Highlight multiple or trailing spaces Fremhev flere eller etterfølgende mellomrom @@ -3046,17 +2915,17 @@ GuiProjectDetails - + Project Details Prosjektdetaljer - + Overview Oversikt - + Contents Innhold @@ -3064,72 +2933,72 @@ GuiProjectDetailsContents - - Title - Tittel - - - - Words - Ord - - - - Pages - Sider - - - - Page - Side - - - - Progress - Fremdrift - - - - Typical word count for a 5 by 8 inch book page with 11 pt font is 350. - Typisk antall ord for en 5 x 8 tommers bokside med 11 pt tekst er 350. - - - - Start counting page numbers from this page. - Begynn sidetall fra denne siden. - - - - Assume a new chapter or partition always start on an odd numbered page. - Beregn at nye kapitler og partisjoner alltid starter på en høyreside. - - - - Words per page - Ord per side - - - - Count pages from - Tell sider fra - - - - Clear double pages - Tøm doble sider - - - + Table of Contents Innholdsfortegnelse - + + Title + Tittel + + + + Words + Ord + + + + Pages + Sider + + + + Page + Side + + + + Progress + Fremdrift + + + + Typical word count for a 5 by 8 inch book page with 11 pt font is 350. + Typisk antall ord for en 5 x 8 tommers bokside med 11 pt tekst er 350. + + + + Start counting page numbers from this page. + Begynn sidetall fra denne siden. + + + + Assume a new chapter or partition always start on an odd numbered page. + Beregn at nye kapitler og partisjoner alltid starter på en høyreside. + + + + Words per page + Ord per side + + + + Count pages from + Tell sider fra + + + + Clear double pages + Tøm doble sider + + + END SLUTT - + Untitled Uten tittel @@ -3137,42 +3006,42 @@ GuiProjectDetailsMain - + Working Title: {0} Arbeidstittel: {0} - + By {0} Av {0} - + Words Ord - + Chapters Kapitler - + Scenes Scener - + Revisions Revisjoner - + Editing Time Redigeringstid - + Path Filbane @@ -3180,58 +3049,58 @@ GuiProjectEditMain - + Project Settings Prosjektinnstillinger - - Working title - Arbeidstittel + + Project name + Prosjektnavn - + Should be set only once. Bør bare settes én gang. - + Novel title Bokens tittel - + Change whenever you want! Kan endres når som helst! - + Author(s) Forfatter(e) - + One name per line. Ett navn per linje. - + Default Ingen valg - + Spell check language Språk for stavekontroll - - + + Overrides main preferences. Overstyrer valg i innstillinger. - + No backup on close Slå av sikkerhetskopi @@ -3239,27 +3108,27 @@ GuiProjectEditReplace - + Text Replace List for Preview and Export Erstatningsliste for forhåndsvisning og eksport - + Keyword Kodeord - + Replace With Erstatt med - + Select item to edit Velg enhet å redigere - + Save Lagre @@ -3399,7 +3268,7 @@ GuiProjectSettings - + Project Settings Prosjektinnstillinger @@ -3424,166 +3293,249 @@ Autoerstatt + + GuiProjectToolBar + + + Project Content + Prosjektets innhold + + + + Quick Links + Hurtiglenker + + + + Move Up + Flytt opp + + + + Move Down + Flytt ned + + + + Add Item + Legg til element + + + + Expand All + Utvid alle + + + + Collapse All + Lukk alle + + + + Undo Move + Angre flytting + + + + Empty Trash + Tøm papirkurven + + + + More Options + Flere valg + + GuiProjectTree - - Project Tree - Prosjektoversikt - - - - Words - Ord - - - - Item label - Enhetens navn - - - - Word count - Antall ord - - - - Include in build - Ta med ved eksport - - - - Item status - Filen eller dokumentets status - - - + Did not find anywhere to add the file or folder! Fant ikke noe sted å legge til filen eller mappen! - + Cannot add new files or folders to the Trash folder. - Kan ikke legge til nye filer eller mapper til søppel-mappen. + Kan ikke legge til nye filer eller mapper i papirkurvmappen. - - New Document - Nytt dokument - - - + New Note Nytt notat - + + New Chapter + Nytt kapittel + + + + New Scene + Ny scene + + + + New Document + Nytt dokument + + + New Folder Ny mappe - + There is currently no Trash folder in this project. - Det er for øyeblikket ingen søppel-mappe i dette prosjektet. + Det er for øyeblikket ingen papirkurv i dette prosjektet. - + The Trash folder is already empty. - Søppel-mappen er allerede tom. + Papirkurven er allerede tom. - + + Empty Trash - Tøm søppel + Tøm papirkurven - + Permanently delete {0} file(s) from Trash? - Vil du slette {0} filer i søppel-mappen for godt? + Vil du slette {0} filer i papirkurven for godt? - - Cannot delete root folder. It is not empty. Recursive deletion is not supported. Please delete the content first. - Kan ikke slette hovedmappen da den ikke er tom. Rekursiv sletting er ikke støttet. Du må slette innholdet først. - - - - + + Delete Slett - - Permanently delete '{0}'? - Slette filen "{0}" for godt? - - - + Move '{0}' to Trash? Vil du flytte filen "{0}" til søpla? - - Could not delete document file. - Kunne ikke slette dokumentets fil. + + Root folders can only be deleted when they are empty. + Rotmapper kan bare slettes når de er tomme. - - There is nowhere to add item with name '{0}'. - Fant ikke noe sted å legge til enheten med navn {0}'. - - - - GuiProjectTreeMenu - - - Edit Project Item - Endre enhet + + Permanently delete '{0}'? + Slette filen "{0}" for godt? - + Open Document Åpne dokument - + View Document Vis dokument - - Toggle Included Flag - Slå av/på inkludering + + Change Label + Endre navn - - New File - Ny fil + + Toggle Exported + Skru av/på eksportert - - New Folder - Ny mappe + + Set Status to ... + Sett status til ... - - Delete Item - Slett enhet + + Set Importance to ... + Sett viktighetsnivå til ... - - Empty Trash - Tøm søppel + + Transform + Transformer - - Move Item Up - Flytt enhet opp + + + Convert to {0} + Konverter til {0} - - Move Item Down - Flytt enhet ned + + Merge Child Items into Self + Lim inn underelementer i dette dokumentet + + + + Merge Child Items into New + Lim inn underelementer i nytt dokument + + + + Combine Documents in Folder + Kombiner dokumenter i mappen + + + + Split Document by Header + Del dokumentet etter overskrift + + + + Expand All + Utvid alle + + + + Collapse All + Lukk alle + + + + Delete Permanently + Slett permanent + + + + Move to Trash + Flytt til papirkurv + + + + Convert Folder + Konverter mappe + + + + Do you want to convert the folder to a {0}? This action cannot be reversed. + Vil du konvertere mappen til et {0}? Denne handlingen kan ikke angres. + + + + No documents selected for merging. + Ingen dokumenter er valgt for sammenslåing. + + + + Merged + Sammenslått + + + + + Could not write document content. + Kan ikke skrive til dokumentet. + + + + There is nowhere to add item with name '{0}'. + Fant ikke noe sted å legge til enheten med navn {0}'. @@ -3623,32 +3575,67 @@ GuiViewsBar - + Project Prosjekt - + + Project Tree View + Prosjektoversikt + + + Novel Roman - + + Novel Tree View + Romanoversikt + + + Outline Oversikt - + + Novel Outline View + Disposisjon + + + + Build + Bygge + + + + Build Novel Project + Bygg prosjektet + + + Details Detaljer - + + Project Details + Prosjektdetaljer + + + Stats Statistikk - + + Writing Statistics + Statistikk + + + Settings Oppsett @@ -3657,7 +3644,7 @@ GuiWordList - + Project Word List Prosjektets ordliste @@ -3675,152 +3662,152 @@ GuiWritingStats - + Writing Statistics Statistikk - + Session Start Starttid - + Length Lengde - + Idle Inaktiv - + Words Ord - + Histogram Histogram - + Sum Totals Totalsummer - + Total Time: Totaltid: - + Idle Time: Inaktiv tid: - + Filtered Time: Filtrert tid: - + Novel Word Count: Ord i roman: - + Notes Word Count: Ord i notater: - + Total Word Count: Ord totalt: - + Filters Filtre - + Count novel files Tell i romanfiler - + Count note files Tell i notatfiler - + Hide zero word count Skjul null-verdier - + Hide negative word count Skjul negative verdier - + Group entries by day Samle rader per dag - + Show idle time Vis inaktiv som tid - + Word count cap for the histogram Maks antall ord for histogram - + Save As Lagre som - + JSON Data File (.json) JSON-format (.json) - + CSV Data File (.csv) CSV-format (.csv) - + JSON Data File JSON-format - + CSV Data File CSV-format - + Save Data As Lagre data som - + {0} file successfully written to: {0}-filen ble skrevet til: - + Failed to write {0} file. Kunne ikke skrive {0}-filen. - + Failed to read session log file. Kunne ikke lese loggfil med skrive-statistikk. @@ -3828,385 +3815,421 @@ NWProject - - + + Could not delete document file. + Kunne ikke slette dokumentets fil. + + + + New Ny - + Note Notat - + Draft Utkast - + Finished Ferdig - + Minor Mindre - + Major Større - + Main Hoved - + New Project Nytt prosjekt - - By - Av - - - - - Novel - Roman - - - - Plot - Plott - - - - Characters - Karakterer - - - - World - Verden - - - - + Title Page Tittelside - - - + + By + Av + + + + New Chapter Nytt kapittel - - + + New Scene Ny scene - + + Summary of the chapter. + Sammendrag av kapittelet. + + + + Summary of the scene. + Sammendrag av scenen. + + + Chapter {0} Kapittel {0} - - + + Scene {0} Scene {0} - + + Main Plot + Hoved-plott + + + + Protagonist + Protagonist + + + + Main Location + Hoved-lokasjon + + + File not found: {0} Fant ikke filen: {0} - - + + Failed to parse project xml. Kunne ikke lese prosjektets xml-data. - + Attempting to open backup project file instead. Forsøker å åpne prosjektets sekundære prosjektfil istedet. - - + + Unknown Ukjent - + Project file does not appear to be a novelWriterXML file. Prosjektfilen later ikke til å være en novelWriterXML-fil. - + Unknown or unsupported novelWriter project file format. The project cannot be opened by this version of novelWriter. The file was saved with novelWriter version {0}. Prosjektfilen har et ukjent eller ikke støttet format, og kan ikke åpnes med denne versjonen av novelWriter. Prosjektet ble lagret av novelWriter versjon {0}. - + File Version Filversjon - + The file format of your project is about to be updated. If you proceed, older versions of novelWriter will no longer be able to open this project. Continue? Filformatet til prosjektet ditt er i ferd med å bli oppdatert. Hvis du fortsetter, vil ikke eldre versjoner av novelWriter lenger kunne åpne dette prosjektet. Fortsette? - + Version Conflict Versjonskonflikt - + This project was saved by a newer version of novelWriter, version {0}. This is version {1}. If you continue to open the project, some attributes and settings may not be preserved, but the overall project should be fine. Continue opening the project? Dette prosjektet ble lagret av en nyere versjon av novelWriter, versjon {0}. Dette er versjon {1}. Hvis du ønsker å fortsette med å åpne prosjektet, kan noen av innstillingene bli borte, men selve prosjektet vil være i orden. Vil du fortsatt åpne prosjektet? - + + There was an error updating the project. Some data may not have been preserved. + Det oppsto en feil under oppdateringen av prosjektet. Det er mulig noe data mangler. + + + Opened Project: {0} Åpnet prosjekt: {0} - + Project path not set, cannot save project. Prosjektet mangler filbane, og kan ikke lagres. - - + + Failed to save project. Kunne ikke lagre prosjektet. - + Saved Project: {0} Lagret prosjekt: {0} - + Backing up project ... Lager sikkerhetskopi ... - + Cannot backup project because no valid backup path is set. Please set a valid backup location in Preferences. Kan ikke ta sikkerhetskopi av prosjektet da ingen filbane er satt. Du må først sette en gyldig filbane i Innstillinger. - + Cannot backup project because no project name is set. Please set a Working Title in Project Settings. Kan ikke ta sikkerhetskopi av prosjektet da ingen arbeidstittel er satt. Du må først sette en arbeidstittel i Prosjektinnstillinger. - + Could not create backup folder. Kunne ikke lage mappe til sikkerhetskopi. - + Cannot backup project because the backup path is within the project folder to be backed up. Please choose a different backup path in Preferences. Kan ikke ta sikkerhetskopi av prosjektet da filbanen er inne i prosjektmappen. Du må sette en ny filbane i Innstillinger. - + Backup from {0} Sikkerhetskopi fra {0} - + Backup archive file written to: {0} Sikkerhetskopi skrevet til: {0} - + Could not write backup archive. Kunne ikke lage sikkerhetskopi. - + Project backed up to '{0}' Sikkerhetskopi skrevet til '{0}' - - + + Failed to create a new example project. Kunne ikke lage nytt eksempel-prosjekt. - + Failed to create a new example project. Could not find the necessary files. They seem to be missing from this installation. Kunne ikke lage nytt eksempel-prosjekt. Kunne ikke finne de nødvendige filene. De ser ut til å mangle i denne installasjonen. - + Could not create new project folder. Kunne ikke lage ny prosjekt-mappe. - + New project folder is not empty. Each project requires a dedicated project folder. Ny prosjektmappe er ikke tom. Hvert prosjekt trenger sin egen mappe. - + You must set a valid backup path in Preferences to use the automatic project backup feature. Du må sette en gyldig filbane i innstillingene for å kunne bruke automatisk sikkerhetskopi. - + You must set a valid project name in Project Settings to use the automatic project backup feature. Du må sette en gyldig arbeidstittel i prosjektinnstillingene for å kunne bruke automatisk sikkerhetskopi. - + and og - + Could not create folder. Kunne ikke opprette mappe. - + Found {0} orphaned file(s) in project folder. Fant {0} tapte filer i prosjektmappen. - + Recovered Gjennopprettet - + [{0}] {1} [{0}] {1} - + Recovered File {0} Gjennopprettet fil {0} - + One or more orphaned files could not be added back into the project. Make sure at least a Novel root folder exists. Én eller flere gjennopprettede filer kunne ikke bli lagt til i posjektet. Pass på at "Roman"-mappen i det minste eksisterer. - - - Not a folder: {0} - Ikke en mappe: {0} - - - - Could not move: {0} - Kunne ikke flytte: {0} - - - - - Could not delete: {0} - Kunne ikke slette: {0} - - - - Could not make folder: {0} - Kunne ikke lage mappe: {0} - - - - Could not move item {0} to {1}. - Kunne ikke flytte {0} til {1}. - ProjWizardCustomPage - + Custom Project Options Flere alternativer - - Select which additional root folders to make, and how to populate the Novel folder. If you don't want to add chapters or scenes, set the values to 0. You can add scenes without chapters. - Velg hvilke mapper du ønsker i prosjektet, og hvordan du ønsker å fylle hovedmappen for boken. Hvis du ikke ønsker å legge til kapitler og scener, sett verdiene til 0. Du kan også legge til scener uten å legge til kapitler. + + Select which additional elements to populate the project with. You can skip making chapters and add only scenes by setting the number of chapters to 0. + Velg hvilke ekstra elementer å fylle prosjektet med. Du kan hoppe over å lage kapitler og bare legge til scener ved å sette antallet kapitler til 0. - - Additional Root Folders - Hovedmapper + + Add a folder for plot notes + Legg til en mappe for plott-notater - - - - - - - {0} folder - {0} + + Add a folder for character notes + Legg til en mappe for karakterer - - Populate Novel Folder - Fyll roman-mappen + + Add a folder for location notes + Legg til en mappe for lokasjoner - - Add chapters - Legg til kapitler + + Add example notes to the above + Lag eksempelfiler til ovennevnte - - Scenes (per chapter) - Scener (per kapittel) + + Add chapters to the novel folder + Legg til kapitler i romanmappen - - Add chapter folders - Lag kapittel-mapper + + Add scenes to each chapter + Legg til scener i hvert kapittel ProjWizardFinalPage - - Finished - Ferdig + + Summary + Sammendrag - - All done. - Alt er klart. + + Project Name: {0} + Prosjektnavn: {0} - + + Project Path: {0} + Filbane: {0} + + + + Fill the project with a minimal set of items + Fyll prosjektet med et minimalt innhold + + + + Fill the project with example files + Fyll prosjektet med eksempelfiler + + + + Add a folder for plot notes + Legg til en mappe for plott-notater + + + + Add a folder for character notes + Legg til en mappe for karakterer + + + + Add a folder for location notes + Legg til en mappe for lokasjoner + + + + Add example notes to the above + Lag eksempelfiler til ovennevnte + + + + Add {0} chapters to the novel folder + Legg til {0} kapitler i romanmappen + + + + Add {0} scenes to each chapter + Legg til {0} scener i hvert kapittel + + + + Add {0} scenes + Legg til {0} scener + + + + You have selected the following: + Du har valgt følgende: + + + Press '{0}' to create the new project. Trykk '{0}' for å opprette det nye prosjektet. - + Done Ferdig - + Finish Fullfør @@ -4214,33 +4237,33 @@ ProjWizardFolderPage - - + + Select Project Folder Velg prosjektmappe - + Select a location to store the project. A new project folder will be created in the selected location. Velg et sted hvor prosjektet skal lagres. En mappe for hele prosjektet vil bli opprettet her. - + Required Påkrevd - + Project Path Filbane - + Error: A project folder cannot be created using this path. Feil: En prosjektmappe kan ikke opprettes ved hjelp av denne banen. - + Error: The selected path already exists. Feil: Den valgte banen finnes allerede. @@ -4248,47 +4271,47 @@ ProjWizardIntroPage - + Create New Project Opprett nytt prosjekt - - Provide at least a working title. The working title should not be change beyond this point as it is used by the application for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. - Du må fylle inn minst en arbeidstittel. Du bør ikke endre arbeidstittelen etter at prosjektet er opprettet da denne brukes til blant annet filnavn for sikkerhetskopi. De andre feltene er valgfrie, og kan endres når som helst i Prosjektinstillinger. + + Provide at least a project name. The project name should not be changed beyond this point as it is used for generating file names for for instance backups. The other fields are optional and can be changed at any time in Project Settings. + Du må fylle inn minst et prosjektnavn. Du bør ikke endre prosjektnavnet etter at prosjektet er opprettet da dette brukes til blant annet filnavn for sikkerhetskopi. De andre feltene er valgfrie, og kan endres når som helst i Prosjektinstillinger. - + Side image by {0}, {1} Illustrasjon av {0}, {1} - + Required Påkrevd - + Optional Valgfritt - + Optional. One name per line. Valgfritt. Ett navn per linje. - - Working Title - Arbeidstittel + + Project Name + Prosjektnavn - + Novel Title Bokens tittel - + Author(s) Forfatter(e) @@ -4296,27 +4319,27 @@ ProjWizardPopulatePage - + Populate Project Fyll prosjektet - + Choose how to pre-fill the project. Either with a minimal set of starter items, an example project explaining and showing many of the features, or show further custom options on the next page. Velg hvordan du vil forhåndsfylle prosjektet. Du kan velge mellom et minimalt sett med mapper og filer, et eksempel-prosjekt som forklarer og viser hvordan du bruker programmet, eller se flere valg på neste side. - + Fill the project with a minimal set of items Fyll prosjektet med et minimalt innhold - + Fill the project with example files Fyll prosjektet med eksempelfiler - + Show detailed options for filling the project Vis detaljerte valg for å fylle prosjektet @@ -4512,17 +4535,17 @@ Tokenizer - + Synopsis Sammendrag - + Document '{0}' is too big ({1} MB). Skipping. Dokumentet '{0}' er for stort ({1} MB). Hopper over. - + ERROR FEIL diff --git a/novelwriter/__init__.py b/novelwriter/__init__.py index 0ae10566..55e73ce9 100644 --- a/novelwriter/__init__.py +++ b/novelwriter/__init__.py @@ -60,9 +60,9 @@ __license__ = "GPLv3" __author__ = "Veronica Berglyd Olsen" __maintainer__ = "Veronica Berglyd Olsen" __email__ = "code@vkbo.net" -__version__ = "1.7-beta1" -__hexversion__ = "0x010700b1" -__date__ = "2022-05-17" +__version__ = "2.0-rc1" +__hexversion__ = "0x020000c1" +__date__ = "2022-10-17" __status__ = "Stable" __domain__ = "novelwriter.io" __url__ = "https://novelwriter.io" @@ -72,32 +72,6 @@ __helpurl__ = "https://github.com/vkbo/novelWriter/discussions" __releaseurl__ = "https://github.com/vkbo/novelWriter/releases/latest" __docurl__ = "https://novelwriter.readthedocs.io" -## -# Logging -# ========= -# Standard used for logging levels in novelWriter: -# CRITICAL Use for errors that result in termination of the program -# ERROR Use when an action fails, but execution continues -# WARNING When something unexpected, but non-critical happens -# INFO Any useful user information like open, save, exit initiated -# ----------- SPAM Threshold : Output above should be minimal ----------------- -# DEBUG Use for descriptions of main program flow -# VERBOSE Use for outputting values and program flow details -## - -# Add verbose logging level -VERBOSE = 5 -logging.addLevelName(VERBOSE, "VERBOSE") - - -def logVerbose(self, message, *args, **kws): - if self.isEnabledFor(VERBOSE): - self._log(VERBOSE, message, args, **kws) - - -logging.Logger.verbose = logVerbose - -# Initiating logging logger = logging.getLogger(__name__) @@ -122,7 +96,6 @@ def main(sysArgs=None): "version", "info", "debug", - "verbose", "style=", "config=", "data=", @@ -143,7 +116,6 @@ def main(sysArgs=None): " -v, --version Print program version and exit.\n" " --info Print additional runtime information.\n" " --debug Print debug output. Includes --info.\n" - " --verbose Increase verbosity of debug output. Includes --debug.\n" " --style= Sets Qt5 style flag. Defaults to 'Fusion'.\n" " --config= Alternative config file.\n" " --data= Alternative user data path.\n" @@ -181,9 +153,6 @@ def main(sysArgs=None): elif inOpt == "--debug": logLevel = logging.DEBUG logFormat = "[{asctime:}] {filename:>17}:{lineno:<4d} {levelname:8} {message:}" - elif inOpt == "--verbose": - logLevel = VERBOSE - logFormat = "[{asctime:}] {filename:>17}:{lineno:<4d} {levelname:8} {message:}" elif inOpt == "--style": qtStyle = inArg elif inOpt == "--config": @@ -214,14 +183,14 @@ def main(sysArgs=None): "At least Python 3.7 is required, found %s" % CONFIG.verPyString ) errorCode |= 0x04 - if CONFIG.verQtValue < 50300: + if CONFIG.verQtValue < 51000: errorData.append( - "At least Qt5 version 5.3 is required, found %s" % CONFIG.verQtString + "At least Qt5 version 5.10 is required, found %s" % CONFIG.verQtString ) errorCode |= 0x08 - if CONFIG.verPyQtValue < 50300: + if CONFIG.verPyQtValue < 51000: errorData.append( - "At least PyQt5 version 5.3 is required, found %s" % CONFIG.verPyQtString + "At least PyQt5 version 5.10 is required, found %s" % CONFIG.verPyQtString ) errorCode |= 0x10 diff --git a/novelwriter/assets/icons/typicons_dark/icons.conf b/novelwriter/assets/icons/typicons_dark/icons.conf index 568c5b24..521e9ee8 100644 --- a/novelwriter/assets/icons/typicons_dark/icons.conf +++ b/novelwriter/assets/icons/typicons_dark/icons.conf @@ -18,10 +18,10 @@ licenseurl = https://creativecommons.org/licenses/by-sa/4.0/ [Map] add = typ_plus.svg backward = typ_chevron-left.svg +bookmark = typ_bookmark.svg bullet-off = typ_media-record-outline.svg bullet-on = typ_media-record.svg check = typ_tick.svg -clear = typ_backspace.svg close = typ_times.svg cls_archive = typ_delete.svg cls_character = typ_user.svg @@ -35,17 +35,9 @@ cls_timeline = typ_calendar.svg cls_trash = typ_trash.svg cls_world = typ_location.svg cross = typ_times.svg -delete = typ_delete.svg -doc_h0 = mixed_heading0.svg -doc_h1 = mixed_heading1.svg -doc_h2 = mixed_heading2.svg -doc_h3 = mixed_heading3.svg -doc_h4 = mixed_heading4.svg -done = typ_input-checked.svg down = typ_chevron-down.svg edit = typ_pencil.svg forward = typ_chevron-right.svg -hash = typ_hash.svg maximise = typ_arrow-maximise.svg menu = typ_th-menu.svg minimise = typ_arrow-minimise.svg @@ -54,13 +46,13 @@ proj_details = typ_th-list-grey.svg proj_document = typ_document-text.svg proj_folder = typ_folder.svg proj_note = mixed_document-note.svg +proj_section = mixed_document-section.svg proj_scene = mixed_document-scene.svg proj_stats = typ_chart-bar-grey.svg proj_title = mixed_document-title.svg reference = typ_at.svg refresh = typ_refresh.svg remove = typ_minus.svg -save = typ_download.svg search = typ_search.svg search_cancel = typ_cancel-grey.svg search_case = nw_search-case.svg diff --git a/novelwriter/assets/icons/typicons_dark/mixed_document-section.svg b/novelwriter/assets/icons/typicons_dark/mixed_document-section.svg new file mode 100644 index 00000000..69542bd9 --- /dev/null +++ b/novelwriter/assets/icons/typicons_dark/mixed_document-section.svg @@ -0,0 +1,47 @@ + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/novelwriter/assets/icons/typicons_dark/mixed_heading0.svg b/novelwriter/assets/icons/typicons_dark/mixed_heading0.svg deleted file mode 100644 index 65ca642c..00000000 --- a/novelwriter/assets/icons/typicons_dark/mixed_heading0.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/mixed_heading1.svg b/novelwriter/assets/icons/typicons_dark/mixed_heading1.svg deleted file mode 100644 index faad4e82..00000000 --- a/novelwriter/assets/icons/typicons_dark/mixed_heading1.svg +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/mixed_heading2.svg b/novelwriter/assets/icons/typicons_dark/mixed_heading2.svg deleted file mode 100644 index 08c8ad09..00000000 --- a/novelwriter/assets/icons/typicons_dark/mixed_heading2.svg +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/mixed_heading3.svg b/novelwriter/assets/icons/typicons_dark/mixed_heading3.svg deleted file mode 100644 index b5a35871..00000000 --- a/novelwriter/assets/icons/typicons_dark/mixed_heading3.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/mixed_heading4.svg b/novelwriter/assets/icons/typicons_dark/mixed_heading4.svg deleted file mode 100644 index 718c0746..00000000 --- a/novelwriter/assets/icons/typicons_dark/mixed_heading4.svg +++ /dev/null @@ -1,59 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_backspace.svg b/novelwriter/assets/icons/typicons_dark/typ_backspace.svg deleted file mode 100644 index f0f8ac94..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_backspace.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_bookmark.svg b/novelwriter/assets/icons/typicons_dark/typ_bookmark.svg index e56ebbee..bea4bafa 100644 --- a/novelwriter/assets/icons/typicons_dark/typ_bookmark.svg +++ b/novelwriter/assets/icons/typicons_dark/typ_bookmark.svg @@ -9,9 +9,9 @@ width="24" height="24" viewBox="0 0 24 24" - id="svg2608"> + id="svg901"> + id="metadata907"> @@ -23,9 +23,9 @@ + id="defs905" /> + id="path899" + style="fill:#6699cc;fill-opacity:1;stroke-width:1.05081" /> diff --git a/novelwriter/assets/icons/typicons_dark/typ_download.svg b/novelwriter/assets/icons/typicons_dark/typ_download.svg deleted file mode 100644 index e53e6fca..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_download.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_globe.svg b/novelwriter/assets/icons/typicons_dark/typ_globe.svg deleted file mode 100644 index aef68b3b..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_globe.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_hash.svg b/novelwriter/assets/icons/typicons_dark/typ_hash.svg deleted file mode 100644 index 2b7419ec..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_hash.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_input-checked.svg b/novelwriter/assets/icons/typicons_dark/typ_input-checked.svg deleted file mode 100644 index 0ef2facc..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_input-checked.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_mod_search-replace.svg b/novelwriter/assets/icons/typicons_dark/typ_mod_search-replace.svg deleted file mode 100644 index 588174a5..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_mod_search-replace.svg +++ /dev/null @@ -1,39 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_dark/typ_stopwatch.svg b/novelwriter/assets/icons/typicons_dark/typ_stopwatch.svg deleted file mode 100644 index 345a74d0..00000000 --- a/novelwriter/assets/icons/typicons_dark/typ_stopwatch.svg +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/icons.conf b/novelwriter/assets/icons/typicons_light/icons.conf index 1d6a6c0c..1b6b1348 100644 --- a/novelwriter/assets/icons/typicons_light/icons.conf +++ b/novelwriter/assets/icons/typicons_light/icons.conf @@ -18,10 +18,10 @@ licenseurl = https://creativecommons.org/licenses/by-sa/4.0/ [Map] add = typ_plus.svg backward = typ_chevron-left.svg +bookmark = typ_bookmark.svg bullet-off = typ_media-record-outline.svg bullet-on = typ_media-record.svg check = typ_tick.svg -clear = typ_backspace.svg close = typ_times.svg cls_archive = typ_delete.svg cls_character = typ_user.svg @@ -35,17 +35,9 @@ cls_timeline = typ_calendar.svg cls_trash = typ_trash.svg cls_world = typ_location.svg cross = typ_times.svg -delete = typ_delete.svg -doc_h0 = mixed_heading0.svg -doc_h1 = mixed_heading1.svg -doc_h2 = mixed_heading2.svg -doc_h3 = mixed_heading3.svg -doc_h4 = mixed_heading4.svg -done = typ_input-checked.svg down = typ_chevron-down.svg edit = typ_pencil.svg forward = typ_chevron-right.svg -hash = typ_hash.svg maximise = typ_arrow-maximise.svg menu = typ_th-menu.svg minimise = typ_arrow-minimise.svg @@ -54,13 +46,13 @@ proj_details = typ_th-list-grey.svg proj_document = typ_document-text.svg proj_folder = typ_folder.svg proj_note = mixed_document-note.svg +proj_section = mixed_document-section.svg proj_scene = mixed_document-scene.svg proj_stats = typ_chart-bar-grey.svg proj_title = mixed_document-title.svg reference = typ_at.svg refresh = typ_refresh.svg remove = typ_minus.svg -save = typ_download.svg search = typ_search.svg search_cancel = typ_cancel-grey.svg search_case = nw_search-case.svg diff --git a/novelwriter/assets/icons/typicons_light/mixed_document-section.svg b/novelwriter/assets/icons/typicons_light/mixed_document-section.svg new file mode 100644 index 00000000..28dc015a --- /dev/null +++ b/novelwriter/assets/icons/typicons_light/mixed_document-section.svg @@ -0,0 +1,47 @@ + + + + + + image/svg+xml + + + + + + + + + + + + diff --git a/novelwriter/assets/icons/typicons_light/mixed_heading0.svg b/novelwriter/assets/icons/typicons_light/mixed_heading0.svg deleted file mode 100644 index 87155b79..00000000 --- a/novelwriter/assets/icons/typicons_light/mixed_heading0.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/mixed_heading1.svg b/novelwriter/assets/icons/typicons_light/mixed_heading1.svg deleted file mode 100644 index 89276c97..00000000 --- a/novelwriter/assets/icons/typicons_light/mixed_heading1.svg +++ /dev/null @@ -1,37 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/mixed_heading2.svg b/novelwriter/assets/icons/typicons_light/mixed_heading2.svg deleted file mode 100644 index 5f69658e..00000000 --- a/novelwriter/assets/icons/typicons_light/mixed_heading2.svg +++ /dev/null @@ -1,43 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/mixed_heading3.svg b/novelwriter/assets/icons/typicons_light/mixed_heading3.svg deleted file mode 100644 index b7a33025..00000000 --- a/novelwriter/assets/icons/typicons_light/mixed_heading3.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/mixed_heading4.svg b/novelwriter/assets/icons/typicons_light/mixed_heading4.svg deleted file mode 100644 index 50b0b351..00000000 --- a/novelwriter/assets/icons/typicons_light/mixed_heading4.svg +++ /dev/null @@ -1,55 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_backspace.svg b/novelwriter/assets/icons/typicons_light/typ_backspace.svg deleted file mode 100644 index 167dba0f..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_backspace.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_bookmark.svg b/novelwriter/assets/icons/typicons_light/typ_bookmark.svg index 3936ba30..e7fa1eee 100644 --- a/novelwriter/assets/icons/typicons_light/typ_bookmark.svg +++ b/novelwriter/assets/icons/typicons_light/typ_bookmark.svg @@ -5,13 +5,13 @@ xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" - id="svg2608" - viewBox="0 0 24 24" - height="24" + version="1.2" width="24" - version="1.2"> + height="24" + viewBox="0 0 24 24" + id="svg901"> + id="metadata907"> @@ -23,9 +23,9 @@ + id="defs905" /> + d="M 16.203226,2 H 7.796774 C 6.05874,2 4.6443545,3.4143855 4.6443545,5.1524195 V 19.86371 c 0,0.540115 0.1092839,0.994063 0.3236484,1.350287 0.5926549,0.982504 1.9072138,1.059213 2.9559187,0.0084 L 11.25708,17.889239 c 0.394052,-0.393002 1.091787,-0.393002 1.485841,0 l 3.333158,3.333158 C 16.592024,21.738349 17.128987,22 17.673304,22 c 0.837492,0 1.682342,-0.660957 1.682342,-2.13629 V 5.1524195 C 19.355646,3.4143855 17.941259,2 16.203226,2 Z M 7.796774,4.101613 h 8.406452 c 0.578994,0 1.050806,0.4718121 1.050806,1.0508065 V 15.560658 l -2.575527,-2.361162 c -1.477434,-1.35449 -3.880628,-1.353439 -5.3580615,0 l -2.574476,2.361162 V 5.1524195 c 0,-0.5789944 0.4718121,-1.0508065 1.0508065,-1.0508065 z m 6.431987,12.301792 C 13.635055,15.809699 12.843798,15.482898 12,15.482898 c -0.843797,0 -1.635054,0.327852 -2.2287605,0.920507 l -3.025272,3.025272 v -2.442075 l 3.2848215,-3.011611 c 1.085483,-0.995114 2.851889,-0.995114 3.937372,0 l 3.285871,3.011611 v 2.442075 z" + id="path899" + style="fill:#4271ae;fill-opacity:1;stroke-width:1.05081" /> diff --git a/novelwriter/assets/icons/typicons_light/typ_download.svg b/novelwriter/assets/icons/typicons_light/typ_download.svg deleted file mode 100644 index eb84cf04..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_download.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_globe.svg b/novelwriter/assets/icons/typicons_light/typ_globe.svg deleted file mode 100644 index c6f46eb4..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_globe.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_hash.svg b/novelwriter/assets/icons/typicons_light/typ_hash.svg deleted file mode 100644 index ced3c240..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_hash.svg +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_input-checked.svg b/novelwriter/assets/icons/typicons_light/typ_input-checked.svg deleted file mode 100644 index 6a2124fe..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_input-checked.svg +++ /dev/null @@ -1,35 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - diff --git a/novelwriter/assets/icons/typicons_light/typ_stopwatch.svg b/novelwriter/assets/icons/typicons_light/typ_stopwatch.svg deleted file mode 100644 index 669d84e9..00000000 --- a/novelwriter/assets/icons/typicons_light/typ_stopwatch.svg +++ /dev/null @@ -1,36 +0,0 @@ - - - - - - image/svg+xml - - - - - - - - - - diff --git a/novelwriter/assets/text/release_notes.htm b/novelwriter/assets/text/release_notes.htm index aeb5fbc7..b24ac288 100644 --- a/novelwriter/assets/text/release_notes.htm +++ b/novelwriter/assets/text/release_notes.htm @@ -2,11 +2,11 @@ -

Release Notes for 1.7 Beta 1

-

Released on 17 May 2022

+

Release Notes for 2.0 RC 1

+

Released on 17 October 2022

-

This is a beta release of the next release version, and is intended for testing purposes. Please -be careful when using this version on live writing projects, and make sure you take frequent +

This is a release candidate of the next release version, and is intended for testing purposes. +Please be careful when using this version on live writing projects, and make sure you take frequent backups.

Please check the changelog for an overview of changes. The full release notes will be added to the final release.

diff --git a/novelwriter/common.py b/novelwriter/common.py index 69f6bc05..60d1f7fa 100644 --- a/novelwriter/common.py +++ b/novelwriter/common.py @@ -35,7 +35,7 @@ from PyQt5.QtCore import QCoreApplication from PyQt5.QtWidgets import qApp from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout -from novelwriter.error import logException +from novelwriter.error import formatException, logException from novelwriter.constants import nwConst, nwUnicode logger = logging.getLogger(__name__) @@ -45,52 +45,54 @@ logger = logging.getLogger(__name__) # Checker Functions # =============================================================================================== # -def checkString(value, default, allowNone=False): +def checkStringNone(value, default): """Check if a variable is a string or a None. """ - if allowNone and (value is None or value == "None"): + if value is None or value == "None": return None if isinstance(value, str): return str(value) return default -def checkInt(value, default, allowNone=False): - """Check if a variable is an integer or a None. +def checkString(value, default): + """Check if a variable is a string. + """ + if isinstance(value, str): + return str(value) + return default + + +def checkInt(value, default): + """Check if a variable is an integer. """ - if allowNone and (value is None or value == "None"): - return None try: return int(value) except Exception: return default -def checkFloat(value, default, allowNone=False): - """Check if a variable is a float or a None. +def checkFloat(value, default): + """Check if a variable is a float. """ - if allowNone and (value is None or value == "None"): - return None try: return float(value) except Exception: return default -def checkBool(value, default, allowNone=False): - """Check if a variable is a boolean or a None. +def checkBool(value, default): + """Check if a variable is a boolean. """ - if allowNone and (value is None or value == "None"): - return None - - if isinstance(value, str): + if isinstance(value, bool): + return value + elif isinstance(value, str): if value == "True": return True elif value == "False": return False else: return default - elif isinstance(value, int): if value == 1: return True @@ -98,7 +100,6 @@ def checkBool(value, default, allowNone=False): return False else: return default - return default @@ -174,16 +175,6 @@ def hexToInt(value, default=0): return default -def checkIntRange(value, first, last, default): - """Check that an int is in a given range. If it isn't, return the - default value. - """ - if isinstance(value, int): - if value >= first and value <= last: - return value - return default - - def minmax(value, minVal, maxVal): """Make sure an integer is between min and max value (inclusive). """ @@ -225,25 +216,25 @@ def formatInt(value): return str(value) -def formatTimeStamp(theTime, fileSafe=False): +def formatTimeStamp(value, fileSafe=False): """Take a number (on the format returned by time.time()) and convert it to a timestamp string. """ if fileSafe: - return datetime.fromtimestamp(theTime).strftime(nwConst.FMT_FSTAMP) + return datetime.fromtimestamp(value).strftime(nwConst.FMT_FSTAMP) else: - return datetime.fromtimestamp(theTime).strftime(nwConst.FMT_TSTAMP) + return datetime.fromtimestamp(value).strftime(nwConst.FMT_TSTAMP) -def formatTime(tS): +def formatTime(t): """Format a time in seconds in HH:MM:SS format or d-HH:MM:SS format if a full day or longer. """ - if isinstance(tS, int): - if tS >= 86400: - return f"{tS//86400:d}-{tS%86400//3600:02d}:{tS%3600//60:02d}:{tS%60:02d}" + if isinstance(t, int): + if t >= 86400: + return f"{t//86400:d}-{t%86400//3600:02d}:{t%3600//60:02d}:{t%60:02d}" else: - return f"{tS//3600:02d}:{tS%3600//60:02d}:{tS%60:02d}" + return f"{t//3600:02d}:{t%3600//60:02d}:{t%60:02d}" return "ERROR" @@ -263,7 +254,7 @@ def splitVersionNumber(value): and patch, and computes an integer value aabbcc. """ if not isinstance(value, str): - return [0, 0, 0, 0] + return 0, 0, 0, 0 vMajor = 0 vMinor = 0 @@ -282,114 +273,114 @@ def splitVersionNumber(value): vInt = vMajor*10000 + vMinor*100 + vPatch - return [vMajor, vMinor, vPatch, vInt] + return vMajor, vMinor, vPatch, vInt -def transferCase(theSource, theTarget): +def transferCase(source, target): """Transfers the case of the source word to the target word. This will consider all upper or lower, and first char capitalisation. """ - theResult = theTarget + theResult = target - if not isinstance(theSource, str) or not isinstance(theTarget, str): + if not isinstance(source, str) or not isinstance(target, str): return theResult - if len(theTarget) < 1 or len(theSource) < 1: + if len(target) < 1 or len(source) < 1: return theResult - if theSource.istitle(): - theResult = theTarget.title() + if source.istitle(): + theResult = target.title() - if theSource.isupper(): - theResult = theTarget.upper() - elif theSource.islower(): - theResult = theTarget.lower() + if source.isupper(): + theResult = target.upper() + elif source.islower(): + theResult = target.lower() return theResult -def fuzzyTime(secDiff): +def fuzzyTime(seconds): """Converts a time difference in seconds into a fuzzy time string. """ - if secDiff < 0: + if seconds < 0: return QCoreApplication.translate( "Common", "in the future" ) - elif secDiff < 30: + elif seconds < 30: return QCoreApplication.translate( "Common", "just now" ) - elif secDiff < 90: + elif seconds < 90: return QCoreApplication.translate( "Common", "a minute ago" ) - elif secDiff < 3300: # 55 minutes + elif seconds < 3300: # 55 minutes return QCoreApplication.translate( "Common", "{0} minutes ago" - ).format(int(round(secDiff/60))) - elif secDiff < 5400: # 90 minutes + ).format(int(round(seconds/60))) + elif seconds < 5400: # 90 minutes return QCoreApplication.translate( "Common", "an hour ago" ) - elif secDiff < 84600: # 23.5 hours + elif seconds < 84600: # 23.5 hours return QCoreApplication.translate( "Common", "{0} hours ago" - ).format(int(round(secDiff/3600))) - elif secDiff < 129600: # 1.5 days + ).format(int(round(seconds/3600))) + elif seconds < 129600: # 1.5 days return QCoreApplication.translate( "Common", "a day ago" ) - elif secDiff < 561600: # 6.5 days + elif seconds < 561600: # 6.5 days return QCoreApplication.translate( "Common", "{0} days ago" - ).format(int(round(secDiff/86400))) - elif secDiff < 907200: # 10.5 days + ).format(int(round(seconds/86400))) + elif seconds < 907200: # 10.5 days return QCoreApplication.translate( "Common", "a week ago" ) - elif secDiff < 2419200: # 28 days + elif seconds < 2419200: # 28 days return QCoreApplication.translate( "Common", "{0} weeks ago" - ).format(int(round(secDiff/604800))) - elif secDiff < 3888000: # 45 days + ).format(int(round(seconds/604800))) + elif seconds < 3888000: # 45 days return QCoreApplication.translate( "Common", "a month ago" ) - elif secDiff < 29808000: # 345 days + elif seconds < 29808000: # 345 days return QCoreApplication.translate( "Common", "{0} months ago" - ).format(int(round(secDiff/2592000))) - elif secDiff < 47336400: # 1.5 years + ).format(int(round(seconds/2592000))) + elif seconds < 47336400: # 1.5 years return QCoreApplication.translate( "Common", "a year ago" ) else: return QCoreApplication.translate( "Common", "{0} years ago" - ).format(int(round(secDiff/31557600))) + ).format(int(round(seconds/31557600))) -def numberToRoman(numVal, toLower=False): +def numberToRoman(value, toLower=False): """Convert an integer to a Roman number. """ - if not isinstance(numVal, int): + if not isinstance(value, int): return "NAN" - if numVal < 1 or numVal > 4999: + if value < 1 or value > 4999: return "OOR" - theValues = [ + lookup = [ (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I"), ] - romNum = "" - for theDiv, theSym in theValues: - n = numVal//theDiv - romNum += n*theSym - numVal -= n*theDiv - if numVal <= 0: + roman = "" + for divisor, symbol in lookup: + n = value//divisor + roman += n*symbol + value -= n*divisor + if value <= 0: break - return romNum.lower() if toLower else romNum + return roman.lower() if toLower else roman # =============================================================================================== # @@ -447,51 +438,70 @@ def jsonEncode(data, n=0, nmax=0): # File and File System Functions # =============================================================================================== # -def readTextFile(filePath): +def readTextFile(path): """Read the content of a text file in a robust manner. """ - if not os.path.isfile(filePath): + if not os.path.isfile(path): return "" - fileText = "" + text = "" try: - with open(filePath, mode="r", encoding="utf-8") as inFile: - fileText = inFile.read() + with open(path, mode="r", encoding="utf-8") as inFile: + text = inFile.read() except Exception: - logger.error("Could not read file: %s", filePath) + logger.error("Could not read file: %s", path) logException() return "" - return fileText + return text def makeFileNameSafe(value): """Returns a filename safe string of the value. """ - cleanName = "" + clean = "" for c in str(value).strip(): if c.isalpha() or c.isdigit() or c == " ": - cleanName += c - return cleanName + clean += c + return clean -def sha256sum(filePath): +def ensureFolder(path, parent=None, errLog=None): + """Make sure a folder exists, and if it doesn't, create it. + """ + try: + if parent: + path = os.path.join(parent, path) + if not os.path.isdir(path): + os.mkdir(path) + except Exception as exc: + logger.error("Could not create folder: %s", path) + logException() + if isinstance(errLog, list): + errLog.append(f"Could not create folder: {path}") + errLog.append(formatException(exc)) + return False + + return True + + +def sha256sum(path): """Make a shasum of a file using a buffer. Based on: https://stackoverflow.com/a/44873382/5825851 """ - hDigest = hashlib.sha256() + digest = hashlib.sha256() bData = bytearray(65536) mData = memoryview(bData) try: - with open(filePath, mode="rb", buffering=0) as inFile: + with open(path, mode="rb", buffering=0) as inFile: for n in iter(lambda: inFile.readinto(mData), 0): - hDigest.update(mData[:n]) + digest.update(mData[:n]) except Exception: - logger.error("Could not create sha256sum of: %s", filePath) + logger.error("Could not create sha256sum of: %s", path) logException() return None - return hDigest.hexdigest() + return digest.hexdigest() # =============================================================================================== # @@ -513,87 +523,59 @@ def getGuiItem(objName): class NWConfigParser(ConfigParser): - CNF_STR = 0 - CNF_INT = 1 - CNF_FLOAT = 2 - CNF_BOOL = 3 - CNF_S_LST = 4 - CNF_I_LST = 5 - def __init__(self): super().__init__() def rdStr(self, section, option, default): """Read string value. """ - return self._parseLine(section, option, default, self.CNF_STR) + return self.get(section, option, fallback=default) def rdInt(self, section, option, default): """Read integer value. """ - return self._parseLine(section, option, default, self.CNF_INT) + try: + return self.getint(section, option, fallback=default) + except ValueError: + logger.error("Could not read '%s':'%s' from config", section, option) + return default def rdFlt(self, section, option, default): """Read float value. """ - return self._parseLine(section, option, default, self.CNF_FLOAT) + try: + return self.getfloat(section, option, fallback=default) + except ValueError: + logger.error("Could not read '%s':'%s' from config", section, option) + return default def rdBool(self, section, option, default): """Read boolean value. """ - return self._parseLine(section, option, default, self.CNF_BOOL) + try: + return self.getboolean(section, option, fallback=default) + except ValueError: + logger.error("Could not read '%s':'%s' from config", section, option) + return default def rdStrList(self, section, option, default): """Read string list. """ - return self._parseLine(section, option, default, self.CNF_S_LST) + result = default.copy() if isinstance(default, list) else [] + if self.has_option(section, option): + data = self.get(section, option, fallback="").split(",") + for i in range(min(len(data), len(result))): + result[i] = data[i].strip() + return result def rdIntList(self, section, option, default): """Read integer list. """ - return self._parseLine(section, option, default, self.CNF_I_LST) - - ## - # Internal Functions - ## - - def _unpackList(self, value, default, type): - """Unpack a comma-separated string of items into a list. - """ - inList = value.split(",") - outList = [] - if isinstance(default, list): - outList = default.copy() - for i in range(min(len(inList), len(outList))): - try: - if type == self.CNF_S_LST: - outList[i] = inList[i].strip() - elif type == self.CNF_I_LST: - outList[i] = int(inList[i].strip()) - except Exception: - continue - return outList - - def _parseLine(self, section, option, default, type): - """Parse a line and return the correct datatype. - """ + result = default.copy() if isinstance(default, list) else [] if self.has_option(section, option): - try: - if type == self.CNF_STR: - return self.get(section, option) - elif type == self.CNF_INT: - return self.getint(section, option) - elif type == self.CNF_FLOAT: - return self.getfloat(section, option) - elif type == self.CNF_BOOL: - return self.getboolean(section, option) - elif type in (self.CNF_I_LST, self.CNF_S_LST): - return self._unpackList(self.get(section, option), default, type) - except ValueError: - logger.error("Could not read '%s':'%s' from config", str(section), str(option)) - logException() - return default - - return default + data = self.get(section, option, fallback="").split(",") + for i in range(min(len(data), len(result))): + result[i] = checkInt(data[i].strip(), result[i]) + return result # END Class NWConfigParser diff --git a/novelwriter/config.py b/novelwriter/config.py index 81487a16..73a8c3c6 100644 --- a/novelwriter/config.py +++ b/novelwriter/config.py @@ -37,7 +37,7 @@ from PyQt5.QtCore import ( ) from novelwriter.error import logException, formatException -from novelwriter.common import splitVersionNumber, formatTimeStamp, NWConfigParser +from novelwriter.common import ensureFolder, splitVersionNumber, formatTimeStamp, NWConfigParser from novelwriter.constants import nwFiles, nwUnicode logger = logging.getLogger(__name__) @@ -52,25 +52,22 @@ class Config: # Set Application Variables self.appName = "novelWriter" - self.appHandle = self.appName.lower() - - # Config Error Handling - self.hasError = False # True if the config class encountered an error - self.errData = [] # List of error messages + self.appHandle = "novelwriter" # Set Paths - self.cmdOpen = None # Path from command line for project to be opened on launch - self.confPath = None # Folder where the config is saved - self.confFile = None # The config file name - self.dataPath = None # Folder where app data is stored - self.lastPath = None # The last user-selected folder (browse dialogs) - self.appPath = None # The full path to the novelwriter package folder - self.appRoot = None # The full path to the novelwriter root folder - self.appIcon = None # The full path to the novelwriter icon file - self.assetPath = None # The full path to the novelwriter/assets folder - self.pdfDocs = None # The location of the PDF manual, if it exists + self.cmdOpen = None # Path from command line for project to be opened on launch + self.confPath = None # Folder where the config is saved + self.dataPath = None # Folder where app data is stored + self.lastPath = None # The last user-selected folder (browse dialogs) + self.appPath = None # The full path to the novelwriter package folder + self.appRoot = None # The full path to the novelwriter root folder + self.appIcon = None # The full path to the novelwriter icon file + self.assetPath = None # The full path to the novelwriter/assets folder + self.pdfDocs = None # The location of the PDF manual, if it exists # Runtime Settings and Variables + self.hasError = False # True if the config class encountered an error + self.errData = [] # List of error messages self.confChanged = False # True whenever the config has chenged, false after save # General @@ -94,14 +91,14 @@ class Config: self.qtTrans = {} # Sizes - self.winGeometry = [1200, 650] - self.prefGeometry = [700, 615] - self.projColWidth = [200, 60, 140] - self.mainPanePos = [300, 800] - self.docPanePos = [400, 400] - self.viewPanePos = [500, 150] - self.outlnPanePos = [500, 150] - self.isFullScreen = False + self.winGeometry = [1200, 650] + self.prefGeometry = [700, 615] + self.projColWidth = [200, 60, 140] + self.mainPanePos = [300, 800] + self.docPanePos = [400, 400] + self.viewPanePos = [500, 150] + self.outlnPanePos = [500, 150] + self.isFullScreen = False # Features self.hideVScroll = False # Hide vertical scroll bars on main widgets @@ -220,8 +217,8 @@ class Config: self.osUnknown = True # Other System Info - self.hostName = "Unknown" - self.kernelVer = "Unknown" + self.hostName = QSysInfo.machineHostName() + self.kernelVer = QSysInfo.kernelVersion() # Packages self.hasEnchant = False # The pyenchant package @@ -264,31 +261,15 @@ class Config: self.confPath = confPath if dataPath is None: - if self.verQtValue >= 50400: - dataRoot = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) - else: - dataRoot = QStandardPaths.writableLocation(QStandardPaths.DataLocation) + dataRoot = QStandardPaths.writableLocation(QStandardPaths.AppDataLocation) self.dataPath = os.path.join(os.path.abspath(dataRoot), self.appHandle) else: logger.info("Setting data path from alternative path: %s", dataPath) self.dataPath = dataPath - logger.verbose("Config path: %s", self.confPath) - logger.verbose("Data path: %s", self.dataPath) + logger.debug("Config path: %s", self.confPath) + logger.debug("Data path: %s", self.dataPath) - # Check Data Path Subdirs - dataDirs = ["syntax", "themes"] - for dataDir in dataDirs: - dirPath = os.path.join(self.dataPath, dataDir) - if not os.path.isdir(dirPath): - try: - os.mkdir(dirPath) - logger.info("Created folder: %s", dirPath) - except Exception: - logger.error("Could not create folder: %s", dirPath) - logException() - - self.confFile = self.appHandle+".conf" self.lastPath = os.path.expanduser("~") self.appPath = getattr(sys, "_MEIPASS", os.path.abspath(os.path.dirname(__file__))) self.appRoot = os.path.abspath(os.path.join(self.appPath, os.path.pardir)) @@ -308,50 +289,33 @@ class Config: self.nwLangPath = os.path.join(self.assetPath, "i18n") logger.debug("Assets: %s", self.assetPath) - logger.verbose("App path: %s", self.appPath) - logger.verbose("Last path: %s", self.lastPath) + logger.debug("App path: %s", self.appPath) + logger.debug("Last path: %s", self.lastPath) - # If the config folder does not exist, create it. - # This assumes that the os config folder itself exists. - if not os.path.isdir(self.confPath): - try: - os.mkdir(self.confPath) - except Exception as exc: - logger.error("Could not create folder: %s", self.confPath) - logException() - self.hasError = True - self.errData.append("Could not create folder: %s" % self.confPath) - self.errData.append(formatException(exc)) - self.confPath = None + # If the config and data folders don't not exist, create them + # This assumes that the os config and data folders exist + if not ensureFolder(self.confPath, errLog=self.errData): + self.hasError = True + self.confPath = None + + if not ensureFolder(self.dataPath, errLog=self.errData): + self.hasError = True + self.dataPath = None + + # We don't error on these failing since they are not essential + if self.dataPath is not None: + ensureFolder("syntax", parent=self.dataPath) + ensureFolder("themes", parent=self.dataPath) # Check if config file exists if self.confPath is not None: - if os.path.isfile(os.path.join(self.confPath, self.confFile)): + if os.path.isfile(os.path.join(self.confPath, nwFiles.CONF_FILE)): # If it exists, load it self.loadConfig() else: # If it does not exist, save a copy of the default values self.saveConfig() - # If the data folder does not exist, create it. - # This assumes that the os data folder itself exists. - if self.dataPath is not None: - if not os.path.isdir(self.dataPath): - try: - os.mkdir(self.dataPath) - except Exception as exc: - logger.error("Could not create folder: %s", self.dataPath) - logException() - self.hasError = True - self.errData.append("Could not create folder: %s" % self.dataPath) - self.errData.append(formatException(exc)) - self.dataPath = None - - # Host and Kernel - if self.verQtValue >= 50600: - self.hostName = QSysInfo.machineHostName() - self.kernelVer = QSysInfo.kernelVersion() - # Load recent projects cache self.loadRecentCache() @@ -397,7 +361,7 @@ class Config: def listLanguages(self, lngSet): """List localisation files in the i18n folder. The default GUI - language 'en_GB' is British English. + language is British English (en_GB). """ if lngSet == self.LANG_NW: fPre = "nw_" @@ -430,7 +394,7 @@ class Config: return False theConf = NWConfigParser() - cnfPath = os.path.join(self.confPath, self.confFile) + cnfPath = os.path.join(self.confPath, nwFiles.CONF_FILE) try: with open(cnfPath, mode="r", encoding="utf-8") as inFile: theConf.read_file(inFile) @@ -653,7 +617,7 @@ class Config: } # Write config file - cnfPath = os.path.join(self.confPath, self.confFile) + cnfPath = os.path.join(self.confPath, nwFiles.CONF_FILE) try: with open(cnfPath, mode="w", encoding="utf-8") as outFile: theConf.write(outFile) @@ -738,7 +702,7 @@ class Config: """ if thePath in self.recentProj: del self.recentProj[thePath] - logger.verbose("Removed recent: %s", thePath) + logger.debug("Removed recent: %s", thePath) self.saveRecentCache() else: logger.error("Unknown recent: %s", thePath) @@ -749,29 +713,6 @@ class Config: # Setters ## - def setConfPath(self, newPath): - """Set the path and filename to the config file. - """ - if newPath is None: - return True - if not os.path.isfile(newPath): - logger.error("File not found, using default config path instead") - return False - self.confPath = os.path.dirname(newPath) - self.confFile = os.path.basename(newPath) - return True - - def setDataPath(self, newPath): - """Set the data path. - """ - if newPath is None: - return True - if not os.path.isdir(newPath): - logger.error("Path not found, using default data path instead") - return False - self.dataPath = os.path.abspath(newPath) - return True - def setLastPath(self, lastPath): """Set the last used path (by the user). """ diff --git a/novelwriter/constants.py b/novelwriter/constants.py index 3d1b5c13..87293a52 100644 --- a/novelwriter/constants.py +++ b/novelwriter/constants.py @@ -68,6 +68,7 @@ class nwHeaders: class nwFiles: + CONF_FILE = "novelwriter.conf" PROJ_FILE = "nwProject.nwx" PROJ_DICT = "wordlist.txt" PROJ_LOCK = "nwProject.lock" @@ -157,6 +158,7 @@ class nwLabels: "doc_h1": QT_TRANSLATE_NOOP("Constant", "Novel Title Page"), "doc_h2": QT_TRANSLATE_NOOP("Constant", "Novel Chapter"), "doc_h3": QT_TRANSLATE_NOOP("Constant", "Novel Scene"), + "doc_h4": QT_TRANSLATE_NOOP("Constant", "Novel Section"), "note": QT_TRANSLATE_NOOP("Constant", "Project Note"), } KEY_NAME = { diff --git a/novelwriter/core/__init__.py b/novelwriter/core/__init__.py index c91ca941..f1b5dfd3 100644 --- a/novelwriter/core/__init__.py +++ b/novelwriter/core/__init__.py @@ -19,6 +19,7 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ +from novelwriter.core.doctools import DocMerger, DocSplitter from novelwriter.core.document import NWDoc from novelwriter.core.index import countWords from novelwriter.core.project import NWProject @@ -28,6 +29,8 @@ from novelwriter.core.toodt import ToOdt from novelwriter.core.tomd import ToMarkdown __all__ = [ + "DocMerger", + "DocSplitter", "countWords", "NWDoc", "NWProject", diff --git a/novelwriter/core/doctools.py b/novelwriter/core/doctools.py new file mode 100644 index 00000000..54cb9d25 --- /dev/null +++ b/novelwriter/core/doctools.py @@ -0,0 +1,240 @@ +""" +novelWriter – Project Document Tools +==================================== +A collection of tools to create and manipulate documents + +File History: +Created: 2022-10-02 [2.0b1] DocMerger +Created: 2022-10-11 [2.0b1] DocSplitter + +This file is a part of novelWriter +Copyright 2018–2022, Veronica Berglyd Olsen + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + +import logging + +from novelwriter.common import minmax +from novelwriter.core.document import NWDoc + +logger = logging.getLogger(__name__) + + +class DocMerger: + + def __init__(self, theProject): + + self.theProject = theProject + + self._error = "" + self._targetDoc = None + self._targetText = [] + + return + + ## + # Methods + ## + + def getError(self): + """Return any collected errors. + """ + return self._error + + def setTargetDoc(self, tHandle): + """Set the target document for the merging. Calling this + function resets the class. + """ + self._targetDoc = tHandle + self._targetText = [] + return + + def newTargetDoc(self, srcHandle, docLabel): + """Create a barnd new target document based on a source handle + and a new doc label. Calling this function resets the class. + """ + srcItem = self.theProject.tree[srcHandle] + if srcItem is None: + return None + + newHandle = self.theProject.newFile(docLabel, srcItem.itemParent) + newItem = self.theProject.tree[newHandle] + newItem.setLayout(srcItem.itemLayout) + newItem.setStatus(srcItem.itemStatus) + newItem.setImport(srcItem.itemImport) + + self._targetDoc = newHandle + self._targetText = [] + + return newHandle + + def appendText(self, srcHandle, addComment, cmtPrefix): + """Append text from an existing document to the text buffer. + """ + srcItem = self.theProject.tree[srcHandle] + if srcItem is None: + return False + + inDoc = NWDoc(self.theProject, srcHandle) + docText = (inDoc.readDocument() or "").rstrip("\n") + + if addComment: + docInfo = srcItem.describeMe() + docSt, _ = srcItem.getImportStatus(incIcon=False) + cmtLine = f"% {cmtPrefix} {docInfo}: {srcItem.itemName} [{docSt}]\n\n" + docText = cmtLine + docText + + self._targetText.append(docText) + + return True + + def writeTargetDoc(self): + """Write the accumulated text into the designated target + document, appending any existing text. + """ + if self._targetDoc is None: + return False + + outDoc = NWDoc(self.theProject, self._targetDoc) + docText = (outDoc.readDocument() or "").rstrip("\n") + if docText: + self._targetText.insert(0, docText) + + status = outDoc.writeDocument("\n\n".join(self._targetText) + "\n\n") + if not status: + self._error = outDoc.getError() + + return status + +# END Class DocMerger + + +class DocSplitter: + + def __init__(self, theProject, sHandle): + + self.theProject = theProject + + self._error = "" + self._parHandle = None + self._srcHandle = None + self._srcItem = None + + self._inFolder = False + self._rawData = [] + + srcItem = self.theProject.tree[sHandle] + if srcItem is not None and srcItem.isFileType(): + self._srcHandle = sHandle + self._srcItem = srcItem + + return + + ## + # Methods + ## + + def getError(self): + """Return any collected errors. + """ + return self._error + + def setParentItem(self, pHandle): + """Set the item that will be the top level parent item for the + new documents. + """ + self._parHandle = pHandle + self._inFolder = False + return + + def newParentFolder(self, pHandle, folderLabel): + """Create a new folder that will be the top level parent item + for the new documents. + """ + if self._srcItem is None: + return None + + newHandle = self.theProject.newFolder(folderLabel, pHandle) + newItem = self.theProject.tree[newHandle] + newItem.setStatus(self._srcItem.itemStatus) + newItem.setImport(self._srcItem.itemImport) + + self._parHandle = newHandle + self._inFolder = True + + return newHandle + + def splitDocument(self, splitData, splitText): + """Loop through the split data record and perform the split job. + """ + self._rawData = [] + buffer = splitText.copy() + for lineNo, hLevel, hLabel in reversed(splitData): + chunk = buffer[lineNo:] + buffer = buffer[:lineNo] + self._rawData.insert(0, (chunk, hLevel, hLabel)) + + return True + + def writeDocuments(self, docHierarchy): + """An iterator that will write each document in the buffer, and + return its new handle, parent handle, and sibling handle. + """ + if self._srcHandle is None: + return + + pHandle = self._parHandle + nHandle = self._parHandle if self._inFolder else self._srcHandle + hHandle = [self._parHandle, None, None, None, None] + + pLevel = 0 + for docText, hLevel, docLabel in self._rawData: + + hLevel = minmax(hLevel, 1, 4) + if pLevel == 0: + pLevel = hLevel + + if docHierarchy: + if hLevel == 1: + pHandle = self._parHandle + elif hLevel == 2: + pHandle = hHandle[1] or hHandle[0] + elif hLevel == 3: + pHandle = hHandle[2] or hHandle[1] or hHandle[0] + elif hLevel == 4: + pHandle = hHandle[3] or hHandle[2] or hHandle[1] or hHandle[0] + + if hLevel < pLevel: + nHandle = hHandle[hLevel] or hHandle[0] + elif hLevel > pLevel: + nHandle = pHandle + + dHandle = self.theProject.newFile(docLabel, pHandle) + hHandle[hLevel] = dHandle + + outDoc = NWDoc(self.theProject, dHandle) + status = outDoc.writeDocument("\n".join(docText)) + if not status: + self._error = outDoc.getError() + + yield status, dHandle, nHandle + + hHandle[hLevel] = dHandle + nHandle = dHandle + pLevel = hLevel + + return + +# END Class DocSplitter diff --git a/novelwriter/core/document.py b/novelwriter/core/document.py index 5420d44e..672fbee5 100644 --- a/novelwriter/core/document.py +++ b/novelwriter/core/document.py @@ -33,7 +33,7 @@ from novelwriter.common import isHandle, sha256sum logger = logging.getLogger(__name__) -class NWDoc(): +class NWDoc: def __init__(self, theProject, theHandle): diff --git a/novelwriter/core/index.py b/novelwriter/core/index.py index 7ea713b6..1058628b 100644 --- a/novelwriter/core/index.py +++ b/novelwriter/core/index.py @@ -176,7 +176,7 @@ class NWIndex: self._indexChange = round(time()) - logger.verbose("Index loaded in %.3f ms", (time() - tStart)*1000) + logger.debug("Index loaded in %.3f ms", (time() - tStart)*1000) return True @@ -202,7 +202,7 @@ class NWIndex: logException() return False - logger.verbose("Index saved in %.3f ms", (time() - tStart)*1000) + logger.debug("Index saved in %.3f ms", (time() - tStart)*1000) return True @@ -243,20 +243,43 @@ class NWIndex: if theItem.itemParent is None: logger.info("Not indexing orphaned item '%s'", tHandle) return False - if theItem.isInactive(): - logger.debug("Not indexing inactive item '%s'", tHandle) - return False logger.debug("Indexing item with handle '%s'", tHandle) + if theItem.isInactive(): + self._scanInactive(theItem, theText) + else: + self._scanActive(tHandle, theItem, theText, itemTags) - # Scan the text content + # Update timestamps for index changes + nowTime = round(time()) + self._indexChange = nowTime + self._rootChange[theItem.itemRoot] = nowTime + + return True + + ## + # Internal Indexer Helpers + ## + + def _scanActive(self, tHandle, theItem, theText, itemTags): + """Scan an active document for meta data. + """ nTitle = 0 + findHeader = True theLines = theText.splitlines() + for nLine, aLine in enumerate(theLines, start=1): + if len(aLine.strip()) == 0: continue if aLine.startswith("#"): + if findHeader: + hDepth, _ = self._splitHeading(aLine) + if hDepth != "H0": + theItem.setMainHeading(hDepth) + findHeader = False + isTitle = self._indexTitle(tHandle, aLine, nLine) if isTitle and nLine > 0: if nTitle > 0: @@ -289,48 +312,49 @@ class NWIndex: # Prune no longer used tags for tTag, isActive in itemTags.items(): if not isActive: - logger.verbose("Deleting removed tag '%s'", tTag) + logger.debug("Deleting removed tag '%s'", tTag) del self._tagsIndex[tTag] - # Update timestamps for index changes - nowTime = round(time()) - self._indexChange = nowTime - self._rootChange[theItem.itemRoot] = nowTime + return - return True + def _scanInactive(self, theItem, theText): + """Scan an inactive document for meta data. + """ + for aLine in theText.splitlines(): + if aLine.startswith("#"): + hDepth, _ = self._splitHeading(aLine) + if hDepth != "H0": + theItem.setMainHeading(hDepth) + break + return - ## - # Internal Indexer Helpers - ## + def _splitHeading(self, aLine): + """Split a heading into its header level and text value. + """ + if aLine.startswith("# "): + return "H1", aLine[2:].strip() + elif aLine.startswith("## "): + return "H2", aLine[3:].strip() + elif aLine.startswith("### "): + return "H3", aLine[4:].strip() + elif aLine.startswith("#### "): + return "H4", aLine[5:].strip() + elif aLine.startswith("#! "): + return "H1", aLine[3:].strip() + elif aLine.startswith("##! "): + return "H2", aLine[4:].strip() + return "H0", "" def _indexTitle(self, tHandle, aLine, nTitle): """Save information about the title and its location in the file to the index. """ - if aLine.startswith("# "): - hDepth = "H1" - hText = aLine[2:].strip() - elif aLine.startswith("## "): - hDepth = "H2" - hText = aLine[3:].strip() - elif aLine.startswith("### "): - hDepth = "H3" - hText = aLine[4:].strip() - elif aLine.startswith("#### "): - hDepth = "H4" - hText = aLine[5:].strip() - elif aLine.startswith("#! "): - hDepth = "H1" - hText = aLine[3:].strip() - elif aLine.startswith("##! "): - hDepth = "H2" - hText = aLine[4:].strip() - else: + hDepth, hText = self._splitHeading(aLine) + if hDepth == "H0": return False sTitle = f"T{nTitle:06d}" self._itemIndex.addItemHeading(tHandle, sTitle, hDepth, hText) - return True def _indexWordCounts(self, tHandle, theText, nTitle): @@ -493,18 +517,15 @@ class NWIndex: for sTitle, hItem in self._itemIndex.iterItemHeaders(tHandle) ] - def getHandleHeaderLevel(self, tHandle): - """Get the header level of the first header of a handle. - """ - return self._itemIndex.mainItemHeader(tHandle) - - def getTableOfContents(self, maxDepth, skipExcl=True): + def getTableOfContents(self, rootHandle, maxDepth, skipExcl=True): """Generate a table of contents up to a maximum depth. """ tOrder = [] tData = {} pKey = None - for tHandle, sTitle, hItem in self._itemIndex.iterNovelStructure(skipExcl=skipExcl): + for tHandle, sTitle, hItem in self._itemIndex.iterNovelStructure( + rootHandle=rootHandle, skipExcl=skipExcl + ): tKey = f"{tHandle}:{sTitle}" iLevel = nwHeaders.H_LEVEL.get(hItem.level, 0) if iLevel > maxDepth: @@ -647,23 +668,17 @@ class TagsIndex: def tagHandle(self, tagKey): """Get the handle of a given tag. """ - if tagKey in self._tags: - return self._tags.get(tagKey).get("handle") - return None + return self._tags.get(tagKey, {}).get("handle", None) def tagHeading(self, tagKey): """Get the heading of a given tag. """ - if tagKey in self._tags: - return self._tags.get(tagKey).get("heading") - return nwHeaders.TT_NONE + return self._tags.get(tagKey, {}).get("heading", nwHeaders.TT_NONE) def tagClass(self, tagKey): """Get the class of a given tag. """ - if tagKey in self._tags: - return self._tags.get(tagKey).get("class") - return None + return self._tags.get(tagKey, {}).get("class", None) ## # Pack/Unpack @@ -755,13 +770,6 @@ class ItemIndex: self._items[tHandle] = IndexItem(tHandle, tItem) return - def mainItemHeader(self, tHandle): - """Return the primary item header for an item. - """ - if tHandle in self._items: - return self._items[tHandle].level - return "H0" - def allItemTags(self, tHandle): """Get all tags set for headings of an item. """ @@ -794,7 +802,7 @@ class ItemIndex: continue if tItem.isNoteLayout(): continue - if skipExcl and not tItem.isExported: + if skipExcl and not tItem.isActive: continue tHandle = tItem.itemHandle @@ -821,7 +829,6 @@ class ItemIndex: """ if tHandle in self._items: tItem = self._items[tHandle] - tItem.updateLevel(hDepth) tItem.addHeading(IndexHeading(sTitle, hDepth, hText)) return @@ -897,7 +904,6 @@ class IndexItem: def __init__(self, tHandle, tItem): self._handle = tHandle self._item = tItem - self._level = "H0" self._headings = {} self._index = 0 @@ -917,21 +923,10 @@ class IndexItem: def item(self): return self._item - @property - def level(self): - return self._level - ## # Setters ## - def updateLevel(self, level): - """Set the level only if it has not already been set. - """ - if self._level == "H0": - self._level = level - return - def addHeading(self, tHeading): """Add a heading to the item. Also remove the placeholder entry if it exists. @@ -1011,7 +1006,7 @@ class IndexItem: if hRefs: refs[sTitle] = hRefs - data = {"level": self._level} + data = {} data["headings"] = heads if refs: data["references"] = refs @@ -1021,7 +1016,6 @@ class IndexItem: def unpackData(self, data): """Unpack an item entry from the data. """ - self._level = data.get("level", "H0") references = data.get("references", {}) for sTitle, hData in data.get("headings", {}).items(): if not isTitleTag(sTitle): @@ -1030,6 +1024,7 @@ class IndexItem: tHeading.unpackData(hData) tHeading.unpackReferences(references.get(sTitle, {})) self.addHeading(tHeading) + return # END Class IndexItem diff --git a/novelwriter/core/item.py b/novelwriter/core/item.py index 95418079..40426d67 100644 --- a/novelwriter/core/item.py +++ b/novelwriter/core/item.py @@ -31,12 +31,12 @@ from novelwriter.enum import nwItemType, nwItemClass, nwItemLayout from novelwriter.common import ( checkInt, isHandle, isItemClass, isItemLayout, isItemType, simplified ) -from novelwriter.constants import nwLabels, trConst +from novelwriter.constants import nwHeaders, nwLabels, trConst logger = logging.getLogger(__name__) -class NWItem(): +class NWItem: def __init__(self, theProject): @@ -52,15 +52,16 @@ class NWItem(): self._layout = nwItemLayout.NO_LAYOUT self._status = None self._import = None + self._active = True self._expanded = False - self._exported = True # Document Meta Data - self._charCount = 0 # Current character count - self._wordCount = 0 # Current word count - self._paraCount = 0 # Current paragraph count - self._cursorPos = 0 # Last cursor position - self._initCount = 0 # Initial word count + self._heading = "H0" # The main heading + self._charCount = 0 # Current character count + self._wordCount = 0 # Current word count + self._paraCount = 0 # Current paragraph count + self._cursorPos = 0 # Last cursor position + self._initCount = 0 # Initial word count return @@ -114,13 +115,17 @@ class NWItem(): def itemImport(self): return self._import + @property + def isActive(self): + return self._active + @property def isExpanded(self): return self._expanded @property - def isExported(self): - return self._exported + def mainHeading(self): + return self._heading @property def charCount(self): @@ -162,6 +167,7 @@ class NWItem(): metaAttrib = {} metaAttrib["expanded"] = str(self._expanded) if self._type == nwItemType.FILE: + metaAttrib["mainHeading"] = str(self._heading) metaAttrib["charCount"] = str(self._charCount) metaAttrib["wordCount"] = str(self._wordCount) metaAttrib["paraCount"] = str(self._paraCount) @@ -171,7 +177,7 @@ class NWItem(): nameAttrib["status"] = str(self._status) nameAttrib["import"] = str(self._import) if self._type == nwItemType.FILE: - nameAttrib["exported"] = str(self._exported) + nameAttrib["active"] = str(self._active) xPack = etree.SubElement(xParent, "item", attrib=itemAttrib) self._subPack(xPack, "meta", attrib=metaAttrib) @@ -202,6 +208,7 @@ class NWItem(): for xValue in xItem: if xValue.tag == "meta": self.setExpanded(xValue.attrib.get("expanded", False)) + self.setMainHeading(xValue.attrib.get("mainHeading", "H0")) self.setCharCount(xValue.attrib.get("charCount", 0)) self.setWordCount(xValue.attrib.get("wordCount", 0)) self.setParaCount(xValue.attrib.get("paraCount", 0)) @@ -210,7 +217,11 @@ class NWItem(): self.setName(xValue.text) self.setStatus(xValue.attrib.get("status", None)) self.setImport(xValue.attrib.get("import", None)) - self.setExported(xValue.attrib.get("exported", True)) + self.setActive(xValue.attrib.get("active", True)) + + # ToDo: Remove before 2.0 release. Only needed for 2.0 pre-releases. + if "exported" in xValue.attrib: + self.setActive(xValue.attrib.get("exported", True)) # Legacy Format (1.3 and earlier) elif xValue.tag == "status": @@ -224,7 +235,7 @@ class NWItem(): elif xValue.tag == "expanded": self.setExpanded(xValue.text) elif xValue.tag == "exported": - self.setExported(xValue.text) + self.setActive(xValue.text) elif xValue.tag == "charCount": self.setCharCount(xValue.text) elif xValue.tag == "wordCount": @@ -269,7 +280,7 @@ class NWItem(): # Lookup Methods ## - def describeMe(self, hLevel=None): + def describeMe(self): """Return a string description of the item. """ descKey = "none" @@ -279,12 +290,14 @@ class NWItem(): descKey = "folder" elif self._type == nwItemType.FILE: if self._layout == nwItemLayout.DOCUMENT: - if hLevel == "H1": + if self._heading == "H1": descKey = "doc_h1" - elif hLevel == "H2": + elif self._heading == "H2": descKey = "doc_h2" - elif hLevel == "H3": + elif self._heading == "H3": descKey = "doc_h3" + elif self._heading == "H4": + descKey = "doc_h4" else: descKey = "document" elif self._layout == nwItemLayout.NOTE: @@ -292,16 +305,16 @@ class NWItem(): return trConst(nwLabels.ITEM_DESCRIPTION.get(descKey, "")) - def getImportStatus(self): + def getImportStatus(self, incIcon=True): """Return the relevant importance or status label and icon for the current item based on its class. """ if self.isNovelLike(): stName = self.theProject.statusItems.name(self._status) - stIcon = self.theProject.statusItems.icon(self._status) + stIcon = self.theProject.statusItems.icon(self._status) if incIcon else None else: stName = self.theProject.importItems.name(self._import) - stIcon = self.theProject.importItems.icon(self._import) + stIcon = self.theProject.importItems.icon(self._import) if incIcon else None return stName, stIcon ## @@ -487,6 +500,15 @@ class NWItem(): self._import = self.theProject.importItems.check(value) return + def setActive(self, state): + """Set the export flag. + """ + if isinstance(state, str): + self._active = (state == str(True)) + else: + self._active = (state is True) + return + def setExpanded(self, state): """Set the expanded status of an item in the project tree. """ @@ -496,19 +518,17 @@ class NWItem(): self._expanded = (state is True) return - def setExported(self, state): - """Set the export flag. - """ - if isinstance(state, str): - self._exported = (state == str(True)) - else: - self._exported = (state is True) - return - ## # Set Document Meta Data ## + def setMainHeading(self, value): + """Set the main heading level. + """ + if value in nwHeaders.H_LEVEL: + self._heading = value + return + def setCharCount(self, count): """Set the character count, and ensure that it is an integer. """ diff --git a/novelwriter/core/options.py b/novelwriter/core/options.py index d64970ae..9d840e0f 100644 --- a/novelwriter/core/options.py +++ b/novelwriter/core/options.py @@ -40,30 +40,30 @@ VALID_MAP = { "GuiWritingStats": { "winWidth", "winHeight", "widthCol0", "widthCol1", "widthCol2", "widthCol3", "sortCol", "sortOrder", "incNovel", "incNotes", - "hideZeros", "hideNegative", "groupByDay", "showIdleTime", "histMax" + "hideZeros", "hideNegative", "groupByDay", "showIdleTime", "histMax", }, - "GuiDocSplit": {"spLevel"}, + "GuiDocSplit": {"spLevel", "intoFolder", "docHierarchy"}, "GuiBuildNovel": { "winWidth", "winHeight", "boxWidth", "docWidth", "hideScene", "hideSection", "addNovel", "addNotes", "ignoreFlag", "justifyText", "excludeBody", "textFont", "textSize", "lineHeight", "noStyling", "incSynopsis", "incComments", "incKeywords", "incBodyText", - "replaceTabs", "replaceUCode" + "replaceTabs", "replaceUCode", "rootFilter", }, "GuiOutline": {"headerOrder", "columnWidth", "columnHidden"}, "GuiProjectSettings": { - "winWidth", "winHeight", "replaceColW", "statusColW", "importColW" + "winWidth", "winHeight", "replaceColW", "statusColW", "importColW", }, "GuiProjectDetails": { "winWidth", "winHeight", "widthCol0", "widthCol1", "widthCol2", - "widthCol3", "widthCol4", "wordsPerPage", "countFrom", "clearDouble" + "widthCol3", "widthCol4", "wordsPerPage", "countFrom", "clearDouble", }, "GuiWordList": {"winWidth", "winHeight"}, "GuiNovelView": {"lastCol"}, } -class OptionState(): +class OptionState: def __init__(self, theProject): self.theProject = theProject @@ -188,8 +188,7 @@ class OptionState(): the default value. """ if group in self._theState: - if name in self._theState[group]: - return checkBool(self._theState[group].get(name, default), default) + return checkBool(self._theState[group].get(name, default), default) return default def getEnum(self, group, name, lookup, default): diff --git a/novelwriter/core/project.py b/novelwriter/core/project.py index 1dffd1aa..66f9617b 100644 --- a/novelwriter/core/project.py +++ b/novelwriter/core/project.py @@ -44,7 +44,7 @@ from novelwriter.core.document import NWDoc from novelwriter.enum import nwItemType, nwItemClass, nwItemLayout, nwAlert from novelwriter.error import logException from novelwriter.common import ( - checkString, checkBool, checkInt, isHandle, formatTimeStamp, + checkString, checkBool, checkInt, checkStringNone, isHandle, formatTimeStamp, makeFileNameSafe, hexToInt, minmax, simplified ) from novelwriter.constants import trConst, nwFiles, nwLabels @@ -52,7 +52,7 @@ from novelwriter.constants import trConst, nwFiles, nwLabels logger = logging.getLogger(__name__) -class NWProject(): +class NWProject: FILE_VERSION = "1.4" # The current project file format version @@ -85,7 +85,6 @@ class NWProject(): self.projDict = None # The spell check dictionary self.projSpell = None # The spell check language, if different than default self.projLang = None # The project language, used for builds - self.projFile = None # The file name of the project main XML file self.projFiles = [] # A list of all files in the content folder on load # Project Meta @@ -176,7 +175,7 @@ class NWProject(): self._projTree.updateItemData(newItem.itemHandle) return newItem.itemHandle - def writeNewFile(self, tHandle, hLevel, isDocument): + def writeNewFile(self, tHandle, hLevel, isDocument, addText=""): """Write content to a new document after it is created. This will not run if the file exists and is not empty. """ @@ -187,11 +186,11 @@ class NWProject(): return False newDoc = NWDoc(self, tHandle) - if newDoc.readDocument().strip(): + if (newDoc.readDocument() or "").strip(): return False hshText = "#"*minmax(hLevel, 1, 4) - newText = f"{hshText} {tItem.itemName}\n\n" + newText = f"{hshText} {tItem.itemName}\n\n{addText}" if tItem.isNovelLike() and isDocument: tItem.setLayout(nwItemLayout.DOCUMENT) else: @@ -202,6 +201,23 @@ class NWProject(): return True + def removeItem(self, tHandle): + """Remove an item from the project. This will delete both the + project entry and a document file if it exists. + """ + if self._projTree.checkType(tHandle, nwItemType.FILE): + delDoc = NWDoc(self, tHandle) + if not delDoc.deleteDocument(): + self.mainGui.makeAlert([ + self.tr("Could not delete document file."), delDoc.getError() + ], nwAlert.ERROR) + return False + + self._projIndex.deleteHandle(tHandle) + del self._projTree[tHandle] + + return True + def trashFolder(self): """Add the special trash root folder to the project. """ @@ -243,7 +259,6 @@ class NWProject(): self.projDict = None self.projSpell = None self.projLang = None - self.projFile = nwFiles.PROJ_FILE self.projFiles = [] self.projName = "" self.bookTitle = "" @@ -437,7 +452,7 @@ class NWProject(): legacyList = [] # Cleanup is done later for projItem in os.listdir(self.projPath): - logger.verbose("Project contains: %s", projItem) + logger.debug("Project contains: %s", projItem) if projItem.startswith("data_") and len(projItem) == 6: legacyList.append(projItem) @@ -457,7 +472,7 @@ class NWProject(): self.clearProject() return False else: - logger.verbose("Project is not locked") + logger.debug("Project is not locked") # Open The Project XML File # ========================= @@ -494,8 +509,8 @@ class NWProject(): hexVersion = xRoot.attrib.get("hexVersion", "0x0") fileVersion = xRoot.attrib.get("fileVersion", self.tr("Unknown")) - logger.verbose("XML root is '%s'", nwxRoot) - logger.verbose("File version is '%s'", fileVersion) + logger.debug("XML root is '%s'", nwxRoot) + logger.debug("File version is '%s'", fileVersion) # Check File Type # =============== @@ -576,16 +591,16 @@ class NWProject(): if xItem.text is None: continue if xItem.tag == "name": - self.projName = checkString(simplified(xItem.text), "") - logger.verbose("Working Title: '%s'", self.projName) + self.projName = simplified(checkString(xItem.text, "")) + logger.info("Project Name: '%s'", self.projName) elif xItem.tag == "title": - self.bookTitle = checkString(simplified(xItem.text), "") - logger.verbose("Title is '%s'", self.bookTitle) + self.bookTitle = simplified(checkString(xItem.text, "")) + logger.info("Project Title: '%s'", self.bookTitle) elif xItem.tag == "author": - author = checkString(simplified(xItem.text), "") + author = simplified(checkString(xItem.text, "")) if author: self.bookAuthors.append(author) - logger.verbose("Author: '%s'", author) + logger.debug("Author: '%s'", author) elif xItem.tag == "saveCount": self.saveCount = checkInt(xItem.text, 0) elif xItem.tag == "autoCount": @@ -601,25 +616,25 @@ class NWProject(): if xItem.tag == "doBackup": self.doBackup = checkBool(xItem.text, False) elif xItem.tag == "language": - self.projLang = checkString(xItem.text, None, True) + self.projLang = checkStringNone(xItem.text, None) elif xItem.tag == "spellCheck": self.spellCheck = checkBool(xItem.text, False) elif xItem.tag == "spellLang": - self.projSpell = checkString(xItem.text, None, True) + self.projSpell = checkStringNone(xItem.text, None) elif xItem.tag == "lastEdited": - self.lastEdited = checkString(xItem.text, None, True) + self.lastEdited = checkStringNone(xItem.text, None) elif xItem.tag == "lastViewed": - self.lastViewed = checkString(xItem.text, None, True) + self.lastViewed = checkStringNone(xItem.text, None) elif xItem.tag == "lastNovel": - self.lastNovel = checkString(xItem.text, None, True) + self.lastNovel = checkStringNone(xItem.text, None) elif xItem.tag == "lastOutline": - self.lastOutline = checkString(xItem.text, None, True) + self.lastOutline = checkStringNone(xItem.text, None) elif xItem.tag == "lastWordCount": - self.lastWCount = checkInt(xItem.text, 0, False) + self.lastWCount = checkInt(xItem.text, 0) elif xItem.tag == "novelWordCount": - self.lastNovelWC = checkInt(xItem.text, 0, False) + self.lastNovelWC = checkInt(xItem.text, 0) elif xItem.tag == "notesWordCount": - self.lastNotesWC = checkInt(xItem.text, 0, False) + self.lastNotesWC = checkInt(xItem.text, 0) elif xItem.tag == "status": self.statusItems.unpackXML(xItem) elif xItem.tag == "importance": @@ -628,12 +643,12 @@ class NWProject(): for xEntry in xItem: if xEntry.tag == "entry" and "key" in xEntry.attrib: self.autoReplace[xEntry.attrib["key"]] = checkString( - xEntry.text, None, False + xEntry.text, "ERROR" ) elif xItem.tag == "titleFormat": titleFormat = self.titleFormat.copy() for xEntry in xItem: - titleFormat[xEntry.tag] = checkString(xEntry.text, "", False) + titleFormat[xEntry.tag] = checkString(xEntry.text, "") self.setTitleFormat(titleFormat) elif xChild.tag == "content": @@ -663,7 +678,7 @@ class NWProject(): # Check the project tree consistency for tItem in self._projTree: tHandle = tItem.itemHandle - logger.verbose("Checking item '%s'", tHandle) + logger.debug("Checking item '%s'", tHandle) if not self._projTree.updateItemData(tHandle): logger.error("There was a problem item '%s', and it has been removed", tHandle) del self._projTree[tHandle] # The file will be re-added as orphaned @@ -757,9 +772,9 @@ class NWProject(): self._projTree.packXML(nwXML) # Write the xml tree to file - tempFile = os.path.join(self.projPath, self.projFile+"~") - saveFile = os.path.join(self.projPath, self.projFile) - backFile = os.path.join(self.projPath, self.projFile[:-3]+"bak") + tempFile = os.path.join(self.projPath, nwFiles.PROJ_FILE+"~") + saveFile = os.path.join(self.projPath, nwFiles.PROJ_FILE) + backFile = os.path.join(self.projPath, nwFiles.PROJ_FILE[:-3]+"bak") try: with open(tempFile, mode="wb") as outFile: outFile.write(etree.tostring( @@ -799,7 +814,7 @@ class NWProject(): return True - def closeProject(self, idleTime=0): + def closeProject(self, idleTime=0.0): """Close the current project and clear all meta data. """ logger.info("Closing project: %s", self.projPath) @@ -1074,7 +1089,7 @@ class NWProject(): def setSpellLang(self, theLang): """Set the project-specific spell check language. """ - theLang = checkString(theLang, None, True) + theLang = checkStringNone(theLang, None) if self.projSpell != theLang: self.projSpell = theLang self.setProjectChanged(True) @@ -1084,7 +1099,7 @@ class NWProject(): def setProjectLang(self, theLang): """Set the project-specific language. """ - theLang = checkString(theLang, None, True) + theLang = checkStringNone(theLang, None) if self.projLang != theLang: self.projLang = theLang self._loadProjectLocalisation() @@ -1168,7 +1183,7 @@ class NWProject(): information to the GUI statusbar. """ self.projChanged = bValue - self.mainGui.statusBar.doUpdateProjectStatus(bValue) + self.mainGui.mainStatus.doUpdateProjectStatus(bValue) if bValue: # If we've changed the project at all, this should be True self.projAltered = True diff --git a/novelwriter/core/spellcheck.py b/novelwriter/core/spellcheck.py index d9c506cd..4a63bf39 100644 --- a/novelwriter/core/spellcheck.py +++ b/novelwriter/core/spellcheck.py @@ -33,7 +33,7 @@ from novelwriter.error import logException logger = logging.getLogger(__name__) -class NWSpellEnchant(): +class NWSpellEnchant: def __init__(self): diff --git a/novelwriter/core/status.py b/novelwriter/core/status.py index 4bade5e7..a379f911 100644 --- a/novelwriter/core/status.py +++ b/novelwriter/core/status.py @@ -37,7 +37,7 @@ from novelwriter.common import checkInt, minmax, simplified logger = logging.getLogger(__name__) -class NWStatus(): +class NWStatus: STATUS = 1 IMPORT = 2 diff --git a/novelwriter/core/tohtml.py b/novelwriter/core/tohtml.py index 86a21786..2110300c 100644 --- a/novelwriter/core/tohtml.py +++ b/novelwriter/core/tohtml.py @@ -38,7 +38,7 @@ class ToHtml(Tokenizer): M_EBOOK = 2 # Tweak output for converting to epub def __init__(self, theProject): - Tokenizer.__init__(self, theProject) + super().__init__(theProject) self._genMode = self.M_EXPORT self._cssStyles = True @@ -107,7 +107,7 @@ class ToHtml(Tokenizer): """Extend the auto-replace to also properly encode some unicode characters into their respective HTML entities. """ - Tokenizer.doPreProcessing(self) + super().doPreProcessing() self._theText = self._theText.translate(self._trMap) return diff --git a/novelwriter/core/tokenizer.py b/novelwriter/core/tokenizer.py index 3a3b52f1..c55e3659 100644 --- a/novelwriter/core/tokenizer.py +++ b/novelwriter/core/tokenizer.py @@ -304,16 +304,10 @@ class Tokenizer(ABC): if self._theItem is None: return False - self._theText = "" - if theText is not None: - # If the text is set, just use that - self._theText = theText - else: - # Otherwise, load it from file - theDoc = NWDoc(self.theProject, theHandle) - theText = theDoc.readDocument() - if theText: - self._theText = theText + if theText is None: + theText = NWDoc(self.theProject, theHandle).readDocument() or "" + + self._theText = theText docSize = len(self._theText) if docSize > nwConst.MAX_DOCSIZE: diff --git a/novelwriter/core/tomd.py b/novelwriter/core/tomd.py index 48d23a35..89ae9e4f 100644 --- a/novelwriter/core/tomd.py +++ b/novelwriter/core/tomd.py @@ -37,7 +37,7 @@ class ToMarkdown(Tokenizer): M_GH = 1 # GitHub Markdown def __init__(self, theProject): - Tokenizer.__init__(self, theProject) + super().__init__(theProject) self._genMode = self.M_STD self._fullMD = [] diff --git a/novelwriter/core/toodt.py b/novelwriter/core/toodt.py index 59eaf30f..022bda4c 100644 --- a/novelwriter/core/toodt.py +++ b/novelwriter/core/toodt.py @@ -89,7 +89,7 @@ M_DEL = ~X_DEL class ToOdt(Tokenizer): def __init__(self, theProject, isFlat): - Tokenizer.__init__(self, theProject) + super().__init__(theProject) self._isFlat = isFlat # Flat: .fodt, otherwise .odt @@ -994,7 +994,7 @@ class ToOdt(Tokenizer): # Auto-Style Classes # =============================================================================================== # -class ODTParagraphStyle(): +class ODTParagraphStyle: """Wrapper class for the paragraph style setting used by the exporter. Only the used settings are exposed here to keep the class minimal and fast. @@ -1208,7 +1208,7 @@ class ODTParagraphStyle(): # END Class ODTParagraphStyle -class ODTTextStyle(): +class ODTTextStyle: """Wrapper class for the text style setting used by the exporter. Only the used settings are exposed here to keep the class minimal and fast. @@ -1297,7 +1297,7 @@ X_SPAN_TEXT = 2 X_SPAN_SING = 3 -class XMLParagraph(): +class XMLParagraph: """This is a helper class to manage the text content of a single XML element using mixed content tags. diff --git a/novelwriter/core/tree.py b/novelwriter/core/tree.py index 6bb24959..506556cd 100644 --- a/novelwriter/core/tree.py +++ b/novelwriter/core/tree.py @@ -38,7 +38,7 @@ from novelwriter.core.item import NWItem logger = logging.getLogger(__name__) -class NWTree(): +class NWTree: MAX_DEPTH = 1000 # Cap of tree traversing for loops @@ -89,20 +89,20 @@ class NWTree(): logger.warning("Duplicate handle '%s' detected, skipping", tHandle) return False - logger.verbose("Adding item '%s' with parent '%s'", str(tHandle), str(pHandle)) + logger.debug("Adding item '%s' with parent '%s'", str(tHandle), str(pHandle)) nwItem.setHandle(tHandle) nwItem.setParent(pHandle) if nwItem.isRootType(): - logger.verbose("Item '%s' is a root item", str(tHandle)) + logger.debug("Item '%s' is a root item", str(tHandle)) self._treeRoots[tHandle] = nwItem if nwItem.itemClass == nwItemClass.ARCHIVE: - logger.verbose("Item '%s' is the archive folder", str(tHandle)) + logger.debug("Item '%s' is the archive folder", str(tHandle)) self._archRoot = tHandle elif nwItem.itemClass == nwItemClass.TRASH: if self._trashRoot is None: - logger.verbose("Item '%s' is the trash folder", str(tHandle)) + logger.debug("Item '%s' is the trash folder", str(tHandle)) self._trashRoot = tHandle else: logger.error("Only one trash folder allowed") @@ -274,11 +274,13 @@ class NWTree(): return rootClasses def iterRoots(self, itemClass): - """Iterate over all items of a given class. + """Iterate over all root items of a given class in order. """ - for tHandle, nwItem in self._treeRoots.items(): - if nwItem.itemClass == itemClass: - yield tHandle, nwItem + for tHandle in self._treeOrder: + nwItem = self.__getitem__(tHandle) + if nwItem is not None and nwItem.isRootType(): + if itemClass is None or nwItem.itemClass == itemClass: + yield tHandle, nwItem return def isRoot(self, tHandle): @@ -347,7 +349,7 @@ class NWTree(): # Save the temp list self._treeOrder = tmpOrder self._setTreeChanged(True) - logger.verbose("Project tree order updated") + logger.debug("Project tree order updated") return @@ -457,7 +459,7 @@ class NWTree(): """Generate a unique item handle. In the event that the key already exists, generate a new one. """ - logger.verbose("Generating new handle") + logger.debug("Generating new handle") handle = f"{random.getrandbits(52):013x}" if handle in self._projTree: logger.warning("Duplicate handle encountered! Retrying ...") diff --git a/novelwriter/gui/custom.py b/novelwriter/custom.py similarity index 95% rename from novelwriter/gui/custom.py rename to novelwriter/custom.py index e571a5a1..d516e2dd 100644 --- a/novelwriter/gui/custom.py +++ b/novelwriter/custom.py @@ -202,7 +202,7 @@ class QConfigLayout(QGridLayout): class QHelpLabel(QLabel): def __init__(self, theText, textCol, fontSize=0.9): - QLabel.__init__(self, theText) + super().__init__(theText) if isinstance(textCol, QColor): qCol = textCol @@ -267,8 +267,8 @@ class QSwitch(QAbstractButton): return self._offset @offset.setter - def offset(self, theOffset): - self._offset = theOffset + def offset(self, offset): + self._offset = offset self.update() return @@ -276,11 +276,11 @@ class QSwitch(QAbstractButton): # Getters and Setters ## - def setChecked(self, isChecked): + def setChecked(self, checked): """Overload setChecked to also alter the offset. """ - super().setChecked(isChecked) - if isChecked: + super().setChecked(checked) + if checked: self.offset = self._xW - self._xR else: self.offset = self._xR @@ -290,10 +290,10 @@ class QSwitch(QAbstractButton): # Events ## - def resizeEvent(self, theEvent): + def resizeEvent(self, event): """Overload resize to ensure correct offset. """ - super().resizeEvent(theEvent) + super().resizeEvent(event) if self.isChecked(): self.offset = self._xW - self._xR else: @@ -377,7 +377,7 @@ class QSwitch(QAbstractButton): class PagedDialog(QDialog): def __init__(self, parent=None): - QDialog.__init__(self, parent=parent) + super().__init__(parent=parent) self._tabBar = VerticalTabBar(self) self._tabBar.setExpanding(False) @@ -410,13 +410,13 @@ class PagedDialog(QDialog): return def addTab(self, widget, label): - """Forwards the adding of tabs to the QTabWidget. + """Forward the adding of tabs to the QTabWidget. """ self._tabBox.addTab(widget, label) return def addControls(self, buttonBar): - """Adds a button bar to the dialog. + """Add a button bar to the dialog. """ self._buttonBox.addWidget(buttonBar) return @@ -427,14 +427,14 @@ class PagedDialog(QDialog): class VerticalTabBar(QTabBar): def __init__(self, parent=None): - QTabBar.__init__(self, parent=parent) + super().__init__(parent=parent) self._mW = novelwriter.CONFIG.pxInt(150) return def tabSizeHint(self, index): - """Returns a transposed size hint for the rotated bar. + """Return a transposed size hint for the rotated bar. """ - tSize = QTabBar.tabSizeHint(self, index) + tSize = super().tabSizeHint(index) tSize.transpose() tSize.setWidth(min(tSize.width(), self._mW)) return tSize diff --git a/novelwriter/dialogs/about.py b/novelwriter/dialogs/about.py index 9cf43daf..5b3a509e 100644 --- a/novelwriter/dialogs/about.py +++ b/novelwriter/dialogs/about.py @@ -44,7 +44,7 @@ logger = logging.getLogger(__name__) class GuiAbout(QDialog): def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiAbout ...") self.setObjectName("GuiAbout") diff --git a/novelwriter/dialogs/docmerge.py b/novelwriter/dialogs/docmerge.py index 22a6eb6b..b6fd8381 100644 --- a/novelwriter/dialogs/docmerge.py +++ b/novelwriter/dialogs/docmerge.py @@ -1,10 +1,11 @@ """ -novelWriter – GUI Doc Merge Tool -================================ -GUI class for merging multiple documents to one document +novelWriter – GUI Doc Merge Dialog +================================== +Custom dialog class for merging documents. File History: -Created: 2020-01-23 [0.4.3] +Created: 2020-01-23 [0.4.3] +Rewritten: 2022-10-06 [2.0b1] This file is a part of novelWriter Copyright 2018–2022, Veronica Berglyd Olsen @@ -26,169 +27,146 @@ along with this program. If not, see . import logging import novelwriter -from PyQt5.QtCore import Qt +from PyQt5.QtCore import Qt, QSize from PyQt5.QtWidgets import ( - QDialog, QVBoxLayout, QLabel, QListWidget, QAbstractItemView, - QListWidgetItem, QDialogButtonBox + QAbstractItemView, QDialog, QDialogButtonBox, QGridLayout, QLabel, + QListWidget, QListWidgetItem, QVBoxLayout, ) -from novelwriter.core import NWDoc -from novelwriter.enum import nwAlert, nwItemType -from novelwriter.gui.custom import QHelpLabel +from novelwriter.custom import QHelpLabel, QSwitch logger = logging.getLogger(__name__) class GuiDocMerge(QDialog): - def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + def __init__(self, mainGui, sHandle, itemList): + super().__init__(parent=mainGui) logger.debug("Initialising GuiDocMerge ...") self.setObjectName("GuiDocMerge") self.mainConf = novelwriter.CONFIG self.mainGui = mainGui + self.mainTheme = mainGui.mainTheme self.theProject = mainGui.theProject - self.sourceItem = None - self.outerBox = QVBoxLayout() + self._data = {} + self.setWindowTitle(self.tr("Merge Documents")) self.headLabel = QLabel("{0}".format(self.tr("Documents to Merge"))) - self.helpLabel = QHelpLabel( - self.tr("Drag and drop items to change the order."), self.mainGui.mainTheme.helpText - ) + self.helpLabel = QHelpLabel(self.tr( + "Drag and drop items to change the order, or uncheck to exclude." + ), self.mainTheme.helpText) + + iPx = self.mainTheme.baseIconSize + hSp = self.mainConf.pxInt(12) + vSp = self.mainConf.pxInt(8) + bSp = self.mainConf.pxInt(12) self.listBox = QListWidget() - self.listBox.setDragDropMode(QAbstractItemView.InternalMove) + self.listBox.setIconSize(QSize(iPx, iPx)) self.listBox.setMinimumWidth(self.mainConf.pxInt(400)) self.listBox.setMinimumHeight(self.mainConf.pxInt(180)) + self.listBox.setSelectionBehavior(QAbstractItemView.SelectRows) + self.listBox.setSelectionMode(QAbstractItemView.SingleSelection) + self.listBox.setDragDropMode(QAbstractItemView.InternalMove) + # Merge Options + self.trashLabel = QLabel(self.tr("Move merged items to Trash")) + self.trashSwitch = QSwitch(width=2*iPx, height=iPx) + + self.optBox = QGridLayout() + self.optBox.addWidget(self.trashLabel, 0, 0) + self.optBox.addWidget(self.trashSwitch, 0, 1) + self.optBox.setHorizontalSpacing(hSp) + self.optBox.setColumnStretch(2, 1) + + # Buttons self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) - self.buttonBox.accepted.connect(self._doMerge) - self.buttonBox.rejected.connect(self._doClose) + self.buttonBox.accepted.connect(self.accept) + self.buttonBox.rejected.connect(self.reject) + self.resetButton = self.buttonBox.addButton(QDialogButtonBox.Reset) + self.resetButton.clicked.connect(self._resetList) + + # Assemble + self.outerBox = QVBoxLayout() self.outerBox.setSpacing(0) self.outerBox.addWidget(self.headLabel) self.outerBox.addWidget(self.helpLabel) - self.outerBox.addSpacing(self.mainConf.pxInt(8)) + self.outerBox.addSpacing(vSp) self.outerBox.addWidget(self.listBox) - self.outerBox.addSpacing(self.mainConf.pxInt(12)) + self.outerBox.addSpacing(vSp) + self.outerBox.addLayout(self.optBox) + self.outerBox.addSpacing(bSp) self.outerBox.addWidget(self.buttonBox) self.setLayout(self.outerBox) - self.rejected.connect(self._doClose) - - self._populateList() + # Load Content + self._loadContent(sHandle, itemList) logger.debug("GuiDocMerge initialisation complete") return - ## - # Buttons - ## - - def _doMerge(self): - """Perform the merge of the files in the selected folder, and - create a new file in the same parent folder. The old files are - not removed in the merge process, and must be deleted manually. + def getData(self): + """Return the user's choices. """ - logger.verbose("GuiDocMerge merge button clicked") - - finalOrder = [] + finalItems = [] for i in range(self.listBox.count()): - finalOrder.append(self.listBox.item(i).data(Qt.UserRole)) + item = self.listBox.item(i) + if item is not None and item.checkState() == Qt.Checked: + finalItems.append(item.data(Qt.UserRole)) - if len(finalOrder) == 0: - self.mainGui.makeAlert(self.tr( - "No source documents found. Nothing to do." - ), nwAlert.ERROR) - return False + self._data["moveToTrash"] = self.trashSwitch.isChecked() + self._data["finalItems"] = finalItems - theText = "" - for tHandle in finalOrder: - inDoc = NWDoc(self.theProject, tHandle) - docText = inDoc.readDocument() - docErr = inDoc.getError() - if docText is None and docErr: - self.mainGui.makeAlert([ - self.tr("Failed to open document file."), docErr - ], nwAlert.ERROR) - if docText: - theText += docText.rstrip("\n")+"\n\n" + return self._data - if self.sourceItem is None: - self.mainGui.makeAlert(self.tr( - "No source folder selected. Nothing to do." - ), nwAlert.ERROR) - return False + ## + # Slots + ## - srcItem = self.theProject.tree[self.sourceItem] - if srcItem is None: - self.mainGui.makeAlert(self.tr("Internal error."), nwAlert.ERROR) - return False - - nHandle = self.theProject.newFile(srcItem.itemName, srcItem.itemParent) - newItem = self.theProject.tree[nHandle] - newItem.setStatus(srcItem.itemStatus) - newItem.setImport(srcItem.itemImport) - - outDoc = NWDoc(self.theProject, nHandle) - if not outDoc.writeDocument(theText): - self.mainGui.makeAlert([ - self.tr("Could not save document."), outDoc.getError() - ], nwAlert.ERROR) - return False - - self.mainGui.projView.revealNewTreeItem(nHandle) - self.mainGui.openDocument(nHandle, doScroll=True) - - self._doClose() - - return True - - def _doClose(self): - """Close the dialog window without doing anything. + def _resetList(self): + """Reset the content of the list box to its original state. """ - self.close() + logger.debug("Resetting list box content") + sHandle = self._data.get("sHandle", None) + itemList = self._data.get("origItems", []) + self._loadContent(sHandle, itemList) return ## # Internal Functions ## - def _populateList(self): - """Get the item selected in the tree, check that it is a folder, - and try to find all files associated with it. The valid files - are then added to the list view in order. The list itself can be - reordered by the user. + def _loadContent(self, sHandle, itemList): + """Load content from a given list of items. """ - tHandle = self.mainGui.projView.getSelectedHandle() - self.sourceItem = tHandle - if tHandle is None: - return False + self._data = {} + self._data["sHandle"] = sHandle + self._data["origItems"] = itemList - nwItem = self.theProject.tree[tHandle] - if nwItem is None: - return False - - if nwItem.itemType is not nwItemType.FOLDER: - self.mainGui.makeAlert(self.tr( - "Element selected in the project tree must be a folder." - ), nwAlert.ERROR) - return False - - for sHandle in self.mainGui.projView.getTreeFromHandle(tHandle): - newItem = QListWidgetItem() - nwItem = self.theProject.tree[sHandle] - if not nwItem.isFileType(): + self.listBox.clear() + for tHandle in itemList: + nwItem = self.theProject.tree[tHandle] + if nwItem is None or not nwItem.isFileType(): continue + + itemIcon = self.mainTheme.getItemIcon( + nwItem.itemType, nwItem.itemClass, nwItem.itemLayout, nwItem.mainHeading + ) + + newItem = QListWidgetItem() + newItem.setIcon(itemIcon) newItem.setText(nwItem.itemName) - newItem.setData(Qt.UserRole, sHandle) + newItem.setData(Qt.UserRole, tHandle) + newItem.setCheckState(Qt.Checked) + self.listBox.addItem(newItem) - return True + return # END Class GuiDocMerge diff --git a/novelwriter/dialogs/docsplit.py b/novelwriter/dialogs/docsplit.py index e4c9b13a..1b6a5f70 100644 --- a/novelwriter/dialogs/docsplit.py +++ b/novelwriter/dialogs/docsplit.py @@ -1,10 +1,11 @@ """ -novelWriter – GUI Doc Split Tool -================================ -GUI class for splitting a single document into multiple documents +novelWriter – GUI Doc Split Dialog +================================== +Custom dialog class for splitting documents. File History: -Created: 2020-02-01 [0.4.3] +Created: 2020-02-01 [0.4.3] +Rewritten: 2022-10-12 [2.0b1] This file is a part of novelWriter Copyright 2018–2022, Veronica Berglyd Olsen @@ -29,32 +30,35 @@ import novelwriter from PyQt5.QtCore import Qt from PyQt5.QtWidgets import ( QDialog, QVBoxLayout, QComboBox, QListWidget, QAbstractItemView, - QListWidgetItem, QDialogButtonBox, QLabel + QListWidgetItem, QDialogButtonBox, QLabel, QGridLayout ) from novelwriter.core import NWDoc -from novelwriter.enum import nwAlert -from novelwriter.gui.custom import QHelpLabel +from novelwriter.custom import QHelpLabel, QSwitch logger = logging.getLogger(__name__) class GuiDocSplit(QDialog): - def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + LINE_ROLE = Qt.UserRole + LEVEL_ROLE = Qt.UserRole + 1 + LABEL_ROLE = Qt.UserRole + 2 + + def __init__(self, mainGui, sHandle): + super().__init__(parent=mainGui) logger.debug("Initialising GuiDocSplit ...") self.setObjectName("GuiDocSplit") self.mainConf = novelwriter.CONFIG self.mainGui = mainGui + self.mainTheme = mainGui.mainTheme self.theProject = mainGui.theProject - self.sourceItem = None - self.sourceText = [] + self._data = {} + self._text = [] - self.outerBox = QVBoxLayout() self.setWindowTitle(self.tr("Split Document")) self.headLabel = QLabel("{0}".format(self.tr("Document Headers"))) @@ -63,6 +67,18 @@ class GuiDocSplit(QDialog): self.mainGui.mainTheme.helpText ) + # Values + iPx = self.mainTheme.baseIconSize + hSp = self.mainConf.pxInt(12) + vSp = self.mainConf.pxInt(8) + bSp = self.mainConf.pxInt(12) + + pOptions = self.theProject.options + spLevel = pOptions.getInt("GuiDocSplit", "spLevel", 3) + intoFolder = pOptions.getBool("GuiDocSplit", "intoFolder", True) + docHierarchy = pOptions.getBool("GuiDocSplit", "docHierarchy", True) + + # Header Selection self.listBox = QListWidget() self.listBox.setDragDropMode(QAbstractItemView.NoDragDrop) self.listBox.setMinimumWidth(self.mainConf.pxInt(400)) @@ -73,206 +89,155 @@ class GuiDocSplit(QDialog): self.splitLevel.addItem(self.tr("Split up to Header Level 2 (Chapter)"), 2) self.splitLevel.addItem(self.tr("Split up to Header Level 3 (Scene)"), 3) self.splitLevel.addItem(self.tr("Split up to Header Level 4 (Section)"), 4) - spIndex = self.splitLevel.findData( - self.theProject.options.getInt("GuiDocSplit", "spLevel", 3) - ) + spIndex = self.splitLevel.findData(spLevel) if spIndex != -1: self.splitLevel.setCurrentIndex(spIndex) - self.splitLevel.currentIndexChanged.connect(self._populateList) + self.splitLevel.currentIndexChanged.connect(self._reloadList) + # Split Options + self.folderLabel = QLabel(self.tr("Split into a new folder")) + self.folderSwitch = QSwitch(width=2*iPx, height=iPx) + self.folderSwitch.setChecked(intoFolder) + + self.hierarchyLabel = QLabel(self.tr("Create document hierarchy")) + self.hierarchySwitch = QSwitch(width=2*iPx, height=iPx) + self.hierarchySwitch.setChecked(docHierarchy) + + self.optBox = QGridLayout() + self.optBox.addWidget(self.folderLabel, 0, 0) + self.optBox.addWidget(self.folderSwitch, 0, 1) + self.optBox.addWidget(self.hierarchyLabel, 1, 0) + self.optBox.addWidget(self.hierarchySwitch, 1, 1) + self.optBox.setVerticalSpacing(vSp) + self.optBox.setHorizontalSpacing(hSp) + self.optBox.setColumnStretch(2, 1) + + # Buttons self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) - self.buttonBox.accepted.connect(self._doSplit) - self.buttonBox.rejected.connect(self._doClose) + self.buttonBox.accepted.connect(self.accept) + self.buttonBox.rejected.connect(self.reject) + # Assemble + self.outerBox = QVBoxLayout() self.outerBox.setSpacing(0) self.outerBox.addWidget(self.headLabel) self.outerBox.addWidget(self.helpLabel) - self.outerBox.addSpacing(self.mainConf.pxInt(8)) + self.outerBox.addSpacing(vSp) self.outerBox.addWidget(self.listBox) self.outerBox.addWidget(self.splitLevel) - self.outerBox.addSpacing(self.mainConf.pxInt(12)) + self.outerBox.addSpacing(vSp) + self.outerBox.addLayout(self.optBox) + self.outerBox.addSpacing(bSp) self.outerBox.addWidget(self.buttonBox) self.setLayout(self.outerBox) - self.rejected.connect(self._doClose) - - self._populateList() + # Load Content + self._loadContent(sHandle) logger.debug("GuiDocSplit initialisation complete") return - ## - # Buttons - ## - - def _doSplit(self): - """Perform the split of the file, create a new folder in the - same parent folder, and multiple files depending on split level - settings. The old file is not removed in the split process, and - must be deleted manually. + def getData(self): + """Return the user's choices. Also save the users options for + the next time the dialog is used. """ - logger.verbose("GuiDocSplit split button clicked") - - if self.sourceItem is None: - self.mainGui.makeAlert(self.tr( - "No source document selected. Nothing to do." - ), nwAlert.ERROR) - return False - - srcItem = self.theProject.tree[self.sourceItem] - if srcItem is None: - self.mainGui.makeAlert(self.tr( - "Could not parse source document." - ), nwAlert.ERROR) - return False - - inDoc = NWDoc(self.theProject, self.sourceItem) - theText = inDoc.readDocument() - - docErr = inDoc.getError() - if theText is None and docErr: - self.mainGui.makeAlert([ - self.tr("Failed to open document file."), docErr - ], nwAlert.ERROR) - - if theText is None: - theText = "" - - nLines = len(self.sourceText) - logger.debug("Splitting document %s with %d lines", self.sourceItem, nLines) - - finalOrder = [] + headerList = [] for i in range(self.listBox.count()): - listItem = self.listBox.item(i) - wTitle = listItem.text() - lineNo = listItem.data(Qt.UserRole) - finalOrder.append([wTitle, lineNo, nLines]) - if i > 0: - finalOrder[i-1][2] = lineNo + item = self.listBox.item(i) + if item is not None: + headerList.append(( + item.data(self.LINE_ROLE), + item.data(self.LEVEL_ROLE), + item.data(self.LABEL_ROLE), + )) - nFiles = len(finalOrder) - if nFiles == 0: - self.mainGui.makeAlert(self.tr( - "No headers found. Nothing to do." - ), nwAlert.ERROR) - return False + spLevel = self.splitLevel.currentData() + intoFolder = self.folderSwitch.isChecked() + docHierarchy = self.hierarchySwitch.isChecked() - msgYes = self.mainGui.askQuestion( - self.tr("Split Document"), - "{0}

{1}".format( - self.tr( - "The document will be split into {0} file(s) in a new folder. " - "The original document will remain intact." - ).format(nFiles), - self.tr( - "Continue with the splitting process?" - ) - ) - ) - if not msgYes: - return False + self._data["spLevel"] = spLevel + self._data["headerList"] = headerList + self._data["intoFolder"] = intoFolder + self._data["docHierarchy"] = docHierarchy - # Create the folder - fHandle = self.theProject.newFolder(srcItem.itemName, srcItem.itemParent) - self.mainGui.projView.revealNewTreeItem(fHandle) - logger.verbose("Creating folder '%s'", fHandle) + pOptions = self.theProject.options + pOptions.setValue("GuiDocSplit", "spLevel", spLevel) + pOptions.setValue("GuiDocSplit", "intoFolder", intoFolder) + pOptions.setValue("GuiDocSplit", "docHierarchy", docHierarchy) - # Loop through, and create the files - for wTitle, iStart, iEnd in finalOrder: + return self._data, self._text - wTitle = wTitle.lstrip("#").strip() - nHandle = self.theProject.newFile(wTitle, fHandle) - newItem = self.theProject.tree[nHandle] - newItem.setStatus(srcItem.itemStatus) - newItem.setImport(srcItem.itemImport) - logger.verbose( - "Creating new document '%s' with text from line %d to %d", - nHandle, iStart+1, iEnd - ) + ## + # Slots + ## - theText = "\n".join(self.sourceText[iStart:iEnd]) - theText = theText.rstrip("\n") + "\n\n" - - outDoc = NWDoc(self.theProject, nHandle) - if not outDoc.writeDocument(theText): - self.mainGui.makeAlert([ - self.tr("Could not save document."), outDoc.getError() - ], nwAlert.ERROR) - return False - - self.mainGui.projView.revealNewTreeItem(nHandle) - - self._doClose() - - return True - - def _doClose(self): - """Close the dialog window without doing anything. + def _reloadList(self): + """Reload the content of the list box. """ - self.theProject.options.saveSettings() - self.close() + sHandle = self._data.get("sHandle", None) + self._loadContent(sHandle) return ## # Internal Functions ## - def _populateList(self): - """Get the item selected in the tree, check that it is a folder, - and try to find all files associated with it. The valid files - are then added to the list view in order. The list itself can be - reordered by the user. + def _loadContent(self, sHandle): + """Load content from a given source item. """ + self._data = {} + self._data["sHandle"] = sHandle + self.listBox.clear() - if self.sourceItem is None: - self.sourceItem = self.mainGui.projView.getSelectedHandle() - if self.sourceItem is None: - return False - - nwItem = self.theProject.tree[self.sourceItem] - if nwItem is None: - return False - - if not nwItem.isFileType(): - self.mainGui.makeAlert(self.tr( - "Element selected in the project tree must be a file." - ), nwAlert.ERROR) - return False - - inDoc = NWDoc(self.theProject, self.sourceItem) - theText = inDoc.readDocument() - if theText is None: - theText = "" - return False + nwItem = self.theProject.tree[sHandle] + if nwItem is None or not nwItem.isFileType(): + return spLevel = self.splitLevel.currentData() - self.theProject.options.setValue("GuiDocSplit", "spLevel", spLevel) - logger.debug( - "Scanning document '%s' for headings level <= %d", - self.sourceItem, spLevel - ) + if not self._text: + inDoc = NWDoc(self.theProject, sHandle) + self._text = (inDoc.readDocument() or "").splitlines() - self.sourceText = theText.splitlines() - for lineNo, aLine in enumerate(self.sourceText): + for lineNo, aLine in enumerate(self._text): onLine = -1 + hLevel = 0 + hLabel = aLine.strip() if aLine.startswith("# ") and spLevel >= 1: onLine = lineNo + hLevel = 1 + hLabel = aLine[2:].strip() elif aLine.startswith("## ") and spLevel >= 2: onLine = lineNo + hLevel = 2 + hLabel = aLine[3:].strip() elif aLine.startswith("### ") and spLevel >= 3: onLine = lineNo + hLevel = 3 + hLabel = aLine[4:].strip() elif aLine.startswith("#### ") and spLevel >= 4: onLine = lineNo + hLevel = 4 + hLabel = aLine[5:].strip() + elif aLine.startswith("#! ") and spLevel >= 1: + onLine = lineNo + hLevel = 1 + hLabel = aLine[3:].strip() + elif aLine.startswith("##! ") and spLevel >= 2: + onLine = lineNo + hLevel = 2 + hLabel = aLine[4:].strip() - if onLine >= 0: + if onLine >= 0 and hLevel > 0: newItem = QListWidgetItem() newItem.setText(aLine.strip()) - newItem.setData(Qt.UserRole, onLine) + newItem.setData(self.LINE_ROLE, onLine) + newItem.setData(self.LEVEL_ROLE, hLevel) + newItem.setData(self.LABEL_ROLE, hLabel) self.listBox.addItem(newItem) - return True + return # END Class GuiDocSplit diff --git a/novelwriter/dialogs/editlabel.py b/novelwriter/dialogs/editlabel.py index 03bf9d08..a1982ede 100644 --- a/novelwriter/dialogs/editlabel.py +++ b/novelwriter/dialogs/editlabel.py @@ -36,7 +36,7 @@ logger = logging.getLogger(__name__) class GuiEditLabel(QDialog): def __init__(self, parent, text=""): - QDialog.__init__(self, parent=parent) + super().__init__(parent=parent) self.setObjectName("GuiEditLabel") self.setWindowTitle(self.tr("Item Label")) diff --git a/novelwriter/dialogs/preferences.py b/novelwriter/dialogs/preferences.py index f807fde1..ae2df4c5 100644 --- a/novelwriter/dialogs/preferences.py +++ b/novelwriter/dialogs/preferences.py @@ -35,7 +35,7 @@ from PyQt5.QtWidgets import ( ) from novelwriter.enum import nwAlert -from novelwriter.gui.custom import QSwitch, QConfigLayout, PagedDialog +from novelwriter.custom import QSwitch, QConfigLayout, PagedDialog from novelwriter.dialogs.quotes import GuiQuoteSelect logger = logging.getLogger(__name__) @@ -44,7 +44,7 @@ logger = logging.getLogger(__name__) class GuiPreferences(PagedDialog): def __init__(self, mainGui): - PagedDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiPreferences ...") self.setObjectName("GuiPreferences") @@ -55,13 +55,13 @@ class GuiPreferences(PagedDialog): self.setWindowTitle(self.tr("Preferences")) - self.tabGeneral = GuiPreferencesGeneral(self.mainGui) - self.tabProjects = GuiPreferencesProjects(self.mainGui) - self.tabDocs = GuiPreferencesDocuments(self.mainGui) - self.tabEditor = GuiPreferencesEditor(self.mainGui) - self.tabSyntax = GuiPreferencesSyntax(self.mainGui) - self.tabAuto = GuiPreferencesAutomation(self.mainGui) - self.tabQuote = GuiPreferencesQuotes(self.mainGui) + self.tabGeneral = GuiPreferencesGeneral(self) + self.tabProjects = GuiPreferencesProjects(self) + self.tabDocs = GuiPreferencesDocuments(self) + self.tabEditor = GuiPreferencesEditor(self) + self.tabSyntax = GuiPreferencesSyntax(self) + self.tabAuto = GuiPreferencesAutomation(self) + self.tabQuote = GuiPreferencesQuotes(self) self.addTab(self.tabGeneral, self.tr("General")) self.addTab(self.tabProjects, self.tr("Projects")) @@ -128,9 +128,7 @@ class GuiPreferences(PagedDialog): def _saveWindowSize(self): """Save the dialog window size. """ - winWidth = self.mainConf.rpxInt(self.width()) - winHeight = self.mainConf.rpxInt(self.height()) - self.mainConf.setPreferencesSize(winWidth, winHeight) + self.mainConf.setPreferencesSize(self.width(), self.height()) return # END Class GuiPreferences @@ -138,12 +136,12 @@ class GuiPreferences(PagedDialog): class GuiPreferencesGeneral(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -344,12 +342,12 @@ class GuiPreferencesGeneral(QWidget): class GuiPreferencesProjects(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -505,12 +503,12 @@ class GuiPreferencesProjects(QWidget): class GuiPreferencesDocuments(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -666,12 +664,12 @@ class GuiPreferencesDocuments(QWidget): class GuiPreferencesEditor(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -840,12 +838,12 @@ class GuiPreferencesEditor(QWidget): class GuiPreferencesSyntax(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -943,12 +941,12 @@ class GuiPreferencesSyntax(QWidget): class GuiPreferencesAutomation(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() @@ -1100,12 +1098,12 @@ class GuiPreferencesAutomation(QWidget): class GuiPreferencesQuotes(QWidget): - def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + def __init__(self, prefsGui): + super().__init__(parent=prefsGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme + self.mainGui = prefsGui.mainGui + self.mainTheme = prefsGui.mainGui.mainTheme # The Form self.mainForm = QConfigLayout() diff --git a/novelwriter/dialogs/projdetails.py b/novelwriter/dialogs/projdetails.py index e83fc0a4..7f2259c3 100644 --- a/novelwriter/dialogs/projdetails.py +++ b/novelwriter/dialogs/projdetails.py @@ -27,16 +27,18 @@ import math import logging import novelwriter -from PyQt5.QtCore import Qt, QSize +from PyQt5.QtCore import Qt, QSize, pyqtSlot from PyQt5.QtGui import QFont from PyQt5.QtWidgets import ( - QWidget, QDialogButtonBox, QVBoxLayout, QTreeWidget, QTreeWidgetItem, - QLabel, QSpinBox, QGridLayout, QHBoxLayout, QLineEdit, QAbstractItemView + QAbstractItemView, QComboBox, QDialogButtonBox, QGridLayout, QHBoxLayout, + QLabel, QLineEdit, QSpinBox, QTreeWidget, QTreeWidgetItem, QVBoxLayout, + QWidget ) +from novelwriter.enum import nwItemClass from novelwriter.common import numberToRoman -from novelwriter.constants import nwUnicode -from novelwriter.gui.custom import PagedDialog, QSwitch +from novelwriter.custom import PagedDialog, QSwitch +from novelwriter.constants import nwLabels, nwUnicode logger = logging.getLogger(__name__) @@ -44,7 +46,7 @@ logger = logging.getLogger(__name__) class GuiProjectDetails(PagedDialog): def __init__(self, mainGui): - PagedDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiProjectDetails ...") self.setObjectName("GuiProjectDetails") @@ -140,7 +142,7 @@ class GuiProjectDetails(PagedDialog): class GuiProjectDetailsMain(QWidget): def __init__(self, mainGui, theProject): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) self.mainConf = novelwriter.CONFIG self.theProject = theProject @@ -272,7 +274,7 @@ class GuiProjectDetailsContents(QWidget): C_PROG = 4 def __init__(self, mainGui, theProject): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) self.mainConf = novelwriter.CONFIG self.theProject = theProject @@ -281,12 +283,26 @@ class GuiProjectDetailsContents(QWidget): # Internal self._theToC = [] + self._currentRoot = None iPx = self.mainTheme.baseIconSize hPx = self.mainConf.pxInt(12) vPx = self.mainConf.pxInt(4) pOptions = self.theProject.options + # Header + # ====== + + self.tocLabel = QLabel("%s" % self.tr("Table of Contents")) + + self.novelValue = QComboBox(self) + self.novelValue.setMinimumWidth(self.mainConf.pxInt(200)) + self.novelValue.currentIndexChanged.connect(self._novelValueChanged) + + self.headBox = QHBoxLayout() + self.headBox.addWidget(self.tocLabel) + self.headBox.addWidget(self.novelValue) + # Contents Tree # ============= @@ -389,7 +405,7 @@ class GuiProjectDetailsContents(QWidget): # ======== self.outerBox = QVBoxLayout() - self.outerBox.addWidget(QLabel("%s" % self.tr("Table of Contents"))) + self.outerBox.addLayout(self.headBox) self.outerBox.addWidget(self.tocTree) self.outerBox.addLayout(self.optionsBox) @@ -412,19 +428,35 @@ class GuiProjectDetailsContents(QWidget): def updateValues(self): """Populate the tree. """ - self._prepareData() + self._currentRoot = None + self._populateNovelList() + + rootHandle = self.novelValue.currentData() + self._prepareData(rootHandle) self._populateTree() + return ## # Internal Functions ## - def _prepareData(self): - """Extract the data for the tree. + def _populateNovelList(self): + """Fill the novel combo box with a list of all novel folders. """ - self._theToC = [] - self._theToC = self.theProject.index.getTableOfContents(2) + self.novelValue.clear() + + tIcon = self.mainTheme.getIcon(nwLabels.CLASS_ICON[nwItemClass.NOVEL]) + for tHandle, nwItem in self.theProject.tree.iterRoots(nwItemClass.NOVEL): + self.novelValue.addItem(tIcon, nwItem.itemName, tHandle) + + return + + def _prepareData(self, rootHandle): + """Extract the information from the project index. + """ + logger.debug("Populating ToC from handle '%s'", rootHandle) + self._theToC = self.theProject.index.getTableOfContents(rootHandle, 2) self._theToC.append(("", 0, self.tr("END"), 0)) return @@ -432,6 +464,18 @@ class GuiProjectDetailsContents(QWidget): # Slots ## + @pyqtSlot() + def _novelValueChanged(self): + """Refresh the tree with another root item. + """ + rootHandle = self.novelValue.currentData() + if rootHandle != self._currentRoot: + self._prepareData(rootHandle) + self._populateTree() + self._currentRoot = rootHandle + return + + @pyqtSlot() def _populateTree(self): """Set the content of the chapter/page tree. """ @@ -466,10 +510,11 @@ class GuiProjectDetailsContents(QWidget): progPage = f"{cPage:n}" progText = f"{pgProg:.1f}{nwUnicode.U_THSP}%" + hDec = self.mainTheme.getHeaderDecoration(tLevel) if tTitle.strip() == "": tTitle = self.tr("Untitled") - newItem.setIcon(self.C_TITLE, self.mainTheme.getIcon("doc_h%d" % tLevel)) + newItem.setData(self.C_TITLE, Qt.DecorationRole, hDec) newItem.setText(self.C_TITLE, tTitle) newItem.setText(self.C_WORDS, f"{wCount:n}") newItem.setText(self.C_PAGES, f"{pCount:n}") diff --git a/novelwriter/dialogs/projload.py b/novelwriter/dialogs/projload.py index c7229f44..c5568f62 100644 --- a/novelwriter/dialogs/projload.py +++ b/novelwriter/dialogs/projload.py @@ -54,7 +54,7 @@ class GuiProjectLoad(QDialog): C_TIME = 2 def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiProjectLoad ...") self.setObjectName("GuiProjectLoad") @@ -158,7 +158,6 @@ class GuiProjectLoad(QDialog): def _doOpenRecent(self): """Close the dialog window with a recent project selected. """ - logger.verbose("GuiProjectLoad open button clicked") self._saveSettings() self.openPath = None @@ -183,7 +182,6 @@ class GuiProjectLoad(QDialog): def _doBrowse(self): """Browse for a folder path. """ - logger.verbose("GuiProjectLoad browse button clicked") extFilter = [ self.tr("novelWriter Project File ({0})").format(nwFiles.PROJ_FILE), self.tr("All files ({0})").format("*"), @@ -203,7 +201,6 @@ class GuiProjectLoad(QDialog): def _doCancel(self): """Close the dialog window without doing anything. """ - logger.verbose("GuiProjectLoad close button clicked") self.openPath = None self.openState = self.NONE_STATE self.close() @@ -212,7 +209,6 @@ class GuiProjectLoad(QDialog): def _doNewProject(self): """Create a new project. """ - logger.verbose("GuiProjectLoad new project button clicked") self._saveSettings() self.openPath = None self.openState = self.NEW_STATE diff --git a/novelwriter/dialogs/projsettings.py b/novelwriter/dialogs/projsettings.py index 11a640b1..86c268d6 100644 --- a/novelwriter/dialogs/projsettings.py +++ b/novelwriter/dialogs/projsettings.py @@ -36,7 +36,7 @@ from PyQt5.QtWidgets import ( from novelwriter.enum import nwAlert from novelwriter.common import simplified -from novelwriter.gui.custom import QSwitch, PagedDialog, QConfigLayout +from novelwriter.custom import QSwitch, PagedDialog, QConfigLayout logger = logging.getLogger(__name__) @@ -44,7 +44,7 @@ logger = logging.getLogger(__name__) class GuiProjectSettings(PagedDialog): def __init__(self, mainGui): - PagedDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiProjectSettings ...") self.setObjectName("GuiProjectSettings") @@ -67,10 +67,10 @@ class GuiProjectSettings(PagedDialog): self.mainConf.pxInt(pOptions.getInt("GuiProjectSettings", "winHeight", wH)) ) - self.tabMain = GuiProjectEditMain(self.mainGui, self.theProject) - self.tabStatus = GuiProjectEditStatus(self.mainGui, self.theProject, True) - self.tabImport = GuiProjectEditStatus(self.mainGui, self.theProject, False) - self.tabReplace = GuiProjectEditReplace(self.mainGui, self.theProject) + self.tabMain = GuiProjectEditMain(self) + self.tabStatus = GuiProjectEditStatus(self, True) + self.tabImport = GuiProjectEditStatus(self, False) + self.tabReplace = GuiProjectEditReplace(self) self.addTab(self.tabMain, self.tr("Settings")) self.addTab(self.tabStatus, self.tr("Status")) @@ -96,8 +96,6 @@ class GuiProjectSettings(PagedDialog): def _doSave(self): """Save settings and close dialog. """ - logger.verbose("GuiProjectSettings save button clicked") - projName = self.tabMain.editName.text() bookTitle = self.tabMain.editTitle.text() bookAuthors = self.tabMain.editAuthors.toPlainText() @@ -166,12 +164,12 @@ class GuiProjectSettings(PagedDialog): class GuiProjectEditMain(QWidget): - def __init__(self, mainGui, theProject): - QWidget.__init__(self, mainGui) + def __init__(self, projGui): + super().__init__(parent=projGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.theProject = theProject + self.mainGui = projGui.mainGui + self.theProject = projGui.theProject # The Form self.mainForm = QConfigLayout() @@ -256,13 +254,13 @@ class GuiProjectEditStatus(QWidget): COL_ROLE = Qt.UserRole + 1 NUM_ROLE = Qt.UserRole + 2 - def __init__(self, mainGui, theProject, isStatus): - QWidget.__init__(self, mainGui) + def __init__(self, projGui, isStatus): + super().__init__(parent=projGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.theProject = theProject - self.mainTheme = mainGui.mainTheme + self.mainGui = projGui.mainGui + self.theProject = projGui.theProject + self.mainTheme = projGui.mainGui.mainTheme if isStatus: self.theStatus = self.theProject.statusItems @@ -367,11 +365,12 @@ class GuiProjectEditStatus(QWidget): newList = [] for n in range(self.listBox.topLevelItemCount()): item = self.listBox.topLevelItem(n) - newList.append({ - "key": item.data(self.COL_LABEL, self.KEY_ROLE), - "name": item.text(self.COL_LABEL), - "cols": item.data(self.COL_LABEL, self.COL_ROLE), - }) + if item is not None: + newList.append({ + "key": item.data(self.COL_LABEL, self.KEY_ROLE), + "name": item.text(self.COL_LABEL), + "cols": item.data(self.COL_LABEL, self.COL_ROLE), + }) return newList, self.colDeleted return [], [] @@ -470,7 +469,8 @@ class GuiProjectEditStatus(QWidget): self.listBox.insertTopLevelItem(nIndex, cItem) self.listBox.clearSelection() - cItem.setSelected(True) + if cItem is not None: + cItem.setSelected(True) self.colChanged = True return @@ -527,13 +527,13 @@ class GuiProjectEditReplace(QWidget): COL_KEY = 0 COL_REPL = 1 - def __init__(self, mainGui, theProject): - QWidget.__init__(self, mainGui) + def __init__(self, projGui): + super().__init__(parent=projGui) self.mainConf = novelwriter.CONFIG - self.mainGui = mainGui - self.mainTheme = mainGui.mainTheme - self.theProject = theProject + self.mainGui = projGui.mainGui + self.mainTheme = projGui.mainGui.mainTheme + self.theProject = projGui.theProject self.arChanged = False wCol0 = self.mainConf.pxInt( @@ -619,10 +619,11 @@ class GuiProjectEditReplace(QWidget): newList = {} for n in range(self.listBox.topLevelItemCount()): tItem = self.listBox.topLevelItem(n) - aKey = self._stripNotAllowed(tItem.text(0)) - aVal = tItem.text(1) - if len(aKey) > 0: - newList[aKey] = aVal + if tItem is not None: + aKey = self._stripNotAllowed(tItem.text(0)) + aVal = tItem.text(1) + if len(aKey) > 0: + newList[aKey] = aVal return newList diff --git a/novelwriter/dialogs/quotes.py b/novelwriter/dialogs/quotes.py index 299386d8..685459d4 100644 --- a/novelwriter/dialogs/quotes.py +++ b/novelwriter/dialogs/quotes.py @@ -43,7 +43,7 @@ class GuiQuoteSelect(QDialog): selectedQuote = "" def __init__(self, parent=None, currentQuote='"'): - QDialog.__init__(self, parent=parent) + super().__init__(parent=parent) self.mainConf = novelwriter.CONFIG diff --git a/novelwriter/dialogs/updates.py b/novelwriter/dialogs/updates.py index c4782e6d..1e79dc26 100644 --- a/novelwriter/dialogs/updates.py +++ b/novelwriter/dialogs/updates.py @@ -44,7 +44,7 @@ logger = logging.getLogger(__name__) class GuiUpdates(QDialog): def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiUpdates ...") self.setObjectName("GuiUpdates") @@ -135,7 +135,7 @@ class GuiUpdates(QDialog): logException() relVersion = rawData.get("tag_name", "Unknown") - relDate = rawData.get("created_at", None) + relDate = rawData.get("created_at", "") try: relDate = datetime.strptime(relDate[:10], "%Y-%m-%d").strftime("%x") diff --git a/novelwriter/dialogs/wordlist.py b/novelwriter/dialogs/wordlist.py index 9a17eed8..01a8afff 100644 --- a/novelwriter/dialogs/wordlist.py +++ b/novelwriter/dialogs/wordlist.py @@ -43,7 +43,7 @@ logger = logging.getLogger(__name__) class GuiWordList(QDialog): def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiWordList ...") self.setObjectName("GuiWordList") @@ -156,7 +156,9 @@ class GuiWordList(QDialog): try: with open(tmpFile, mode="w", encoding="utf-8") as outFile: for i in range(self.listBox.count()): - outFile.write(self.listBox.item(i).text() + "\n") + item = self.listBox.item(i) + if item is not None: + outFile.write(item.text() + "\n") except Exception: logger.error("Could not save new word list") diff --git a/novelwriter/error.py b/novelwriter/error.py index 2ceae1e3..855f3723 100644 --- a/novelwriter/error.py +++ b/novelwriter/error.py @@ -44,7 +44,8 @@ def logException(): """Log the content of an exception message. """ exType, exValue, _ = sys.exc_info() - logger.error("%s: %s", exType.__name__, str(exValue)) + if exType is not None: + logger.error("%s: %s", exType.__name__, str(exValue)) def formatException(exc): @@ -61,7 +62,7 @@ def formatException(exc): class NWErrorMessage(QDialog): def __init__(self, parent): - QDialog.__init__(self, parent=parent) + super().__init__(parent=parent) self.setObjectName("NWErrorMessage") # Widgets @@ -131,7 +132,7 @@ class NWErrorMessage(QDialog): try: import lxml - lxmlVersion = lxml.__version__ + lxmlVersion = lxml.__version__ # type: ignore except Exception: lxmlVersion = "Unknown" @@ -198,8 +199,8 @@ def exceptionHandler(exType, exValue, exTrace): try: # Try a controlled shutdown - nwGUI.closeProject(isYes=True) - nwGUI.closeMain() + nwGUI.closeProject(isYes=True) # type: ignore + nwGUI.closeMain() # type: ignore logger.info("Emergency shutdown successful") except Exception as exc: diff --git a/novelwriter/gui/doceditor.py b/novelwriter/gui/doceditor.py index 134b2e1c..8a1b60bb 100644 --- a/novelwriter/gui/doceditor.py +++ b/novelwriter/gui/doceditor.py @@ -73,7 +73,7 @@ class GuiDocEditor(QTextEdit): loadDocumentTagRequest = pyqtSignal(str, Enum) def __init__(self, mainGui): - QTextEdit.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiDocEditor ...") @@ -303,10 +303,7 @@ class GuiDocEditor(QTextEdit): self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Refresh the tab stops - if self.mainConf.verQtValue >= 51000: - self.setTabStopDistance(self.mainConf.getTabWidth()) - else: # pragma: no cover - self.setTabStopWidth(self.mainConf.getTabWidth()) + self.setTabStopDistance(self.mainConf.getTabWidth()) # Initialise the syntax highlighter self.highLight.initHighlighter() @@ -511,12 +508,12 @@ class GuiDocEditor(QTextEdit): self.setDocumentChanged(False) - oldHeader = self.theProject.index.getHandleHeaderLevel(tHandle) + oldHeader = self._nwItem.mainHeading self.theProject.index.scanText(tHandle, docText) - newHeader = self.theProject.index.getHandleHeaderLevel(tHandle) + newHeader = self._nwItem.mainHeading # ToDo: This should be a signal - if self._updateHeaders(checkLevel=True): + if self._updateHeaders(): self.mainGui.requestNovelTreeRefresh() else: self.mainGui.novelView.updateWordCounts(tHandle) @@ -604,19 +601,15 @@ class GuiDocEditor(QTextEdit): ## def getText(self): - """Get the text content of the current document. This method - uses QTextEdit->toPlainText for Qt versions lower than 5.9, and - the QTextDocument->toRawText for higher version. The latter - preserves non-breaking spaces, which the former does not. - We still want to get rid of page and line separators though. + """Get the text content of the current document. This method uses + QTextDocument->toRawText instead of toPlainText(). The former preserves + non-breaking spaces, the latter does not. We still want to get rid of + page and line separators though. See: https://doc.qt.io/qt-5/qtextdocument.html#toPlainText """ - if self.mainConf.verQtValue >= 50900: - theText = self.document().toRawText() - theText = theText.replace(nwUnicode.U_LSEP, "\n") # Line separators - theText = theText.replace(nwUnicode.U_PSEP, "\n") # Paragraph separators - else: - theText = self.toPlainText() + theText = self.document().toRawText() + theText = theText.replace(nwUnicode.U_LSEP, "\n") # Line separators + theText = theText.replace(nwUnicode.U_PSEP, "\n") # Paragraph separators return theText def getCursorPosition(self): @@ -671,7 +664,7 @@ class GuiDocEditor(QTextEdit): if theBlock: self.setCursorPosition(theBlock.position()) self.docFooter.updateLineCount() - logger.verbose("Cursor moved to line %d", theLine) + logger.debug("Cursor moved to line %d", theLine) return True @@ -725,7 +718,7 @@ class GuiDocEditor(QTextEdit): if not self._bigDoc: self.spellCheckDocument() - logger.verbose("Spell check is set to '%s'", str(theMode)) + logger.debug("Spell check is set to '%s'", str(theMode)) return True @@ -735,7 +728,7 @@ class GuiDocEditor(QTextEdit): of Qt 5.13, is to clear the text and put it back. This clears the undo stack, so we only do it for big documents. """ - logger.verbose("Running spell checker") + logger.debug("Running spell checker") if self._spellCheck: bfTime = time() qApp.setOverrideCursor(QCursor(Qt.WaitCursor)) @@ -747,7 +740,7 @@ class GuiDocEditor(QTextEdit): qApp.restoreOverrideCursor() afTime = time() logger.debug("Document highlighted in %.3f ms", 1000*(afTime-bfTime)) - self.mainGui.statusBar.setStatus(self.tr("Spell check complete")) + self.mainGui.mainStatus.setStatus(self.tr("Spell check complete")) return True @@ -770,7 +763,7 @@ class GuiDocEditor(QTextEdit): logger.error("Not a document action") return False - logger.verbose("Requesting action: %s", theAction.name) + logger.debug("Requesting action: %s", theAction.name) self._allowAutoReplace(False) if theAction == nwDocAction.UNDO: @@ -951,7 +944,7 @@ class GuiDocEditor(QTextEdit): logger.error("Invalid keyword '%s'", keyWord) return False - logger.verbose("Inserting keyword '%s'", keyWord) + logger.debug("Inserting keyword '%s'", keyWord) theState = self.insertNewBlock("%s: " % keyWord) return theState @@ -1003,7 +996,7 @@ class GuiDocEditor(QTextEdit): if self.mainConf.autoScroll: cOld = self.cursorRect().center().y() - QTextEdit.keyPressEvent(self, keyEvent) + super().keyPressEvent(keyEvent) kMod = keyEvent.modifiers() okMod = kMod == Qt.NoModifier or kMod == Qt.ShiftModifier @@ -1022,7 +1015,7 @@ class GuiDocEditor(QTextEdit): doAnim.start() else: - QTextEdit.keyPressEvent(self, keyEvent) + super().keyPressEvent(keyEvent) self.docFooter.updateLineCount() @@ -1049,7 +1042,7 @@ class GuiDocEditor(QTextEdit): theCursor = self.cursorForPosition(theEvent.pos()) self._followTag(theCursor) - QTextEdit.mouseReleaseEvent(self, theEvent) + super().mouseReleaseEvent(theEvent) self.docFooter.updateLineCount() return @@ -1059,7 +1052,7 @@ class GuiDocEditor(QTextEdit): has its margins adjusted according to user preferences. """ self.updateDocMargins() - QTextEdit.resizeEvent(self, theEvent) + super().resizeEvent(theEvent) return ## @@ -1179,7 +1172,7 @@ class GuiDocEditor(QTextEdit): spellCheck &= theWord != "" if spellCheck: - logger.verbose("Looking up '%s' in the dictionary", theWord) + logger.debug("Looking up '%s' in the dictionary", theWord) spellCheck &= not self.spEnchant.checkWord(theWord) if spellCheck: @@ -1245,11 +1238,11 @@ class GuiDocEditor(QTextEdit): return if self.wCounterDoc.isRunning(): - logger.verbose("Word counter is busy") + logger.debug("Word counter is busy") return if time() - self._lastEdit < 5 * self.wcInterval: - logger.verbose("Running word counter") + logger.debug("Running word counter") self.mainGui.threadPool.start(self.wCounterDoc) return @@ -1261,7 +1254,7 @@ class GuiDocEditor(QTextEdit): if self._docHandle is None or self._nwItem is None: return - logger.verbose("Updating word count") + logger.debug("Updating word count") self._charCount = cCount self._wordCount = wCount @@ -1304,7 +1297,7 @@ class GuiDocEditor(QTextEdit): return if self.wCounterSel.isRunning(): - logger.verbose("Selection word counter is busy") + logger.debug("Selection word counter is busy") return self.mainGui.threadPool.start(self.wCounterSel) @@ -1318,7 +1311,7 @@ class GuiDocEditor(QTextEdit): if self._docHandle is None or self._nwItem is None: return - logger.verbose("User selectee %d words", wCount) + logger.debug("User selectee %d words", wCount) self.docFooter.updateCounts(wCount=wCount, cCount=cCount) self.wcTimerSel.stop() @@ -1336,11 +1329,11 @@ class GuiDocEditor(QTextEdit): QPointF(theSize.width(), theSize.height()), Qt.FuzzyHit ) if self._queuePos <= thePos: - logger.verbose("Allowed cursor move to %d <= %d", self._queuePos, thePos) + logger.debug("Allowed cursor move to %d <= %d", self._queuePos, thePos) self.setCursorPosition(self._queuePos) self._queuePos = None else: - logger.verbose("Denied cursor move to %d > %d", self._queuePos, thePos) + logger.debug("Denied cursor move to %d > %d", self._queuePos, thePos) return @@ -1527,7 +1520,7 @@ class GuiDocEditor(QTextEdit): theCursor.endEditBlock() theCursor.setPosition(theCursor.selectionEnd()) self.setTextCursor(theCursor) - logger.verbose( + logger.debug( "Replaced occurrence of '%s' with '%s' on line %d", searchFor, replWith, theCursor.blockNumber() ) @@ -1905,10 +1898,10 @@ class GuiDocEditor(QTextEdit): return False if loadTag: - logger.verbose("Attempting to follow tag '%s'", theWord) + logger.debug("Attempting to follow tag '%s'", theWord) self.loadDocumentTagRequest.emit(theWord, nwDocMode.VIEW) else: - logger.verbose("Potential tag '%s'", theWord) + logger.debug("Potential tag '%s'", theWord) return True @@ -1992,13 +1985,22 @@ class GuiDocEditor(QTextEdit): nDelete = 3 tInsert = nwUnicode.U_HELLIP + elif theOne == nwUnicode.U_LSEP: + # This resolves issue #1150 + nDelete = 1 + tInsert = nwUnicode.U_PSEP + tCheck = tInsert - if tCheck in self.mainConf.fmtPadBefore: + if self.mainConf.fmtPadBefore and tCheck in self.mainConf.fmtPadBefore: if self._allowSpaceBeforeColon(theText, tCheck): nDelete = max(nDelete, 1) + chkPos = thePos - nDelete - 1 + if chkPos >= 0 and theText[chkPos].isspace(): + # Strip existing space before inserting a new (#1061) + nDelete += 1 tInsert = self._typPadChar + tInsert - if tCheck in self.mainConf.fmtPadAfter: + if self.mainConf.fmtPadAfter and tCheck in self.mainConf.fmtPadAfter: if self._allowSpaceBeforeColon(theText, tCheck): nDelete = max(nDelete, 1) tInsert = tInsert + self._typPadChar @@ -2023,7 +2025,7 @@ class GuiDocEditor(QTextEdit): return False return True - def _updateHeaders(self, checkPos=False, checkLevel=False): + def _updateHeaders(self): """Update the headers record and return True if anything changed, if a check flag was provided. """ @@ -2031,21 +2033,12 @@ class GuiDocEditor(QTextEdit): return False newHeaders = self.theProject.index.getHandleHeaders(self._docHandle) - if checkPos: - newPos = [x[0] for x in newHeaders] - oldPos = [x[0] for x in self._docHeaders] - if checkLevel: - newLev = [x[1] for x in newHeaders] - oldLev = [x[1] for x in self._docHeaders] + newLev = [x[1] for x in newHeaders] + oldLev = [x[1] for x in self._docHeaders] self._docHeaders = newHeaders - if checkPos: - return newPos != oldPos - if checkLevel: - return newLev != oldLev - - return False + return newLev != oldLev def _checkDocSize(self, theSize): """Check if document size crosses the big document limit set in @@ -2152,7 +2145,7 @@ class GuiDocEditor(QTextEdit): class BackgroundWordCounter(QRunnable): def __init__(self, docEditor, forSelection=False): - QRunnable.__init__(self) + super().__init__() self._docEditor = docEditor self._forSelection = forSelection @@ -2202,7 +2195,7 @@ class BackgroundWordCounterSignals(QObject): class GuiDocEditSearch(QFrame): def __init__(self, docEditor): - QFrame.__init__(self, docEditor) + super().__init__(parent=docEditor) logger.debug("Initialising GuiDocEditSearch ...") @@ -2429,7 +2422,6 @@ class GuiDocEditSearch(QFrame): self.searchBox.selectAll() if self.isRegEx: self._alertSearchValid(True) - logger.verbose("Setting search text to '%s'", theText) return True def setReplaceText(self, theText): @@ -2469,7 +2461,8 @@ class GuiDocEditSearch(QFrame): self._alertSearchValid(theRegEx.isValid()) return theRegEx - else: # >= 50300 to < 51300 + else: # pragma: no cover + # >= 50300 to < 51300 if self.isCaseSense: rxOpt = Qt.CaseSensitive else: @@ -2590,7 +2583,7 @@ class GuiDocEditSearch(QFrame): class GuiDocEditHeader(QWidget): def __init__(self, docEditor): - QWidget.__init__(self, docEditor) + super().__init__(parent=docEditor) logger.debug("Initialising GuiDocEditHeader ...") @@ -2636,7 +2629,7 @@ class GuiDocEditHeader(QWidget): self.editButton.setStyleSheet(buttonStyle) self.editButton.setToolButtonStyle(Qt.ToolButtonIconOnly) self.editButton.setVisible(False) - self.editButton.setToolTip(self.tr("Edit document meta")) + self.editButton.setToolTip(self.tr("Edit document label")) self.editButton.clicked.connect(self._editDocument) self.searchButton = QToolButton(self) @@ -2814,7 +2807,7 @@ class GuiDocEditHeader(QWidget): class GuiDocEditFooter(QWidget): def __init__(self, docEditor): - QWidget.__init__(self, docEditor) + super().__init__(parent=docEditor) logger.debug("Initialising GuiDocEditFooter ...") @@ -2942,7 +2935,7 @@ class GuiDocEditFooter(QWidget): """ self._docHandle = tHandle if self._docHandle is None: - logger.verbose("No handle set, so clearing the editor footer") + logger.debug("No handle set, so clearing the editor footer") self._theItem = None else: self._theItem = self.theProject.tree[self._docHandle] @@ -2969,8 +2962,7 @@ class GuiDocEditFooter(QWidget): else: theStatus, theIcon = self._theItem.getImportStatus() sIcon = theIcon.pixmap(self.sPx, self.sPx) - hLevel = self.theProject.index.getHandleHeaderLevel(self._docHandle) - sText = f"{theStatus} / {self._theItem.describeMe(hLevel)}" + sText = f"{theStatus} / {self._theItem.describeMe()}" self.statusIcon.setPixmap(sIcon) self.statusText.setText(sText) diff --git a/novelwriter/gui/dochighlight.py b/novelwriter/gui/dochighlight.py index 8b7ec1a5..91aa0416 100644 --- a/novelwriter/gui/dochighlight.py +++ b/novelwriter/gui/dochighlight.py @@ -47,7 +47,7 @@ class GuiDocHighlighter(QSyntaxHighlighter): BLOCK_TITLE = 4 def __init__(self, theDoc, mainGui, spEnchant): - QSyntaxHighlighter.__init__(self, theDoc) + super().__init__(theDoc) logger.debug("Initialising GuiDocHighlighter ...") self.mainConf = novelwriter.CONFIG diff --git a/novelwriter/gui/docviewer.py b/novelwriter/gui/docviewer.py index 6ce275a3..644c3b6d 100644 --- a/novelwriter/gui/docviewer.py +++ b/novelwriter/gui/docviewer.py @@ -54,7 +54,7 @@ class GuiDocViewer(QTextBrowser): loadDocumentTagRequest = pyqtSignal(str, Enum) def __init__(self, mainGui): - QTextBrowser.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiDocViewer ...") @@ -150,10 +150,7 @@ class GuiDocViewer(QTextBrowser): self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded) # Refresh the tab stops - if self.mainConf.verQtValue >= 51000: - self.setTabStopDistance(self.mainConf.getTabWidth()) - else: - self.setTabStopWidth(self.mainConf.getTabWidth()) + self.setTabStopDistance(self.mainConf.getTabWidth()) # If we have a document open, we should reload it in case the font changed if self._docHandle is not None: @@ -193,10 +190,7 @@ class GuiDocViewer(QTextBrowser): return False # Refresh the tab stops - if self.mainConf.verQtValue >= 51000: - self.setTabStopDistance(self.mainConf.getTabWidth()) - else: - self.setTabStopWidth(self.mainConf.getTabWidth()) + self.setTabStopDistance(self.mainConf.getTabWidth()) # Must be before setHtml if updateHistory: @@ -247,7 +241,7 @@ class GuiDocViewer(QTextBrowser): """Wrapper function for various document actions on the current document. """ - logger.verbose("Requesting action: '%s'", theAction.name) + logger.debug("Requesting action: '%s'", theAction.name) if self._docHandle is None: logger.error("No document open") return False @@ -270,7 +264,7 @@ class GuiDocViewer(QTextBrowser): if not isinstance(tAnchor, str): return False if tAnchor.startswith("#"): - logger.verbose("Moving to anchor '%s'", tAnchor) + logger.debug("Moving to anchor '%s'", tAnchor) self.setSource(QUrl(tAnchor)) return True @@ -356,7 +350,7 @@ class GuiDocViewer(QTextBrowser): theBlock = self.document().findBlockByLineNumber(theLine) if theBlock: self.setCursorPosition(theBlock.position()) - logger.verbose("Cursor moved to line %d", theLine) + logger.debug("Cursor moved to line %d", theLine) return True def setScrollPosition(self, thePos): @@ -402,7 +396,7 @@ class GuiDocViewer(QTextBrowser): """Process a clicked link internally in the document. """ theLink = theURL.url() - logger.verbose("Clicked link: '%s'", theLink) + logger.debug("Clicked link: '%s'", theLink) if len(theLink) > 0: theBits = theLink.split("=") if len(theBits) == 2: @@ -461,7 +455,7 @@ class GuiDocViewer(QTextBrowser): has its margins adjusted according to user preferences. """ self.updateDocMargins() - QTextBrowser.resizeEvent(self, theEvent) + super().resizeEvent(theEvent) return def mouseReleaseEvent(self, theEvent): @@ -472,7 +466,7 @@ class GuiDocViewer(QTextBrowser): elif theEvent.button() == Qt.ForwardButton: self.navForward() else: - QTextBrowser.mouseReleaseEvent(self, theEvent) + super().mouseReleaseEvent(theEvent) return ## @@ -568,7 +562,7 @@ class GuiDocViewer(QTextBrowser): # END Class GuiDocViewer -class GuiDocViewHistory(): +class GuiDocViewHistory: def __init__(self, docViewer): @@ -584,7 +578,7 @@ class GuiDocViewHistory(): def clear(self): """Clear the view history. """ - logger.verbose("View history cleared") + logger.debug("View history cleared") self._navHistory = [] self._posHistory = [] self._currPos = -1 @@ -598,7 +592,7 @@ class GuiDocViewHistory(): """ if self._currPos >= 0 and self._currPos < len(self._navHistory): if tHandle == self._navHistory[self._currPos]: - logger.verbose("Not updating view hsitory") + logger.debug("Not updating view hsitory") return False self._truncateHistory(self._currPos) @@ -613,7 +607,7 @@ class GuiDocViewHistory(): self._dumpHistory() - logger.verbose("Added '%s' to view history", tHandle) + logger.debug("Added '%s' to view history", tHandle) return True @@ -622,7 +616,7 @@ class GuiDocViewHistory(): """ newPos = self._currPos + 1 if newPos < len(self._navHistory): - logger.verbose("Move forward in view history") + logger.debug("Move forward in view history") self._prevPos = self._currPos self._updateScrollBar() @@ -640,7 +634,7 @@ class GuiDocViewHistory(): """ newPos = self._currPos - 1 if newPos >= 0: - logger.verbose("Move backward in view history") + logger.debug("Move backward in view history") self._prevPos = self._currPos self._updateScrollBar() @@ -686,11 +680,11 @@ class GuiDocViewHistory(): def _dumpHistory(self): """Debug function to dump history to the logger. Since it is a - for loop, it is skipped entirely if log level isn't VERBOSE. + for loop, it is skipped entirely if log level isn't DEBUG. """ - if logger.getEffectiveLevel() < logging.DEBUG: + if logger.getEffectiveLevel() == logging.DEBUG: for i, (h, p) in enumerate(zip(self._navHistory, self._posHistory)): - logger.verbose( + logger.debug( "History %02d: %s %13s [x:%d]" % ( i + 1, ">" if i == self._currPos else " ", h, p ) @@ -708,7 +702,7 @@ class GuiDocViewHistory(): class GuiDocViewHeader(QWidget): def __init__(self, docViewer): - QWidget.__init__(self, docViewer) + super().__init__(parent=docViewer) logger.debug("Initialising GuiDocViewHeader ...") @@ -915,7 +909,7 @@ class GuiDocViewHeader(QWidget): class GuiDocViewFooter(QWidget): def __init__(self, docViewer): - QWidget.__init__(self, docViewer) + super().__init__(parent=docViewer) logger.debug("Initialising GuiDocViewFooter ...") @@ -1110,7 +1104,7 @@ class GuiDocViewFooter(QWidget): def _doToggleSticky(self, theState): """Toggle the sticky flag for the reference panel. """ - logger.verbose("Reference sticky is %s", str(theState)) + logger.debug("Reference sticky is %s", str(theState)) self.docViewer.stickyRef = theState if not theState and self.docViewer.docHandle() is not None: self.viewMeta.refreshReferences(self.docViewer.docHandle()) @@ -1141,7 +1135,7 @@ class GuiDocViewFooter(QWidget): class GuiDocViewDetails(QScrollArea): def __init__(self, mainGui): - QScrollArea.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiDocViewDetails ...") self.mainConf = novelwriter.CONFIG @@ -1205,7 +1199,7 @@ class GuiDocViewDetails(QScrollArea): """Capture the link-click and forward it to the document viewer class for handling. """ - logger.verbose("Clicked link: '%s'", theLink) + logger.debug("Clicked link: '%s'", theLink) if len(theLink) == 21: tHandle = theLink[:13] tAnchor = theLink[13:] diff --git a/novelwriter/gui/itemdetails.py b/novelwriter/gui/itemdetails.py index a467ed04..a99650c2 100644 --- a/novelwriter/gui/itemdetails.py +++ b/novelwriter/gui/itemdetails.py @@ -38,7 +38,7 @@ logger = logging.getLogger(__name__) class GuiItemDetails(QWidget): def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiItemDetails ...") self.mainConf = novelwriter.CONFIG @@ -247,7 +247,7 @@ class GuiItemDetails(QWidget): theLabel = theLabel[:96].rstrip()+" ..." if nwItem.isFileType(): - if nwItem.isExported: + if nwItem.isActive: self.labelIcon.setPixmap(self._expCheck) else: self.labelIcon.setPixmap(self._expCross) @@ -273,12 +273,11 @@ class GuiItemDetails(QWidget): # Layout # ====== - hLevel = self.theProject.index.getHandleHeaderLevel(tHandle) usageIcon = self.mainTheme.getItemIcon( - nwItem.itemType, nwItem.itemClass, nwItem.itemLayout, hLevel + nwItem.itemType, nwItem.itemClass, nwItem.itemLayout, nwItem.mainHeading ) self.usageIcon.setPixmap(usageIcon.pixmap(iPx, iPx)) - self.usageData.setText(nwItem.describeMe(hLevel)) + self.usageData.setText(nwItem.describeMe()) # Counts # ====== diff --git a/novelwriter/gui/mainmenu.py b/novelwriter/gui/mainmenu.py index 59af7691..a110cb8a 100644 --- a/novelwriter/gui/mainmenu.py +++ b/novelwriter/gui/mainmenu.py @@ -40,9 +40,13 @@ logger = logging.getLogger(__name__) class GuiMainMenu(QMenuBar): + """The GUI main menu. All menu actions are defined here with the + main menu as the owner. Each widget that need them elsewhere need to + add them from this class. + """ def __init__(self, mainGui): - QMenuBar.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiMainMenu ...") self.mainConf = novelwriter.CONFIG @@ -79,12 +83,6 @@ class GuiMainMenu(QMenuBar): self.aSpellCheck.setChecked(theMode) return - def setFocusMode(self, theMode): - """Forward focus mode check state to its action. - """ - self.aFocusMode.setChecked(theMode) - return - ## # Slots ## @@ -164,14 +162,14 @@ class GuiMainMenu(QMenuBar): # Project > Edit self.aEditItem = QAction(self.tr("Rename Item"), self) - self.aEditItem.setShortcuts(["F2"]) + self.aEditItem.setShortcut("F2") self.aEditItem.triggered.connect(lambda: self.mainGui.editItemLabel(None)) self.projMenu.addAction(self.aEditItem) # Project > Delete self.aDeleteItem = QAction(self.tr("Delete Item"), self) self.aDeleteItem.setShortcut("Ctrl+Shift+Del") - self.aDeleteItem.triggered.connect(lambda: self.mainGui.projView.deleteItem(None)) + self.aDeleteItem.triggered.connect(lambda: self.mainGui.projView.requestDeleteItem(None)) self.projMenu.addAction(self.aDeleteItem) # Project > Empty Trash @@ -244,16 +242,6 @@ class GuiMainMenu(QMenuBar): self.aImportFile.triggered.connect(lambda: self.mainGui.importDocument()) self.docuMenu.addAction(self.aImportFile) - # Document > Merge Documents - self.aMergeDocs = QAction(self.tr("Merge Folder to Document"), self) - self.aMergeDocs.triggered.connect(lambda: self.mainGui.mergeDocuments()) - self.docuMenu.addAction(self.aMergeDocs) - - # Document > Split Document - self.aSplitDoc = QAction(self.tr("Split Document to Folder"), self) - self.aSplitDoc.triggered.connect(lambda: self.mainGui.splitDocument()) - self.docuMenu.addAction(self.aSplitDoc) - return def _buildEditMenu(self): @@ -375,8 +363,6 @@ class GuiMainMenu(QMenuBar): # View > Focus Mode self.aFocusMode = QAction(self.tr("Focus Mode"), self) self.aFocusMode.setShortcut("F8") - self.aFocusMode.setCheckable(True) - self.aFocusMode.setChecked(self.mainGui.isFocusMode) self.aFocusMode.triggered.connect(lambda: self.mainGui.toggleFocusMode()) self.viewMenu.addAction(self.aFocusMode) diff --git a/novelwriter/gui/noveltree.py b/novelwriter/gui/noveltree.py index c8d88b88..acadd29f 100644 --- a/novelwriter/gui/noveltree.py +++ b/novelwriter/gui/noveltree.py @@ -63,7 +63,7 @@ class GuiNovelView(QWidget): openDocumentRequest = pyqtSignal(str, Enum, int, str) def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) self.mainGui = mainGui self.theProject = mainGui.theProject @@ -166,7 +166,7 @@ class GuiNovelView(QWidget): class GuiNovelToolBar(QWidget): def __init__(self, novelView): - QTreeWidget.__init__(self, novelView) + super().__init__(parent=novelView) logger.debug("Initialising GuiNovelToolBar ...") @@ -333,7 +333,7 @@ class GuiNovelTree(QTreeWidget): D_KEY = Qt.UserRole + 2 def __init__(self, novelView): - QTreeWidget.__init__(self, novelView) + super().__init__(parent=novelView) logger.debug("Initialising GuiNovelTree ...") @@ -390,13 +390,6 @@ class GuiNovelTree(QTreeWidget): fH2.setBold(True) self._hFonts = [self.font(), fH1, fH2, self.font(), self.font()] - self._pIndent = [ - self.mainTheme.loadDecoration("deco_doc_h0", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h1", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h2", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h3", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h4", pxH=iPx), - ] self._pMore = self.mainTheme.loadDecoration("deco_doc_more", pxH=iPx) # Connect signals @@ -450,14 +443,14 @@ class GuiNovelTree(QTreeWidget): def refreshTree(self, rootHandle=None, overRide=False): """Called whenever the Novel tab is activated. """ - logger.verbose("Requesting refresh of the novel tree") + logger.debug("Requesting refresh of the novel tree") if rootHandle is None: rootHandle = self.theProject.tree.findRoot(nwItemClass.NOVEL) treeChanged = self.mainGui.projView.changedSince(self._lastBuild) indexChanged = self.theProject.index.rootChangedSince(rootHandle, self._lastBuild) if not (treeChanged or indexChanged or overRide): - logger.verbose("No changes have been made to the novel index") + logger.debug("No changes have been made to the novel index") return selItem = self.selectedItems() @@ -515,18 +508,19 @@ class GuiNovelTree(QTreeWidget): self._actHandle = tHandle for i in range(self.topLevelItemCount()): tItem = self.topLevelItem(i) - if tItem.data(self.C_TITLE, self.D_HANDLE) == tHandle: - tItem.setBackground(self.C_TITLE, self.palette().alternateBase()) - tItem.setBackground(self.C_WORDS, self.palette().alternateBase()) - tItem.setBackground(self.C_EXTRA, self.palette().alternateBase()) - tItem.setBackground(self.C_MORE, self.palette().alternateBase()) - else: - tItem.setBackground(self.C_TITLE, self.palette().base()) - tItem.setBackground(self.C_WORDS, self.palette().base()) - tItem.setBackground(self.C_EXTRA, self.palette().base()) - tItem.setBackground(self.C_MORE, self.palette().base()) + if tItem is not None: + if tItem.data(self.C_TITLE, self.D_HANDLE) == tHandle: + tItem.setBackground(self.C_TITLE, self.palette().alternateBase()) + tItem.setBackground(self.C_WORDS, self.palette().alternateBase()) + tItem.setBackground(self.C_EXTRA, self.palette().alternateBase()) + tItem.setBackground(self.C_MORE, self.palette().alternateBase()) + else: + tItem.setBackground(self.C_TITLE, self.palette().base()) + tItem.setBackground(self.C_WORDS, self.palette().base()) + tItem.setBackground(self.C_EXTRA, self.palette().base()) + tItem.setBackground(self.C_MORE, self.palette().base()) - logger.verbose("Highlighted Novel Tree in %.3f ms", (time() - tStart)*1000) + logger.debug("Highlighted Novel Tree in %.3f ms", (time() - tStart)*1000) return @@ -539,7 +533,7 @@ class GuiNovelTree(QTreeWidget): mouse in a blank area of the tree view, and to load a document for viewing if the user middle-clicked. """ - QTreeWidget.mousePressEvent(self, theEvent) + super().mousePressEvent(theEvent) if theEvent.button() == Qt.LeftButton: selItem = self.indexAt(theEvent.pos()) @@ -562,7 +556,7 @@ class GuiNovelTree(QTreeWidget): def focusOutEvent(self, theEvent): """Clear the selection when the tree no longer has focus. """ - QTreeWidget.focusOutEvent(self, theEvent) + super().focusOutEvent(theEvent) self.clearSelection() return @@ -610,7 +604,7 @@ class GuiNovelTree(QTreeWidget): """ self.clearContent() tStart = time() - logger.verbose("Building novel tree for root item '%s'", rootHandle) + logger.debug("Building novel tree for root item '%s'", rootHandle) novStruct = self.theProject.index.novelStructure(rootHandle=rootHandle, skipExcl=True) for tKey, tHandle, sTitle, novIdx in novStruct: @@ -619,8 +613,10 @@ class GuiNovelTree(QTreeWidget): if iLevel == 0: continue + hDec = self.mainTheme.getHeaderDecoration(iLevel) + newItem = QTreeWidgetItem() - newItem.setData(self.C_TITLE, Qt.DecorationRole, self._pIndent[iLevel]) + newItem.setData(self.C_TITLE, Qt.DecorationRole, hDec) newItem.setText(self.C_TITLE, novIdx.title) newItem.setData(self.C_TITLE, self.D_HANDLE, tHandle) newItem.setData(self.C_TITLE, self.D_TITLE, sTitle) @@ -641,7 +637,7 @@ class GuiNovelTree(QTreeWidget): self.setActiveHandle(self._actHandle) - logger.verbose("Novel Tree built in %.3f ms", (time() - tStart)*1000) + logger.debug("Novel Tree built in %.3f ms", (time() - tStart)*1000) self._lastBuild = time() return diff --git a/novelwriter/gui/outline.py b/novelwriter/gui/outline.py index e8514c15..bb900d9f 100644 --- a/novelwriter/gui/outline.py +++ b/novelwriter/gui/outline.py @@ -57,7 +57,7 @@ class GuiOutlineView(QWidget): loadDocumentTagRequest = pyqtSignal(str, Enum) def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) self.mainConf = novelwriter.CONFIG self.mainGui = mainGui @@ -198,7 +198,7 @@ class GuiOutlineToolBar(QToolBar): viewColumnToggled = pyqtSignal(bool, Enum) def __init__(self, theOutline): - QTreeWidget.__init__(self, theOutline) + super().__init__(parent=theOutline) logger.debug("Initialising GuiOutlineToolBar ...") @@ -357,7 +357,7 @@ class GuiOutlineTree(QTreeWidget): activeItemChanged = pyqtSignal(str, str) def __init__(self, theOutline): - QTreeWidget.__init__(self, theOutline) + super().__init__(parent=theOutline) logger.debug("Initialising GuiOutlineTree ...") @@ -391,13 +391,6 @@ class GuiOutlineTree(QTreeWidget): fH2.setBold(True) self._hFonts = [self.font(), fH1, fH2, self.font(), self.font()] - self._pIndent = [ - self.mainTheme.loadDecoration("deco_doc_h0", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h1", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h2", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h3", pxH=iPx), - self.mainTheme.loadDecoration("deco_doc_h4", pxH=iPx), - ] self._dIcon = { "H0": self.mainTheme.getItemIcon(nwItemType.FILE, None, nwItemLayout.DOCUMENT, "H0"), "H1": self.mainTheme.getItemIcon(nwItemType.FILE, None, nwItemLayout.DOCUMENT, "H1"), @@ -491,7 +484,7 @@ class GuiOutlineTree(QTreeWidget): # was last built, we rebuild the tree from the updated index. indexChanged = self.theProject.index.rootChangedSince(rootHandle, self._lastBuild) if not (novelChanged or indexChanged or overRide): - logger.verbose("No changes have been made to the novel index") + logger.debug("No changes have been made to the novel index") return self._populateTree(rootHandle) @@ -561,11 +554,9 @@ class GuiOutlineTree(QTreeWidget): """Receive the changes to column visibility forwarded by the column selection menu. """ - logger.verbose("User toggled Outline column '%s'", theItem.name) if theItem in self._colIdx: self.setColumnHidden(self._colIdx[theItem], not isChecked) self._saveHeaderState() - return ## @@ -684,28 +675,29 @@ class GuiOutlineTree(QTreeWidget): self.setColumnHidden(self._colIdx[nwOutline.TITLE], False) headItem = self.headerItem() - headItem.setTextAlignment(self._colIdx[nwOutline.CCOUNT], Qt.AlignRight) - headItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight) - headItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight) + if headItem is not None: + headItem.setTextAlignment(self._colIdx[nwOutline.CCOUNT], Qt.AlignRight) + headItem.setTextAlignment(self._colIdx[nwOutline.WCOUNT], Qt.AlignRight) + headItem.setTextAlignment(self._colIdx[nwOutline.PCOUNT], Qt.AlignRight) novStruct = self.theProject.index.novelStructure(rootHandle=rootHandle, skipExcl=True) for _, tHandle, sTitle, novIdx in novStruct: iLevel = nwHeaders.H_LEVEL.get(novIdx.level, 0) - dLevel = self.theProject.index.getHandleHeaderLevel(tHandle) if iLevel == 0: continue trItem = QTreeWidgetItem() nwItem = self.theProject.tree[tHandle] + hDec = self.mainTheme.getHeaderDecoration(iLevel) - trItem.setData(self._colIdx[nwOutline.TITLE], Qt.DecorationRole, self._pIndent[iLevel]) + trItem.setData(self._colIdx[nwOutline.TITLE], Qt.DecorationRole, hDec) trItem.setText(self._colIdx[nwOutline.TITLE], novIdx.title) trItem.setData(self._colIdx[nwOutline.TITLE], self.D_HANDLE, tHandle) trItem.setData(self._colIdx[nwOutline.TITLE], self.D_TITLE, sTitle) trItem.setFont(self._colIdx[nwOutline.TITLE], self._hFonts[iLevel]) trItem.setText(self._colIdx[nwOutline.LEVEL], novIdx.level) - trItem.setIcon(self._colIdx[nwOutline.LABEL], self._dIcon[dLevel]) + trItem.setIcon(self._colIdx[nwOutline.LABEL], self._dIcon[nwItem.mainHeading]) trItem.setText(self._colIdx[nwOutline.LABEL], nwItem.itemName) trItem.setText(self._colIdx[nwOutline.LINE], sTitle[1:].lstrip("0")) trItem.setText(self._colIdx[nwOutline.SYNOP], novIdx.synopsis) @@ -741,7 +733,7 @@ class GuiOutlineHeaderMenu(QMenu): columnToggled = pyqtSignal(bool, Enum) def __init__(self, theOutline): - QMenu.__init__(self, theOutline) + super().__init__(parent=theOutline) self.acceptToggle = True @@ -792,7 +784,7 @@ class GuiOutlineDetails(QScrollArea): itemTagClicked = pyqtSignal(str) def __init__(self, theOutline): - QScrollArea.__init__(self, theOutline) + super().__init__(parent=theOutline) logger.debug("Initialising GuiOutlineDetails ...") @@ -1048,7 +1040,7 @@ class GuiOutlineDetails(QScrollArea): self.titleLabel.setText("%s" % self.tr("Title")) self.titleValue.setText(novIdx.title) - itemStatus, _ = nwItem.getImportStatus() + itemStatus, _ = nwItem.getImportStatus(incIcon=False) self.fileValue.setText(nwItem.itemName) self.itemValue.setText(itemStatus) diff --git a/novelwriter/gui/projtree.py b/novelwriter/gui/projtree.py index e6acd81d..96dc98f1 100644 --- a/novelwriter/gui/projtree.py +++ b/novelwriter/gui/projtree.py @@ -34,15 +34,15 @@ from time import time from PyQt5.QtGui import QPalette from PyQt5.QtCore import Qt, QSize, pyqtSignal, pyqtSlot from PyQt5.QtWidgets import ( - QAbstractItemView, QFrame, QHBoxLayout, QHeaderView, QLabel, + QAbstractItemView, QDialog, QFrame, QHBoxLayout, QHeaderView, QLabel, QMenu, QShortcut, QSizePolicy, QToolButton, QTreeWidget, QTreeWidgetItem, QVBoxLayout, QWidget ) -from novelwriter.core import NWDoc +from novelwriter.core import DocMerger, DocSplitter from novelwriter.enum import nwDocMode, nwItemType, nwItemClass, nwItemLayout, nwAlert +from novelwriter.dialogs import GuiDocMerge, GuiDocSplit, GuiEditLabel from novelwriter.constants import nwHeaders, trConst, nwLabels -from novelwriter.dialogs.editlabel import GuiEditLabel logger = logging.getLogger(__name__) @@ -63,7 +63,7 @@ class GuiProjectView(QWidget): openDocumentRequest = pyqtSignal(str, Enum, int, str) def __init__(self, mainGui): - QWidget.__init__(self, mainGui) + super().__init__(parent=mainGui) self.mainGui = mainGui @@ -106,7 +106,7 @@ class GuiProjectView(QWidget): self.renameTreeItem = self.projTree.renameTreeItem self.getTreeFromHandle = self.projTree.getTreeFromHandle self.emptyTrash = self.projTree.emptyTrash - self.deleteItem = self.projTree.deleteItem + self.requestDeleteItem = self.projTree.requestDeleteItem self.setTreeItemValues = self.projTree.setTreeItemValues self.propagateCount = self.projTree.propagateCount self.getSelectedHandle = self.projTree.getSelectedHandle @@ -120,18 +120,33 @@ class GuiProjectView(QWidget): ## def initSettings(self): + """Initialise GUI elements that depend on specific settings. + """ self.projTree.initSettings() return def clearProject(self): + """Clear project-related GUI content. + """ + self.projBar.clearContent() self.projTree.clearTree() return - def saveProjectTree(self): + def openProjectTasks(self): + """Run open project tasks. + """ + self.projBar.buildQuickLinkMenu() + return + + def saveProjectTasks(self): + """Run save project tasks. + """ self.projTree.saveTreeOrder() return def populateTree(self): + """Build the tree structure from project data. + """ self.projTree.buildTree() return @@ -158,13 +173,20 @@ class GuiProjectView(QWidget): self.wordCountsChanged.emit() return + @pyqtSlot(str) + def updateRootItem(self, tHandle): + """If any root item changes, rebuild the quick link root menu. + """ + self.projBar.buildQuickLinkMenu() + return + # END Class GuiProjectView class GuiProjectToolBar(QWidget): def __init__(self, projView): - QTreeWidget.__init__(self, projView) + super().__init__(parent=projView) logger.debug("Initialising GuiProjectToolBar ...") @@ -196,6 +218,18 @@ class GuiProjectToolBar(QWidget): self.viewLabel.setContentsMargins(0, 0, 0, 0) self.viewLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) + # Quick Links + self.mQuick = QMenu() + + self.tbQuick = QToolButton(self) + self.tbQuick.setToolTip("%s [Ctrl+L]" % self.tr("Quick Links")) + self.tbQuick.setShortcut("Ctrl+L") + self.tbQuick.setIcon(self.mainTheme.getIcon("bookmark")) + self.tbQuick.setIconSize(QSize(iPx, iPx)) + self.tbQuick.setStyleSheet(buttonStyle) + self.tbQuick.setMenu(self.mQuick) + self.tbQuick.setPopupMode(QToolButton.InstantPopup) + # Move Buttons self.tbMoveU = QToolButton(self) self.tbMoveU.setToolTip("%s [Ctrl+Up]" % self.tr("Move Up")) @@ -268,6 +302,12 @@ class GuiProjectToolBar(QWidget): # More Options Menu self.mMore = QMenu() + self.aExpand = self.mMore.addAction(self.tr("Expand All")) + self.aExpand.triggered.connect(lambda: self.projTree.setExpandedFromHandle(None, True)) + + self.aCollapse = self.mMore.addAction(self.tr("Collapse All")) + self.aCollapse.triggered.connect(lambda: self.projTree.setExpandedFromHandle(None, False)) + self.aMoreUndo = self.mMore.addAction(self.tr("Undo Move")) self.aMoreUndo.triggered.connect(lambda: self.projTree.undoLastMove()) @@ -285,6 +325,7 @@ class GuiProjectToolBar(QWidget): # Assemble self.outerBox = QHBoxLayout() self.outerBox.addWidget(self.viewLabel) + self.outerBox.addWidget(self.tbQuick) self.outerBox.addWidget(self.tbMoveU) self.outerBox.addWidget(self.tbMoveD) self.outerBox.addWidget(self.tbAdd) @@ -298,6 +339,32 @@ class GuiProjectToolBar(QWidget): return + ## + # Methods + ## + + def clearContent(self): + """Clear dynamic content on the tool bar. + """ + self.mQuick.clear() + return + + def buildQuickLinkMenu(self): + """Build the quick link menu. + """ + logger.debug("Rebuilding quick links menu") + + self.mQuick.clear() + for n, (tHandle, nwItem) in enumerate(self.theProject.tree.iterRoots(None)): + aRoot = self.mQuick.addAction(nwItem.itemName) + aRoot.setData(tHandle) + aRoot.setIcon(self.mainTheme.getIcon(nwLabels.CLASS_ICON[nwItem.itemClass])) + aRoot.triggered.connect( + lambda n, tHandle=tHandle: self.projView.setSelectedHandle(tHandle, doScroll=True) + ) + + return + ## # Internal Functions ## @@ -317,18 +384,18 @@ class GuiProjectTree(QTreeWidget): C_NAME = 0 C_COUNT = 1 - C_EXPORT = 2 + C_ACTIVE = 2 C_STATUS = 3 def __init__(self, projView): - QTreeWidget.__init__(self, projView) + super().__init__(parent=projView) logger.debug("Initialising GuiProjectTree ...") self.mainConf = novelwriter.CONFIG self.projView = projView self.mainGui = projView.mainGui - self.mainTheme = projView.mainGui.mainTheme + self.mainTheme = projView.mainGui.mainTheme self.theProject = projView.mainGui.theProject # Internal Variables @@ -363,9 +430,9 @@ class GuiProjectTree(QTreeWidget): treeHeader.setMinimumSectionSize(iPx + cMg) treeHeader.setSectionResizeMode(self.C_NAME, QHeaderView.Stretch) treeHeader.setSectionResizeMode(self.C_COUNT, QHeaderView.ResizeToContents) - treeHeader.setSectionResizeMode(self.C_EXPORT, QHeaderView.Fixed) + treeHeader.setSectionResizeMode(self.C_ACTIVE, QHeaderView.Fixed) treeHeader.setSectionResizeMode(self.C_STATUS, QHeaderView.Fixed) - treeHeader.resizeSection(self.C_EXPORT, iPx + cMg) + treeHeader.resizeSection(self.C_ACTIVE, iPx + cMg) treeHeader.resizeSection(self.C_STATUS, iPx + cMg) # Allow Move by Drag & Drop @@ -376,9 +443,12 @@ class GuiProjectTree(QTreeWidget): trRoot = self.invisibleRootItem() trRoot.setFlags(trRoot.flags() ^ Qt.ItemIsDropEnabled) - # Set Multiple Selection by CTRL - # Disabled for now, until the merge files option has been added - # self.setSelectionMode(QAbstractItemView.ExtendedSelection) + # Cached values + self._lblActive = self.tr("Active") + self._lblInactive = self.tr("Inactive") + + # Set selection options + self.setSelectionMode(QAbstractItemView.SingleSelection) self.setSelectionBehavior(QAbstractItemView.SelectRows) # Connect signals @@ -450,7 +520,7 @@ class GuiProjectTree(QTreeWidget): # Collect some information about the selected item that pItem = self.theProject.tree[sHandle] qItem = self._getTreeItem(sHandle) - sLevel = nwHeaders.H_LEVEL.get(self.theProject.index.getHandleHeaderLevel(sHandle), 0) + sLevel = nwHeaders.H_LEVEL.get(pItem.mainHeading, 0) sIsParent = False if qItem is None else qItem.childCount() > 0 if self.theProject.tree.isTrash(sHandle): @@ -511,18 +581,14 @@ class GuiProjectTree(QTreeWidget): # Handle new file creation if itemType == nwItemType.FILE and hLevel > 0: - if self.theProject.writeNewFile(tHandle, hLevel, not isNote): - # If successful, update word count - wC = self.theProject.index.getCounts(tHandle)[1] - self.propagateCount(tHandle, wC) - self.projView.wordCountsChanged.emit() + self.theProject.writeNewFile(tHandle, hLevel, not isNote) # Add the new item to the project tree - self.revealNewTreeItem(tHandle, nHandle) + self.revealNewTreeItem(tHandle, nHandle=nHandle, wordCount=True) return True - def revealNewTreeItem(self, tHandle, nHandle=None): + def revealNewTreeItem(self, tHandle, nHandle=None, wordCount=False): """Reveal a newly added project item in the project tree. """ nwItem = self.theProject.tree[tHandle] @@ -533,13 +599,17 @@ class GuiProjectTree(QTreeWidget): if trItem is None: return False + if nwItem.isFileType() and wordCount: + wC = self.theProject.index.getCounts(tHandle)[1] + self.propagateCount(tHandle, wC) + self.projView.wordCountsChanged.emit() + pHandle = nwItem.itemParent if pHandle is not None and pHandle in self._treeMap: self._treeMap[pHandle].setExpanded(True) - self._alertTreeChange(tHandle=tHandle, flush=True) - self.clearSelection() - trItem.setSelected(True) + self._alertTreeChange(tHandle, flush=True) + self.setCurrentItem(trItem) return True @@ -549,7 +619,7 @@ class GuiProjectTree(QTreeWidget): tHandle = self.getSelectedHandle() trItem = self._getTreeItem(tHandle) if trItem is None: - logger.verbose("No item selected") + logger.debug("No item selected") return False pItem = trItem.parent() @@ -577,9 +647,8 @@ class GuiProjectTree(QTreeWidget): pItem.insertChild(nIndex, cItem) self._recordLastMove(cItem, pItem, tIndex) - self._alertTreeChange(tHandle=tHandle, flush=True) - self.clearSelection() - trItem.setSelected(True) + self._alertTreeChange(tHandle, flush=True) + self.setCurrentItem(trItem) trItem.setExpanded(isExp) return True @@ -595,9 +664,9 @@ class GuiProjectTree(QTreeWidget): if dlgOk: tItem.setName(newLabel) self.setTreeItemValues(tHandle) - self._alertTreeChange(tHandle=tHandle, flush=False) + self._alertTreeChange(tHandle, flush=False) - return + return True def saveTreeOrder(self): """Build a list of the items in the project tree and send them @@ -622,6 +691,42 @@ class GuiProjectTree(QTreeWidget): theList = self._scanChildren(theList, theItem, 0) return theList + def requestDeleteItem(self, tHandle=None): + """Request an item deleted from the project tree. This function + can be called on any item, and will check whether to attempt a + permanent deletion or moving the item to Trash. + """ + if not self.mainGui.hasProject: + logger.error("No project open") + return False + + if not self.hasFocus(): + logger.info("Delete action blocked due to no widget focus") + return False + + if tHandle is None: + tHandle = self.getSelectedHandle() + + if tHandle is None: + logger.error("There is no item to delete") + return False + + trashHandle = self.theProject.tree.trashRoot() + if tHandle == trashHandle: + logger.error("Cannot delete the Trash folder") + return False + + nwItem = self.theProject.tree[tHandle] + if nwItem is None: + return False + + if self.theProject.tree.isTrash(tHandle) or nwItem.isRootType(): + status = self.permanentlyDeleteItem(tHandle) + else: + status = self.moveItemToTrash(tHandle) + + return status + def emptyTrash(self): """Permanently delete all documents in the Trash folder. This function only asks for confirmation once, and calls the regular @@ -656,41 +761,24 @@ class GuiProjectTree(QTreeWidget): self.tr("Permanently delete {0} file(s) from Trash?").format(nTrash) ) if not msgYes: + logger.info("Action cancelled by user") return False - logger.verbose("Deleting %d file(s) from Trash", nTrash) + logger.debug("Deleting %d file(s) from Trash", nTrash) for tHandle in reversed(self.getTreeFromHandle(trashHandle)): if tHandle == trashHandle: continue - self.deleteItem(tHandle, alreadyAsked=True, bulkAction=True) + self.permanentlyDeleteItem(tHandle, askFirst=False, flush=False) if nTrash > 0: - self._alertTreeChange(tHandle=trashHandle, flush=True) + self._alertTreeChange(trashHandle, flush=True) return True - def deleteItem(self, tHandle=None, alreadyAsked=False, bulkAction=False): - """Delete an item from the project tree. As a first step, files are - moved to the Trash folder. Permanent deletion is a second step. This - second step also deletes the item from the project object as well as - delete the files on disk. Root folders are deleted if they're empty - only, and the deletion is always permanent. + def moveItemToTrash(self, tHandle, askFirst=True, flush=True): + """Move an item to Trash. Root folders cannot be moved to Trash, + so such a request is cancelled. """ - if not self.mainGui.hasProject: - logger.error("No project open") - return False - - if not self.hasFocus() and not bulkAction: - logger.info("Delete action blocked due to no widget focus") - return False - - if tHandle is None: - tHandle = self.getSelectedHandle() - - if tHandle is None: - logger.error("There is no item to delete") - return False - trItemS = self._getTreeItem(tHandle) nwItemS = self.theProject.tree[tHandle] @@ -698,87 +786,107 @@ class GuiProjectTree(QTreeWidget): logger.error("Could not find tree item for deletion") return False + if self.theProject.tree.isTrash(tHandle): + logger.error("Item is already in the Trash folder") + return False + + if nwItemS.isRootType(): + logger.error("Root folders cannot be moved to Trash") + return False + + logger.debug("User requested file or folder '%s' move to Trash", tHandle) + + trItemP = trItemS.parent() + trItemT = self._addTrashRoot() + if trItemP is None or trItemT is None: + logger.error("Could not delete item") + return False + + if askFirst: + msgYes = self.mainGui.askQuestion( + self.tr("Delete"), + self.tr("Move '{0}' to Trash?").format(nwItemS.itemName), + ) + if not msgYes: + logger.info("Action cancelled by user") + return False + wCount = self._getItemWordCount(tHandle) - autoFlush = not bulkAction + self.propagateCount(tHandle, 0) + + tIndex = trItemP.indexOfChild(trItemS) + trItemC = trItemP.takeChild(tIndex) + trItemT.addChild(trItemC) + + self._postItemMove(tHandle, wCount) + self._recordLastMove(trItemS, trItemP, tIndex) + self._alertTreeChange(tHandle, flush=flush) + + logger.debug("Moved item '%s' to Trash", tHandle) + + return True + + def permanentlyDeleteItem(self, tHandle, askFirst=True, flush=True): + """Permanently delete a tree item from the project and the map. + Root items are handled a little different than other items. + """ + trItemS = self._getTreeItem(tHandle) + nwItemS = self.theProject.tree[tHandle] + if trItemS is None or nwItemS is None: + logger.error("Could not find tree item for deletion") + return False + if nwItemS.isRootType(): # Only an empty ROOT folder can be deleted - logger.debug("User requested a root folder '%s' deleted", tHandle) - tIndex = self.indexOfTopLevelItem(trItemS) - if trItemS.childCount() == 0: - self.takeTopLevelItem(tIndex) - self._deleteTreeItem(tHandle) - self._alertTreeChange(tHandle=tHandle, flush=True) - else: + if trItemS.childCount() > 0: self.mainGui.makeAlert(self.tr( - "Cannot delete root folder. It is not empty. " - "Recursive deletion is not supported. " - "Please delete the content first." + "Root folders can only be deleted when they are empty." ), nwAlert.ERROR) return False - elif nwItemS.isFolderType() and trItemS.childCount() == 0: - # An empty FOLDER is just deleted without any further checks - logger.debug("User requested an empty folder '%s' deleted", tHandle) + logger.debug("Permanently deleting root folder '%s'", tHandle) + + tIndex = self.indexOfTopLevelItem(trItemS) + self.takeTopLevelItem(tIndex) + self.theProject.removeItem(tHandle) + self._treeMap.pop(tHandle, None) + self._alertTreeChange(tHandle, flush=True) + + # These are not emitted by the alert function because the + # item has already been deleted + self.projView.rootFolderChanged.emit(tHandle) + self.projView.treeItemChanged.emit(tHandle) + + else: + if askFirst: + msgYes = self.mainGui.askQuestion( + self.tr("Delete"), + self.tr("Permanently delete '{0}'?").format(nwItemS.itemName) + ) + if not msgYes: + logger.info("Action cancelled by user") + return False + + logger.debug("Permanently deleting item '%s'", tHandle) + + self.propagateCount(tHandle, 0) + trItemP = trItemS.parent() tIndex = trItemP.indexOfChild(trItemS) trItemP.takeChild(tIndex) - self._deleteTreeItem(tHandle) - self._alertTreeChange(tHandle=tHandle, flush=autoFlush) - else: - # A populated FOLDER or a FILE requires confirmtation - logger.debug("User requested a file or folder '%s' deleted", tHandle) - trItemP = trItemS.parent() - trItemT = self._addTrashRoot() - if trItemP is None or trItemT is None: - logger.error("Could not delete item") - return False + for dHandle in reversed(self.getTreeFromHandle(tHandle)): + if self.mainGui.docEditor.docHandle() == dHandle: + self.mainGui.closeDocument() + self.theProject.removeItem(dHandle) + self._treeMap.pop(dHandle, None) - if self.theProject.tree.isTrash(tHandle): - # If the file is in the trash folder already, as the - # user if they want to permanently delete the file. - doPermanent = False - if not alreadyAsked: - msgYes = self.mainGui.askQuestion( - self.tr("Delete"), - self.tr("Permanently delete '{0}'?").format(nwItemS.itemName) - ) - if msgYes: - doPermanent = True - else: - doPermanent = True + self._alertTreeChange(tHandle, flush=flush) + self.projView.wordCountsChanged.emit() - if doPermanent: - logger.debug("Permanently deleting item with handle '%s'", tHandle) - - self.propagateCount(tHandle, 0) - tIndex = trItemP.indexOfChild(trItemS) - trItemC = trItemP.takeChild(tIndex) - for dHandle in reversed(self.getTreeFromHandle(tHandle)): - if self.mainGui.docEditor.docHandle() == dHandle: - self.mainGui.closeDocument() - self._deleteTreeItem(dHandle) - - self._alertTreeChange(tHandle=tHandle, flush=autoFlush) - self.projView.wordCountsChanged.emit() - - else: - # The item is not already in the trash folder, so we - # move it there. - msgYes = self.mainGui.askQuestion( - self.tr("Delete"), - self.tr("Move '{0}' to Trash?").format(nwItemS.itemName), - ) - if msgYes: - logger.debug("Moving item '%s' to trash", tHandle) - - self.propagateCount(tHandle, 0) - tIndex = trItemP.indexOfChild(trItemS) - trItemC = trItemP.takeChild(tIndex) - trItemT.addChild(trItemC) - self._postItemMove(tHandle, wCount) - self._recordLastMove(trItemS, trItemP, tIndex) - self._alertTreeChange(tHandle=tHandle, flush=autoFlush) + # This is not emitted by the alert function because the item + # has already been deleted + self.projView.treeItemChanged.emit(tHandle) return True @@ -793,7 +901,7 @@ class GuiProjectTree(QTreeWidget): return itemStatus, statusIcon = nwItem.getImportStatus() - hLevel = self.theProject.index.getHandleHeaderLevel(tHandle) + hLevel = nwItem.mainHeading itemIcon = self.mainTheme.getItemIcon( nwItem.itemType, nwItem.itemClass, nwItem.itemLayout, hLevel ) @@ -804,9 +912,10 @@ class GuiProjectTree(QTreeWidget): trItem.setToolTip(self.C_STATUS, itemStatus) if nwItem.isFileType(): - trItem.setIcon( - self.C_EXPORT, self.mainTheme.getIcon("check" if nwItem.isExported else "cross") - ) + iconName = "check" if nwItem.isActive else "cross" + toolTip = self._lblActive if nwItem.isActive else self._lblInactive + trItem.setIcon(self.C_ACTIVE, self.mainTheme.getIcon(iconName)) + trItem.setToolTip(self.C_ACTIVE, toolTip) if self.mainConf.emphLabels and nwItem.isDocumentLayout(): trFont = trItem.font(self.C_NAME) @@ -879,8 +988,10 @@ class GuiProjectTree(QTreeWidget): dstItem = self._lastMove.get("parent", None) dstIndex = self._lastMove.get("index", None) - if srcItem is None or dstItem is None or dstIndex is None: - logger.verbose("No tree move to undo") + srcOK = isinstance(srcItem, QTreeWidgetItem) + dstOk = isinstance(dstItem, QTreeWidgetItem) + if not srcOK or not dstOk or dstIndex is None: + logger.debug("No tree move to undo") return False if srcItem not in self._treeMap.values(): @@ -904,10 +1015,9 @@ class GuiProjectTree(QTreeWidget): dstItem.insertChild(dstIndex, movItem) self._postItemMove(sHandle, wCount) - self._alertTreeChange(tHandle=sHandle, flush=True) + self._alertTreeChange(sHandle, flush=True) - self.clearSelection() - movItem.setSelected(True) + self.setCurrentItem(movItem) self._lastMove = {} return True @@ -929,15 +1039,25 @@ class GuiProjectTree(QTreeWidget): if tItem is None: return False - self.clearSelection() - self._treeMap[tHandle].setSelected(True) + self.setFocus() + if tHandle in self._treeMap: + self.setCurrentItem(self._treeMap[tHandle]) - selItems = self.selectedIndexes() - if selItems and doScroll: - self.scrollTo(selItems[0], QAbstractItemView.PositionAtCenter) + selIndex = self.selectedIndexes() + if selIndex and doScroll: + self.scrollTo(selIndex[0], QAbstractItemView.PositionAtCenter) return True + def setExpandedFromHandle(self, tHandle, isExpanded): + """Iterate through items below tHandle and change expanded + status for all child items. If tHandle is None, it affects the + entire tree. + """ + trItem = self._getTreeItem(tHandle) or self.invisibleRootItem() + self._recursiveSetExpanded(trItem, isExpanded) + return + def openContextOnSelected(self): """Open the context menu on the current selected item. """ @@ -966,7 +1086,7 @@ class GuiProjectTree(QTreeWidget): return @pyqtSlot("QTreeWidgetItem*", int) - def _treeDoubleClick(self, tItem, colNo): + def _treeDoubleClick(self, trItem, colNo): """Capture a double-click event and either request the document for editing if it is a file, or expand/close the node it is not. """ @@ -981,9 +1101,7 @@ class GuiProjectTree(QTreeWidget): if tItem.isFileType(): self.projView.openDocumentRequest.emit(tHandle, nwDocMode.EDIT, -1, "") else: - trItem = self._getTreeItem(tHandle) - if trItem is not None: - trItem.setExpanded(not trItem.isExpanded()) + trItem.setExpanded(not trItem.isExpanded()) return @@ -1022,7 +1140,7 @@ class GuiProjectTree(QTreeWidget): isRoot = tItem.isRootType() isFolder = tItem.isFolderType() isFile = tItem.isFileType() - isEmpty = selItem.childCount() == 0 + hasChild = selItem.childCount() > 0 if isFile: ctxMenu.addAction( @@ -1044,7 +1162,7 @@ class GuiProjectTree(QTreeWidget): if isFile: ctxMenu.addAction( - self.tr("Toggle Exported"), lambda: self._toggleItemExported(tHandle) + self.tr("Toggle Active"), lambda: self._toggleItemActive(tHandle) ) if tItem.isNovelLike(): @@ -1062,36 +1180,77 @@ class GuiProjectTree(QTreeWidget): lambda n, key=key: self._changeItemImport(tHandle, key) ) - if isFile and tItem.documentAllowed(): - if tItem.isNoteLayout(): - ctxMenu.addAction( - self.tr("Convert to {0}").format( - trConst(nwLabels.LAYOUT_NAME[nwItemLayout.DOCUMENT]) - ), + # Transform Item + # ============== + + if not isRoot: + mTrans = ctxMenu.addMenu(self.tr("Transform")) + + trDoc = trConst(nwLabels.LAYOUT_NAME[nwItemLayout.DOCUMENT]) + trNote = trConst(nwLabels.LAYOUT_NAME[nwItemLayout.NOTE]) + + isDocFile = isFile and tItem.isDocumentLayout() + isNoteFile = isFile and tItem.isNoteLayout() + + if (isNoteFile or isFolder) and tItem.documentAllowed(): + mTrans.addAction( + self.tr("Convert to {0}").format(trDoc), lambda: self._changeItemLayout(tHandle, nwItemLayout.DOCUMENT) ) - else: - ctxMenu.addAction( - self.tr("Convert to {0}").format( - trConst(nwLabels.LAYOUT_NAME[nwItemLayout.NOTE]) - ), + + if isDocFile or isFolder: + mTrans.addAction( + self.tr("Convert to {0}").format(trNote), lambda: self._changeItemLayout(tHandle, nwItemLayout.NOTE) ) + if hasChild and isFile: + mTrans.addAction( + self.tr("Merge Child Items into Self"), + lambda: self._mergeDocuments(tHandle, False) + ) + mTrans.addAction( + self.tr("Merge Child Items into New"), + lambda: self._mergeDocuments(tHandle, True) + ) + + if hasChild and isFolder: + mTrans.addAction( + self.tr("Merge Documents in Folder"), + lambda: self._mergeDocuments(tHandle, True) + ) + + if isFile: + mTrans.addAction( + self.tr("Split Document by Headers"), + lambda: self._splitDocument(tHandle) + ) + + # Expand/Collapse/Delete + # ====================== + ctxMenu.addSeparator() - # Delete Item - # =========== - - if tItem.itemClass == nwItemClass.TRASH or isRoot or (isFolder and isEmpty): + if hasChild: ctxMenu.addAction( - self.tr("Delete Permanently"), lambda: self.deleteItem(tHandle) + self.tr("Expand All"), + lambda: self.setExpandedFromHandle(tHandle, True) + ) + ctxMenu.addAction( + self.tr("Collapse All"), + lambda: self.setExpandedFromHandle(tHandle, False) + ) + + if tItem.itemClass == nwItemClass.TRASH or isRoot or (isFolder and not hasChild): + ctxMenu.addAction( + self.tr("Delete Permanently"), lambda: self.permanentlyDeleteItem(tHandle) ) else: ctxMenu.addAction( - self.tr("Move to Trash"), lambda: self.deleteItem(tHandle) + self.tr("Move to Trash"), lambda: self.moveItemToTrash(tHandle) ) + # Show Context Menu ctxMenu.exec_(self.viewport().mapToGlobal(clickPos)) return True @@ -1105,7 +1264,7 @@ class GuiProjectTree(QTreeWidget): mouse in a blank area of the tree view, and to load a document for viewing if the user middle-clicked. """ - QTreeWidget.mousePressEvent(self, theEvent) + super().mousePressEvent(theEvent) if theEvent.button() == Qt.LeftButton: selItem = self.indexAt(theEvent.pos()) @@ -1151,11 +1310,12 @@ class GuiProjectTree(QTreeWidget): wCount = self._getItemWordCount(sHandle) self.propagateCount(sHandle, 0) - QTreeWidget.dropEvent(self, theEvent) + super().dropEvent(theEvent) self._postItemMove(sHandle, wCount) self._recordLastMove(sItem, pItem, pIndex) - self._alertTreeChange(tHandle=sHandle, flush=True) - sItem.setExpanded(isExpanded) + self._alertTreeChange(sHandle, flush=True) + if sItem is not None: + sItem.setExpanded(isExpanded) return @@ -1212,30 +1372,26 @@ class GuiProjectTree(QTreeWidget): """ return self._treeMap.get(tHandle, None) - def _deleteTreeItem(self, tHandle): - """Permanently delete a tree item from the project and the map. - """ - if self.theProject.tree.checkType(tHandle, nwItemType.FILE): - delDoc = NWDoc(self.theProject, tHandle) - if not delDoc.deleteDocument(): - self.mainGui.makeAlert([ - self.tr("Could not delete document file."), delDoc.getError() - ], nwAlert.ERROR) - return False - - self.theProject.index.deleteHandle(tHandle) - del self.theProject.tree[tHandle] - self._treeMap.pop(tHandle, None) - - return True - - def _toggleItemExported(self, tHandle): - """Toggle the exported status of an item. + def _toggleItemActive(self, tHandle): + """Toggle the active status of an item. """ tItem = self.theProject.tree[tHandle] if tItem is not None: - tItem.setExported(not tItem.isExported) + tItem.setActive(not tItem.isActive) self.setTreeItemValues(tItem.itemHandle) + self._alertTreeChange(tHandle, flush=False) + return + + def _recursiveSetExpanded(self, trItem, isExpanded): + """Recursive function to set expanded status starting from (and + not including) a given item. + """ + if isinstance(trItem, QTreeWidgetItem): + chCount = trItem.childCount() + for i in range(chCount): + chItem = trItem.child(i) + chItem.setExpanded(isExpanded) + self._recursiveSetExpanded(chItem, isExpanded) return def _changeItemStatus(self, tHandle, tStatus): @@ -1245,6 +1401,7 @@ class GuiProjectTree(QTreeWidget): if tItem is not None: tItem.setStatus(tStatus) self.setTreeItemValues(tItem.itemHandle) + self._alertTreeChange(tHandle, flush=False) return def _changeItemImport(self, tHandle, tImport): @@ -1254,6 +1411,7 @@ class GuiProjectTree(QTreeWidget): if tItem is not None: tItem.setImport(tImport) self.setTreeItemValues(tItem.itemHandle) + self._alertTreeChange(tHandle, flush=False) return def _changeItemLayout(self, tHandle, itemLayout): @@ -1263,12 +1421,166 @@ class GuiProjectTree(QTreeWidget): if tItem is not None: if itemLayout == nwItemLayout.DOCUMENT and tItem.documentAllowed(): tItem.setLayout(nwItemLayout.DOCUMENT) - self.setTreeItemValues(tItem.itemHandle) + self.setTreeItemValues(tHandle) + self._alertTreeChange(tHandle, flush=False) elif itemLayout == nwItemLayout.NOTE: tItem.setLayout(nwItemLayout.NOTE) - self.setTreeItemValues(tItem.itemHandle) + self.setTreeItemValues(tHandle) + self._alertTreeChange(tHandle, flush=False) return + def _covertFolderToFile(self, tHandle, itemLayout): + """Convert a folder to a note or document. + """ + tItem = self.theProject.tree[tHandle] + if tItem is not None and tItem.isFolderType(): + msgYes = self.mainGui.askQuestion( + self.tr("Convert Folder"), + self.tr( + "Do you want to convert the folder to a {0}? " + "This action cannot be reversed." + ).format(trConst(nwLabels.LAYOUT_NAME[itemLayout])) + ) + if msgYes and itemLayout == nwItemLayout.DOCUMENT and tItem.documentAllowed(): + tItem.setType(nwItemType.FILE) + tItem.setLayout(nwItemLayout.DOCUMENT) + self.setTreeItemValues(tHandle) + self._alertTreeChange(tHandle, flush=False) + elif msgYes and itemLayout == nwItemLayout.NOTE: + tItem.setType(nwItemType.FILE) + tItem.setLayout(nwItemLayout.NOTE) + self.setTreeItemValues(tHandle) + self._alertTreeChange(tHandle, flush=False) + else: + logger.info("Folder conversion cancelled") + return + + def _mergeDocuments(self, tHandle, newFile): + """Merge an item's child documents into a single document. + """ + logger.info("Request to merge items under handle '%s'", tHandle) + itemList = self.getTreeFromHandle(tHandle) + + tItem = self.theProject.tree[tHandle] + if tItem is None: + return False + + if tItem.isRootType(): + logger.error("Cannot merge root item") + return False + + if not newFile: + itemList.remove(tHandle) + + dlgMerge = GuiDocMerge(self.mainGui, tHandle, itemList) + dlgMerge.exec_() + + if dlgMerge.result() == QDialog.Accepted: + + mrgData = dlgMerge.getData() + mrgList = mrgData.get("finalItems", []) + if not mrgList: + self.mainGui.makeAlert([ + self.tr("No documents selected for merging.") + ], nwAlert.INFO) + return False + + # Save the open document first, in case it's part of merge + self.mainGui.saveDocument() + + # Create merge object, and append docs + docMerger = DocMerger(self.theProject) + mLabel = self.tr("Merged") + + if newFile: + docLabel = f"[{mLabel}] {tItem.itemName}" + mHandle = docMerger.newTargetDoc(tHandle, docLabel) + elif tItem.isFileType(): + docMerger.setTargetDoc(tHandle) + mHandle = tHandle + else: + return False + + for sHandle in mrgList: + docMerger.appendText(sHandle, True, mLabel) + + if not docMerger.writeTargetDoc(): + self.mainGui.makeAlert([ + self.tr("Could not write document content."), docMerger.getError() + ], nwAlert.ERROR) + return False + + self.theProject.index.reIndexHandle(mHandle) + if newFile: + self.revealNewTreeItem(mHandle, nHandle=tHandle, wordCount=True) + + self.mainGui.openDocument(mHandle, doScroll=True) + + if mrgData.get("moveToTrash", False): + for sHandle in reversed(mrgData.get("finalItems", [])): + trItem = self._getTreeItem(sHandle) + if isinstance(trItem, QTreeWidgetItem) and trItem.childCount() == 0: + self.moveItemToTrash(sHandle, askFirst=False, flush=False) + + self._alertTreeChange(mHandle, flush=True) + self.projView.wordCountsChanged.emit() + + else: + logger.info("Action cancelled by user") + return False + + return True + + def _splitDocument(self, tHandle): + """Split a document into multiple documents. + """ + logger.info("Request to split items with handle '%s'", tHandle) + + tItem = self.theProject.tree[tHandle] + if tItem is None: + return False + + if not tItem.isFileType(): + logger.error("Only documents can be split") + return False + + dlgSplit = GuiDocSplit(self.mainGui, tHandle) + dlgSplit.exec_() + + if dlgSplit.result() == QDialog.Accepted: + + splitData, splitText = dlgSplit.getData() + + headerList = splitData.get("headerList", []) + intoFolder = splitData.get("intoFolder", False) + docHierarchy = splitData.get("docHierarchy", False) + + docSplit = DocSplitter(self.theProject, tHandle) + if intoFolder: + fHandle = docSplit.newParentFolder(tItem.itemParent, tItem.itemName) + self.revealNewTreeItem(fHandle, nHandle=tHandle) + self._alertTreeChange(fHandle, flush=False) + else: + docSplit.setParentItem(tItem.itemParent) + + docSplit.splitDocument(headerList, splitText) + for writeOk, dHandle, nHandle in docSplit.writeDocuments(docHierarchy): + self.theProject.index.reIndexHandle(dHandle) + self.revealNewTreeItem(dHandle, nHandle=nHandle, wordCount=True) + self._alertTreeChange(dHandle, flush=False) + if not writeOk: + self.mainGui.makeAlert([ + self.tr("Could not write document content."), docSplit.getError() + ], nwAlert.ERROR) + + self.saveTreeOrder() + + else: + logger.info("Action cancelled by user") + return False + + return True + def _scanChildren(self, theList, tItem, tIndex): """This is a recursive function returning all items in a tree starting at a given QTreeWidgetItem. @@ -1278,8 +1590,9 @@ class GuiProjectTree(QTreeWidget): # Update tree-related meta data nwItem = self.theProject.tree[tHandle] - nwItem.setExpanded(tItem.isExpanded() and cCount > 0) - nwItem.setOrder(tIndex) + if nwItem is not None: + nwItem.setExpanded(tItem.isExpanded() and cCount > 0) + nwItem.setOrder(tIndex) theList.append(tHandle) for i in range(cCount): @@ -1293,16 +1606,16 @@ class GuiProjectTree(QTreeWidget): """ tHandle = nwItem.itemHandle pHandle = nwItem.itemParent - newItem = QTreeWidgetItem([""]*4) + newItem = QTreeWidgetItem() newItem.setText(self.C_NAME, "") newItem.setText(self.C_COUNT, "0") - newItem.setText(self.C_EXPORT, "") + newItem.setText(self.C_ACTIVE, "") newItem.setText(self.C_STATUS, "") newItem.setTextAlignment(self.C_NAME, Qt.AlignLeft) newItem.setTextAlignment(self.C_COUNT, Qt.AlignRight) - newItem.setTextAlignment(self.C_EXPORT, Qt.AlignLeft) + newItem.setTextAlignment(self.C_ACTIVE, Qt.AlignLeft) newItem.setTextAlignment(self.C_STATUS, Qt.AlignLeft) newItem.setData(self.C_NAME, Qt.UserRole, tHandle) @@ -1351,25 +1664,28 @@ class GuiProjectTree(QTreeWidget): trItem = self._addTreeItem(self.theProject.tree[trashHandle]) if trItem is not None: trItem.setExpanded(True) - self._alertTreeChange(tHandle=trashHandle, flush=True) + self._alertTreeChange(trashHandle, flush=True) return trItem - def _alertTreeChange(self, tHandle=None, flush=True): + def _alertTreeChange(self, tHandle, flush=False): """Update information on tree change state, and emit necessary - signals. + signals. A flush is only needed if an item is moved, created or + deleted. """ self._timeChanged = time() self.theProject.setProjectChanged(True) if flush: self.saveTreeOrder() - tItem = self.theProject.tree[tHandle] - if tItem is None: + if tHandle is None: return - itemType = tItem.itemType - if itemType == nwItemType.ROOT: + if tHandle not in self.theProject.tree: + return + + tItem = self.theProject.tree[tHandle] + if tItem.isRootType(): self.projView.rootFolderChanged.emit(tHandle) self.projView.treeItemChanged.emit(tHandle) diff --git a/novelwriter/gui/statusbar.py b/novelwriter/gui/statusbar.py index a0cf9416..c6191b8d 100644 --- a/novelwriter/gui/statusbar.py +++ b/novelwriter/gui/statusbar.py @@ -42,7 +42,7 @@ logger = logging.getLogger(__name__) class GuiMainStatus(QStatusBar): def __init__(self, mainGui): - QStatusBar.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiMainStatus ...") diff --git a/novelwriter/gui/theme.py b/novelwriter/gui/theme.py index e72a8c97..4c76179d 100644 --- a/novelwriter/gui/theme.py +++ b/novelwriter/gui/theme.py @@ -38,7 +38,7 @@ from PyQt5.QtGui import ( from novelwriter.enum import nwItemLayout, nwItemType from novelwriter.error import logException -from novelwriter.common import NWConfigParser, readTextFile +from novelwriter.common import NWConfigParser, minmax, readTextFile from novelwriter.constants import nwLabels logger = logging.getLogger(__name__) @@ -120,11 +120,13 @@ class GuiTheme: self._availThemes = {} self._availSyntax = {} - self._listConf(self._availSyntax, os.path.join(self.mainConf.dataPath, "syntax")) self._listConf(self._availSyntax, os.path.join(self.mainConf.assetPath, "syntax")) - self._listConf(self._availThemes, os.path.join(self.mainConf.dataPath, "themes")) self._listConf(self._availThemes, os.path.join(self.mainConf.assetPath, "themes")) + if self.mainConf.dataPath: # Not guaranteed to be set + self._listConf(self._availSyntax, os.path.join(self.mainConf.dataPath, "syntax")) + self._listConf(self._availThemes, os.path.join(self.mainConf.dataPath, "themes")) + self.updateFont() self.updateTheme() self.iconCache.updateTheme() @@ -134,13 +136,14 @@ class GuiTheme: self.getPixmap = self.iconCache.getPixmap self.getItemIcon = self.iconCache.getItemIcon self.loadDecoration = self.iconCache.loadDecoration + self.getHeaderDecoration = self.iconCache.getHeaderDecoration # Extract Other Info self.guiDPI = qApp.primaryScreen().logicalDotsPerInchX() self.guiScale = qApp.primaryScreen().logicalDotsPerInchX()/96.0 self.mainConf.guiScale = self.guiScale - logger.verbose("GUI DPI: %.1f", self.guiDPI) - logger.verbose("GUI Scale: %.2f", self.guiScale) + logger.debug("GUI DPI: %.1f", self.guiDPI) + logger.debug("GUI Scale: %.2f", self.guiScale) # Fonts self.guiFont = qApp.font() @@ -157,12 +160,12 @@ class GuiTheme: self.guiFontFixed.setPointSizeF(0.95*self.fontPointSize) self.guiFontFixed.setFamily(QFontDatabase.systemFont(QFontDatabase.FixedFont).family()) - logger.verbose("GUI Font Family: %s", self.guiFont.family()) - logger.verbose("GUI Font Point Size: %.2f", self.fontPointSize) - logger.verbose("GUI Font Pixel Size: %d", self.fontPixelSize) - logger.verbose("GUI Base Icon Size: %d", self.baseIconSize) - logger.verbose("Text 'N' Height: %d", self.textNHeight) - logger.verbose("Text 'N' Width: %d", self.textNWidth) + logger.debug("GUI Font Family: %s", self.guiFont.family()) + logger.debug("GUI Font Point Size: %.2f", self.fontPointSize) + logger.debug("GUI Font Pixel Size: %d", self.fontPixelSize) + logger.debug("GUI Base Icon Size: %d", self.baseIconSize) + logger.debug("Text 'N' Height: %d", self.textNHeight) + logger.debug("Text 'N' Width: %d", self.textNWidth) return @@ -355,7 +358,7 @@ class GuiTheme: confParser = NWConfigParser() for themeKey, themePath in self._availThemes.items(): - logger.verbose("Checking theme config for '%s'", themeKey) + logger.debug("Checking theme config for '%s'", themeKey) themeName = _loadInternalName(confParser, themePath) if themeName: self._themeList.append((themeKey, themeName)) @@ -372,7 +375,7 @@ class GuiTheme: confParser = NWConfigParser() for syntaxKey, syntaxPath in self._availSyntax.items(): - logger.verbose("Checking theme syntax for '%s'", syntaxKey) + logger.debug("Checking theme syntax for '%s'", syntaxKey) syntaxName = _loadInternalName(confParser, syntaxPath) if syntaxName: self._syntaxList.append((syntaxKey, syntaxName)) @@ -457,17 +460,17 @@ class GuiIcons: ICON_KEYS = { # Project and GUI icons "novelwriter", "cls_archive", "cls_character", "cls_custom", "cls_entity", "cls_none", - "cls_novel", "cls_object", "cls_plot", "cls_timeline", "cls_trash", "cls_world", "doc_h0", - "doc_h1", "doc_h2", "doc_h3", "doc_h4", "proj_chapter", "proj_details", "proj_document", - "proj_folder", "proj_note", "proj_nwx", "proj_scene", "proj_stats", "proj_title", - "search_cancel", "search_case", "search_loop", "search_preserve", "search_project", - "search_regex", "search_word", "status_idle", "status_lang", "status_lines", - "status_stats", "status_time", "view_build", "view_editor", "view_novel", "view_outline", + "cls_novel", "cls_object", "cls_plot", "cls_timeline", "cls_trash", "cls_world", + "proj_chapter", "proj_details", "proj_document", "proj_folder", "proj_note", "proj_nwx", + "proj_section", "proj_scene", "proj_stats", "proj_title", "search_cancel", "search_case", + "search_loop", "search_preserve", "search_project", "search_regex", "search_word", + "status_idle", "status_lang", "status_lines", "status_stats", "status_time", "view_build", + "view_editor", "view_novel", "view_outline", # General Button Icons - "add", "backward", "check", "clear", "close", "cross", "delete", "done", "down", "edit", - "forward", "hash", "maximise", "menu", "minimise", "reference", "refresh", "remove", - "save", "search_replace", "search", "settings", "up", + "add", "backward", "bookmark", "check", "close", "cross", "down", "edit", "forward", + "maximise", "menu", "minimise", "reference", "refresh", "remove", "search_replace", + "search", "settings", "up", # Switches "sticky-on", "sticky-off", @@ -490,6 +493,7 @@ class GuiIcons: self._qIcons = {} self._themeMap = {} self._themeList = [] + self._headerDec = [] self._confName = "icons.conf" # Icon Theme Path @@ -557,7 +561,7 @@ class GuiIcons: iconPath = os.path.join(self._themePath, iconFile) if os.path.isfile(iconPath): self._themeMap[iconName] = iconPath - logger.verbose("Icon slot '%s' using file '%s'", iconName, iconFile) + logger.debug("Icon slot '%s' using file '%s'", iconName, iconFile) else: logger.error("Icon file '%s' not in theme folder", iconFile) @@ -641,6 +645,8 @@ class GuiIcons: iconName = "proj_chapter" elif hLevel == "H3": iconName = "proj_scene" + elif hLevel == "H4": + iconName = "proj_section" elif tLayout == nwItemLayout.NOTE: iconName = "proj_note" if iconName is None: @@ -648,6 +654,20 @@ class GuiIcons: return self.getIcon(iconName) + def getHeaderDecoration(self, hLevel): + """Get the decoration for a specific header level. + """ + if not self._headerDec: + iPx = self.mainTheme.baseIconSize + self._headerDec = [ + self.loadDecoration("deco_doc_h0", pxH=iPx), + self.loadDecoration("deco_doc_h1", pxH=iPx), + self.loadDecoration("deco_doc_h2", pxH=iPx), + self.loadDecoration("deco_doc_h3", pxH=iPx), + self.loadDecoration("deco_doc_h4", pxH=iPx), + ] + return self._headerDec[minmax(hLevel, 0, 4)] + def listThemes(self): """Scan the icons themes folder and list all themes. """ @@ -660,7 +680,7 @@ class GuiIcons: if not os.path.isdir(themePath): continue - logger.verbose("Checking icon theme config for '%s'", themeDir) + logger.debug("Checking icon theme config for '%s'", themeDir) themeConf = os.path.join(themePath, self._confName) themeName = _loadInternalName(confParser, themeConf) if themeName: @@ -708,7 +728,7 @@ class GuiIcons: # Otherwise, we load from the theme folder if iconKey in self._themeMap: relPath = os.path.relpath(self._themeMap[iconKey], self._iconPath) - logger.verbose("Loading: %s", relPath) + logger.debug("Loading: %s", relPath) return QIcon(self._themeMap[iconKey]) # If we didn't find one, give up and return an empty icon diff --git a/novelwriter/gui/viewsbar.py b/novelwriter/gui/viewsbar.py index 031f4316..dcd697db 100644 --- a/novelwriter/gui/viewsbar.py +++ b/novelwriter/gui/viewsbar.py @@ -41,7 +41,7 @@ class GuiViewsBar(QToolBar): viewChangeRequested = pyqtSignal(nwView) def __init__(self, mainGui): - QToolBar.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiViewsBar ...") @@ -67,52 +67,49 @@ class GuiViewsBar(QToolBar): stretch.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) # Actions - self.aProject = QAction(self.tr("Project")) + self.aProject = QAction(self.tr("Project"), self) self.aProject.setFont(lblFont) - self.aProject.setToolTip(self.tr("Show project tree and editor")) + self.aProject.setToolTip(self.tr("Project Tree View")) self.aProject.setIcon(self.mainTheme.getIcon("view_editor")) self.aProject.triggered.connect(lambda: self.viewChangeRequested.emit(nwView.PROJECT)) - self.aNovel = QAction(self.tr("Novel")) + self.aNovel = QAction(self.tr("Novel"), self) self.aNovel.setFont(lblFont) - self.aNovel.setToolTip(self.tr("Show novel tree and editor")) + self.aNovel.setToolTip(self.tr("Novel Tree View")) self.aNovel.setIcon(self.mainTheme.getIcon("view_novel")) self.aNovel.triggered.connect(lambda: self.viewChangeRequested.emit(nwView.NOVEL)) - self.aOutline = QAction(self.tr("Outline")) + self.aOutline = QAction(self.tr("Outline"), self) self.aOutline.setFont(lblFont) - self.aOutline.setToolTip(self.tr("Show novel outline")) + self.aOutline.setToolTip(self.tr("Novel Outline View")) self.aOutline.setIcon(self.mainTheme.getIcon("view_outline")) self.aOutline.triggered.connect(lambda: self.viewChangeRequested.emit(nwView.OUTLINE)) - self.aBuild = QAction(self.tr("Build")) + self.aBuild = QAction(self.tr("Build"), self) self.aBuild.setFont(lblFont) - self.aBuild.setToolTip(self.tr("Build novel project")) + self.aBuild.setToolTip(self.tr("Build Novel Project")) self.aBuild.setIcon(self.mainTheme.getIcon("view_build")) self.aBuild.triggered.connect(lambda: self.mainGui.showBuildProjectDialog()) - self.aDetails = QAction(self.tr("Details")) + self.aDetails = QAction(self.tr("Details"), self) self.aDetails.setFont(lblFont) - self.aDetails.setToolTip(self.tr("Show project details")) + self.aDetails.setToolTip(self.tr("Project Details")) self.aDetails.setIcon(self.mainTheme.getIcon("proj_details")) self.aDetails.triggered.connect(lambda: self.mainGui.showProjectDetailsDialog()) - self.aStats = QAction(self.tr("Stats")) + self.aStats = QAction(self.tr("Stats"), self) self.aStats.setFont(lblFont) - self.aStats.setToolTip(self.tr("Show project statistics")) + self.aStats.setToolTip(self.tr("Writing Statistics")) self.aStats.setIcon(self.mainTheme.getIcon("proj_stats")) self.aStats.triggered.connect(lambda: self.mainGui.showWritingStatsDialog()) # Settings Menu self.mSettings = QMenu() - self.aPrjSettings = QAction(self.tr("Project Settings")) - self.aPrjSettings.triggered.connect(lambda: self.mainGui.showProjectSettingsDialog()) - self.mSettings.addAction(self.aPrjSettings) - - self.aPreferences = QAction(self.tr("Preferences")) - self.aPreferences.triggered.connect(lambda: self.mainGui.showPreferencesDialog()) - self.mSettings.addAction(self.aPreferences) + self.mSettings.addAction(self.mainGui.mainMenu.aEditWordList) + self.mSettings.addAction(self.mainGui.mainMenu.aProjectSettings) + self.mSettings.addSeparator() + self.mSettings.addAction(self.mainGui.mainMenu.aPreferences) self.tbSettings = QToolButton(self) self.tbSettings.setFont(lblFont) diff --git a/novelwriter/guimain.py b/novelwriter/guimain.py index bad8c904..fee7c7d6 100644 --- a/novelwriter/guimain.py +++ b/novelwriter/guimain.py @@ -44,8 +44,8 @@ from novelwriter.gui import ( GuiViewsBar ) from novelwriter.dialogs import ( - GuiAbout, GuiDocMerge, GuiDocSplit, GuiPreferences, GuiProjectDetails, - GuiProjectLoad, GuiProjectSettings, GuiUpdates, GuiWordList + GuiAbout, GuiPreferences, GuiProjectDetails, GuiProjectLoad, + GuiProjectSettings, GuiUpdates, GuiWordList ) from novelwriter.tools import ( GuiBuildNovel, GuiLipsum, GuiProjectWizard, GuiWritingStats @@ -55,6 +55,7 @@ from novelwriter.enum import ( nwDocMode, nwItemType, nwItemClass, nwAlert, nwWidget, nwState, nwView ) from novelwriter.common import getGuiItem, hexToInt +from novelwriter.constants import nwFiles logger = logging.getLogger(__name__) @@ -62,7 +63,7 @@ logger = logging.getLogger(__name__) class GuiMain(QMainWindow): def __init__(self): - QMainWindow.__init__(self) + super().__init__() logger.debug("Initialising GUI ...") self.setObjectName("GuiMain") @@ -104,7 +105,7 @@ class GuiMain(QMainWindow): hWd = self.mainConf.pxInt(4) # Main GUI Elements - self.statusBar = GuiMainStatus(self) + self.mainStatus = GuiMainStatus(self) self.projView = GuiProjectView(self) self.novelView = GuiNovelView(self) self.docEditor = GuiDocEditor(self) @@ -189,8 +190,9 @@ class GuiMain(QMainWindow): # Set Main Window Elements self.setMenuBar(self.mainMenu) self.setCentralWidget(self.mainStack) - self.setStatusBar(self.statusBar) + self.setStatusBar(self.mainStatus) self.addToolBar(Qt.LeftToolBarArea, self.viewsBar) + self.setContextMenuPolicy(Qt.NoContextMenu) # Issue #1147 # Connect Signals # =============== @@ -205,12 +207,13 @@ class GuiMain(QMainWindow): self.projView.treeItemChanged.connect(self.itemDetails.updateViewBox) self.projView.rootFolderChanged.connect(self.outlineView.updateRootItem) self.projView.rootFolderChanged.connect(self.novelView.updateRootItem) + self.projView.rootFolderChanged.connect(self.projView.updateRootItem) self.novelView.selectedItemChanged.connect(self.itemDetails.updateViewBox) self.novelView.openDocumentRequest.connect(self._openDocument) - self.docEditor.spellDictionaryChanged.connect(self.statusBar.setLanguage) - self.docEditor.docEditedStatusChanged.connect(self.statusBar.doUpdateDocumentStatus) + self.docEditor.spellDictionaryChanged.connect(self.mainStatus.setLanguage) + self.docEditor.docEditedStatusChanged.connect(self.mainStatus.doUpdateDocumentStatus) self.docEditor.docCountsChanged.connect(self.itemDetails.updateCounts) self.docEditor.docCountsChanged.connect(self.projView.updateCounts) self.docEditor.loadDocumentTagRequest.connect(self._followTag) @@ -252,7 +255,7 @@ class GuiMain(QMainWindow): keyEscape.activated.connect(self._keyPressEscape) # Forward Functions - self.setStatus = self.statusBar.setStatus + self.setStatus = self.mainStatus.setStatus # Force a show of the GUI self.show() @@ -264,7 +267,7 @@ class GuiMain(QMainWindow): self.initMain() self.asProjTimer.start() self.asDocTimer.start() - self.statusBar.clearStatus() + self.mainStatus.clearStatus() # Handle Windows Mode self.showNormal() @@ -305,7 +308,7 @@ class GuiMain(QMainWindow): self.outlineView.clearProject() # General - self.statusBar.clearStatus() + self.mainStatus.clearStatus() self._updateWindowTitle() return True @@ -351,7 +354,7 @@ class GuiMain(QMainWindow): logger.error("No projData or projPath set") return False - if os.path.isfile(os.path.join(projPath, self.theProject.projFile)): + if os.path.isfile(os.path.join(projPath, nwFiles.PROJ_FILE)): self.makeAlert(self.tr( "A project already exists in that location. " "Please choose another folder." @@ -360,18 +363,27 @@ class GuiMain(QMainWindow): logger.info("Creating new project") if self.theProject.newProject(projData): + self.hasProject = True + self.idleRefTime = time() + self.idleTime = 0.0 + self.rebuildTrees() self.saveProject() + self.docEditor.setDictionaries() + self.projView.openProjectTasks() self.novelView.openProjectTasks() self.outlineView.openProjectTasks() self.rebuildIndex(beQuiet=True) - self.statusBar.setRefTime(self.theProject.projOpened) - self.statusBar.setProjectStatus(nwState.GOOD) - self.statusBar.setDocumentStatus(nwState.NONE) - self.statusBar.setStatus(self.tr("New project created ...")) + + self.mainStatus.setRefTime(self.theProject.projOpened) + self.mainStatus.setProjectStatus(nwState.GOOD) + self.mainStatus.setDocumentStatus(nwState.NONE) + self.mainStatus.setStatus(self.tr("New project created ...")) + self._updateWindowTitle(self.theProject.projName) + else: self.theProject.clearProject() return False @@ -512,7 +524,8 @@ class GuiMain(QMainWindow): self.rebuildTrees() self.docEditor.setDictionaries() self.docEditor.toggleSpellCheck(self.theProject.spellCheck) - self.statusBar.setRefTime(self.theProject.projOpened) + self.mainStatus.setRefTime(self.theProject.projOpened) + self.projView.openProjectTasks() self.novelView.openProjectTasks() self.outlineView.openProjectTasks() self._updateStatusWordCount() @@ -547,7 +560,7 @@ class GuiMain(QMainWindow): logger.error("No project open") return False - self.projView.saveProjectTree() + self.projView.saveProjectTasks() if self.theProject.saveProject(autoSave=autoSave): self.theProject.index.saveIndex() @@ -613,7 +626,7 @@ class GuiMain(QMainWindow): fHandle = None # The first file handle we encounter foundIt = False # We've found tHandle, pick the next we see for tItem in self.theProject.tree: - if not self.theProject.tree.checkType(tItem.itemHandle, nwItemType.FILE): + if tItem is None or not tItem.isFileType(): continue if fHandle is None: fHandle = tItem.itemHandle @@ -654,21 +667,18 @@ class GuiMain(QMainWindow): logger.debug("Viewing document, but no handle provided") if self.docEditor.hasFocus(): - logger.verbose("Trying editor document") tHandle = self.docEditor.docHandle() if tHandle is not None: self.saveDocument() else: - logger.verbose("Trying selected document") tHandle = self.projView.getSelectedHandle() if tHandle is None: - logger.verbose("Trying last viewed document") tHandle = self.theProject.lastViewed if tHandle is None: - logger.verbose("No document to view, giving up") + logger.debug("No document to view, giving up") return False # Make sure main tab is in Editor view @@ -745,30 +755,6 @@ class GuiMain(QMainWindow): return True - def mergeDocuments(self): - """Merge multiple documents to one single new document. - """ - if not self.hasProject: - logger.error("No project open") - return False - - dlgMerge = GuiDocMerge(self) - dlgMerge.exec_() - - return True - - def splitDocument(self): - """Split a single document into multiple documents. - """ - if not self.hasProject: - logger.error("No project open") - return False - - dlgSplit = GuiDocSplit(self) - dlgSplit.exec_() - - return True - def passDocumentAction(self, theAction): """Pass on document action to the document viewer if it has focus, or pass it to the document editor if it or any of @@ -856,14 +842,14 @@ class GuiMain(QMainWindow): qApp.setOverrideCursor(QCursor(Qt.WaitCursor)) tStart = time() - self.projView.saveProjectTree() + self.projView.saveProjectTasks() self.theProject.index.clearIndex() for tItem in self.theProject.tree: if tItem is None: # pragma: no cover continue # This is a bug trap - logger.verbose("Indexing '%s'", tItem.itemName) + logger.debug("Indexing '%s'", tItem.itemName) if self.theProject.index.reIndexHandle(tItem.itemHandle): # Update Word Counts self.projView.propagateCount(tItem.itemHandle, tItem.wordCount, countChildren=True) @@ -964,6 +950,7 @@ class GuiMain(QMainWindow): dlgDetails = getGuiItem("GuiProjectDetails") if dlgDetails is None: dlgDetails = GuiProjectDetails(self) + assert isinstance(dlgDetails, GuiProjectDetails) dlgDetails.setModal(False) dlgDetails.show() @@ -982,6 +969,7 @@ class GuiMain(QMainWindow): dlgBuild = getGuiItem("GuiBuildNovel") if dlgBuild is None: dlgBuild = GuiBuildNovel(self) + assert isinstance(dlgBuild, GuiBuildNovel) dlgBuild.setModal(False) dlgBuild.show() @@ -1001,6 +989,7 @@ class GuiMain(QMainWindow): dlgLipsum = getGuiItem("GuiLipsum") if dlgLipsum is None: dlgLipsum = GuiLipsum(self) + assert isinstance(dlgLipsum, GuiLipsum) dlgLipsum.setModal(False) dlgLipsum.show() @@ -1035,6 +1024,7 @@ class GuiMain(QMainWindow): dlgStats = getGuiItem("GuiWritingStats") if dlgStats is None: dlgStats = GuiWritingStats(self) + assert isinstance(dlgStats, GuiWritingStats) dlgStats.setModal(False) dlgStats.show() @@ -1050,6 +1040,7 @@ class GuiMain(QMainWindow): dlgAbout = getGuiItem("GuiAbout") if dlgAbout is None: dlgAbout = GuiAbout(self) + assert isinstance(dlgAbout, GuiAbout) dlgAbout.setModal(True) dlgAbout.show() @@ -1075,6 +1066,7 @@ class GuiMain(QMainWindow): dlgUpdate = getGuiItem("GuiUpdates") if dlgUpdate is None: dlgUpdate = GuiUpdates(self) + assert isinstance(dlgUpdate, GuiUpdates) dlgUpdate.setModal(True) dlgUpdate.show() @@ -1225,11 +1217,9 @@ class GuiMain(QMainWindow): """ if self.docEditor.docHandle() is None: logger.error("No document open, so not activating Focus Mode") - self.mainMenu.setFocusMode(self.isFocusMode) return False self.isFocusMode = not self.isFocusMode - self.mainMenu.setFocusMode(self.isFocusMode) if self.isFocusMode: logger.debug("Activating Focus Mode") self.switchFocus(nwWidget.EDITOR) @@ -1238,7 +1228,7 @@ class GuiMain(QMainWindow): isVisible = not self.isFocusMode self.treePane.setVisible(isVisible) - self.statusBar.setVisible(isVisible) + self.mainStatus.setVisible(isVisible) self.mainMenu.setVisible(isVisible) self.viewsBar.setVisible(isVisible) @@ -1522,12 +1512,12 @@ class GuiMain(QMainWindow): if editIdle or userIdle: self.idleTime += currTime - self.idleRefTime - self.statusBar.setUserIdle(True) + self.mainStatus.setUserIdle(True) else: - self.statusBar.setUserIdle(False) + self.mainStatus.setUserIdle(False) self.idleRefTime = currTime - self.statusBar.updateTime(idleTime=self.idleTime) + self.mainStatus.updateTime(idleTime=self.idleTime) return @@ -1536,9 +1526,8 @@ class GuiMain(QMainWindow): """Update the word count on the status bar. """ if not self.hasProject: - self.statusBar.setProjectStats(0, 0) + self.mainStatus.setProjectStats(0, 0) - logger.verbose("Updating total word count") self.theProject.updateWordCounts() if self.mainConf.incNotesWCount: currWords = self.theProject.currWCount @@ -1547,7 +1536,7 @@ class GuiMain(QMainWindow): currWords = self.theProject.currNovelWC diffWords = currWords - self.theProject.lastNovelWC - self.statusBar.setProjectStats(currWords, diffWords) + self.mainStatus.setProjectStats(currWords, diffWords) return @@ -1575,13 +1564,9 @@ class GuiMain(QMainWindow): def _mainStackChanged(self, stIndex): """Activated when the main window tab is changed. """ - if stIndex == self.idxEditorView: - logger.verbose("Editor View activated") - elif stIndex == self.idxOutlineView: - logger.verbose("Outline View activated") + if stIndex == self.idxOutlineView: if self.hasProject: self.outlineView.refreshTree() - return @pyqtSlot(int) @@ -1591,11 +1576,9 @@ class GuiMain(QMainWindow): sHandle = None if stIndex == self.idxProjView: - logger.verbose("Project Tree View activated") sHandle = self.projView.getSelectedHandle() elif stIndex == self.idxNovelView: - logger.verbose("Novel Tree View activated") if self.hasProject: self.novelView.refreshTree() sHandle, _ = self.novelView.getSelectedHandle() diff --git a/novelwriter/tools/build.py b/novelwriter/tools/build.py index 7a0eba6c..683f8e99 100644 --- a/novelwriter/tools/build.py +++ b/novelwriter/tools/build.py @@ -47,8 +47,8 @@ from novelwriter.core import ToHtml, ToOdt, ToMarkdown from novelwriter.enum import nwAlert, nwItemType, nwItemLayout, nwItemClass from novelwriter.error import formatException, logException from novelwriter.common import fuzzyTime, makeFileNameSafe +from novelwriter.custom import QSwitch from novelwriter.constants import nwConst, nwFiles -from novelwriter.gui.custom import QSwitch logger = logging.getLogger(__name__) @@ -66,7 +66,7 @@ class GuiBuildNovel(QDialog): FMT_JSON_M = 9 # nW Markdown wrapped in JSON def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiBuildNovel ...") self.setObjectName("GuiBuildNovel") @@ -351,6 +351,36 @@ class GuiBuildNovel(QDialog): self.textForm.setColumnStretch(0, 1) self.textForm.setColumnStretch(1, 0) + # Root Filter Options + # =================== + + self.rootGroup = QGroupBox(self.tr("Root Filter Options"), self) + self.rootForm = QGridLayout(self) + self.rootGroup.setLayout(self.rootForm) + + rootFilter = pOptions.getValue("GuiBuildNovel", "rootFilter", []) + if not isinstance(rootFilter, list): + rootFilter = [] + + iRow = 0 + self.rootSelection = {} + for tHandle, nwItem in self.theProject.tree.iterRoots(None): + if not nwItem.isInactive(): + rootLabel = QLabel(nwItem.itemName) + rootLabel.setWordWrap(True) + + rootValue = QSwitch(width=wS, height=hS) + rootValue.setChecked(tHandle not in rootFilter) + + self.rootSelection[tHandle] = rootValue + self.rootForm.addWidget(rootLabel, iRow, 0, 1, 1, Qt.AlignLeft) + self.rootForm.addWidget(rootValue, iRow, 1, 1, 1, Qt.AlignRight) + + iRow += 1 + + self.rootForm.setColumnStretch(0, 1) + self.rootForm.setColumnStretch(1, 0) + # File Filter Options # =================== @@ -375,13 +405,13 @@ class GuiBuildNovel(QDialog): novelLabel = QLabel(self.tr("Include novel files")) notesLabel = QLabel(self.tr("Include note files")) - exportLabel = QLabel(self.tr("Ignore export flag")) + activeLabel = QLabel(self.tr("Include inactive files")) self.fileForm.addWidget(novelLabel, 0, 0, 1, 1, Qt.AlignLeft) self.fileForm.addWidget(self.novelFiles, 0, 1, 1, 1, Qt.AlignRight) self.fileForm.addWidget(notesLabel, 1, 0, 1, 1, Qt.AlignLeft) self.fileForm.addWidget(self.noteFiles, 1, 1, 1, 1, Qt.AlignRight) - self.fileForm.addWidget(exportLabel, 2, 0, 1, 1, Qt.AlignLeft) + self.fileForm.addWidget(activeLabel, 2, 0, 1, 1, Qt.AlignLeft) self.fileForm.addWidget(self.ignoreFlag, 2, 1, 1, 1, Qt.AlignRight) self.fileForm.setColumnStretch(0, 1) @@ -503,6 +533,7 @@ class GuiBuildNovel(QDialog): self.toolsBox.addWidget(self.fontGroup) self.toolsBox.addWidget(self.styleGroup) self.toolsBox.addWidget(self.textGroup) + self.toolsBox.addWidget(self.rootGroup) self.toolsBox.addWidget(self.fileGroup) self.toolsBox.addWidget(self.exportGroup) self.toolsBox.addStretch(1) @@ -716,6 +747,7 @@ class GuiBuildNovel(QDialog): self.buildProgress.setMaximum(len(self.theProject.tree)) self.buildProgress.setValue(0) + rootFilter = set(self._generateRootFilter()) for nItt, tItem in enumerate(self.theProject.tree): noteRoot = noteFiles @@ -730,7 +762,7 @@ class GuiBuildNovel(QDialog): if doConvert: bldObj.doConvert() - elif self._checkInclude(tItem, noteFiles, novelFiles, ignoreFlag): + elif self._checkInclude(tItem, noteFiles, novelFiles, ignoreFlag, rootFilter): bldObj.setText(tItem.itemHandle) bldObj.doPreProcessing() bldObj.tokenizeText() @@ -766,7 +798,7 @@ class GuiBuildNovel(QDialog): return - def _checkInclude(self, theItem, noteFiles, novelFiles, ignoreFlag): + def _checkInclude(self, theItem, noteFiles, novelFiles, ignoreFlag, rootFilter): """This function checks whether a file should be included in the export or not. For standard note and novel files, this is controlled by the options selected by the user. For other files @@ -781,7 +813,10 @@ class GuiBuildNovel(QDialog): if theItem is None: return False - if not (theItem.isExported or ignoreFlag): + if not (theItem.isActive or ignoreFlag): + return False + + if theItem.itemRoot in rootFilter: return False isNone = not theItem.isFileType() @@ -1045,6 +1080,11 @@ class GuiBuildNovel(QDialog): return + def _generateRootFilter(self): + """Return a list of all root folders that are filtered out. + """ + return [h for h, s in self.rootSelection.items() if not s.isChecked()] + def _loadCache(self): """Save the current data to cache. """ @@ -1146,6 +1186,7 @@ class GuiBuildNovel(QDialog): incBodyText = self.includeBody.isChecked() replaceTabs = self.replaceTabs.isChecked() replaceUCode = self.replaceUCode.isChecked() + rootFilter = self._generateRootFilter() mainSplit = self.mainSplit.sizes() boxWidth = self.mainConf.rpxInt(mainSplit[0]) @@ -1175,6 +1216,7 @@ class GuiBuildNovel(QDialog): pOptions.setValue("GuiBuildNovel", "incBodyText", incBodyText) pOptions.setValue("GuiBuildNovel", "replaceTabs", replaceTabs) pOptions.setValue("GuiBuildNovel", "replaceUCode", replaceUCode) + pOptions.setValue("GuiBuildNovel", "rootFilter", rootFilter) pOptions.saveSettings() return @@ -1194,7 +1236,7 @@ class GuiBuildNovel(QDialog): class GuiBuildNovelDocView(QTextBrowser): def __init__(self, mainGui, theProject): - QTextBrowser.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiBuildNovelDocView ...") @@ -1223,10 +1265,7 @@ class GuiBuildNovelDocView(QTextBrowser): self.setFont(theFont) # Set the tab stops - if self.mainConf.verQtValue >= 51000: - self.setTabStopDistance(self.mainConf.getTabWidth()) - else: - self.setTabStopWidth(self.mainConf.getTabWidth()) + self.setTabStopDistance(self.mainConf.getTabWidth()) docPalette = self.palette() docPalette.setColor(QPalette.Base, QColor(255, 255, 255)) @@ -1343,7 +1382,7 @@ class GuiBuildNovelDocView(QTextBrowser): def resizeEvent(self, theEvent): """Make sure the document title is the same width as the window. """ - QTextBrowser.resizeEvent(self, theEvent) + super().resizeEvent(theEvent) self._updateDocMargins() return diff --git a/novelwriter/tools/lipsum.py b/novelwriter/tools/lipsum.py index 2086d615..976732dd 100644 --- a/novelwriter/tools/lipsum.py +++ b/novelwriter/tools/lipsum.py @@ -34,8 +34,8 @@ from PyQt5.QtWidgets import ( QSpinBox ) -from novelwriter.gui.custom import QSwitch from novelwriter.common import readTextFile +from novelwriter.custom import QSwitch logger = logging.getLogger(__name__) @@ -43,7 +43,7 @@ logger = logging.getLogger(__name__) class GuiLipsum(QDialog): def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiLipsum ...") self.setObjectName("GuiLipsum") diff --git a/novelwriter/tools/projwizard.py b/novelwriter/tools/projwizard.py index 5b21f69a..94cab911 100644 --- a/novelwriter/tools/projwizard.py +++ b/novelwriter/tools/projwizard.py @@ -35,7 +35,7 @@ from PyQt5.QtWidgets import ( ) from novelwriter.common import makeFileNameSafe -from novelwriter.gui.custom import QSwitch +from novelwriter.custom import QSwitch logger = logging.getLogger(__name__) @@ -49,7 +49,7 @@ PAGE_FINAL = 4 class GuiProjectWizard(QWizard): def __init__(self, mainGui): - QWizard.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiProjectWizard ...") self.setObjectName("GuiProjectWizard") @@ -88,7 +88,7 @@ class GuiProjectWizard(QWizard): class ProjWizardIntroPage(QWizardPage): def __init__(self, theWizard): - QWizardPage.__init__(self) + super().__init__() self.mainConf = novelwriter.CONFIG self.theWizard = theWizard @@ -158,7 +158,7 @@ class ProjWizardIntroPage(QWizardPage): class ProjWizardFolderPage(QWizardPage): def __init__(self, theWizard): - QWizardPage.__init__(self) + super().__init__() self.mainConf = novelwriter.CONFIG self.theWizard = theWizard @@ -209,12 +209,12 @@ class ProjWizardFolderPage(QWizardPage): """Check that the selected path isn't already being used. """ self.errLabel.setText("") - if not QWizardPage.isComplete(self): + if not super().isComplete(): return False setPath = os.path.abspath(os.path.expanduser(self.projPath.text())) parPath = os.path.dirname(setPath) - logger.verbose("Path is: %s", setPath) + logger.debug("Path is: %s", setPath) if parPath and not os.path.isdir(parPath): self.errLabel.setText(self.tr( "Error: A project folder cannot be created using this path." @@ -259,7 +259,7 @@ class ProjWizardFolderPage(QWizardPage): class ProjWizardPopulatePage(QWizardPage): def __init__(self, theWizard): - QWizardPage.__init__(self) + super().__init__() self.mainConf = novelwriter.CONFIG self.theWizard = theWizard @@ -315,7 +315,7 @@ class ProjWizardPopulatePage(QWizardPage): class ProjWizardCustomPage(QWizardPage): def __init__(self, theWizard): - QWizardPage.__init__(self) + super().__init__() self.mainConf = novelwriter.CONFIG self.theWizard = theWizard @@ -334,13 +334,18 @@ class ProjWizardCustomPage(QWizardPage): # Root Folders self.addPlot = QSwitch() - self.addChar = QSwitch() - self.addWorld = QSwitch() - self.addNotes = QSwitch() - self.addPlot.setChecked(True) + self.addPlot.clicked.connect(self._syncSwitches) + + self.addChar = QSwitch() self.addChar.setChecked(True) + self.addChar.clicked.connect(self._syncSwitches) + + self.addWorld = QSwitch() self.addWorld.setChecked(False) + self.addWorld.clicked.connect(self._syncSwitches) + + self.addNotes = QSwitch() self.addNotes.setChecked(False) # Generate Content @@ -391,13 +396,27 @@ class ProjWizardCustomPage(QWizardPage): return + ## + # Internal Functions + ## + + def _syncSwitches(self): + """Check if the add notes option should also be switched off. + """ + addPlot = self.addPlot.isChecked() + addChar = self.addChar.isChecked() + addWorld = self.addWorld.isChecked() + if not (addPlot or addChar or addWorld): + self.addNotes.setChecked(False) + return + # END Class ProjWizardCustomPage class ProjWizardFinalPage(QWizardPage): def __init__(self, theWizard): - QWizardPage.__init__(self) + super().__init__() self.mainConf = novelwriter.CONFIG self.theWizard = theWizard @@ -418,7 +437,7 @@ class ProjWizardFinalPage(QWizardPage): def initializePage(self): """Update the summary information on the final page. """ - QWizardPage.initializePage(self) + super().initializePage() sumList = [] sumList.append(self.tr("Project Name: {0}").format(self.field("projName"))) diff --git a/novelwriter/tools/writingstats.py b/novelwriter/tools/writingstats.py index add052ec..2a579837 100644 --- a/novelwriter/tools/writingstats.py +++ b/novelwriter/tools/writingstats.py @@ -39,9 +39,9 @@ from PyQt5.QtWidgets import ( from novelwriter.enum import nwAlert from novelwriter.error import formatException -from novelwriter.common import formatTime, checkInt, checkIntRange, checkIntTuple +from novelwriter.common import formatTime, checkInt, checkIntTuple, minmax +from novelwriter.custom import QSwitch from novelwriter.constants import nwConst, nwFiles -from novelwriter.gui.custom import QSwitch logger = logging.getLogger(__name__) @@ -58,7 +58,7 @@ class GuiWritingStats(QDialog): FMT_CSV = 1 def __init__(self, mainGui): - QDialog.__init__(self, mainGui) + super().__init__(parent=mainGui) logger.debug("Initialising GuiWritingStats ...") self.setObjectName("GuiWritingStats") @@ -112,11 +112,12 @@ class GuiWritingStats(QDialog): self.listBox.setColumnWidth(self.C_COUNT, wCol3) hHeader = self.listBox.headerItem() - hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight) - hHeader.setTextAlignment(self.C_IDLE, Qt.AlignRight) - hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight) + if hHeader is not None: + hHeader.setTextAlignment(self.C_LENGTH, Qt.AlignRight) + hHeader.setTextAlignment(self.C_IDLE, Qt.AlignRight) + hHeader.setTextAlignment(self.C_COUNT, Qt.AlignRight) - sortCol = checkIntRange(pOptions.getInt("GuiWritingStats", "sortCol", 0), 0, 2, 0) + sortCol = minmax(pOptions.getInt("GuiWritingStats", "sortCol", 0), 0, 2) sortOrder = checkIntTuple( pOptions.getInt("GuiWritingStats", "sortOrder", Qt.DescendingOrder), (Qt.AscendingOrder, Qt.DescendingOrder), Qt.DescendingOrder @@ -449,7 +450,7 @@ class GuiWritingStats(QDialog): if inLine.startswith("#"): if inLine.startswith("# Offset"): self.wordOffset = checkInt(inLine[9:].strip(), 0) - logger.verbose( + logger.debug( "Initial word count when log was started is %d" % self.wordOffset ) continue diff --git a/sample/nwProject.nwx b/sample/nwProject.nwx index b5bf2647..e32d66f8 100644 --- a/sample/nwProject.nwx +++ b/sample/nwProject.nwx @@ -1,13 +1,13 @@ - + Sample Project Sample Project Jane Smith Jay Doh - 1378 + 1385 236 - 69273 + 69348 False @@ -55,56 +55,56 @@ Novel - - Title Page + + Title Page - - Page + + Page - - Part One + + Part One - - Chapter One + + Chapter One - - Making a Scene + + Making a Scene - - Another Scene + + Another Scene - - Interlude + + Interlude - - A Note on Structure + + A Note on Structure - - Chapter Two + + Chapter Two - - We Found John! + + We Found John! Sequel - - Title Page + + Title Page - - Chapter One + + Chapter One @@ -115,28 +115,28 @@ Main Characters - - John Smith + + John Smith - - Jane Smith + + Jane Smith Locations - - Earth + + Earth - - Space + + Space - - Mars + + Mars @@ -147,16 +147,16 @@ Scenes - - Old File + + Old File Trash - - Delete Me! + + Delete Me! diff --git a/tests/conftest.py b/tests/conftest.py index 769f855c..40725923 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -190,14 +190,20 @@ def mockRnd(monkeypatch): from 0. This one will generate status/importance flags and handles in a predictable sequence. """ - def rnd(n): - for x in range(n): - yield x + class MockRnd: - gen = rnd(1000) - monkeypatch.setattr("random.getrandbits", lambda *a: next(gen)) + def __init__(self): + self.reset() - return + def _rnd(self, n): + for x in range(n): + yield x + + def reset(self): + gen = self._rnd(1000) + monkeypatch.setattr("random.getrandbits", lambda *a: next(gen)) + + return MockRnd() ## diff --git a/tests/lipsum/nwProject.nwx b/tests/lipsum/nwProject.nwx index 4eac7bc6..bfaedd84 100644 --- a/tests/lipsum/nwProject.nwx +++ b/tests/lipsum/nwProject.nwx @@ -1,12 +1,12 @@ - + Lorem Ipsum Lorem Ipsum lipsum.com - 26 + 28 24 - 1863 + 1874 False @@ -50,84 +50,84 @@ Novel - - Lorem Ipsum + + Lorem Ipsum - - Front Matter + + Front Matter - - Prologue + + Prologue - - Act One + + Act One Chapter One - - Chapter One + + Chapter One - - Scene One + + Scene One - - Scene Two + + Scene Two - - Interlude + + Interlude Chapter Two - - Chapter Two + + Chapter Two - - Scene Three + + Scene Three - - Scene Four + + Scene Four - - Scene Five + + Scene Five Characters - - Mr. Nobody + + Mr. Nobody Plot - - Main + + Main World - - Ancient Europe + + Ancient Europe diff --git a/tests/minimal/nwProject.nwx b/tests/minimal/nwProject.nwx index 5862d48c..b9180838 100644 --- a/tests/minimal/nwProject.nwx +++ b/tests/minimal/nwProject.nwx @@ -1,13 +1,13 @@ - + Test Minimal Minimal Jane Doe John Doh - 17 + 19 2 - 150 + 167 True @@ -16,7 +16,7 @@ None None None - None + a508bb932959c None 10 10 @@ -48,20 +48,20 @@ Novel - - Title Page + + Title Page New Chapter - - New Chapter + + New Chapter - - New Scene + + New Scene diff --git a/tests/mock.py b/tests/mock.py index 23938d41..ff67f4bf 100644 --- a/tests/mock.py +++ b/tests/mock.py @@ -24,13 +24,13 @@ along with this program. If not, see . # Mock GUI # =========================================================================== # -class MockGuiMain(): +class MockGuiMain: def __init__(self): self.mainConf = None self.hasProject = True self.theProject = None - self.statusBar = MockStatusBar() + self.mainStatus = MockStatusBar() # Test Variables self.askResponse = True @@ -81,7 +81,7 @@ class MockGuiMain(): # END Class MockGuiMain -class MockStatusBar(): +class MockStatusBar: def __init__(self): return diff --git a/tests/reference/coreDocTools_DocMerger_0000000000010.nwd b/tests/reference/coreDocTools_DocMerger_0000000000010.nwd new file mode 100644 index 00000000..eb13ead2 --- /dev/null +++ b/tests/reference/coreDocTools_DocMerger_0000000000010.nwd @@ -0,0 +1,33 @@ +%%~name: Chapter 1 +%%~path: 0000000000008/0000000000010 +%%~kind: NOVEL/DOCUMENT +## Chapter 1 + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc maximus justo non dictum commodo. Curabitur lacinia tempor orci vel luctus. Phasellus porta metus eu massa luctus, eget euismod risus rhoncus. Vestibulum sed arcu nisi. Maecenas pretium facilisis velit, vel semper lacus aliquam sit amet. Vestibulum vulputate neque ligula, rhoncus blandit turpis consequat id. Mauris sagittis vehicula imperdiet. Duis sed nunc pretium, ornare purus vel, sodales augue. Maecenas a suscipit risus. Quisque volutpat justo eleifend est ullamcorper fermentum. Donec ullamcorper et tortor a laoreet. Nam id risus nisi. Vivamus non imperdiet erat, sit amet imperdiet felis. Mauris vitae neque et est aliquam scelerisque non non ipsum. + +Nullam laoreet lorem nec malesuada vehicula. Vivamus tempus sodales lectus sed viverra. Aenean lacinia sollicitudin quam, quis tempus eros suscipit id. Duis sed rutrum nisi, ut pulvinar magna. Nam et cursus tortor. Phasellus ac odio tellus. Nullam in iaculis ipsum. Vivamus ante sem, ultricies sed varius quis, tristique nec tellus. Nullam eu urna vitae lacus hendrerit gravida. Quisque pulvinar erat ex, id efficitur velit sodales vitae. Proin vestibulum, sapien eget mattis euismod, tortor quam viverra risus, at congue mauris tortor eu nunc. Mauris pellentesque elit leo, quis eleifend sem placerat a. Vivamus iaculis dui eget tellus volutpat, ac varius nisi facilisis. + +% Merge Novel Scene: Scene 1.1 [New] + +### Scene 1.1 + +Nullam laoreet lorem nec malesuada vehicula. Vivamus tempus sodales lectus sed viverra. Aenean lacinia sollicitudin quam, quis tempus eros suscipit id. Duis sed rutrum nisi, ut pulvinar magna. Nam et cursus tortor. Phasellus ac odio tellus. Nullam in iaculis ipsum. Vivamus ante sem, ultricies sed varius quis, tristique nec tellus. Nullam eu urna vitae lacus hendrerit gravida. Quisque pulvinar erat ex, id efficitur velit sodales vitae. Proin vestibulum, sapien eget mattis euismod, tortor quam viverra risus, at congue mauris tortor eu nunc. Mauris pellentesque elit leo, quis eleifend sem placerat a. Vivamus iaculis dui eget tellus volutpat, ac varius nisi facilisis. + +Nullam a nisl magna. Praesent commodo nec diam aliquet vestibulum. In sapien velit, sodales feugiat porta ut, rhoncus a elit. Quisque egestas nisi eu eros laoreet, quis facilisis est pretium. Nullam bibendum sed tellus nec lobortis. Duis elit massa, volutpat a lacinia a, ullamcorper in dui. Suspendisse ac laoreet dui. Curabitur elementum, tortor elementum ultricies laoreet, nunc massa vulputate augue, vitae tincidunt nunc enim eget nisl. + +% Merge Novel Scene: Scene 1.2 [New] + +### Scene 1.2 + +Nullam a nisl magna. Praesent commodo nec diam aliquet vestibulum. In sapien velit, sodales feugiat porta ut, rhoncus a elit. Quisque egestas nisi eu eros laoreet, quis facilisis est pretium. Nullam bibendum sed tellus nec lobortis. Duis elit massa, volutpat a lacinia a, ullamcorper in dui. Suspendisse ac laoreet dui. Curabitur elementum, tortor elementum ultricies laoreet, nunc massa vulputate augue, vitae tincidunt nunc enim eget nisl. + +Pellentesque nibh urna, volutpat et feugiat porta, rutrum sed lectus. Aliquam eget risus id orci tincidunt condimentum et sit amet purus. Curabitur tincidunt odio vel ante feugiat feugiat. Proin nunc lorem, molestie a sapien et, varius elementum nunc. Donec non fermentum nisl. In et massa placerat, faucibus felis eu, congue nisi. Proin sed tortor non lorem mattis cursus. Vestibulum magna neque, bibendum vel nibh et, tincidunt rhoncus nisi. Duis pulvinar mi a quam rutrum maximus. Nunc sollicitudin, urna in cursus facilisis, augue neque imperdiet metus, ac finibus lorem ante id nulla. Sed maximus eleifend justo id feugiat. Cras eget diam vel est blandit tempor nec a leo. Mauris risus est, fringilla in aliquam a, sagittis vel enim. Nullam sodales id erat placerat lobortis. + +% Merge Novel Scene: Scene 1.3 [New] + +### Scene 1.3 + +Pellentesque nibh urna, volutpat et feugiat porta, rutrum sed lectus. Aliquam eget risus id orci tincidunt condimentum et sit amet purus. Curabitur tincidunt odio vel ante feugiat feugiat. Proin nunc lorem, molestie a sapien et, varius elementum nunc. Donec non fermentum nisl. In et massa placerat, faucibus felis eu, congue nisi. Proin sed tortor non lorem mattis cursus. Vestibulum magna neque, bibendum vel nibh et, tincidunt rhoncus nisi. Duis pulvinar mi a quam rutrum maximus. Nunc sollicitudin, urna in cursus facilisis, augue neque imperdiet metus, ac finibus lorem ante id nulla. Sed maximus eleifend justo id feugiat. Cras eget diam vel est blandit tempor nec a leo. Mauris risus est, fringilla in aliquam a, sagittis vel enim. Nullam sodales id erat placerat lobortis. + +Integer ac gravida quam. Quisque eleifend nisl nec pretium tincidunt. Quisque sollicitudin nisi in hendrerit scelerisque. Sed ornare nisl lacus, sit amet consectetur lectus egestas et. Vivamus nec arcu lorem. Donec rhoncus, purus a porta accumsan, nunc lectus iaculis libero, et fringilla tellus augue et velit. Integer varius felis scelerisque, vulputate tellus eu, laoreet justo. Suspendisse sit amet sem vehicula, auctor odio sed, aliquet enim. In ac tortor sed tortor fringilla elementum. Nulla non odio at magna vulputate scelerisque. Nam elementum diam eu rutrum scelerisque. Sed fermentum, felis quis vulputate fermentum, libero metus sollicitudin est, in faucibus purus nulla non dolor. Ut vitae felis porta, feugiat nunc et, bibendum neque. Nullam nec lorem nec metus ullamcorper malesuada ut a nisl. Etiam eget tristique dui. Nulla sed mi finibus, venenatis tellus non, maximus enim. + diff --git a/tests/reference/coreDocTools_DocMerger_0000000000014.nwd b/tests/reference/coreDocTools_DocMerger_0000000000014.nwd new file mode 100644 index 00000000..199454dc --- /dev/null +++ b/tests/reference/coreDocTools_DocMerger_0000000000014.nwd @@ -0,0 +1,35 @@ +%%~name: All of Chapter 1 +%%~path: 0000000000008/0000000000014 +%%~kind: NOVEL/DOCUMENT +% Merge Novel Chapter: Chapter 1 [New] + +## Chapter 1 + +Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc maximus justo non dictum commodo. Curabitur lacinia tempor orci vel luctus. Phasellus porta metus eu massa luctus, eget euismod risus rhoncus. Vestibulum sed arcu nisi. Maecenas pretium facilisis velit, vel semper lacus aliquam sit amet. Vestibulum vulputate neque ligula, rhoncus blandit turpis consequat id. Mauris sagittis vehicula imperdiet. Duis sed nunc pretium, ornare purus vel, sodales augue. Maecenas a suscipit risus. Quisque volutpat justo eleifend est ullamcorper fermentum. Donec ullamcorper et tortor a laoreet. Nam id risus nisi. Vivamus non imperdiet erat, sit amet imperdiet felis. Mauris vitae neque et est aliquam scelerisque non non ipsum. + +Nullam laoreet lorem nec malesuada vehicula. Vivamus tempus sodales lectus sed viverra. Aenean lacinia sollicitudin quam, quis tempus eros suscipit id. Duis sed rutrum nisi, ut pulvinar magna. Nam et cursus tortor. Phasellus ac odio tellus. Nullam in iaculis ipsum. Vivamus ante sem, ultricies sed varius quis, tristique nec tellus. Nullam eu urna vitae lacus hendrerit gravida. Quisque pulvinar erat ex, id efficitur velit sodales vitae. Proin vestibulum, sapien eget mattis euismod, tortor quam viverra risus, at congue mauris tortor eu nunc. Mauris pellentesque elit leo, quis eleifend sem placerat a. Vivamus iaculis dui eget tellus volutpat, ac varius nisi facilisis. + +% Merge Novel Scene: Scene 1.1 [New] + +### Scene 1.1 + +Nullam laoreet lorem nec malesuada vehicula. Vivamus tempus sodales lectus sed viverra. Aenean lacinia sollicitudin quam, quis tempus eros suscipit id. Duis sed rutrum nisi, ut pulvinar magna. Nam et cursus tortor. Phasellus ac odio tellus. Nullam in iaculis ipsum. Vivamus ante sem, ultricies sed varius quis, tristique nec tellus. Nullam eu urna vitae lacus hendrerit gravida. Quisque pulvinar erat ex, id efficitur velit sodales vitae. Proin vestibulum, sapien eget mattis euismod, tortor quam viverra risus, at congue mauris tortor eu nunc. Mauris pellentesque elit leo, quis eleifend sem placerat a. Vivamus iaculis dui eget tellus volutpat, ac varius nisi facilisis. + +Nullam a nisl magna. Praesent commodo nec diam aliquet vestibulum. In sapien velit, sodales feugiat porta ut, rhoncus a elit. Quisque egestas nisi eu eros laoreet, quis facilisis est pretium. Nullam bibendum sed tellus nec lobortis. Duis elit massa, volutpat a lacinia a, ullamcorper in dui. Suspendisse ac laoreet dui. Curabitur elementum, tortor elementum ultricies laoreet, nunc massa vulputate augue, vitae tincidunt nunc enim eget nisl. + +% Merge Novel Scene: Scene 1.2 [New] + +### Scene 1.2 + +Nullam a nisl magna. Praesent commodo nec diam aliquet vestibulum. In sapien velit, sodales feugiat porta ut, rhoncus a elit. Quisque egestas nisi eu eros laoreet, quis facilisis est pretium. Nullam bibendum sed tellus nec lobortis. Duis elit massa, volutpat a lacinia a, ullamcorper in dui. Suspendisse ac laoreet dui. Curabitur elementum, tortor elementum ultricies laoreet, nunc massa vulputate augue, vitae tincidunt nunc enim eget nisl. + +Pellentesque nibh urna, volutpat et feugiat porta, rutrum sed lectus. Aliquam eget risus id orci tincidunt condimentum et sit amet purus. Curabitur tincidunt odio vel ante feugiat feugiat. Proin nunc lorem, molestie a sapien et, varius elementum nunc. Donec non fermentum nisl. In et massa placerat, faucibus felis eu, congue nisi. Proin sed tortor non lorem mattis cursus. Vestibulum magna neque, bibendum vel nibh et, tincidunt rhoncus nisi. Duis pulvinar mi a quam rutrum maximus. Nunc sollicitudin, urna in cursus facilisis, augue neque imperdiet metus, ac finibus lorem ante id nulla. Sed maximus eleifend justo id feugiat. Cras eget diam vel est blandit tempor nec a leo. Mauris risus est, fringilla in aliquam a, sagittis vel enim. Nullam sodales id erat placerat lobortis. + +% Merge Novel Scene: Scene 1.3 [New] + +### Scene 1.3 + +Pellentesque nibh urna, volutpat et feugiat porta, rutrum sed lectus. Aliquam eget risus id orci tincidunt condimentum et sit amet purus. Curabitur tincidunt odio vel ante feugiat feugiat. Proin nunc lorem, molestie a sapien et, varius elementum nunc. Donec non fermentum nisl. In et massa placerat, faucibus felis eu, congue nisi. Proin sed tortor non lorem mattis cursus. Vestibulum magna neque, bibendum vel nibh et, tincidunt rhoncus nisi. Duis pulvinar mi a quam rutrum maximus. Nunc sollicitudin, urna in cursus facilisis, augue neque imperdiet metus, ac finibus lorem ante id nulla. Sed maximus eleifend justo id feugiat. Cras eget diam vel est blandit tempor nec a leo. Mauris risus est, fringilla in aliquam a, sagittis vel enim. Nullam sodales id erat placerat lobortis. + +Integer ac gravida quam. Quisque eleifend nisl nec pretium tincidunt. Quisque sollicitudin nisi in hendrerit scelerisque. Sed ornare nisl lacus, sit amet consectetur lectus egestas et. Vivamus nec arcu lorem. Donec rhoncus, purus a porta accumsan, nunc lectus iaculis libero, et fringilla tellus augue et velit. Integer varius felis scelerisque, vulputate tellus eu, laoreet justo. Suspendisse sit amet sem vehicula, auctor odio sed, aliquet enim. In ac tortor sed tortor fringilla elementum. Nulla non odio at magna vulputate scelerisque. Nam elementum diam eu rutrum scelerisque. Sed fermentum, felis quis vulputate fermentum, libero metus sollicitudin est, in faucibus purus nulla non dolor. Ut vitae felis porta, feugiat nunc et, bibendum neque. Nullam nec lorem nec metus ullamcorper malesuada ut a nisl. Etiam eget tristique dui. Nulla sed mi finibus, venenatis tellus non, maximus enim. + diff --git a/tests/reference/coreIndex_LoadSave_tagsIndex.json b/tests/reference/coreIndex_LoadSave_tagsIndex.json index 60c59d86..cba693dc 100644 --- a/tests/reference/coreIndex_LoadSave_tagsIndex.json +++ b/tests/reference/coreIndex_LoadSave_tagsIndex.json @@ -6,31 +6,26 @@ }, "itemIndex": { "7a992350f3eb6": { - "level": "H1", "headings": { "T000001": {"level": "H1", "title": "Lorem Ipsum", "tag": "", "cCount": 230, "wCount": 40, "pCount": 3, "synopsis": ""} } }, "8c58a65414c23": { - "level": "H0", "headings": { "T000000": {"level": "H0", "title": "", "tag": "", "cCount": 1058, "wCount": 176, "pCount": 2, "synopsis": ""} } }, "88d59a277361b": { - "level": "H2", "headings": { "T000001": {"level": "H2", "title": "Prologue", "tag": "", "cCount": 584, "wCount": 92, "pCount": 1, "synopsis": "Explanation from the lipsum.com website."} } }, "db7e733775d4d": { - "level": "H1", "headings": { "T000001": {"level": "H1", "title": "Act One", "tag": "", "cCount": 35, "wCount": 6, "pCount": 1, "synopsis": ""} } }, "fb609cd8319dc": { - "level": "H2", "headings": { "T000001": {"level": "H2", "title": "Chapter One", "tag": "", "cCount": 419, "wCount": 67, "pCount": 1, "synopsis": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque at aliquam quam."} }, @@ -39,7 +34,6 @@ } }, "88243afbe5ed8": { - "level": "H3", "headings": { "T000001": {"level": "H3", "title": "Scene One", "tag": "", "cCount": 1197, "wCount": 174, "pCount": 2, "synopsis": "Aenean ut placerat velit. Etiam laoreet ullamcorper risus, eget lobortis enim scelerisque non. Suspendisse id maximus nunc, et mollis sapien. Curabitur vel semper sapien, non pulvinar dolor. Etiam finibus nisi vel mi molestie consectetur."}, "T000013": {"level": "H4", "title": "Scene One, Section Two", "tag": "", "cCount": 1561, "wCount": 230, "pCount": 2, "synopsis": ""} @@ -49,7 +43,6 @@ } }, "f96ec11c6a3da": { - "level": "H3", "headings": { "T000001": {"level": "H3", "title": "Scene Two", "tag": "", "cCount": 2034, "wCount": 299, "pCount": 3, "synopsis": "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Integer sapien nulla, dictum at lacus a, dignissim consectetur dolor. Nunc vel eleifend lacus, eu dapibus orci."}, "T000015": {"level": "H4", "title": "Scene Two, Section Two", "tag": "", "cCount": 2009, "wCount": 301, "pCount": 3, "synopsis": ""} @@ -59,13 +52,11 @@ } }, "846352075de7d": { - "level": "H2", "headings": { "T000001": {"level": "H2", "title": "Why do we use it?", "tag": "", "cCount": 631, "wCount": 109, "pCount": 3, "synopsis": ""} } }, "441420a886d82": { - "level": "H2", "headings": { "T000001": {"level": "H2", "title": "Chapter Two", "tag": "", "cCount": 477, "wCount": 70, "pCount": 1, "synopsis": "Curabitur a elit posuere, varius ex et, convallis neque. Phasellus sagittis pharetra sem vitae dapibus. Curabitur varius lorem non pulvinar congue."} }, @@ -74,7 +65,6 @@ } }, "eb103bc70c90c": { - "level": "H3", "headings": { "T000001": {"level": "H3", "title": "Scene Three", "tag": "", "cCount": 3006, "wCount": 439, "pCount": 4, "synopsis": "Aenean ut libero ut lectus porttitor rhoncus vel et massa. Nam pretium, nibh et varius vehicula, urna metus blandit eros, euismod pharetra diam diam et libero. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos."} }, @@ -83,7 +73,6 @@ } }, "f8c0562e50f1b": { - "level": "H3", "headings": { "T000001": {"level": "H3", "title": "Scene Four", "tag": "", "cCount": 3839, "wCount": 563, "pCount": 6, "synopsis": "Nam tempor blandit magna laoreet aliquet. Vestibulum auctor posuere leo, ac gravida nisi rhoncus varius. Aenean posuere dolor vitae condimentum volutpat. Donec egestas volutpat risus, quis luctus justo."} }, @@ -92,7 +81,6 @@ } }, "47666c91c7ccf": { - "level": "H3", "headings": { "T000001": {"level": "H3", "title": "Scene Five", "tag": "", "cCount": 3644, "wCount": 543, "pCount": 5, "synopsis": "Praesent eget est porta, dictum ante in, egestas risus. Mauris risus mauris, consequat aliquam mauris et, feugiat iaculis ipsum. Aliquam arcu ipsum, fermentum ut arcu sed, lobortis euismod sem. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus."} }, @@ -101,7 +89,6 @@ } }, "4c4f28287af27": { - "level": "H1", "headings": { "T000001": {"level": "H1", "title": "Nobody Owens", "tag": "Bod", "cCount": 1864, "wCount": 284, "pCount": 3, "synopsis": ""} }, @@ -110,13 +97,11 @@ } }, "2426c6f0ca922": { - "level": "H1", "headings": { "T000001": {"level": "H1", "title": "Main Plot", "tag": "Main", "cCount": 1369, "wCount": 195, "pCount": 2, "synopsis": ""} } }, "04468803b92e1": { - "level": "H1", "headings": { "T000001": {"level": "H1", "title": "Ancient Europe", "tag": "Europe", "cCount": 1770, "wCount": 259, "pCount": 3, "synopsis": ""} } diff --git a/tests/reference/coreProject_NewCustomA_nwProject.nwx b/tests/reference/coreProject_NewCustomA_nwProject.nwx index 48ae6363..ef2056f7 100644 --- a/tests/reference/coreProject_NewCustomA_nwProject.nwx +++ b/tests/reference/coreProject_NewCustomA_nwProject.nwx @@ -1,5 +1,5 @@ - + Test Custom Test Novel @@ -48,80 +48,80 @@ Novel - - Title Page + + Title Page - - Chapter 1 + + Chapter 1 - - Scene 1.1 + + Scene 1.1 - - Scene 1.2 + + Scene 1.2 - - Scene 1.3 + + Scene 1.3 - - Chapter 2 + + Chapter 2 - - Scene 2.1 + + Scene 2.1 - - Scene 2.2 + + Scene 2.2 - - Scene 2.3 + + Scene 2.3 - - Chapter 3 + + Chapter 3 - - Scene 3.1 + + Scene 3.1 - - Scene 3.2 + + Scene 3.2 - - Scene 3.3 + + Scene 3.3 Plot - - Main Plot + + Main Plot Characters - - Protagonist + + Protagonist Locations - - Main Location + + Main Location diff --git a/tests/reference/coreProject_NewCustomB_nwProject.nwx b/tests/reference/coreProject_NewCustomB_nwProject.nwx index 9399dd3f..30d6c2a9 100644 --- a/tests/reference/coreProject_NewCustomB_nwProject.nwx +++ b/tests/reference/coreProject_NewCustomB_nwProject.nwx @@ -1,5 +1,5 @@ - + Test Custom Test Novel @@ -48,56 +48,56 @@ Novel - - Title Page + + Title Page - - Scene 1 + + Scene 1 - - Scene 2 + + Scene 2 - - Scene 3 + + Scene 3 - - Scene 4 + + Scene 4 - - Scene 5 + + Scene 5 - - Scene 6 + + Scene 6 Plot - - Main Plot + + Main Plot Characters - - Protagonist + + Protagonist Locations - - Main Location + + Main Location diff --git a/tests/reference/coreProject_NewFileFolder_nwProject.nwx b/tests/reference/coreProject_NewFileFolder_nwProject.nwx index b8df1c93..e1faf5a7 100644 --- a/tests/reference/coreProject_NewFileFolder_nwProject.nwx +++ b/tests/reference/coreProject_NewFileFolder_nwProject.nwx @@ -1,5 +1,5 @@ - + New Project New Novel @@ -17,9 +17,9 @@ None None None - 2 - 1 - 1 + 13 + 10 + 3 %title% @@ -29,62 +29,62 @@
- New - Note - Draft - Finished + New + Note + Draft + Finished - New - Minor - Major - Main + New + Minor + Major + Main
- + - Novel + Novel - + - Plot + Plot - + - Characters + Characters - + - World + World - - - Title Page + + + Title Page - + - New Chapter + New Chapter - - - New Chapter + + + New Chapter - - - New Scene + + + New Scene - + - Stuff + Stuff - - - Hello + + + Hello - - - Jane + + + Jane
diff --git a/tests/reference/coreProject_NewMinimal_nwProject.nwx b/tests/reference/coreProject_NewMinimal_nwProject.nwx index 633f9f4c..282aa1f3 100644 --- a/tests/reference/coreProject_NewMinimal_nwProject.nwx +++ b/tests/reference/coreProject_NewMinimal_nwProject.nwx @@ -1,5 +1,5 @@ - + New Project @@ -46,16 +46,16 @@ Novel - - Title Page + + Title Page - - New Chapter + + New Chapter - - New Scene + + New Scene diff --git a/tests/reference/coreProject_NewRoot_nwProject.nwx b/tests/reference/coreProject_NewRoot_nwProject.nwx index 9102601d..af7e0b73 100644 --- a/tests/reference/coreProject_NewRoot_nwProject.nwx +++ b/tests/reference/coreProject_NewRoot_nwProject.nwx @@ -1,5 +1,5 @@ - + New Project New Novel @@ -17,8 +17,8 @@ None None None - 0 - 0 + 9 + 9 0 @@ -29,82 +29,82 @@
- New - Note - Draft - Finished + New + Note + Draft + Finished - New - Minor - Major - Main + New + Minor + Major + Main - + - Novel + Novel - + - Plot + Plot - + - Characters + Characters - + - World + World - - - Title Page + + + Title Page - + - New Chapter + New Chapter - - - New Chapter + + + New Chapter - - - New Scene + + + New Scene - + - Novel + Novel - + - Plot + Plot - + - Characters + Characters - + - Locations + Locations - + - Timeline + Timeline - + - Objects + Objects - + - Custom + Custom - + - Custom + Custom
diff --git a/tests/reference/guiEditor_Main_Final_000000000000f.nwd b/tests/reference/guiEditor_Main_Final_000000000000f.nwd index 1ac700fb..b45a9dca 100644 --- a/tests/reference/guiEditor_Main_Final_000000000000f.nwd +++ b/tests/reference/guiEditor_Main_Final_000000000000f.nwd @@ -21,6 +21,9 @@ This is a paragraph of nonsense text. +This is another paragraph +with a line separator in it. + This is another paragraph of much longer nonsense text. It is in fact 1 very very NONSENSICAL nonsense text! We can also try replacing “quotes”, even single ‘quotes’ are replaced. Isn’t that nice? We can hyphen-ate, make dashes – and even longer dashes — if we want. Ellipsis? Not a problem either … How about three hyphens — for long dash? It works too. “Full line double quoted text.” @@ -35,6 +38,8 @@ Some “ double quoted text with spaces padded ”. Add space before this colon : See? +But don’t add a double space : See? + “Tab-indented text” >“Paragraph-indented text” diff --git a/tests/reference/guiEditor_Main_Final_nwProject.nwx b/tests/reference/guiEditor_Main_Final_nwProject.nwx index 5496b5b3..fb58330e 100644 --- a/tests/reference/guiEditor_Main_Final_nwProject.nwx +++ b/tests/reference/guiEditor_Main_Final_nwProject.nwx @@ -1,5 +1,5 @@ - + New Project New Novel @@ -17,8 +17,8 @@ None 0000000000008 0000000000008 - 145 - 118 + 163 + 136 27 @@ -47,44 +47,44 @@ Novel
- - Title Page + + Title Page New Chapter - - New Chapter + + New Chapter - - New Scene + + New Scene Plot - - New Note + + New Note Characters - - New Note + + New Note World - - New Note + + New Note diff --git a/tests/reference/guiEditor_Main_Initial_nwProject.nwx b/tests/reference/guiEditor_Main_Initial_nwProject.nwx index 0563c440..aa3b3057 100644 --- a/tests/reference/guiEditor_Main_Initial_nwProject.nwx +++ b/tests/reference/guiEditor_Main_Initial_nwProject.nwx @@ -1,5 +1,5 @@ - + New Project New Novel @@ -47,20 +47,20 @@ Novel - - Title Page + + Title Page New Chapter - - New Chapter + + New Chapter - - New Scene + + New Scene diff --git a/tests/reference/guiProjSettings_Dialog_nwProject.nwx b/tests/reference/guiProjSettings_Dialog_nwProject.nwx index 1db9d48c..307aae55 100644 --- a/tests/reference/guiProjSettings_Dialog_nwProject.nwx +++ b/tests/reference/guiProjSettings_Dialog_nwProject.nwx @@ -1,5 +1,5 @@ - + Project Name Project Title @@ -52,20 +52,20 @@ Novel - - Title Page + + Title Page New Chapter - - New Chapter + + New Chapter - - New Scene + + New Scene diff --git a/tests/test_base/test_base_common.py b/tests/test_base/test_base_common.py index 0ce153b4..23b487e7 100644 --- a/tests/test_base/test_base_common.py +++ b/tests/test_base/test_base_common.py @@ -29,25 +29,38 @@ from tools import writeFile from novelwriter.guimain import GuiMain from novelwriter.common import ( - checkString, checkInt, checkFloat, checkBool, checkHandle, isHandle, - isTitleTag, isItemClass, isItemType, isItemLayout, hexToInt, checkIntRange, + checkStringNone, checkString, checkInt, checkFloat, checkBool, checkHandle, + isHandle, isTitleTag, isItemClass, isItemType, isItemLayout, hexToInt, minmax, checkIntTuple, formatInt, formatTimeStamp, formatTime, simplified, splitVersionNumber, transferCase, fuzzyTime, numberToRoman, jsonEncode, - readTextFile, makeFileNameSafe, sha256sum, getGuiItem, NWConfigParser + readTextFile, makeFileNameSafe, ensureFolder, sha256sum, getGuiItem, + NWConfigParser ) +@pytest.mark.base +def testBaseCommon_CheckStringNone(): + """Test the checkStringNone function. + """ + assert checkStringNone("Stuff", "NotNone") == "Stuff" + assert checkStringNone("None", "NotNone") is None + assert checkStringNone(None, "NotNone") is None + assert checkStringNone(1, "NotNone") == "NotNone" + assert checkStringNone(1.0, "NotNone") == "NotNone" + assert checkStringNone(True, "NotNone") == "NotNone" + +# END Test testBaseCommon_CheckStringNone + + @pytest.mark.base def testBaseCommon_CheckString(): """Test the checkString function. """ - assert checkString(None, "NotNone", True) is None - assert checkString("None", "NotNone", True) is None - assert checkString("None", "NotNone", False) == "None" - assert checkString(None, "NotNone", False) == "NotNone" - assert checkString(1, "NotNone", False) == "NotNone" - assert checkString(1.0, "NotNone", False) == "NotNone" - assert checkString(True, "NotNone", False) == "NotNone" + assert checkString("None", "NotNone") == "None" + assert checkString(None, "NotNone") == "NotNone" + assert checkString(1, "NotNone") == "NotNone" + assert checkString(1.0, "NotNone") == "NotNone" + assert checkString(True, "NotNone") == "NotNone" # END Test testBaseCommon_CheckString @@ -56,12 +69,12 @@ def testBaseCommon_CheckString(): def testBaseCommon_CheckInt(): """Test the checkInt function. """ - assert checkInt(None, 3, True) is None - assert checkInt("None", 3, True) is None - assert checkInt(None, 3, False) == 3 - assert checkInt(1, 3, False) == 1 - assert checkInt(1.0, 3, False) == 1 - assert checkInt(True, 3, False) == 1 + assert checkInt(None, 3) == 3 + assert checkInt("1", 3) == 1 + assert checkInt("1.0", 3) == 3 + assert checkInt(1, 3) == 1 + assert checkInt(1.0, 3) == 1 + assert checkInt(True, 3) == 1 # END Test testBaseCommon_CheckInt @@ -70,12 +83,12 @@ def testBaseCommon_CheckInt(): def testBaseCommon_CheckFloat(): """Test the checkFloat function. """ - assert checkFloat(None, 3.0, True) is None - assert checkFloat("None", 3.0, True) is None - assert checkFloat(None, 3.0, False) == 3.0 - assert checkFloat(1, 3.0, False) == 1.0 - assert checkFloat(1.0, 3.0, False) == 1.0 - assert checkFloat(True, 3.0, False) == 1.0 + assert checkFloat(None, 3.0) == 3.0 + assert checkFloat("1", 3.0) == 1.0 + assert checkFloat("1.0", 3.0) == 1.0 + assert checkFloat(1, 3.0) == 1.0 + assert checkFloat(1.0, 3.0) == 1.0 + assert checkFloat(True, 3.0) == 1.0 # END Test testBaseCommon_CheckInt @@ -84,17 +97,18 @@ def testBaseCommon_CheckFloat(): def testBaseCommon_CheckBool(): """Test the checkBool function. """ - assert checkBool(None, 3, True) is None - assert checkBool("None", 3, True) is None - assert checkBool("True", False, False) is True - assert checkBool("False", True, False) is False - assert checkBool("Boo", None, False) is None - assert checkBool(0, None, False) is False - assert checkBool(1, None, False) is True - assert checkBool(2, None, False) is None - assert checkBool(0.0, None, False) is None - assert checkBool(1.0, None, False) is None - assert checkBool(2.0, None, False) is None + assert checkBool("True", False) is True + assert checkBool("False", True) is False + assert checkBool("Boo", False) is False + assert checkBool("Boo", True) is True + assert checkBool(0, True) is False + assert checkBool(1, False) is True + assert checkBool(2, True) is True + assert checkBool(2, False) is False + assert checkBool(0.0, True) is True + assert checkBool(1.0, False) is False + assert checkBool(2.0, True) is True + assert checkBool(2.0, False) is False # END Test testBaseCommon_CheckBool @@ -228,18 +242,6 @@ def testBaseCommon_HexToInt(): # END Test testBaseCommon_HexToInt -@pytest.mark.base -def testBaseCommon_CheckIntRange(): - """Test the checkIntRange function. - """ - assert checkIntRange(5, 0, 9, 3) == 5 - assert checkIntRange(5, 0, 4, 3) == 3 - assert checkIntRange(5, 0, 5, 3) == 5 - assert checkIntRange(0, 0, 5, 3) == 0 - -# END Test testBaseCommon_CheckIntRange - - @pytest.mark.base def testBaseCommon_MinMax(): """Test the minmax function. @@ -310,16 +312,16 @@ def testBaseCommon_SplitVersionNumber(): """Test the splitVersionNumber function. """ # OK Values - assert splitVersionNumber("1") == [1, 0, 0, 10000] - assert splitVersionNumber("1.2") == [1, 2, 0, 10200] - assert splitVersionNumber("1.2.3") == [1, 2, 3, 10203] - assert splitVersionNumber("1.2.3.4") == [1, 2, 3, 10203] - assert splitVersionNumber("99.99.99") == [99, 99, 99, 999999] + assert splitVersionNumber("1") == (1, 0, 0, 10000) + assert splitVersionNumber("1.2") == (1, 2, 0, 10200) + assert splitVersionNumber("1.2.3") == (1, 2, 3, 10203) + assert splitVersionNumber("1.2.3.4") == (1, 2, 3, 10203) + assert splitVersionNumber("99.99.99") == (99, 99, 99, 999999) # Failed Values - assert splitVersionNumber(None) == [0, 0, 0, 0] - assert splitVersionNumber(1234) == [0, 0, 0, 0] - assert splitVersionNumber("1.2abc") == [1, 0, 0, 10000] + assert splitVersionNumber(None) == (0, 0, 0, 0) + assert splitVersionNumber(1234) == (0, 0, 0, 0) + assert splitVersionNumber("1.2abc") == (1, 0, 0, 10000) # END Test testBaseCommon_SplitVersionNumber @@ -541,6 +543,32 @@ def testBaseCommon_MakeFileNameSafe(): # END Test testBaseCommon_MakeFileNameSafe +@pytest.mark.base +def testBaseCommon_EnsureFolder(monkeypatch, fncDir): + """Test the ensureFolder function. + """ + newDir1 = os.path.join(fncDir, "newDir1") + newDir2 = os.path.join(fncDir, "newDir2") + newDir3 = os.path.join(fncDir, "newDir3") + + assert ensureFolder(None) is False + + assert ensureFolder(newDir1) is True + assert os.path.isdir(newDir1) + + assert ensureFolder("newDir2", parent=fncDir) is True + assert os.path.isdir(newDir2) + + with monkeypatch.context() as mp: + mp.setattr("os.mkdir", causeOSError) + errLog = [] + assert ensureFolder("newDir3", parent=fncDir, errLog=errLog) is False + assert errLog[0] == f"Could not create folder: {newDir3}" + assert not os.path.isdir(newDir3) + +# END Test testBaseCommon_EnsureFolder + + @pytest.mark.base def testBaseCommon_Sha256Sum(monkeypatch, fncDir, ipsumText): """Test the sha256sum function. @@ -645,10 +673,10 @@ def testBaseCommon_NWConfigParser(fncDir): # Read Float assert cfgParser.rdFlt("main", "intopt1", 13.0) == 42.0 assert cfgParser.rdFlt("main", "float1", 13.0) == 4.2 - assert cfgParser.rdInt("main", "stropt", 13.0) == 13.0 + assert cfgParser.rdFlt("main", "stropt", 13.0) == 13.0 - assert cfgParser.rdInt("nope", "intopt1", 13.0) == 13.0 - assert cfgParser.rdInt("main", "blabla", 13.0) == 13.0 + assert cfgParser.rdFlt("nope", "intopt1", 13.0) == 13.0 + assert cfgParser.rdFlt("main", "blabla", 13.0) == 13.0 # Read String List assert cfgParser.rdStrList("main", "list1", []) == [] @@ -676,9 +704,4 @@ def testBaseCommon_NWConfigParser(fncDir): assert cfgParser.rdIntList("nope", "list2", [1]) == [1] assert cfgParser.rdIntList("main", "blabla", [1]) == [1] - # Internal - # ======== - - assert cfgParser._parseLine("main", "stropt", None, 999) is None - # END Test testBaseCommon_NWConfigParser diff --git a/tests/test_base/test_base_config.py b/tests/test_base/test_base_config.py index 83ff3160..f6721493 100644 --- a/tests/test_base/test_base_config.py +++ b/tests/test_base/test_base_config.py @@ -96,12 +96,6 @@ def testBaseConfig_Init(monkeypatch, tmpDir, fncDir, outDir, refDir, filesDir): # Let the config class figure out the path with monkeypatch.context() as mp: mp.setattr("PyQt5.QtCore.QStandardPaths.writableLocation", lambda *a: fncDir) - tstConf.verQtValue = 50600 - tstConf.initConfig() - assert tstConf.confPath == os.path.join(fncDir, tstConf.appHandle) - assert tstConf.dataPath == os.path.join(fncDir, tstConf.appHandle) - assert not os.path.isfile(confFile) - tstConf.verQtValue = 50000 tstConf.initConfig() assert tstConf.confPath == os.path.join(fncDir, tstConf.appHandle) assert tstConf.dataPath == os.path.join(fncDir, tstConf.appHandle) @@ -322,38 +316,6 @@ def testBaseConfig_RecentCache(monkeypatch, tmpConf, tmpDir, fncDir): # END Test testBaseConfig_RecentCache -@pytest.mark.base -def testBaseConfig_SetPath(tmpConf, tmpDir): - """Test path setters. - """ - # Conf Path - assert tmpConf.setConfPath(None) - assert not tmpConf.setConfPath(os.path.join("somewhere", "over", "the", "rainbow")) - assert tmpConf.setConfPath(os.path.join(tmpDir, "novelwriter.conf")) - assert tmpConf.confPath == tmpDir - assert tmpConf.confFile == "novelwriter.conf" - assert not tmpConf.confChanged - - # Data Path - assert tmpConf.setDataPath(None) - assert not tmpConf.setDataPath(os.path.join("somewhere", "over", "the", "rainbow")) - assert tmpConf.setDataPath(tmpDir) - assert tmpConf.dataPath == tmpDir - assert not tmpConf.confChanged - - # Last Path - assert tmpConf.setLastPath(None) - assert tmpConf.lastPath == "" - - assert tmpConf.setLastPath(os.path.join(tmpDir, "file.tmp")) - assert tmpConf.lastPath == tmpDir - - assert tmpConf.setLastPath("") - assert tmpConf.lastPath == "" - -# END Test testBaseConfig_SetPath - - @pytest.mark.base def testBaseConfig_SettersGetters(tmpConf, tmpDir, outDir, refDir): """Set various sizes and positions diff --git a/tests/test_base/test_base_init.py b/tests/test_base/test_base_init.py index 9b7a6171..4cebcb6a 100644 --- a/tests/test_base/test_base_init.py +++ b/tests/test_base/test_base_init.py @@ -111,12 +111,6 @@ def testBaseInit_Options(monkeypatch, tmpDir): assert novelwriter.logger.getEffectiveLevel() == logging.DEBUG assert nwGUI.closeMain() == "closeMain" - nwGUI = novelwriter.main( - ["--testmode", "--verbose", "--config=%s" % tmpDir, "--data=%s" % tmpDir] - ) - assert novelwriter.logger.getEffectiveLevel() == 5 - assert nwGUI.closeMain() == "closeMain" - # Help and Version with pytest.raises(SystemExit) as ex: nwGUI = novelwriter.main( diff --git a/tests/test_core/test_core_doctools.py b/tests/test_core/test_core_doctools.py new file mode 100644 index 00000000..bcff60ce --- /dev/null +++ b/tests/test_core/test_core_doctools.py @@ -0,0 +1,254 @@ +""" +novelWriter – Project Document Tools Tester +=========================================== + +This file is a part of novelWriter +Copyright 2018–2022, Veronica Berglyd Olsen + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, but +WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +""" + +import os +import pytest + +from shutil import copyfile + +from mock import causeOSError +from tools import C, buildTestProject, cmpFiles + +from novelwriter.core.project import NWProject +from novelwriter.core.doctools import DocMerger, DocSplitter +from novelwriter.core.document import NWDoc + + +@pytest.mark.core +def testCoreDocTools_DocMerger(monkeypatch, mockGUI, fncDir, outDir, refDir, mockRnd, ipsumText): + """Test the DocMerger utility. + """ + theProject = NWProject(mockGUI) + mockRnd.reset() + buildTestProject(theProject, fncDir) + + # Create Files to Merge + # ===================== + + hChapter1 = theProject.newFile("Chapter 1", C.hNovelRoot) + hSceneOne11 = theProject.newFile("Scene 1.1", hChapter1) + hSceneOne12 = theProject.newFile("Scene 1.2", hChapter1) + hSceneOne13 = theProject.newFile("Scene 1.3", hChapter1) + + docText1 = "\n\n".join(ipsumText[0:2]) + "\n\n" + docText2 = "\n\n".join(ipsumText[1:3]) + "\n\n" + docText3 = "\n\n".join(ipsumText[2:4]) + "\n\n" + docText4 = "\n\n".join(ipsumText[3:5]) + "\n\n" + + theProject.writeNewFile(hChapter1, 2, True, docText1) + theProject.writeNewFile(hSceneOne11, 3, True, docText2) + theProject.writeNewFile(hSceneOne12, 3, True, docText3) + theProject.writeNewFile(hSceneOne13, 3, True, docText4) + + # Basic Checks + # ============ + + docMerger = DocMerger(theProject) + + # No writing without a target set + assert docMerger.writeTargetDoc() is False + + # Cannot append invalid handle + assert docMerger.appendText(C.hInvalid, True, "Merge") is False + + # Cannot create new target from invalid handle + assert docMerger.newTargetDoc(C.hInvalid, "Test") is None + + # Merge to New + # ============ + + saveFile = os.path.join(fncDir, "content", "0000000000014.nwd") + testFile = os.path.join(outDir, "coreDocTools_DocMerger_0000000000014.nwd") + compFile = os.path.join(refDir, "coreDocTools_DocMerger_0000000000014.nwd") + + assert docMerger.newTargetDoc(hChapter1, "All of Chapter 1") == "0000000000014" + + assert docMerger.appendText(hChapter1, True, "Merge") is True + assert docMerger.appendText(hSceneOne11, True, "Merge") is True + assert docMerger.appendText(hSceneOne12, True, "Merge") is True + assert docMerger.appendText(hSceneOne13, True, "Merge") is True + + # Block writing and check error handling + with monkeypatch.context() as mp: + mp.setattr("builtins.open", causeOSError) + assert docMerger.writeTargetDoc() is False + assert not os.path.isfile(saveFile) + assert docMerger.getError() != "" + + # Write properly, and compare + assert docMerger.writeTargetDoc() is True + copyfile(saveFile, testFile) + assert cmpFiles(testFile, compFile) + + # Merge into Existing + # =================== + + saveFile = os.path.join(fncDir, "content", "0000000000010.nwd") + testFile = os.path.join(outDir, "coreDocTools_DocMerger_0000000000010.nwd") + compFile = os.path.join(refDir, "coreDocTools_DocMerger_0000000000010.nwd") + + docMerger.setTargetDoc(hChapter1) + + assert docMerger.appendText(hSceneOne11, True, "Merge") is True + assert docMerger.appendText(hSceneOne12, True, "Merge") is True + assert docMerger.appendText(hSceneOne13, True, "Merge") is True + + assert docMerger.writeTargetDoc() is True + copyfile(saveFile, testFile) + assert cmpFiles(testFile, compFile) + + # Just for debugging + docMerger.writeTargetDoc() + +# END Test testCoreDocTools_DocMerger + + +@pytest.mark.core +def testCoreDocTools_DocSplitter(monkeypatch, mockGUI, fncDir, outDir, refDir, mockRnd, ipsumText): + """Test the DocSplitter utility. + """ + theProject = NWProject(mockGUI) + mockRnd.reset() + buildTestProject(theProject, fncDir) + + # Create File to Split + # ==================== + + hSplitDoc = theProject.newFile("Split Doc", C.hNovelRoot) + + docData = [ + "# Part One", ipsumText[0], + "## Chapter One", ipsumText[1], + "### Scene One", ipsumText[2], + "#### Section One", ipsumText[3], + "#### Section Two", ipsumText[4], + "### Scene Two", ipsumText[0], + "## Chapter Two", ipsumText[1], + "### Scene Three", ipsumText[2], + "### Scene Four", ipsumText[3], + "### Scene Five", ipsumText[4], + ] + splitData = [ + (0, 1, "Part One"), + (4, 2, "Chapter One"), + (8, 3, "Scene One"), + (12, 4, "Section One"), + (16, 4, "Section Two"), + (20, 3, "Scene Two"), + (24, 2, "Chapter Two"), + (28, 3, "Scene Three"), + (32, 3, "Scene Four"), + (36, 3, "Scene Five"), + ] + + docText = "\n\n".join(docData) + docRaw = docText.splitlines() + assert NWDoc(theProject, hSplitDoc).writeDocument(docText) is True + + docSplitter = DocSplitter(theProject, hSplitDoc) + assert docSplitter._srcItem.isFileType() + assert docSplitter.getError() == "" + + # Run the split algorithm + docSplitter.splitDocument(splitData, docRaw) + for i, (lineNo, hLevel, hLabel) in enumerate(splitData): + assert docSplitter._rawData[i] == (docRaw[lineNo:lineNo+4], hLevel, hLabel) + + # Test flat split into same parent + docSplitter.setParentItem(C.hNovelRoot) + assert docSplitter._inFolder is False + + # Cause write error on all chunks + with monkeypatch.context() as mp: + mp.setattr("builtins.open", causeOSError) + resStatus = [] + for status, _, _ in docSplitter.writeDocuments(False): + resStatus.append(status) + assert not any(resStatus) + assert docSplitter.getError() == "OSError: Mock OSError" + + # Generate as flat structure in root folder + resStatus = [] + resDocHandle = [] + resNearHandle = [] + for status, dHandle, nHandle in docSplitter.writeDocuments(False): + resStatus.append(status) + resDocHandle.append(dHandle) + resNearHandle.append(nHandle) + + assert all(resStatus) + assert resDocHandle == [ + "000000000001b", "000000000001c", "000000000001d", "000000000001e", "000000000001f", + "0000000000020", "0000000000021", "0000000000022", "0000000000023", "0000000000024", + ] + assert resNearHandle == [ # Each document should be next to the previous one + hSplitDoc, "000000000001b", "000000000001c", "000000000001d", "000000000001e", + "000000000001f", "0000000000020", "0000000000021", "0000000000022", "0000000000023", + ] + + # Generate as hierarchy in new folder + hSplitFolder = docSplitter.newParentFolder(C.hNovelRoot, "Split Folder") + assert docSplitter._inFolder is True + + resStatus = [] + resDocHandle = [] + resNearHandle = [] + for status, dHandle, nHandle in docSplitter.writeDocuments(True): + resStatus.append(status) + resDocHandle.append(dHandle) + resNearHandle.append(nHandle) + + assert all(resStatus) + assert resDocHandle == [ + "0000000000026", # Part One + "0000000000027", # Chapter One + "0000000000028", # Scene One + "0000000000029", # Section One + "000000000002a", # Section Two + "000000000002b", # Scene Two + "000000000002c", # Chapter Two + "000000000002d", # Scene Three + "000000000002e", # Scene Four + "000000000002f", # Scene Five + ] + assert resNearHandle == [ + hSplitFolder, # Part One is after Split Folder + "0000000000026", # Chapter One is after Part One + "0000000000027", # Scene One is after Chapter One + "0000000000028", # Section One is after Scene One + "0000000000029", # Section Two is after Section One + "0000000000028", # Scene Two is after Scene One + "0000000000027", # Chapter Two is after Chapter One + "000000000002c", # Scene Three is after Chapter Two + "000000000002d", # Scene Four is after Scene Three + "000000000002e", # Scene Five is after Scene Four + ] + + # Check handling of improper initialisation + docSplitter = DocSplitter(theProject, C.hInvalid) + assert docSplitter._srcHandle is None + assert docSplitter._srcItem is None + assert docSplitter.newParentFolder(C.hNovelRoot, "Split Folder") is None + assert list(docSplitter.writeDocuments(False)) == [] + + theProject.saveProject() + +# END Test testCoreDocTools_DocSplitter diff --git a/tests/test_core/test_core_document.py b/tests/test_core/test_core_document.py index 2f80e45a..ecc23e9c 100644 --- a/tests/test_core/test_core_document.py +++ b/tests/test_core/test_core_document.py @@ -25,8 +25,9 @@ import pytest from mock import causeOSError from tools import readFile, writeFile -from novelwriter.core import NWProject, NWDoc from novelwriter.enum import nwItemClass, nwItemLayout +from novelwriter.core.project import NWProject +from novelwriter.core.document import NWDoc @pytest.mark.core diff --git a/tests/test_core/test_core_index.py b/tests/test_core/test_core_index.py index 8f126e56..0e416e09 100644 --- a/tests/test_core/test_core_index.py +++ b/tests/test_core/test_core_index.py @@ -26,11 +26,11 @@ import pytest from shutil import copyfile from mock import causeException -from tools import buildTestProject, cmpFiles, writeFile +from tools import C, buildTestProject, cmpFiles, writeFile -from novelwriter.core.project import NWProject -from novelwriter.core.index import NWIndex, countWords, TagsIndex from novelwriter.enum import nwItemClass, nwItemLayout +from novelwriter.core.index import NWIndex, countWords, TagsIndex +from novelwriter.core.project import NWProject @pytest.mark.core @@ -189,15 +189,17 @@ def testCoreIndex_CheckThese(mockGUI, fncDir, mockRnd): """Test the tag checker function checkThese. """ theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) theIndex = theProject.index + theIndex.clearIndex() - nHandle = theProject.newFile("Hello", "0000000000010") - cHandle = theProject.newFile("Jane", "0000000000012") + nHandle = theProject.newFile("Hello", C.hNovelRoot) + cHandle = theProject.newFile("Jane", C.hCharRoot) nItem = theProject.tree[nHandle] cItem = theProject.tree[cHandle] - assert theIndex.rootChangedSince("0000000000010", 0) is False + assert theIndex.rootChangedSince(C.hNovelRoot, 0) is False assert theIndex.indexChangedSince(0) is False assert theIndex.scanText(cHandle, ( @@ -227,11 +229,11 @@ def testCoreIndex_CheckThese(mockGUI, fncDir, mockRnd): "@time": [] } - assert theIndex.rootChangedSince("0000000000010", 0) is True + assert theIndex.rootChangedSince(C.hNovelRoot, 0) is True assert theIndex.indexChangedSince(0) is True - assert theIndex.getHandleHeaderLevel(cHandle) == "H1" - assert theIndex.getHandleHeaderLevel(nHandle) == "H1" + assert cItem.mainHeading == "H1" + assert nItem.mainHeading == "H1" # Zero Items assert theIndex.checkThese([], cItem) == [] @@ -265,12 +267,13 @@ def testCoreIndex_ScanText(mockGUI, fncDir, mockRnd): """Check the index text scanner. """ theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) theIndex = theProject.index # Some items for fail to scan tests - dHandle = theProject.newFolder("Folder", "0000000000010") - xHandle = theProject.newFile("No Layout", "0000000000010") + dHandle = theProject.newFolder("Folder", C.hNovelRoot) + xHandle = theProject.newFile("No Layout", C.hNovelRoot) xItem = theProject.tree[xHandle] xItem.setLayout(nwItemLayout.NO_LAYOUT) @@ -290,21 +293,23 @@ def testCoreIndex_ScanText(mockGUI, fncDir, mockRnd): theProject.tree.updateItemData(xItem.itemHandle) assert xItem.itemRoot == tHandle assert xItem.itemClass == nwItemClass.TRASH - assert theIndex.scanText(xHandle, "Hello World!") is False + assert theIndex.scanText(xHandle, "## Hello World!") is True + assert xItem.mainHeading == "H2" # Create the archive root aHandle = theProject.newRoot(nwItemClass.ARCHIVE) assert theProject.tree[aHandle] is not None xItem.setParent(aHandle) theProject.tree.updateItemData(xItem.itemHandle) - assert theIndex.scanText(xHandle, "Hello World!") is False + assert theIndex.scanText(xHandle, "### Hello World!") is True + assert xItem.mainHeading == "H3" # Make some usable items - tHandle = theProject.newFile("Title", "0000000000010") - pHandle = theProject.newFile("Page", "0000000000010") - nHandle = theProject.newFile("Hello", "0000000000010") - cHandle = theProject.newFile("Jane", "0000000000012") - sHandle = theProject.newFile("Scene", "0000000000010") + tHandle = theProject.newFile("Title", C.hNovelRoot) + pHandle = theProject.newFile("Page", C.hNovelRoot) + nHandle = theProject.newFile("Hello", C.hNovelRoot) + cHandle = theProject.newFile("Jane", C.hCharRoot) + sHandle = theProject.newFile("Scene", C.hNovelRoot) # Text Indexing # ============= @@ -474,23 +479,24 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): """Check the index data extraction functions. """ theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) theIndex = theProject.index - theIndex.reIndexHandle("0000000000010") - theIndex.reIndexHandle("0000000000011") - theIndex.reIndexHandle("0000000000012") - theIndex.reIndexHandle("0000000000013") - theIndex.reIndexHandle("0000000000014") - theIndex.reIndexHandle("0000000000015") - theIndex.reIndexHandle("0000000000016") - theIndex.reIndexHandle("0000000000017") + theIndex.reIndexHandle(C.hNovelRoot) + theIndex.reIndexHandle(C.hPlotRoot) + theIndex.reIndexHandle(C.hCharRoot) + theIndex.reIndexHandle(C.hWorldRoot) + theIndex.reIndexHandle(C.hTitlePage) + theIndex.reIndexHandle(C.hChapterDir) + theIndex.reIndexHandle(C.hChapterDoc) + theIndex.reIndexHandle(C.hSceneDoc) - nHandle = theProject.newFile("Hello", "0000000000010") - cHandle = theProject.newFile("Jane", "0000000000012") + nHandle = theProject.newFile("Hello", C.hNovelRoot) + cHandle = theProject.newFile("Jane", C.hCharRoot) assert theIndex.getNovelData("", "") is None - assert theIndex.getNovelData("0000000000010", "") is None + assert theIndex.getNovelData(C.hNovelRoot, "") is None assert theIndex.scanText(cHandle, ( "# Jane Smith\n" @@ -511,24 +517,24 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): theKeys.append(aKey) assert theKeys == [ - "0000000000014:T000001", - "0000000000016:T000001", - "0000000000017:T000001", - "%s:T000001" % nHandle, + f"{C.hTitlePage}:T000001", + f"{C.hChapterDoc}:T000001", + f"{C.hSceneDoc}:T000001", + f"{nHandle}:T000001", ] # Check that excluded files can be skipped - theProject.tree[nHandle].setExported(False) + theProject.tree[nHandle].setActive(False) theKeys = [] for aKey, _, _, _ in theIndex.novelStructure(skipExcl=False): theKeys.append(aKey) assert theKeys == [ - "0000000000014:T000001", - "0000000000016:T000001", - "0000000000017:T000001", - "%s:T000001" % nHandle, + f"{C.hTitlePage}:T000001", + f"{C.hChapterDoc}:T000001", + f"{C.hSceneDoc}:T000001", + f"{nHandle}:T000001", ] theKeys = [] @@ -536,9 +542,9 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): theKeys.append(aKey) assert theKeys == [ - "0000000000014:T000001", - "0000000000016:T000001", - "0000000000017:T000001", + f"{C.hTitlePage}:T000001", + f"{C.hChapterDoc}:T000001", + f"{C.hSceneDoc}:T000001", ] # The novel file should have the correct counts @@ -567,7 +573,7 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): assert theIndex.getBackReferenceList(None) == {} # The Title Page file should have no references as it has no tag - assert theIndex.getBackReferenceList("0000000000014") == {} + assert theIndex.getBackReferenceList(C.hTitlePage) == {} # The character file should have a record of the reference from the novel file theRefs = theIndex.getBackReferenceList(cHandle) @@ -656,9 +662,9 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): # Novel Stats # =========== - hHandle = theProject.newFile("Chapter", "0000000000010") - sHandle = theProject.newFile("Scene One", "0000000000010") - tHandle = theProject.newFile("Scene Two", "0000000000010") + hHandle = theProject.newFile("Chapter", C.hNovelRoot) + sHandle = theProject.newFile("Scene One", C.hNovelRoot) + tHandle = theProject.newFile("Scene Two", C.hNovelRoot) theProject.tree[hHandle].itemLayout == nwItemLayout.DOCUMENT theProject.tree[sHandle].itemLayout == nwItemLayout.DOCUMENT @@ -669,9 +675,9 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): assert theIndex.scanText(tHandle, "### Scene Two\n\n") assert [(h, t) for h, t, _ in theIndex._itemIndex.iterNovelStructure(skipExcl=False)] == [ - ("0000000000014", "T000001"), - ("0000000000016", "T000001"), - ("0000000000017", "T000001"), + (C.hTitlePage, "T000001"), + (C.hChapterDoc, "T000001"), + (C.hSceneDoc, "T000001"), (nHandle, "T000001"), (nHandle, "T000011"), (hHandle, "T000001"), @@ -680,9 +686,9 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): ] assert [(h, t) for h, t, _ in theIndex._itemIndex.iterNovelStructure(skipExcl=True)] == [ - ("0000000000014", "T000001"), - ("0000000000016", "T000001"), - ("0000000000017", "T000001"), + (C.hTitlePage, "T000001"), + (C.hChapterDoc, "T000001"), + (C.hSceneDoc, "T000001"), (hHandle, "T000001"), (sHandle, "T000001"), (tHandle, "T000001"), @@ -691,9 +697,9 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): # Add a fake handle to the tree and check that it's ignored theProject.tree._treeOrder.append("0000000000000") assert [(h, t) for h, t, _ in theIndex._itemIndex.iterNovelStructure(skipExcl=False)] == [ - ("0000000000014", "T000001"), - ("0000000000016", "T000001"), - ("0000000000017", "T000001"), + (C.hTitlePage, "T000001"), + (C.hChapterDoc, "T000001"), + (C.hSceneDoc, "T000001"), (nHandle, "T000001"), (nHandle, "T000011"), (hHandle, "T000001"), @@ -709,29 +715,29 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): assert theIndex.getNovelTitleCounts(skipExcl=True) == [0, 1, 2, 3, 0] # Table of Contents - assert theIndex.getTableOfContents(0, skipExcl=True) == [] - assert theIndex.getTableOfContents(1, skipExcl=True) == [ - ("0000000000014:T000001", 1, "New Novel", 15), + assert theIndex.getTableOfContents(C.hNovelRoot, 0, skipExcl=True) == [] + assert theIndex.getTableOfContents(C.hNovelRoot, 1, skipExcl=True) == [ + (f"{C.hTitlePage}:T000001", 1, "New Novel", 15), ] - assert theIndex.getTableOfContents(2, skipExcl=True) == [ - ("0000000000014:T000001", 1, "New Novel", 5), - ("0000000000016:T000001", 2, "New Chapter", 4), - ("%s:T000001" % hHandle, 2, "Chapter One", 6), + assert theIndex.getTableOfContents(C.hNovelRoot, 2, skipExcl=True) == [ + (f"{C.hTitlePage}:T000001", 1, "New Novel", 5), + (f"{C.hChapterDoc}:T000001", 2, "New Chapter", 4), + (f"{hHandle}:T000001", 2, "Chapter One", 6), ] - assert theIndex.getTableOfContents(3, skipExcl=True) == [ - ("0000000000014:T000001", 1, "New Novel", 5), - ("0000000000016:T000001", 2, "New Chapter", 2), - ("0000000000017:T000001", 3, "New Scene", 2), - ("%s:T000001" % hHandle, 2, "Chapter One", 2), - ("%s:T000001" % sHandle, 3, "Scene One", 2), - ("%s:T000001" % tHandle, 3, "Scene Two", 2), + assert theIndex.getTableOfContents(C.hNovelRoot, 3, skipExcl=True) == [ + (f"{C.hTitlePage}:T000001", 1, "New Novel", 5), + (f"{C.hChapterDoc}:T000001", 2, "New Chapter", 2), + (f"{C.hSceneDoc}:T000001", 3, "New Scene", 2), + (f"{hHandle}:T000001", 2, "Chapter One", 2), + (f"{sHandle}:T000001", 3, "Scene One", 2), + (f"{tHandle}:T000001", 3, "Scene Two", 2), ] - assert theIndex.getTableOfContents(0, skipExcl=False) == [] - assert theIndex.getTableOfContents(1, skipExcl=False) == [ - ("0000000000014:T000001", 1, "New Novel", 9), - ("%s:T000001" % nHandle, 1, "Hello World!", 12), - ("%s:T000011" % nHandle, 1, "Hello World!", 22), + assert theIndex.getTableOfContents(C.hNovelRoot, 0, skipExcl=False) == [] + assert theIndex.getTableOfContents(C.hNovelRoot, 1, skipExcl=False) == [ + (f"{C.hTitlePage}:T000001", 1, "New Novel", 9), + (f"{nHandle}:T000001", 1, "Hello World!", 12), + (f"{nHandle}:T000011", 1, "Hello World!", 22), ] # Header Word Counts @@ -741,7 +747,7 @@ def testCoreIndex_ExtractData(mockGUI, fncDir, mockRnd): assert theIndex.getHandleWordCounts(sHandle) == [("%s:T000001" % sHandle, 2)] assert theIndex.getHandleWordCounts(tHandle) == [("%s:T000001" % tHandle, 2)] assert theIndex.getHandleWordCounts(nHandle) == [ - ("%s:T000001" % nHandle, 12), ("%s:T000011" % nHandle, 16) + (f"{nHandle}:T000001", 12), (f"{nHandle}:T000011", 16) ] assert theIndex.saveIndex() is True @@ -926,11 +932,13 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): """Check the ItemIndex class. """ theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) + theProject.index.clearIndex() - nHandle = "0000000000014" - cHandle = "0000000000016" - sHandle = "0000000000017" + nHandle = C.hTitlePage + cHandle = C.hChapterDoc + sHandle = C.hSceneDoc assert theProject.index.saveIndex() is True itemIndex = theProject.index._itemIndex @@ -948,13 +956,11 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): itemIndex.add(cHandle, theProject.tree[cHandle]) assert cHandle in itemIndex assert itemIndex[cHandle].item == theProject.tree[cHandle] - assert itemIndex.mainItemHeader(cHandle) == "H0" assert itemIndex.allItemTags(cHandle) == [] assert list(itemIndex.iterItemHeaders(cHandle))[0][0] == "T000000" # Add a heading to the item, which should replace the T000000 heading itemIndex.addItemHeading(cHandle, "T000001", "H2", "Chapter One") - assert itemIndex.mainItemHeader(cHandle) == "H2" assert list(itemIndex.iterItemHeaders(cHandle))[0][0] == "T000001" # Set the remainig data values @@ -966,7 +972,6 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): itemIndex.addHeadingReferences(cHandle, "T000001", ["Jane", "John"], "@char") idxData = itemIndex.packData() - assert idxData[cHandle]["level"] == "H2" assert idxData[cHandle]["headings"]["T000001"] == { "level": "H2", "title": "Chapter One", "tag": "One", "cCount": 60, "wCount": 10, "pCount": 2, "synopsis": "In the beginning ...", @@ -1026,7 +1031,6 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): assert allHeads[2][1] == "T000001" # Ask for stuff that doesn't exist - assert itemIndex.mainItemHeader("blablabla") == "H0" assert itemIndex.allItemTags("blablabla") == [] # Novel Structure @@ -1048,7 +1052,7 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): assert nStruct[3][0] == uHandle # Novel structure with root handle set - nStruct = list(itemIndex.iterNovelStructure(rootHandle="0000000000010")) + nStruct = list(itemIndex.iterNovelStructure(rootHandle=C.hNovelRoot)) assert len(nStruct) == 3 assert nStruct[0][0] == nHandle assert nStruct[1][0] == cHandle @@ -1068,7 +1072,7 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): assert nStruct[3][0] == uHandle # Skip excluded - theProject.tree[sHandle].setExported(False) + theProject.tree[sHandle].setActive(False) nStruct = list(itemIndex.iterNovelStructure(skipExcl=True)) assert len(nStruct) == 3 assert nStruct[0][0] == nHandle @@ -1098,7 +1102,7 @@ def testCoreIndex_ItemIndex(mockGUI, fncDir, mockRnd): itemIndex.unpackData({"stuff": "more stuff"}) # Unknown keys should be skipped - itemIndex.unpackData({"0000000000000": {}}) + itemIndex.unpackData({C.hInvalid: {}}) assert itemIndex._items == {} # Known keys can be added, even witout data diff --git a/tests/test_core/test_core_item.py b/tests/test_core/test_core_item.py index e2fa75e0..e7a72336 100644 --- a/tests/test_core/test_core_item.py +++ b/tests/test_core/test_core_item.py @@ -25,8 +25,8 @@ from lxml import etree from PyQt5.QtGui import QIcon -from novelwriter.core import NWProject from novelwriter.core.item import NWItem +from novelwriter.core.project import NWProject from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout @@ -136,18 +136,18 @@ def testCoreItem_Setters(mockGUI, mockRnd): assert theItem.isExpanded is True # Exported - theItem.setExported(8) - assert theItem.isExported is False - theItem.setExported(None) - assert theItem.isExported is False - theItem.setExported("None") - assert theItem.isExported is False - theItem.setExported("What?") - assert theItem.isExported is False - theItem.setExported("True") - assert theItem.isExported is True - theItem.setExported(True) - assert theItem.isExported is True + theItem.setActive(8) + assert theItem.isActive is False + theItem.setActive(None) + assert theItem.isActive is False + theItem.setActive("None") + assert theItem.isActive is False + theItem.setActive("What?") + assert theItem.isActive is False + theItem.setActive("True") + assert theItem.isActive is True + theItem.setActive(True) + assert theItem.isActive is True # CharCount theItem.setCharCount(None) @@ -213,12 +213,34 @@ def testCoreItem_Methods(mockGUI): theItem.setLayout("DOCUMENT") assert theItem.isFileType() is True assert theItem.isDocumentLayout() is True + + theItem.setMainHeading("HH") + assert theItem.mainHeading == "H0" assert theItem.describeMe() == "Novel Document" - assert theItem.describeMe("H0") == "Novel Document" - assert theItem.describeMe("H1") == "Novel Title Page" - assert theItem.describeMe("H2") == "Novel Chapter" - assert theItem.describeMe("H3") == "Novel Scene" - assert theItem.describeMe("H4") == "Novel Document" + + theItem.setMainHeading("H0") + assert theItem.mainHeading == "H0" + assert theItem.describeMe() == "Novel Document" + + theItem.setMainHeading("H1") + assert theItem.mainHeading == "H1" + assert theItem.describeMe() == "Novel Title Page" + + theItem.setMainHeading("H2") + assert theItem.mainHeading == "H2" + assert theItem.describeMe() == "Novel Chapter" + + theItem.setMainHeading("H3") + assert theItem.mainHeading == "H3" + assert theItem.describeMe() == "Novel Scene" + + theItem.setMainHeading("H4") + assert theItem.mainHeading == "H4" + assert theItem.describeMe() == "Novel Section" + + theItem.setMainHeading("H5") + assert theItem.mainHeading == "H4" + assert theItem.describeMe() == "Novel Section" theItem.setLayout("NOTE") assert theItem.isNoteLayout() is True @@ -491,7 +513,7 @@ def testCoreItem_XMLPackUnpack(mockGUI, caplog, mockRnd): theItem.setType("FILE") theItem.setImport(importKeys[3]) theItem.setLayout("NOTE") - theItem.setExported(False) + theItem.setActive(False) theItem.setParaCount(3) theItem.setWordCount(5) theItem.setCharCount(7) @@ -503,9 +525,9 @@ def testCoreItem_XMLPackUnpack(mockGUI, caplog, mockRnd): assert etree.tostring(xContent, pretty_print=False, encoding="utf-8") == ( b'' b'A Name' + b'type="FILE" class="NOVEL" layout="NOTE">A Name' b'' ) % bytes(importKeys[3], encoding="utf8") @@ -516,7 +538,7 @@ def testCoreItem_XMLPackUnpack(mockGUI, caplog, mockRnd): assert theItem.itemParent == "0123456789abc" assert theItem.itemRoot == "0123456789abc" assert theItem.itemOrder == 1 - assert theItem.isExported is False + assert theItem.isActive is False assert theItem.paraCount == 3 assert theItem.wordCount == 5 assert theItem.charCount == 7 @@ -541,7 +563,7 @@ def testCoreItem_XMLPackUnpack(mockGUI, caplog, mockRnd): theItem.setStatus(statusKeys[1]) theItem.setLayout("NOTE") theItem.setExpanded(True) - theItem.setExported(False) + theItem.setActive(False) theItem.setParaCount(3) theItem.setWordCount(5) theItem.setCharCount(7) @@ -566,7 +588,7 @@ def testCoreItem_XMLPackUnpack(mockGUI, caplog, mockRnd): assert theItem.itemRoot == "0123456789abc" assert theItem.itemOrder == 1 assert theItem.isExpanded is True - assert theItem.isExported is True + assert theItem.isActive is True assert theItem.paraCount == 0 assert theItem.wordCount == 0 assert theItem.charCount == 0 @@ -673,7 +695,7 @@ def testCoreItem_ConvertFromFmt13(mockGUI): assert theItem.itemParent == "b000000000001" assert theItem.itemOrder == 1 assert theItem.isExpanded is True - assert theItem.isExported is True + assert theItem.isActive is True assert theItem.charCount == 0 assert theItem.wordCount == 0 assert theItem.paraCount == 0 @@ -706,7 +728,7 @@ def testCoreItem_ConvertFromFmt13(mockGUI): assert theItem.itemParent == "a000000000001" assert theItem.itemOrder == 2 assert theItem.isExpanded is False - assert theItem.isExported is True + assert theItem.isActive is True assert theItem.charCount == 600 assert theItem.wordCount == 100 assert theItem.paraCount == 6 diff --git a/tests/test_core/test_core_options.py b/tests/test_core/test_core_options.py index b13d4799..0535ca71 100644 --- a/tests/test_core/test_core_options.py +++ b/tests/test_core/test_core_options.py @@ -26,8 +26,8 @@ import pytest from mock import causeOSError from tools import writeFile -from novelwriter.core import NWProject from novelwriter.core.options import OptionState +from novelwriter.core.project import NWProject from novelwriter.constants import nwFiles diff --git a/tests/test_core/test_core_project.py b/tests/test_core/test_core_project.py index 3be812e1..5a95295b 100644 --- a/tests/test_core/test_core_project.py +++ b/tests/test_core/test_core_project.py @@ -22,11 +22,11 @@ along with this program. If not, see . import os import pytest +from lxml import etree from shutil import copyfile from zipfile import ZipFile -from lxml import etree -from tools import cmpFiles, writeFile, readFile, buildTestProject, XML_IGNORE +from tools import cmpFiles, writeFile, readFile, buildTestProject, XML_IGNORE, C from mock import causeOSError from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout @@ -256,6 +256,7 @@ def testCoreProject_NewRoot(fncDir, outDir, refDir, mockGUI, mockRnd): compFile = os.path.join(refDir, "coreProject_NewRoot_nwProject.nwx") theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) assert theProject.setProjectPath(fncDir) is True @@ -263,14 +264,14 @@ def testCoreProject_NewRoot(fncDir, outDir, refDir, mockGUI, mockRnd): assert theProject.closeProject() is True assert theProject.openProject(projFile) is True - assert isinstance(theProject.newRoot(nwItemClass.NOVEL), str) - assert isinstance(theProject.newRoot(nwItemClass.PLOT), str) - assert isinstance(theProject.newRoot(nwItemClass.CHARACTER), str) - assert isinstance(theProject.newRoot(nwItemClass.WORLD), str) - assert isinstance(theProject.newRoot(nwItemClass.TIMELINE), str) - assert isinstance(theProject.newRoot(nwItemClass.OBJECT), str) - assert isinstance(theProject.newRoot(nwItemClass.CUSTOM), str) - assert isinstance(theProject.newRoot(nwItemClass.CUSTOM), str) + assert theProject.newRoot(nwItemClass.NOVEL) == "0000000000020" + assert theProject.newRoot(nwItemClass.PLOT) == "0000000000021" + assert theProject.newRoot(nwItemClass.CHARACTER) == "0000000000022" + assert theProject.newRoot(nwItemClass.WORLD) == "0000000000023" + assert theProject.newRoot(nwItemClass.TIMELINE) == "0000000000024" + assert theProject.newRoot(nwItemClass.OBJECT) == "0000000000025" + assert theProject.newRoot(nwItemClass.CUSTOM) == "0000000000026" + assert theProject.newRoot(nwItemClass.CUSTOM) == "0000000000027" assert theProject.projChanged is True assert theProject.saveProject() is True @@ -280,11 +281,30 @@ def testCoreProject_NewRoot(fncDir, outDir, refDir, mockGUI, mockRnd): assert cmpFiles(testFile, compFile, ignoreStart=XML_IGNORE) assert theProject.projChanged is False + # Delete the new items + assert theProject.removeItem("0000000000020") is True + assert theProject.removeItem("0000000000021") is True + assert theProject.removeItem("0000000000022") is True + assert theProject.removeItem("0000000000023") is True + assert theProject.removeItem("0000000000024") is True + assert theProject.removeItem("0000000000025") is True + assert theProject.removeItem("0000000000026") is True + assert theProject.removeItem("0000000000027") is True + + assert "0000000000020" not in theProject.tree + assert "0000000000021" not in theProject.tree + assert "0000000000022" not in theProject.tree + assert "0000000000023" not in theProject.tree + assert "0000000000024" not in theProject.tree + assert "0000000000025" not in theProject.tree + assert "0000000000026" not in theProject.tree + assert "0000000000027" not in theProject.tree + # END Test testCoreProject_NewRoot @pytest.mark.core -def testCoreProject_NewFileFolder(fncDir, outDir, refDir, mockGUI, mockRnd): +def testCoreProject_NewFileFolder(monkeypatch, fncDir, outDir, refDir, mockGUI, mockRnd): """Check that new files can be added to the project. """ projFile = os.path.join(fncDir, "nwProject.nwx") @@ -292,6 +312,7 @@ def testCoreProject_NewFileFolder(fncDir, outDir, refDir, mockGUI, mockRnd): compFile = os.path.join(refDir, "coreProject_NewFileFolder_nwProject.nwx") theProject = NWProject(mockGUI) + mockRnd.reset() buildTestProject(theProject, fncDir) assert theProject.setProjectPath(fncDir) is True @@ -304,35 +325,58 @@ def testCoreProject_NewFileFolder(fncDir, outDir, refDir, mockGUI, mockRnd): assert theProject.newFile("New File", "1234567890abc") is None # Add files properly - assert theProject.newFolder("Stuff", "0000000000015") == "0000000000028" - assert theProject.newFile("Hello", "0000000000015") == "0000000000029" - assert theProject.newFile("Jane", "0000000000012") == "000000000002a" + assert theProject.newFolder("Stuff", C.hNovelRoot) == "0000000000020" + assert theProject.newFile("Hello", "0000000000020") == "0000000000021" + assert theProject.newFile("Jane", C.hCharRoot) == "0000000000022" - assert "0000000000028" in theProject.tree - assert "0000000000029" in theProject.tree - assert "000000000002a" in theProject.tree + assert "0000000000020" in theProject.tree + assert "0000000000021" in theProject.tree + assert "0000000000022" in theProject.tree # Write to file, failed assert theProject.writeNewFile("blabla", 1, True) is False # Not a handle - assert theProject.writeNewFile("0000000000028", 1, True) is False # Not a file - assert theProject.writeNewFile("0000000000014", 1, True) is False # Already has content + assert theProject.writeNewFile("0000000000020", 1, True) is False # Not a file + assert theProject.writeNewFile(C.hTitlePage, 1, True) is False # Already has content # Write to file, success - assert theProject.writeNewFile("0000000000029", 2, True) is True - assert NWDoc(theProject, "0000000000029").readDocument() == "## Hello\n\n" + assert theProject.writeNewFile("0000000000021", 2, True) is True + assert NWDoc(theProject, "0000000000021").readDocument() == "## Hello\n\n" - assert theProject.writeNewFile("000000000002a", 1, False) is True - assert NWDoc(theProject, "000000000002a").readDocument() == "# Jane\n\n" + # Write to file with additional text, success + assert theProject.writeNewFile("0000000000022", 1, False, "Hi Jane\n\n") is True + assert NWDoc(theProject, "0000000000022").readDocument() == "# Jane\n\nHi Jane\n\n" # Save, close and check assert theProject.projChanged is True assert theProject.saveProject() is True - assert theProject.closeProject() is True copyfile(projFile, testFile) assert cmpFiles(testFile, compFile, ignoreStart=XML_IGNORE) assert theProject.projChanged is False + # Delete new file, but block access + with monkeypatch.context() as mp: + mp.setattr("os.unlink", causeOSError) + assert theProject.removeItem("0000000000021") is False + assert "0000000000021" in theProject.tree + + # Delete new files and folders + assert os.path.isfile(os.path.join(fncDir, "content", "0000000000022.nwd")) + assert os.path.isfile(os.path.join(fncDir, "content", "0000000000021.nwd")) + + assert theProject.removeItem("0000000000022") is True + assert theProject.removeItem("0000000000021") is True + assert theProject.removeItem("0000000000020") is True + + assert not os.path.isfile(os.path.join(fncDir, "content", "0000000000022.nwd")) + assert not os.path.isfile(os.path.join(fncDir, "content", "0000000000021.nwd")) + + assert "0000000000020" not in theProject.tree + assert "0000000000021" not in theProject.tree + assert "0000000000022" not in theProject.tree + + assert theProject.closeProject() is True + # END Test testCoreProject_NewFileFolder diff --git a/tests/test_core/test_core_tohtml.py b/tests/test_core/test_core_tohtml.py index f21d5d78..8880206c 100644 --- a/tests/test_core/test_core_tohtml.py +++ b/tests/test_core/test_core_tohtml.py @@ -24,7 +24,8 @@ import pytest from tools import readFile -from novelwriter.core import NWProject, ToHtml +from novelwriter.core.tohtml import ToHtml +from novelwriter.core.project import NWProject @pytest.mark.core diff --git a/tests/test_core/test_core_tokenizer.py b/tests/test_core/test_core_tokenizer.py index 97023201..38121268 100644 --- a/tests/test_core/test_core_tokenizer.py +++ b/tests/test_core/test_core_tokenizer.py @@ -24,7 +24,8 @@ import pytest from tools import readFile -from novelwriter.core import NWProject, NWDoc +from novelwriter.core.project import NWProject +from novelwriter.core.document import NWDoc from novelwriter.core.tokenizer import Tokenizer diff --git a/tests/test_core/test_core_tomd.py b/tests/test_core/test_core_tomd.py index 2e49d16b..3ec56a6b 100644 --- a/tests/test_core/test_core_tomd.py +++ b/tests/test_core/test_core_tomd.py @@ -24,7 +24,8 @@ import pytest from tools import readFile -from novelwriter.core import NWProject, ToMarkdown +from novelwriter.core.tomd import ToMarkdown +from novelwriter.core.project import NWProject @pytest.mark.core diff --git a/tests/test_core/test_core_toodt.py b/tests/test_core/test_core_toodt.py index c714b5f5..a564a053 100644 --- a/tests/test_core/test_core_toodt.py +++ b/tests/test_core/test_core_toodt.py @@ -28,8 +28,8 @@ from shutil import copyfile from tools import cmpFiles -from novelwriter.core import NWProject, ToOdt -from novelwriter.core.toodt import ODTParagraphStyle, ODTTextStyle, XMLParagraph, _mkTag +from novelwriter.core.toodt import ToOdt, ODTParagraphStyle, ODTTextStyle, XMLParagraph, _mkTag +from novelwriter.core.project import NWProject XML_NS = [ ' xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"', diff --git a/tests/test_core/test_core_tree.py b/tests/test_core/test_core_tree.py index 23eb7f73..588d23f5 100644 --- a/tests/test_core/test_core_tree.py +++ b/tests/test_core/test_core_tree.py @@ -27,9 +27,11 @@ from lxml import etree from tools import readFile -from novelwriter.core.project import NWProject, NWItem, NWTree from novelwriter.enum import nwItemClass, nwItemType, nwItemLayout from novelwriter.constants import nwFiles +from novelwriter.core.item import NWItem +from novelwriter.core.tree import NWTree +from novelwriter.core.project import NWProject @pytest.fixture(scope="function") @@ -418,13 +420,13 @@ def testCoreTree_XMLPackUnpack(mockGUI, mockItems): b'type="FOLDER" class="NOVEL">Act One' b'Chapter One' + b'type="FILE" class="NOVEL" layout="DOCUMENT">Chapter One' b'Scene One' + b'type="FILE" class="NOVEL" layout="DOCUMENT">Scene One' b'Outtakes' @@ -435,9 +437,9 @@ def testCoreTree_XMLPackUnpack(mockGUI, mockItems): b'class="CHARACTER">Characters' b'Jane Doe' + b'type="FILE" class="CHARACTER" layout="NOTE">Jane Doe' b'' b'
' ) diff --git a/tests/test_dialogs/test_dlg_about.py b/tests/test_dialogs/test_dlg_about.py index a4623c1f..80a6ca06 100644 --- a/tests/test_dialogs/test_dlg_about.py +++ b/tests/test_dialogs/test_dlg_about.py @@ -25,7 +25,7 @@ from tools import getGuiItem from PyQt5.QtWidgets import QAction, QMessageBox -from novelwriter.dialogs import GuiAbout +from novelwriter.dialogs.about import GuiAbout @pytest.mark.gui diff --git a/tests/test_dialogs/test_dlg_dialogs.py b/tests/test_dialogs/test_dlg_dialogs.py index 3423beb5..9afcf410 100644 --- a/tests/test_dialogs/test_dlg_dialogs.py +++ b/tests/test_dialogs/test_dlg_dialogs.py @@ -24,7 +24,9 @@ import pytest from PyQt5.QtCore import QItemSelectionModel from PyQt5.QtWidgets import QAction, QListWidgetItem, QDialog, QMessageBox -from novelwriter.dialogs import GuiQuoteSelect, GuiUpdates, GuiEditLabel +from novelwriter.dialogs.quotes import GuiQuoteSelect +from novelwriter.dialogs.updates import GuiUpdates +from novelwriter.dialogs.editlabel import GuiEditLabel @pytest.mark.gui diff --git a/tests/test_dialogs/test_dlg_docmerge.py b/tests/test_dialogs/test_dlg_docmerge.py index 4e3138f6..4b86fa78 100644 --- a/tests/test_dialogs/test_dlg_docmerge.py +++ b/tests/test_dialogs/test_dlg_docmerge.py @@ -19,17 +19,14 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ -import os import pytest -from mock import causeOSError -from tools import getGuiItem, readFile, writeFile, buildTestProject +from tools import buildTestProject, C -from PyQt5.QtWidgets import QAction, QMessageBox +from PyQt5.QtCore import Qt +from PyQt5.QtWidgets import QMessageBox -from novelwriter.enum import nwItemType, nwWidget -from novelwriter.dialogs import GuiDocMerge, GuiEditLabel -from novelwriter.core.tree import NWTree +from novelwriter.dialogs.docmerge import GuiDocMerge @pytest.mark.gui @@ -39,142 +36,58 @@ def testDlgMerge_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): # Block message box monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Ok) - monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) # Create a new project buildTestProject(nwGUI, fncProj) - # Handles for new objects - hNovelRoot = "0000000000008" - hChapterDir = "000000000000d" - hChapterOne = "000000000000e" - hSceneOne = "000000000000f" - hSceneTwo = "0000000000010" - hSceneThree = "0000000000011" - hSceneFour = "0000000000012" - hMergedDoc = "0000000000023" - - # Add Project Content - nwGUI.switchFocus(nwWidget.TREE) - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True) - nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) - nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) - nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) - - assert nwGUI.saveProject() is True - assert nwGUI.closeProject() is True - - tChapterOne = "## Chapter One\n\n% Chapter one comment\n" - tSceneOne = "### Scene One\n\nThere once was a man from Nantucket" - tSceneTwo = "### Scene Two\n\nWho kept all his cash in a bucket." - tSceneThree = "### Scene Three\n\n\tBut his daughter, named Nan, \n\tRan away with a man" - tSceneFour = "### Scene Four\n\nAnd as for the bucket, Nantucket." - - contentDir = os.path.join(fncProj, "content") - writeFile(os.path.join(contentDir, hChapterOne+".nwd"), tChapterOne) - writeFile(os.path.join(contentDir, hSceneOne+".nwd"), tSceneOne) - writeFile(os.path.join(contentDir, hSceneTwo+".nwd"), tSceneTwo) - writeFile(os.path.join(contentDir, hSceneThree+".nwd"), tSceneThree) - writeFile(os.path.join(contentDir, hSceneFour+".nwd"), tSceneFour) - - assert nwGUI.openProject(fncProj) is True - - # Open the Merge tool - nwGUI.switchFocus(nwWidget.TREE) - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True) - - monkeypatch.setattr(GuiDocMerge, "exec_", lambda *a: None) - nwGUI.mainMenu.aMergeDocs.activate(QAction.Trigger) - qtbot.waitUntil(lambda: getGuiItem("GuiDocMerge") is not None, timeout=1000) - - nwMerge = getGuiItem("GuiDocMerge") - assert isinstance(nwMerge, GuiDocMerge) + # Check that the dialog kan handle invalid items + nwMerge = GuiDocMerge(nwGUI, C.hInvalid, [C.hInvalid]) + qtbot.addWidget(nwMerge) nwMerge.show() - qtbot.wait(50) - - # Populate List - # ============= - - nwMerge.listBox.clear() assert nwMerge.listBox.count() == 0 + nwMerge.reject() - # No item selected - nwGUI.projView.projTree.clearSelection() - assert nwMerge._populateList() is False - assert nwMerge.listBox.count() == 0 + # Load items from chapter dir + nwMerge = GuiDocMerge(nwGUI, C.hChapterDir, [C.hChapterDir, C.hChapterDoc, C.hSceneDoc]) + qtbot.addWidget(nwMerge) + nwMerge.show() - # Non-existing item - with monkeypatch.context() as mp: - mp.setattr(NWTree, "__getitem__", lambda *a: None) - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True) - assert nwMerge._populateList() is False - assert nwMerge.listBox.count() == 0 + assert nwMerge.listBox.count() == 2 - # Select a non-folder - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterOne).setSelected(True) - assert nwMerge._populateList() is False - assert nwMerge.listBox.count() == 0 + itemOne = nwMerge.listBox.item(0) + itemTwo = nwMerge.listBox.item(1) - # Select the chapter folder - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True) - assert nwMerge._populateList() is True - assert nwMerge.listBox.count() == 5 + assert itemOne.data(Qt.UserRole) == C.hChapterDoc + assert itemTwo.data(Qt.UserRole) == C.hSceneDoc - # Merge Documents - # =============== + assert itemOne.checkState() == Qt.Checked + assert itemTwo.checkState() == Qt.Checked - # First, a successful merge - with monkeypatch.context() as mp: - mp.setattr(GuiDocMerge, "_doClose", lambda *a: None) - assert nwMerge._doMerge() is True - assert nwGUI.saveProject() is True - mergedFile = os.path.join(contentDir, hMergedDoc+".nwd") - assert os.path.isfile(mergedFile) - assert readFile(mergedFile) == ( - "%%%%~name: New Chapter\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - "%s\n\n" - "%s\n\n" - "%s\n\n" - "%s\n\n" - ) % ( - hNovelRoot, - hMergedDoc, - tChapterOne.strip(), - tSceneOne.strip(), - tSceneTwo.strip(), - tSceneThree.strip(), - tSceneFour.strip(), - ) + data = nwMerge.getData() + assert data["sHandle"] == C.hChapterDir + assert data["origItems"] == [C.hChapterDir, C.hChapterDoc, C.hSceneDoc] + assert data["moveToTrash"] is False + assert data["finalItems"] == [C.hChapterDoc, C.hSceneDoc] - # OS error - with monkeypatch.context() as mp: - mp.setattr("builtins.open", causeOSError) - assert nwMerge._doMerge() is False + # Uncheck second item and toggle trash switch + itemTwo.setCheckState(Qt.Unchecked) + nwMerge.trashSwitch.setChecked(True) - # Can't find the source item - with monkeypatch.context() as mp: - mp.setattr(NWTree, "__getitem__", lambda *a: None) - assert nwMerge._doMerge() is False + data = nwMerge.getData() + assert data["sHandle"] == C.hChapterDir + assert data["origItems"] == [C.hChapterDir, C.hChapterDoc, C.hSceneDoc] + assert data["moveToTrash"] is True + assert data["finalItems"] == [C.hChapterDoc] - # No source handle set - nwMerge.sourceItem = None - assert nwMerge._doMerge() is False + # Restore default values + nwMerge._resetList() - # No documents to merge - nwMerge.listBox.clear() - assert nwMerge._doMerge() is False + data = nwMerge.getData() + assert data["sHandle"] == C.hChapterDir + assert data["origItems"] == [C.hChapterDir, C.hChapterDoc, C.hSceneDoc] + assert data["moveToTrash"] is True + assert data["finalItems"] == [C.hChapterDoc, C.hSceneDoc] - # Close up - nwMerge._doClose() - - # qtbot.stopForInteraction() + # qtbot.stop() # END Test testDlgMerge_Main diff --git a/tests/test_dialogs/test_dlg_docsplit.py b/tests/test_dialogs/test_dlg_docsplit.py index d0201d6a..4689f76d 100644 --- a/tests/test_dialogs/test_dlg_docsplit.py +++ b/tests/test_dialogs/test_dlg_docsplit.py @@ -19,18 +19,14 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ -import os import pytest -from mock import causeOSError -from tools import getGuiItem, readFile, writeFile, buildTestProject +from tools import C, buildTestProject -from PyQt5.QtWidgets import QAction, QMessageBox +from PyQt5.QtWidgets import QMessageBox -from novelwriter.enum import nwItemType, nwWidget -from novelwriter.dialogs import GuiDocSplit, GuiEditLabel -from novelwriter.core.tree import NWTree -from novelwriter.core.document import NWDoc +from novelwriter.dialogs.docsplit import GuiDocSplit +from novelwriter.dialogs.editlabel import GuiEditLabel @pytest.mark.gui @@ -45,207 +41,66 @@ def testDlgSplit_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): # Create a new project buildTestProject(nwGUI, fncProj) - # Handles for new objects - hNovelRoot = "0000000000008" - hChapterDir = "000000000000d" - hToSplit = "0000000000010" - hNewFolder = "0000000000021" - hPartition = "0000000000022" - hChapterOne = "0000000000023" - hSceneOne = "0000000000024" - hSceneTwo = "0000000000025" - hSceneThree = "0000000000026" - hSceneFour = "0000000000027" - hSceneFive = "0000000000028" + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree - # Add Project Content - nwGUI.switchFocus(nwWidget.TREE) - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hNovelRoot).setSelected(True) - nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) - - assert nwGUI.saveProject() is True - assert nwGUI.closeProject() is True - - tPartition = "# Nantucket" - tChapterOne = "## Chapter One\n\n% Chapter one comment" - tSceneOne = "### Scene One\n\nThere once was a man from Nantucket" - tSceneTwo = "### Scene Two\n\nWho kept all his cash in a bucket." - tSceneThree = "### Scene Three\n\n\tBut his daughter, named Nan, \n\tRan away with a man" - tSceneFour = "### Scene Four\n\nAnd as for the bucket, Nantucket." - tSceneFive = "#### The End\n\nend" - - tToSplit = ( - f"{tPartition}\n\n{tChapterOne}\n\n" - f"{tSceneOne}\n\n{tSceneTwo}\n\n" - f"{tSceneThree}\n\n{tSceneFour}\n\n" - f"{tSceneFive}\n\n" + docText = ( + "Text\n\n" + "##! Prologue\n\nText\n\n" + "## Chapter One\n\nText\n\n" + "### Scene One\n\nText\n\n" + "### Scene Two\n\nText\n\n" + "## Chapter Two\n\nText\n\n" + "### Scene Three\n\nText\n\n" + "### Scene Four\n\nText\n\n" + "#! New Title\n\nText\n\n" + "## New Chapter\n\nText\n\n" + "### New Scene\n\nText\n\n" + "#### New Section\n\nText\n\n" ) - contentDir = os.path.join(fncProj, "content") - writeFile(os.path.join(contentDir, hToSplit+".nwd"), tToSplit) + hSplitDoc = theProject.newFile("Split Doc", C.hNovelRoot) + theProject.writeNewFile(hSplitDoc, 1, True, docText) + projTree.revealNewTreeItem(hSplitDoc, nHandle=C.hNovelRoot, wordCount=True) - assert nwGUI.openProject(fncProj) is True + docText = f"# Split Doc\n\n{docText}" - # Open the Split tool - nwGUI.switchFocus(nwWidget.TREE) - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hToSplit).setSelected(True) - - monkeypatch.setattr(GuiDocSplit, "exec_", lambda *a: None) - nwGUI.mainMenu.aSplitDoc.activate(QAction.Trigger) - qtbot.waitUntil(lambda: getGuiItem("GuiDocSplit") is not None, timeout=1000) - - nwSplit = getGuiItem("GuiDocSplit") - assert isinstance(nwSplit, GuiDocSplit) + nwSplit = GuiDocSplit(nwGUI, hSplitDoc) nwSplit.show() - qtbot.wait(50) + qtbot.addWidget(nwSplit) - # Populate List - # ============= + # By default, only up to level three headinsg should be listed + assert nwSplit.splitLevel.currentData() == 3 + assert nwSplit.listBox.count() == 11 - nwSplit.listBox.clear() - assert nwSplit.listBox.count() == 0 - - # No item selected - nwSplit.sourceItem = None - nwGUI.projView.projTree.clearSelection() - assert nwSplit._populateList() is False - assert nwSplit.listBox.count() == 0 - - # Non-existing item - with monkeypatch.context() as mp: - mp.setattr(NWTree, "__getitem__", lambda *a: None) - nwSplit.sourceItem = None - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hToSplit).setSelected(True) - assert nwSplit._populateList() is False - assert nwSplit.listBox.count() == 0 - - # Select a non-file - nwSplit.sourceItem = None - nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem(hChapterDir).setSelected(True) - assert nwSplit._populateList() is False - assert nwSplit.listBox.count() == 0 - - # Error when reading documents - with monkeypatch.context() as mp: - mp.setattr(NWDoc, "readDocument", lambda *a: None) - nwSplit.sourceItem = hToSplit - assert nwSplit._populateList() is False - assert nwSplit.listBox.count() == 0 - - # Read properly, and check split levels - - # Level 1 - nwSplit.splitLevel.setCurrentIndex(0) - nwSplit.sourceItem = hToSplit - assert nwSplit._populateList() is True - assert nwSplit.listBox.count() == 1 - - # Level 2 - nwSplit.splitLevel.setCurrentIndex(1) - nwSplit.sourceItem = hToSplit - assert nwSplit._populateList() is True - assert nwSplit.listBox.count() == 2 - - # Level 3 - nwSplit.splitLevel.setCurrentIndex(2) - nwSplit.sourceItem = hToSplit - assert nwSplit._populateList() is True - assert nwSplit.listBox.count() == 6 - - # Level 4 + # Changing to level 4, should reload and add the last section nwSplit.splitLevel.setCurrentIndex(3) - nwSplit.sourceItem = hToSplit - assert nwSplit._populateList() is True - assert nwSplit.listBox.count() == 7 + assert nwSplit.listBox.count() == 12 - # Split Document - # ============== + data, text = nwSplit.getData() + assert text == docText.splitlines() + assert data["sHandle"] == hSplitDoc + assert data["spLevel"] == 4 + assert data["intoFolder"] is True + assert data["docHierarchy"] is True + assert data["headerList"][0] == (0, 1, "Split Doc") + assert data["headerList"][1] == (4, 2, "Prologue") + assert data["headerList"][2] == (8, 2, "Chapter One") + assert data["headerList"][3] == (12, 3, "Scene One") + assert data["headerList"][4] == (16, 3, "Scene Two") + assert data["headerList"][5] == (20, 2, "Chapter Two") + assert data["headerList"][6] == (24, 3, "Scene Three") + assert data["headerList"][7] == (28, 3, "Scene Four") + assert data["headerList"][8] == (32, 1, "New Title") + assert data["headerList"][9] == (36, 2, "New Chapter") + assert data["headerList"][10] == (40, 3, "New Scene") + assert data["headerList"][11] == (44, 4, "New Section") - # Test a proper split first - with monkeypatch.context() as mp: - mp.setattr(GuiDocSplit, "_doClose", lambda *a: None) - assert nwSplit._doSplit() is True - assert nwGUI.saveProject() + # Loading the dialog on a non-file item produces an empty list + nwSplit._loadContent(C.hNovelRoot) + assert nwSplit.listBox.count() == 0 - assert readFile(os.path.join(contentDir, hPartition+".nwd")) == ( - "%%%%~name: Nantucket\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hPartition, tPartition) - - assert readFile(os.path.join(contentDir, hChapterOne+".nwd")) == ( - "%%%%~name: Chapter One\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hChapterOne, tChapterOne) - - assert readFile(os.path.join(contentDir, hSceneOne+".nwd")) == ( - "%%%%~name: Scene One\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hSceneOne, tSceneOne) - - assert readFile(os.path.join(contentDir, hSceneTwo+".nwd")) == ( - "%%%%~name: Scene Two\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hSceneTwo, tSceneTwo) - - assert readFile(os.path.join(contentDir, hSceneThree+".nwd")) == ( - "%%%%~name: Scene Three\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hSceneThree, tSceneThree) - - assert readFile(os.path.join(contentDir, hSceneFour+".nwd")) == ( - "%%%%~name: Scene Four\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hSceneFour, tSceneFour) - - assert readFile(os.path.join(contentDir, hSceneFive+".nwd")) == ( - "%%%%~name: The End\n" - "%%%%~path: %s/%s\n" - "%%%%~kind: NOVEL/DOCUMENT\n" - "%s\n\n" - ) % (hNewFolder, hSceneFive, tSceneFive) - - # OS error - with monkeypatch.context() as mp: - mp.setattr("builtins.open", causeOSError) - assert nwSplit._doSplit() is False - - # Select to not split - with monkeypatch.context() as mp: - mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) - assert nwSplit._doSplit() is False - - # Clear the list - nwSplit.listBox.clear() - assert nwSplit._doSplit() is False - - # Can't find sourcv item - with monkeypatch.context() as mp: - mp.setattr(NWTree, "__getitem__", lambda *a: None) - assert nwSplit._doSplit() is False - - # No source item set - nwSplit.sourceItem = None - assert nwSplit._doSplit() is False - - # Close - nwSplit._doClose() - - # qtbot.stopForInteraction() + nwSplit.reject() + # qtbot.stop() # END Test testDlgSplit_Main diff --git a/tests/test_dialogs/test_dlg_preferences.py b/tests/test_dialogs/test_dlg_preferences.py index 1507d351..22461751 100644 --- a/tests/test_dialogs/test_dlg_preferences.py +++ b/tests/test_dialogs/test_dlg_preferences.py @@ -32,7 +32,8 @@ from PyQt5.QtWidgets import ( ) from novelwriter.config import Config -from novelwriter.dialogs import GuiPreferences, GuiQuoteSelect +from novelwriter.dialogs.quotes import GuiQuoteSelect +from novelwriter.dialogs.preferences import GuiPreferences keyDelay = 2 typeDelay = 1 diff --git a/tests/test_dialogs/test_dlg_projdetails.py b/tests/test_dialogs/test_dlg_projdetails.py index 16f73e1e..b2952ad6 100644 --- a/tests/test_dialogs/test_dlg_projdetails.py +++ b/tests/test_dialogs/test_dlg_projdetails.py @@ -25,7 +25,7 @@ from tools import getGuiItem from PyQt5.QtWidgets import QAction, QMessageBox -from novelwriter.dialogs import GuiProjectDetails +from novelwriter.dialogs.projdetails import GuiProjectDetails keyDelay = 2 typeDelay = 1 diff --git a/tests/test_dialogs/test_dlg_projload.py b/tests/test_dialogs/test_dlg_projload.py index 6edb7a0d..5916d185 100644 --- a/tests/test_dialogs/test_dlg_projload.py +++ b/tests/test_dialogs/test_dlg_projload.py @@ -30,7 +30,7 @@ from PyQt5.QtWidgets import ( QMessageBox ) -from novelwriter.dialogs import GuiProjectLoad +from novelwriter.dialogs.projload import GuiProjectLoad keyDelay = 2 typeDelay = 1 diff --git a/tests/test_dialogs/test_dlg_projsettings.py b/tests/test_dialogs/test_dlg_projsettings.py index f193194a..d194229c 100644 --- a/tests/test_dialogs/test_dlg_projsettings.py +++ b/tests/test_dialogs/test_dlg_projsettings.py @@ -29,7 +29,7 @@ from PyQt5.QtGui import QColor from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QDialog, QAction, QMessageBox, QColorDialog -from novelwriter.dialogs import GuiProjectSettings +from novelwriter.dialogs.projsettings import GuiProjectSettings keyDelay = 2 typeDelay = 1 diff --git a/tests/test_dialogs/test_dlg_wordlist.py b/tests/test_dialogs/test_dlg_wordlist.py index d9993d4d..994fb407 100644 --- a/tests/test_dialogs/test_dlg_wordlist.py +++ b/tests/test_dialogs/test_dlg_wordlist.py @@ -28,8 +28,8 @@ from PyQt5.QtWidgets import QDialog, QMessageBox, QAction from tools import writeFile, readFile, getGuiItem from mock import causeOSError -from novelwriter.dialogs import GuiWordList from novelwriter.constants import nwFiles +from novelwriter.dialogs.wordlist import GuiWordList keyDelay = 2 typeDelay = 1 diff --git a/tests/test_gui/test_gui_doceditor.py b/tests/test_gui/test_gui_doceditor.py index 572998cb..b3bc49b1 100644 --- a/tests/test_gui/test_gui_doceditor.py +++ b/tests/test_gui/test_gui_doceditor.py @@ -27,10 +27,10 @@ from PyQt5.QtCore import Qt from PyQt5.QtGui import QTextBlock, QTextCursor, QTextOption from PyQt5.QtWidgets import QAction, QMessageBox, qApp -from novelwriter.gui.doceditor import GuiDocEditor -from novelwriter.core import countWords from novelwriter.enum import nwDocAction, nwDocInsert, nwItemLayout from novelwriter.constants import nwKeyWords, nwUnicode +from novelwriter.core.index import countWords +from novelwriter.gui.doceditor import GuiDocEditor keyDelay = 2 typeDelay = 1 @@ -213,7 +213,8 @@ def testGuiEditor_MetaData(qtbot, monkeypatch, nwGUI, nwMinimal): qtbot.wait(stepDelay) # Get Text - # Both methods should return the same result for line breaks, but not for spaces + # This should replace line and paragraph separators, but preserve + # non-breaking spaces. newText = ( "### New Scene\u2029\u2029" "Some\u2028text.\u2029" @@ -221,10 +222,6 @@ def testGuiEditor_MetaData(qtbot, monkeypatch, nwGUI, nwMinimal): ) assert nwGUI.docEditor.replaceText(newText) assert nwGUI.docEditor.getText() == "### New Scene\n\nSome\ntext.\nMore\u00a0text.\n" - verQtValue = nwGUI.mainConf.verQtValue - nwGUI.mainConf.verQtValue = 50800 - assert nwGUI.docEditor.getText() == "### New Scene\n\nSome\ntext.\nMore text.\n" - nwGUI.mainConf.verQtValue = verQtValue # Check Propertoes assert nwGUI.docEditor.docChanged() is True @@ -250,7 +247,7 @@ def testGuiEditor_MetaData(qtbot, monkeypatch, nwGUI, nwMinimal): nwGUI.docEditor.setDocumentChanged(True) assert nwGUI.docEditor._docChanged is True - # qtbot.stopForInteraction() + # qtbot.stop() # END Test testGuiEditor_MetaData diff --git a/tests/test_gui/test_gui_docviewer.py b/tests/test_gui/test_gui_docviewer.py index 2226a4c3..ef76d51c 100644 --- a/tests/test_gui/test_gui_docviewer.py +++ b/tests/test_gui/test_gui_docviewer.py @@ -27,7 +27,7 @@ from PyQt5.QtWidgets import qApp, QAction, QMessageBox from mock import causeException from novelwriter.enum import nwDocAction -from novelwriter.core import ToHtml +from novelwriter.core.tohtml import ToHtml keyDelay = 2 typeDelay = 1 diff --git a/tests/test_gui/test_gui_guimain.py b/tests/test_gui/test_gui_guimain.py index b2e446bc..5d434601 100644 --- a/tests/test_gui/test_gui_guimain.py +++ b/tests/test_gui/test_gui_guimain.py @@ -22,17 +22,20 @@ along with this program. If not, see . import os import pytest +from tools import C, cmpFiles, buildTestProject, XML_IGNORE, writeFile from shutil import copyfile -from tools import cmpFiles, buildTestProject, XML_IGNORE, writeFile from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QMessageBox, QInputDialog -from novelwriter.gui import GuiDocEditor, GuiNovelView, GuiOutlineView from novelwriter.enum import nwItemType, nwView, nwWidget from novelwriter.tools import GuiProjectWizard -from novelwriter.gui.projtree import GuiProjectTree from novelwriter.dialogs import GuiEditLabel +from novelwriter.constants import nwFiles +from novelwriter.gui.outline import GuiOutlineView +from novelwriter.gui.projtree import GuiProjectTree +from novelwriter.gui.doceditor import GuiDocEditor +from novelwriter.gui.noveltree import GuiNovelView keyDelay = 2 typeDelay = 1 @@ -54,8 +57,6 @@ def testGuiMain_ProjectBlocker(monkeypatch, nwGUI): assert nwGUI.saveDocument() is False assert nwGUI.viewDocument(None) is False assert nwGUI.importDocument() is False - assert nwGUI.mergeDocuments() is False - assert nwGUI.splitDocument() is False assert nwGUI.openSelectedItem() is False assert nwGUI.editItemLabel() is False assert nwGUI.requestNovelTreeRefresh() is False @@ -91,7 +92,7 @@ def testGuiMain_NewProject(monkeypatch, nwGUI, fncProj): assert nwGUI.newProject(projData={}) is False # Project file already exists - projFile = os.path.join(fncProj, nwGUI.theProject.projFile) + projFile = os.path.join(fncProj, nwFiles.PROJ_FILE) writeFile(projFile, "Stuff") assert nwGUI.newProject(projData={"projPath": fncProj}) is False os.unlink(projFile) @@ -102,7 +103,7 @@ def testGuiMain_NewProject(monkeypatch, nwGUI, fncProj): # This one should work just fine assert nwGUI.newProject(projData={"projPath": fncProj}) is True - assert os.path.isfile(os.path.join(fncProj, nwGUI.theProject.projFile)) + assert os.path.isfile(os.path.join(fncProj, nwFiles.PROJ_FILE)) assert os.path.isdir(os.path.join(fncProj, "content")) # END Test testGuiMain_NewProject @@ -183,7 +184,6 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock assert nwGUI.theProject.tree.trashRoot() is None assert nwGUI.theProject.projPath is None assert nwGUI.theProject.projMeta is None - assert nwGUI.theProject.projFile == "nwProject.nwx" assert nwGUI.theProject.projName == "" assert nwGUI.theProject.bookTitle == "" assert len(nwGUI.theProject.bookAuthors) == 0 @@ -197,8 +197,6 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock assert cmpFiles(testFile, compFile, ignoreStart=XML_IGNORE) qtbot.wait(stepDelay) - # qtbot.stopForInteraction() - # Re-open project assert nwGUI.openProject(fncProj) qtbot.wait(stepDelay) @@ -210,21 +208,20 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock assert nwGUI.theProject.tree.trashRoot() is None assert nwGUI.theProject.projPath == fncProj assert nwGUI.theProject.projMeta == os.path.join(fncProj, "meta") - assert nwGUI.theProject.projFile == "nwProject.nwx" assert nwGUI.theProject.projName == "New Project" assert nwGUI.theProject.bookTitle == "New Novel" assert len(nwGUI.theProject.bookAuthors) == 1 assert nwGUI.theProject.spellCheck is False # Check that tree items have been created - assert nwGUI.projView.projTree._getTreeItem("0000000000008") is not None - assert nwGUI.projView.projTree._getTreeItem("0000000000009") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000a") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000b") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000c") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000d") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000e") is not None - assert nwGUI.projView.projTree._getTreeItem("000000000000f") is not None + assert nwGUI.projView.projTree._getTreeItem(C.hNovelRoot) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hPlotRoot) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hCharRoot) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hWorldRoot) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hTitlePage) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hChapterDir) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hChapterDoc) is not None + assert nwGUI.projView.projTree._getTreeItem(C.hSceneDoc) is not None nwGUI.mainMenu.aSpellCheck.setChecked(True) assert nwGUI.mainMenu._toggleSpellCheck() @@ -238,7 +235,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock # Add a Character File nwGUI.switchFocus(nwWidget.TREE) nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem("000000000000a").setSelected(True) + nwGUI.projView.projTree._getTreeItem(C.hCharRoot).setSelected(True) nwGUI.projView.projTree.newTreeItem(nwItemType.FILE, None, isNote=True) assert nwGUI.openSelectedItem() @@ -260,7 +257,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock # Add a Plot File nwGUI.switchFocus(nwWidget.TREE) nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem("0000000000009").setSelected(True) + nwGUI.projView.projTree._getTreeItem(C.hPlotRoot).setSelected(True) nwGUI.projView.projTree.newTreeItem(nwItemType.FILE, None, isNote=True) assert nwGUI.openSelectedItem() @@ -282,7 +279,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock # Add a World File nwGUI.switchFocus(nwWidget.TREE) nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem("000000000000b").setSelected(True) + nwGUI.projView.projTree._getTreeItem(C.hWorldRoot).setSelected(True) nwGUI.projView.projTree.newTreeItem(nwItemType.FILE, None, isNote=True) assert nwGUI.openSelectedItem() @@ -313,9 +310,9 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock # Select the 'New Scene' file nwGUI.switchFocus(nwWidget.TREE) nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem("0000000000008").setExpanded(True) - nwGUI.projView.projTree._getTreeItem("000000000000d").setExpanded(True) - nwGUI.projView.projTree._getTreeItem("000000000000f").setSelected(True) + nwGUI.projView.projTree._getTreeItem(C.hNovelRoot).setExpanded(True) + nwGUI.projView.projTree._getTreeItem(C.hChapterDir).setExpanded(True) + nwGUI.projView.projTree._getTreeItem(C.hSceneDoc).setSelected(True) assert nwGUI.openSelectedItem() # Type something into the document @@ -373,6 +370,15 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + # Don't allow Shift+Enter to insert a line separator (issue #1150) + for c in "This is another paragraph": + qtbot.keyClick(nwGUI.docEditor, c, delay=typeDelay) + qtbot.keyClick(nwGUI.docEditor, Qt.Key_Enter, modifier=Qt.ShiftModifier, delay=typeDelay) + for c in "with a line separator in it.": + qtbot.keyClick(nwGUI.docEditor, c, delay=typeDelay) + qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + # Auto-Replace # ============ @@ -439,6 +445,11 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + for c in "But don't add a double space : See?": + qtbot.keyClick(nwGUI.docEditor, c, delay=typeDelay) + qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + qtbot.keyClick(nwGUI.docEditor, Qt.Key_Return, delay=keyDelay) + nwGUI.mainConf.fmtPadBefore = "" # Indent and Align @@ -488,8 +499,8 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock # Open and view the edited document nwGUI.switchFocus(nwWidget.VIEWER) - assert nwGUI.openDocument("000000000000f") - assert nwGUI.viewDocument("000000000000f") + assert nwGUI.openDocument(C.hSceneDoc) + assert nwGUI.viewDocument(C.hSceneDoc) qtbot.wait(stepDelay) assert nwGUI.saveProject() assert nwGUI.closeDocViewer() @@ -499,9 +510,9 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock assert nwGUI.projView.projTree.newTreeItem(nwItemType.FILE, None) newHandle = nwGUI.projView.getSelectedHandle() assert nwGUI.theProject.tree["0000000000020"] is not None - assert nwGUI.projView.deleteItem() + assert nwGUI.projView.requestDeleteItem() assert nwGUI.projView.setSelectedHandle(newHandle) - assert nwGUI.projView.deleteItem() + assert nwGUI.projView.requestDeleteItem() assert nwGUI.theProject.tree["0000000000024"] is not None # Trash assert nwGUI.saveProject() @@ -536,7 +547,7 @@ def testGuiMain_Editing(qtbot, monkeypatch, nwGUI, fncProj, refDir, outDir, mock copyfile(projFile, testFile) assert cmpFiles(testFile, compFile) - # qtbot.stopForInteraction() + # qtbot.stop() # END Test testGuiMain_Editing @@ -557,13 +568,13 @@ def testGuiMain_FocusFullMode(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): assert nwGUI.toggleFocusMode() is False # Open a file in editor and viewer - assert nwGUI.openDocument("000000000000f") - assert nwGUI.viewDocument("000000000000f") + assert nwGUI.openDocument(C.hSceneDoc) + assert nwGUI.viewDocument(C.hSceneDoc) # Enable focus mode assert nwGUI.toggleFocusMode() is True assert nwGUI.treePane.isVisible() is False - assert nwGUI.statusBar.isVisible() is False + assert nwGUI.mainStatus.isVisible() is False assert nwGUI.mainMenu.isVisible() is False assert nwGUI.viewsBar.isVisible() is False assert nwGUI.splitView.isVisible() is False @@ -571,7 +582,7 @@ def testGuiMain_FocusFullMode(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): # Disable focus mode assert nwGUI.toggleFocusMode() is True assert nwGUI.treePane.isVisible() is True - assert nwGUI.statusBar.isVisible() is True + assert nwGUI.mainStatus.isVisible() is True assert nwGUI.mainMenu.isVisible() is True assert nwGUI.viewsBar.isVisible() is True assert nwGUI.splitView.isVisible() is True diff --git a/tests/test_gui/test_gui_mainmenu.py b/tests/test_gui/test_gui_mainmenu.py index f579a1a0..c4bf2dd3 100644 --- a/tests/test_gui/test_gui_mainmenu.py +++ b/tests/test_gui/test_gui_mainmenu.py @@ -26,11 +26,11 @@ from PyQt5.QtCore import Qt from PyQt5.QtGui import QTextCursor, QTextBlock from PyQt5.QtWidgets import QAction, QFileDialog, QMessageBox -from tools import writeFile, buildTestProject +from tools import C, writeFile, buildTestProject -from novelwriter.gui.doceditor import GuiDocEditor from novelwriter.enum import nwDocAction, nwDocInsert from novelwriter.constants import nwKeyWords, nwUnicode +from novelwriter.gui.doceditor import GuiDocEditor keyDelay = 2 typeDelay = 1 @@ -467,8 +467,8 @@ def testGuiMenu_Insert(qtbot, monkeypatch, nwGUI, fncDir, fncProj, mockRnd): buildTestProject(nwGUI, fncProj) - assert nwGUI.projView.projTree._getTreeItem("000000000000f") is not None - assert nwGUI.openDocument("000000000000f") is True + assert nwGUI.projView.projTree._getTreeItem(C.hSceneDoc) is not None + assert nwGUI.openDocument(C.hSceneDoc) is True nwGUI.docEditor.clear() # Test Faulty Inserts @@ -566,10 +566,7 @@ def testGuiMenu_Insert(qtbot, monkeypatch, nwGUI, fncDir, fncProj, mockRnd): nwGUI.docEditor.clear() nwGUI.mainMenu.aInsNBSpace.activate(QAction.Trigger) - if nwGUI.mainConf.verQtValue >= 50900: - assert nwGUI.docEditor.getText() == nwUnicode.U_NBSP - else: - assert nwGUI.docEditor.getText() == " " + assert nwGUI.docEditor.getText() == nwUnicode.U_NBSP nwGUI.docEditor.clear() nwGUI.mainMenu.aInsThinSpace.activate(QAction.Trigger) @@ -577,10 +574,7 @@ def testGuiMenu_Insert(qtbot, monkeypatch, nwGUI, fncDir, fncProj, mockRnd): nwGUI.docEditor.clear() nwGUI.mainMenu.aInsThinNBSpace.activate(QAction.Trigger) - if nwGUI.mainConf.verQtValue >= 50900: - assert nwGUI.docEditor.getText() == nwUnicode.U_THNBSP - else: - assert nwGUI.docEditor.getText() == " " + assert nwGUI.docEditor.getText() == nwUnicode.U_THNBSP nwGUI.docEditor.clear() ## @@ -677,7 +671,7 @@ def testGuiMenu_Insert(qtbot, monkeypatch, nwGUI, fncDir, fncProj, mockRnd): assert not nwGUI.importDocument() # Open the document from before, and add some text to it - nwGUI.openDocument("000000000000f") + nwGUI.openDocument(C.hSceneDoc) nwGUI.docEditor.setText("Bar") assert nwGUI.docEditor.getText() == "Bar" diff --git a/tests/test_gui/test_gui_noveltree.py b/tests/test_gui/test_gui_noveltree.py index f8f18875..e38d5555 100644 --- a/tests/test_gui/test_gui_noveltree.py +++ b/tests/test_gui/test_gui_noveltree.py @@ -22,15 +22,15 @@ along with this program. If not, see . import os import pytest -from tools import buildTestProject, writeFile +from tools import C, buildTestProject, writeFile from PyQt5.QtGui import QFocusEvent from PyQt5.QtCore import Qt, QEvent from PyQt5.QtWidgets import QMessageBox, QToolTip from novelwriter.enum import nwWidget, nwItemType -from novelwriter.dialogs import GuiEditLabel from novelwriter.gui.noveltree import NovelTreeColumn +from novelwriter.dialogs.editlabel import GuiEditLabel @pytest.mark.gui @@ -46,7 +46,7 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): nwGUI.switchFocus(nwWidget.TREE) nwGUI.projView.projTree.clearSelection() - nwGUI.projView.projTree._getTreeItem("000000000000a").setSelected(True) + nwGUI.projView.projTree._getTreeItem(C.hCharRoot).setSelected(True) nwGUI.projView.projTree.newTreeItem(nwItemType.FILE) writeFile( @@ -94,7 +94,7 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): assert not topItem.isSelected() topItem.setSelected(True) assert novelTree.selectedItems()[0] == topItem - assert novelView.getSelectedHandle() == ("000000000000c", 0) + assert novelView.getSelectedHandle() == (C.hTitlePage, 0) # Refresh using the slot for the butoom novelBar._refreshNovelTree() @@ -119,7 +119,7 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): assert scItem.isSelected() assert nwGUI.docEditor.docHandle() is None novelTree._treeDoubleClick(scItem, 0) - assert nwGUI.docEditor.docHandle() == "000000000000f" + assert nwGUI.docEditor.docHandle() == C.hSceneDoc # Open item with middle mouse button scItem.setSelected(True) @@ -136,7 +136,7 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): scItem.setData(novelTree.C_TITLE, novelTree.D_HANDLE, oldData) qtbot.mouseClick(vPort, Qt.MiddleButton, pos=scRect.center(), delay=10) - assert nwGUI.docViewer.docHandle() == "000000000000f" + assert nwGUI.docViewer.docHandle() == C.hSceneDoc # Last Column # =========== @@ -144,26 +144,26 @@ def testGuiNovelTree_TreeItems(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): novelBar.setLastColType(NovelTreeColumn.HIDDEN) assert novelTree.isColumnHidden(novelTree.C_EXTRA) is True assert novelTree.lastColType == NovelTreeColumn.HIDDEN - assert novelTree._getLastColumnText("000000000000f", "T000001") == ("", "") + assert novelTree._getLastColumnText(C.hSceneDoc, "T000001") == ("", "") novelBar.setLastColType(NovelTreeColumn.POV) assert novelTree.isColumnHidden(novelTree.C_EXTRA) is False assert novelTree.lastColType == NovelTreeColumn.POV - assert novelTree._getLastColumnText("000000000000f", "T000001") == ( + assert novelTree._getLastColumnText(C.hSceneDoc, "T000001") == ( "Jane", "Point of View: Jane" ) novelBar.setLastColType(NovelTreeColumn.FOCUS) assert novelTree.isColumnHidden(novelTree.C_EXTRA) is False assert novelTree.lastColType == NovelTreeColumn.FOCUS - assert novelTree._getLastColumnText("000000000000f", "T000001") == ( + assert novelTree._getLastColumnText(C.hSceneDoc, "T000001") == ( "Jane", "Focus: Jane" ) novelBar.setLastColType(NovelTreeColumn.PLOT) assert novelTree.isColumnHidden(novelTree.C_EXTRA) is False assert novelTree.lastColType == NovelTreeColumn.PLOT - assert novelTree._getLastColumnText("000000000000f", "T000001") == ( + assert novelTree._getLastColumnText(C.hSceneDoc, "T000001") == ( "", "Plot: " ) diff --git a/tests/test_gui/test_gui_projtree.py b/tests/test_gui/test_gui_projtree.py index feef859d..b5201846 100644 --- a/tests/test_gui/test_gui_projtree.py +++ b/tests/test_gui/test_gui_projtree.py @@ -19,16 +19,21 @@ You should have received a copy of the GNU General Public License along with this program. If not, see . """ -import pytest import os +import pytest -from tools import buildTestProject +from mock import causeOSError +from tools import C, buildTestProject -from PyQt5.QtWidgets import QMessageBox, QMenu +from PyQt5.QtCore import Qt +from PyQt5.QtWidgets import QMessageBox, QMenu, QTreeWidgetItem, QDialog from novelwriter.enum import nwItemLayout, nwItemType, nwItemClass -from novelwriter.dialogs import GuiEditLabel +from novelwriter.core import NWDoc from novelwriter.gui.projtree import GuiProjectTree +from novelwriter.dialogs.docmerge import GuiDocMerge +from novelwriter.dialogs.docsplit import GuiDocSplit +from novelwriter.dialogs.editlabel import GuiEditLabel @pytest.mark.gui @@ -42,113 +47,127 @@ def testGuiProjTree_NewItems(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd) monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) - nwTree = nwGUI.projView + projView = nwGUI.projView + projTree = nwGUI.projView.projTree + theProject = nwGUI.theProject # Try to add item with no project - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is False + assert projView.projTree.newTreeItem(nwItemType.FILE) is False # Create a project prjDir = os.path.join(fncDir, "project") buildTestProject(nwGUI, prjDir) # No itemType set - nwTree.projTree.clearSelection() - assert nwTree.projTree.newTreeItem(None) is False + projView.projTree.clearSelection() + assert projView.projTree.newTreeItem(None) is False # Root Items # ========== # No class set - assert nwTree.projTree.newTreeItem(nwItemType.ROOT) is False + assert projView.projTree.newTreeItem(nwItemType.ROOT) is False # Create root item - assert nwTree.projTree.newTreeItem(nwItemType.ROOT, nwItemClass.WORLD) is True - assert "0000000000010" in nwGUI.theProject.tree + assert projView.projTree.newTreeItem(nwItemType.ROOT, nwItemClass.WORLD) is True + assert "0000000000010" in theProject.tree # File/Folder Items # ================= # No location selected for new item - nwTree.projTree.clearSelection() + projView.projTree.clearSelection() caplog.clear() - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is False - assert nwTree.projTree.newTreeItem(nwItemType.FOLDER) is False + assert projView.projTree.newTreeItem(nwItemType.FILE) is False + assert projView.projTree.newTreeItem(nwItemType.FOLDER) is False assert "Did not find anywhere" in caplog.text # Create new folder as child of Novel folder - nwTree.setSelectedHandle("0000000000008") - assert nwTree.projTree.newTreeItem(nwItemType.FOLDER) is True - assert nwGUI.theProject.tree["0000000000011"].itemParent == "0000000000008" - assert nwGUI.theProject.tree["0000000000011"].itemRoot == "0000000000008" - assert nwGUI.theProject.tree["0000000000011"].itemClass == nwItemClass.NOVEL + projView.setSelectedHandle(C.hNovelRoot) + assert projView.projTree.newTreeItem(nwItemType.FOLDER) is True + assert theProject.tree["0000000000011"].itemParent == C.hNovelRoot + assert theProject.tree["0000000000011"].itemRoot == C.hNovelRoot + assert theProject.tree["0000000000011"].itemClass == nwItemClass.NOVEL # Add a new file in the new folder - nwTree.setSelectedHandle("0000000000011") - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwGUI.theProject.tree["0000000000012"].itemParent == "0000000000011" - assert nwGUI.theProject.tree["0000000000012"].itemRoot == "0000000000008" - assert nwGUI.theProject.tree["0000000000012"].itemClass == nwItemClass.NOVEL + projView.setSelectedHandle("0000000000011") + assert projView.projTree.newTreeItem(nwItemType.FILE) is True + assert theProject.tree["0000000000012"].itemParent == "0000000000011" + assert theProject.tree["0000000000012"].itemRoot == C.hNovelRoot + assert theProject.tree["0000000000012"].itemClass == nwItemClass.NOVEL # Add a new chapter next to the other new file - nwTree.setSelectedHandle("0000000000012") - assert nwTree.projTree.newTreeItem(nwItemType.FILE, hLevel=2) is True - assert nwGUI.theProject.tree["0000000000013"].itemParent == "0000000000011" - assert nwGUI.theProject.tree["0000000000013"].itemRoot == "0000000000008" - assert nwGUI.theProject.tree["0000000000013"].itemClass == nwItemClass.NOVEL + projView.setSelectedHandle("0000000000012") + assert projView.projTree.newTreeItem(nwItemType.FILE, hLevel=2) is True + assert theProject.tree["0000000000013"].itemParent == "0000000000011" + assert theProject.tree["0000000000013"].itemRoot == C.hNovelRoot + assert theProject.tree["0000000000013"].itemClass == nwItemClass.NOVEL assert nwGUI.openDocument("0000000000013") assert nwGUI.docEditor.getText() == "## New Chapter\n\n" # Add a new scene next to the other new file - nwTree.setSelectedHandle("0000000000012") - assert nwTree.projTree.newTreeItem(nwItemType.FILE, hLevel=3) is True - assert nwGUI.theProject.tree["0000000000014"].itemParent == "0000000000011" - assert nwGUI.theProject.tree["0000000000014"].itemRoot == "0000000000008" - assert nwGUI.theProject.tree["0000000000014"].itemClass == nwItemClass.NOVEL + projView.setSelectedHandle("0000000000012") + assert projView.projTree.newTreeItem(nwItemType.FILE, hLevel=3) is True + assert theProject.tree["0000000000014"].itemParent == "0000000000011" + assert theProject.tree["0000000000014"].itemRoot == C.hNovelRoot + assert theProject.tree["0000000000014"].itemClass == nwItemClass.NOVEL assert nwGUI.openDocument("0000000000014") assert nwGUI.docEditor.getText() == "### New Scene\n\n" # Add a new file to the characters folder - nwTree.setSelectedHandle("000000000000a") - assert nwTree.projTree.newTreeItem(nwItemType.FILE, hLevel=1, isNote=True) is True - assert nwGUI.theProject.tree["0000000000015"].itemParent == "000000000000a" - assert nwGUI.theProject.tree["0000000000015"].itemRoot == "000000000000a" - assert nwGUI.theProject.tree["0000000000015"].itemClass == nwItemClass.CHARACTER + projView.setSelectedHandle(C.hCharRoot) + assert projView.projTree.newTreeItem(nwItemType.FILE, hLevel=1, isNote=True) is True + assert theProject.tree["0000000000015"].itemParent == C.hCharRoot + assert theProject.tree["0000000000015"].itemRoot == C.hCharRoot + assert theProject.tree["0000000000015"].itemClass == nwItemClass.CHARACTER assert nwGUI.openDocument("0000000000015") assert nwGUI.docEditor.getText() == "# New Note\n\n" # Make sure the sibling folder bug trap works - nwTree.setSelectedHandle("0000000000013") - nwGUI.theProject.tree["0000000000013"].setParent(None) # This should not happen + projView.setSelectedHandle("0000000000013") + theProject.tree["0000000000013"].setParent(None) # This should not happen caplog.clear() - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is False + assert projView.projTree.newTreeItem(nwItemType.FILE) is False assert "Internal error" in caplog.text - nwGUI.theProject.tree["0000000000013"].setParent("0000000000011") + theProject.tree["0000000000013"].setParent("0000000000011") # Cancel during creation with monkeypatch.context() as mp: mp.setattr(GuiEditLabel, "getLabel", lambda *a, **k: ("", False)) - nwTree.setSelectedHandle("0000000000013") - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is False + projView.setSelectedHandle("0000000000013") + assert projView.projTree.newTreeItem(nwItemType.FILE) is False # Get the trash folder - nwTree.projTree._addTrashRoot() - trashHandle = nwGUI.theProject.trashFolder() - nwTree.setSelectedHandle(trashHandle) - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is False + projView.projTree._addTrashRoot() + trashHandle = theProject.trashFolder() + projView.setSelectedHandle(trashHandle) + assert projView.projTree.newTreeItem(nwItemType.FILE) is False assert "Cannot add new files or folders to the Trash folder" in caplog.text + # Rename Item + # =========== + + # Rename plot folder + with monkeypatch.context() as mp: + mp.setattr(GuiEditLabel, "getLabel", lambda *a, **k: ("Stuff", True)) + projTree.renameTreeItem(C.hPlotRoot) is True + assert theProject.tree[C.hPlotRoot].itemName == "Stuff" + + # Rename invalid folder + projTree.renameTreeItem("0000000000000") is False + # Other Checks # ============ # Also check error handling in reveal function - assert nwTree.revealNewTreeItem("abc") is False + assert projView.revealNewTreeItem("abc") is False # Add an item that cannot be displayed in the tree - nHandle = nwGUI.theProject.newFile("Test", None) - assert nwTree.revealNewTreeItem(nHandle) is False + nHandle = theProject.newFile("Test", None) + assert projView.revealNewTreeItem(nHandle) is False # Clean up - # qtbot.stopForInteraction() + # qtbot.stop() nwGUI.closeProject() # END Test testGuiProjTree_NewItems @@ -178,12 +197,12 @@ def testGuiProjTree_MoveItems(qtbot, monkeypatch, nwGUI, fncDir, mockRnd): # ============== # Add some files - nwTree.setSelectedHandle("000000000000d") + nwTree.setSelectedHandle(C.hChapterDir) assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000011", "0000000000012", ] @@ -192,75 +211,75 @@ def testGuiProjTree_MoveItems(qtbot, monkeypatch, nwGUI, fncDir, mockRnd): assert nwTree.projTree.moveTreeItem(1) is False # Move second item up twice (should give same result) - nwTree.setSelectedHandle("000000000000f") + nwTree.setSelectedHandle(C.hSceneDoc) assert nwTree.projTree.moveTreeItem(-1) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000f", "000000000000e", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hSceneDoc, C.hChapterDoc, "0000000000010", "0000000000011", "0000000000012", ] assert nwTree.projTree.moveTreeItem(-1) is False - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000f", "000000000000e", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hSceneDoc, C.hChapterDoc, "0000000000010", "0000000000011", "0000000000012", ] # Restore assert nwTree.projTree.moveTreeItem(1) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000011", "0000000000012", ] # Move fifth item down twice (should give same result) nwTree.setSelectedHandle("0000000000011") assert nwTree.projTree.moveTreeItem(1) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000012", "0000000000011", ] assert nwTree.projTree.moveTreeItem(1) is False - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000012", "0000000000011", ] # Restore assert nwTree.projTree.moveTreeItem(-1) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000011", "0000000000012", ] # Move down again, and restore via undo nwTree.setSelectedHandle("0000000000011") assert nwTree.projTree.moveTreeItem(1) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000012", "0000000000011", ] assert nwTree.projTree.undoLastMove() is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwTree.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000011", "0000000000012", ] # Root Folder # =========== - nwTree.setSelectedHandle("0000000000008") - assert nwGUI.theProject.tree._treeOrder.index("0000000000008") == 0 + nwTree.setSelectedHandle(C.hNovelRoot) + assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 # Move novel folder up assert nwTree.projTree.moveTreeItem(-1) is False - assert nwGUI.theProject.tree._treeOrder.index("0000000000008") == 0 + assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 # Move novel folder down assert nwTree.projTree.moveTreeItem(1) is True - assert nwGUI.theProject.tree._treeOrder.index("0000000000008") == 1 + assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 1 # Move novel folder up again assert nwTree.projTree.moveTreeItem(-1) is True - assert nwGUI.theProject.tree._treeOrder.index("0000000000008") == 0 + assert nwGUI.theProject.tree._treeOrder.index(C.hNovelRoot) == 0 # Clean up # qtbot.stopForInteraction() @@ -270,8 +289,8 @@ def testGuiProjTree_MoveItems(qtbot, monkeypatch, nwGUI, fncDir, mockRnd): @pytest.mark.gui -def testGuiProjTree_DeleteItems(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): - """Test adding and removing items from the project tree. +def testGuiProjTree_RequestDeleteItem(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): + """Test external requests for removing items from project tree. """ # Block message box monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) @@ -280,185 +299,261 @@ def testGuiProjTree_DeleteItems(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockR monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) - nwTree = nwGUI.projView + nwView = nwGUI.projView # Try to run with no project - assert nwTree.emptyTrash() is False - assert nwTree.deleteItem() is False + assert nwView.requestDeleteItem() is False # Create a project prjDir = os.path.join(fncDir, "project") buildTestProject(nwGUI, prjDir) # Try emptying the trash already now, when there is no trash folder - assert nwTree.emptyTrash() is False + assert nwView.emptyTrash() is False # Add some files - nwTree.setSelectedHandle("000000000000d") - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + nwView.setSelectedHandle(C.hChapterDir) + assert nwView.projTree.newTreeItem(nwItemType.FILE) is True + assert nwView.projTree.newTreeItem(nwItemType.FILE) is True + assert nwView.projTree.newTreeItem(nwItemType.FILE) is True + assert nwView.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010", "0000000000011", "0000000000012", ] # Delete item without focus -> blocked monkeypatch.setattr(GuiProjectTree, "hasFocus", lambda *a: False) - nwTree.setSelectedHandle("0000000000012") - assert nwTree.deleteItem() is False + nwView.setSelectedHandle("0000000000012") + assert nwView.requestDeleteItem() is False monkeypatch.setattr(GuiProjectTree, "hasFocus", lambda *a: True) # No selection made - nwTree.projTree.clearSelection() + nwView.projTree.clearSelection() caplog.clear() - assert nwTree.deleteItem() is False + assert nwView.requestDeleteItem() is False assert "no item to delete" in caplog.text # Not a valid handle - nwTree.projTree.clearSelection() + nwView.projTree.clearSelection() caplog.clear() - assert nwTree.deleteItem("0000000000000") is False - assert "Could not find tree item" in caplog.text + assert nwView.requestDeleteItem("0000000000000") is False + assert "No tree item with handle '0000000000000'" in caplog.text - # Delete Folder/Root - # ================== + # Delete Root Folders + # =================== - # Deleting non-empty folders is blocked - assert nwTree.deleteItem("0000000000008") is False # Novel Root - assert nwTree.deleteItem("000000000000a") is True # Character Root + assert nwView.requestDeleteItem(C.hNovelRoot) is False # Novel Root is blocked + assert nwView.requestDeleteItem(C.hCharRoot) is True # Character Root # Delete File # =========== # Block adding trash folder - funcPointer = nwTree.projTree._addTrashRoot - nwTree.projTree._addTrashRoot = lambda *a: None - assert nwTree.deleteItem("0000000000012") is False - nwTree.projTree._addTrashRoot = funcPointer + funcPointer = nwView.projTree._addTrashRoot + nwView.projTree._addTrashRoot = lambda *a: None + assert nwView.requestDeleteItem("0000000000012") is False + nwView.projTree._addTrashRoot = funcPointer # Delete last two documents, which also adds the trash folder - assert nwTree.deleteItem("0000000000012") is True - assert nwTree.deleteItem("0000000000011") is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e", "000000000000f", + assert nwView.requestDeleteItem("0000000000012") is True + assert nwView.requestDeleteItem("0000000000011") is True + assert nwView.getTreeFromHandle(C.hChapterDir) == [ + C.hChapterDir, C.hChapterDoc, C.hSceneDoc, "0000000000010" ] trashHandle = nwGUI.theProject.tree.trashRoot() - assert nwTree.getTreeFromHandle(trashHandle) == [ + assert nwView.getTreeFromHandle(trashHandle) == [ trashHandle, "0000000000012", "0000000000011" ] - # Delete the first file again (permanent), and ask for permission - # Also open the document in the editor, which should trigger a close - assert os.path.isfile(os.path.join(prjDir, "content", "0000000000012.nwd")) - assert "0000000000012" in nwGUI.theProject.tree - assert nwGUI.docEditor.docHandle() is None - assert nwGUI.openDocument("0000000000012") is True - assert nwGUI.docEditor.docHandle() == "0000000000012" - assert nwTree.deleteItem("0000000000012") is True - assert nwGUI.docEditor.docHandle() is None - assert not os.path.isfile(os.path.join(prjDir, "content", "0000000000012.nwd")) - assert "0000000000012" not in nwGUI.theProject.tree - assert nwTree.getTreeFromHandle(trashHandle) == [ - trashHandle, "0000000000011" - ] + # Try to delete the trash folder + caplog.clear() + assert nwView.requestDeleteItem("0000000000013") is False + assert "Cannot delete the Trash folder" in caplog.text - # Delete the second file, and skip asking for permission - assert os.path.isfile(os.path.join(prjDir, "content", "0000000000011.nwd")) - assert "0000000000011" in nwGUI.theProject.tree - assert nwTree.deleteItem("0000000000011", alreadyAsked=True) is True - assert not os.path.isfile(os.path.join(prjDir, "content", "0000000000011.nwd")) - assert "0000000000011" not in nwGUI.theProject.tree - assert nwTree.getTreeFromHandle(trashHandle) == [trashHandle] - - # Delete Folder - # ============= - - trashHandle = nwGUI.theProject.tree.trashRoot() - - # Add a folder with two files - nwTree.setSelectedHandle("0000000000009") - assert nwTree.projTree.newTreeItem(nwItemType.FOLDER) is True - nwTree.setSelectedHandle("0000000000014") - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert nwTree.projTree.newTreeItem(nwItemType.FILE) is True - assert os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000015.nwd")) - assert os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000016.nwd")) - - # Delete the folder, which moves everything to Trash - assert nwTree.getTreeFromHandle("0000000000014") == [ - "0000000000014", "0000000000015", "0000000000016" - ] - assert nwTree.deleteItem("0000000000014") is True - assert nwTree.getTreeFromHandle(trashHandle) == [ - trashHandle, "0000000000014", "0000000000015", "0000000000016" - ] - assert os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000015.nwd")) - assert os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000016.nwd")) - - # Delete again, which should delete folder and all files - assert nwTree.deleteItem("0000000000014") is True - assert nwTree.getTreeFromHandle(trashHandle) == [trashHandle] - assert not os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000015.nwd")) - assert not os.path.isfile(os.path.join(fncDir, "project", "content", "0000000000016.nwd")) - - # Add an empty folder, which can be deleted with no further restrictions - nwTree.setSelectedHandle("0000000000009") - assert nwTree.projTree.newTreeItem(nwItemType.FOLDER) is True - assert nwTree.getTreeFromHandle("0000000000009") == ["0000000000009", "0000000000017"] - - nwTree.setSelectedHandle("0000000000017") - assert nwTree.deleteItem("0000000000017") is True - assert nwTree.getTreeFromHandle("0000000000009") == ["0000000000009"] - - # Empty Trash - # =========== - - # Try to empty trash that is already empty - assert nwTree.getTreeFromHandle(trashHandle) == [trashHandle] - assert nwTree.emptyTrash() is False - - # Move the two remaining scene documents to trash - assert nwTree.deleteItem("000000000000f") is True - assert nwTree.deleteItem("0000000000010") is True - assert nwTree.getTreeFromHandle("000000000000d") == [ - "000000000000d", "000000000000e" - ] - assert nwTree.getTreeFromHandle(trashHandle) == [ - trashHandle, "000000000000f", "0000000000010" - ] - - # Empty trash, but select no on question - with monkeypatch.context() as mp: - mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) - assert nwTree.emptyTrash() is False - - # Empty the trash proper - assert nwTree.emptyTrash() is True - assert nwTree.getTreeFromHandle(trashHandle) == [trashHandle] - - # Try to delete a file, but block the underlying deletion of the file on disk - assert os.path.isfile(os.path.join(fncDir, "project", "content", "000000000000e.nwd")) - with monkeypatch.context() as mp: - mp.setattr("novelwriter.core.document.NWDoc.deleteDocument", lambda *a: False) - assert nwTree.deleteItem("000000000000e") is True - assert nwTree.deleteItem("000000000000e") is True - assert os.path.isfile(os.path.join(fncDir, "project", "content", "000000000000e.nwd")) - - # Delete proper - assert nwTree.projTree._deleteTreeItem("000000000000e") is True - assert not os.path.isfile(os.path.join(fncDir, "project", "content", "000000000000e.nwd")) - - # Clean up - # qtbot.stopForInteraction() nwGUI.closeProject() -# END Test testGuiProjTree_DeleteItems +# END Test testGuiProjTree_RequestDeleteItem @pytest.mark.gui -def testGuiProjTree_ContextMenu(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): +def testGuiProjTree_MoveItemToTrash(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): + """Test moving items to Trash. + """ + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) + + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + # Invalid item + caplog.clear() + assert projTree.moveItemToTrash(C.hInvalid) is False + assert "Could not find tree item for deletion" in caplog.text + + # Root folders cannot be moved to Trash + caplog.clear() + assert projTree.moveItemToTrash(C.hNovelRoot) is False + assert "Root folders cannot be moved to Trash" in caplog.text + + # Block adding trash folder + funcPointer = projTree._addTrashRoot + projTree._addTrashRoot = lambda *a: None + + caplog.clear() + assert projTree.moveItemToTrash(C.hTitlePage) is False + assert theProject.tree.isTrash(C.hTitlePage) is False + assert "Could not delete item" in caplog.text + + projTree._addTrashRoot = funcPointer + + # User cancels action + with monkeypatch.context() as mp: + mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) + assert projTree.moveItemToTrash(C.hTitlePage) is False + assert theProject.tree.isTrash(C.hTitlePage) is False + + # Move a document to Trash + assert projTree.moveItemToTrash(C.hTitlePage) is True + assert theProject.tree.isTrash(C.hTitlePage) is True + + # Cannot be moved again + caplog.clear() + assert projTree.moveItemToTrash(C.hTitlePage) is False + assert "Item is already in the Trash folder" in caplog.text + + nwGUI.closeProject() + +# END Test testGuiProjTree_MoveItemToTrash + + +@pytest.mark.gui +def testGuiProjTree_PermanentlyDeleteItem(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): + """Test permanently deleting items. + """ + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) + + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + # Invalid item + caplog.clear() + assert projTree.permanentlyDeleteItem(C.hInvalid) is False + assert "Could not find tree item for deletion" in caplog.text + + # Not deleting root item in use + caplog.clear() + assert projTree.permanentlyDeleteItem(C.hNovelRoot) is False + assert "Root folders can only be deleted when they are empty" in caplog.text + assert C.hNovelRoot in theProject.tree + + # Deleting unused root item is allowed + caplog.clear() + assert projTree.permanentlyDeleteItem(C.hPlotRoot) is True + assert C.hPlotRoot not in theProject.tree + + # User cancels action + with monkeypatch.context() as mp: + mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) + assert projTree.permanentlyDeleteItem(C.hTitlePage) is False + assert C.hTitlePage in theProject.tree + + # Deleting file is OK, and if it is open, it should close + assert nwGUI.openDocument(C.hTitlePage) is True + assert nwGUI.docEditor.docHandle() == C.hTitlePage + assert projTree.permanentlyDeleteItem(C.hTitlePage) is True + assert C.hTitlePage not in theProject.tree + assert nwGUI.docEditor.docHandle() is None + + # Deleting folder + files recursiely is ok + assert projTree.permanentlyDeleteItem(C.hChapterDir) is True + assert C.hChapterDir not in theProject.tree + assert C.hChapterDoc not in theProject.tree + assert C.hSceneDoc not in theProject.tree + + nwGUI.closeProject() + +# END Test testGuiProjTree_PermanentlyDeleteItem + + +@pytest.mark.gui +def testGuiProjTree_EmptyTrash(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockRnd): + """Test emptying Trash. + """ + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(GuiEditLabel, "getLabel", lambda *a, text: (text, True)) + + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree + + # No project open + caplog.clear() + assert projTree.emptyTrash() is False + assert "No project open" in caplog.text + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + # No Trash folder + assert projTree.emptyTrash() is False + + # Move some documents to Trash + assert projTree.moveItemToTrash(C.hTitlePage) is True + assert projTree.moveItemToTrash(C.hChapterDir) is True + + assert theProject.tree.isTrash(C.hTitlePage) is True + assert theProject.tree.isTrash(C.hChapterDir) is True + assert theProject.tree.isTrash(C.hChapterDoc) is True + assert theProject.tree.isTrash(C.hSceneDoc) is True + + # User cancels + with monkeypatch.context() as mp: + mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) + assert projTree.emptyTrash() is False + assert C.hTitlePage in theProject.tree + assert C.hChapterDir in theProject.tree + assert C.hChapterDoc in theProject.tree + assert C.hSceneDoc in theProject.tree + + # Run again to empty all items + assert projTree.emptyTrash() is True + assert C.hTitlePage not in theProject.tree + assert C.hChapterDir not in theProject.tree + assert C.hChapterDoc not in theProject.tree + assert C.hSceneDoc not in theProject.tree + + # Running Emtpy Trash again is cancelled due to empty folder + assert projTree.emptyTrash() is False + + nwGUI.closeProject() + +# END Test testGuiProjTree_EmptyTrash + + +@pytest.mark.gui +def testGuiProjTree_ContextMenu(qtbot, monkeypatch, nwGUI, fncDir, mockRnd): """Test the building of the project tree context menu. All this does is test that the menu builds. It doesn't open the actual menu, """ @@ -475,26 +570,28 @@ def testGuiProjTree_ContextMenu(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockR buildTestProject(nwGUI, prjDir) # Handles for new objects - hNovelRoot = "0000000000008" - hTitlePage = "000000000000c" - hChapterDir = "000000000000d" - hChapterFile = "000000000000e" - hCharRoot = "000000000000a" - hCharNote = "0000000000011" - hNovelNote = "0000000000012" + hCharNote = "0000000000011" + hNovelNote = "0000000000012" + hSubNote = "0000000000013" + hNewFolderOne = "0000000000014" + hNewFolderTwo = "0000000000016" + projView = nwGUI.projView projTree = nwGUI.projView.projTree - projTree._getTreeItem(hNovelRoot).setExpanded(True) - projTree._getTreeItem(hChapterDir).setExpanded(True) + projTree.setExpandedFromHandle(None, True) projTree._addTrashRoot() hTrashRoot = projTree.theProject.tree.trashRoot() - projTree.setSelectedHandle(hCharRoot) + projTree.setSelectedHandle(C.hCharRoot) projTree.newTreeItem(nwItemType.FILE) - projTree.setSelectedHandle(hNovelRoot) + projTree.setSelectedHandle(C.hNovelRoot) projTree.newTreeItem(nwItemType.FILE, isNote=True) + nwGUI.theProject.newFile("SubNote", hNovelNote) + projTree.revealNewTreeItem(hSubNote) + assert nwGUI.theProject.tree[hSubNote].itemParent == hNovelNote + def itemPos(tHandle): return projTree.visualItemRect(projTree._getTreeItem(tHandle)).center() @@ -503,16 +600,17 @@ def testGuiProjTree_ContextMenu(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockR # Generate the possible menu combinarions assert projTree._openContextMenu(itemPos(hTrashRoot)) is True - assert projTree._openContextMenu(itemPos(hNovelRoot)) is True + assert projTree._openContextMenu(itemPos(C.hNovelRoot)) is True assert projTree._openContextMenu(itemPos(hNovelNote)) is True - assert projTree._openContextMenu(itemPos(hTitlePage)) is True - assert projTree._openContextMenu(itemPos(hChapterDir)) is True - assert projTree._openContextMenu(itemPos(hChapterFile)) is True - assert projTree._openContextMenu(itemPos(hCharRoot)) is True + assert projTree._openContextMenu(itemPos(C.hTitlePage)) is True + assert projTree._openContextMenu(itemPos(C.hChapterDir)) is True + assert projTree._openContextMenu(itemPos(C.hChapterDoc)) is True + assert projTree._openContextMenu(itemPos(C.hCharRoot)) is True assert projTree._openContextMenu(itemPos(hCharNote)) is True + assert projTree._openContextMenu(itemPos(hNovelNote)) is True # Check the keyboard shortcut handler as well - projTree.setSelectedHandle(hNovelRoot) + projTree.setSelectedHandle(C.hNovelRoot) assert projTree.openContextOnSelected() is True projTree.clearSelection() assert projTree.openContextOnSelected() is False @@ -522,10 +620,10 @@ def testGuiProjTree_ContextMenu(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockR # Trigger the dedicated functions the menu entries connect to nwItem = projTree.theProject.tree[hNovelNote] - # Toggle exported flag - assert nwItem.isExported is True - projTree._toggleItemExported(hNovelNote) - assert nwItem.isExported is False + # Toggle active flag + assert nwItem.isActive is True + projTree._toggleItemActive(hNovelNote) + assert nwItem.isActive is False # Change item status assert nwItem.itemStatus == "s000000" @@ -544,6 +642,352 @@ def testGuiProjTree_ContextMenu(qtbot, caplog, monkeypatch, nwGUI, fncDir, mockR projTree._changeItemLayout(hNovelNote, nwItemLayout.NOTE) assert nwItem.itemLayout == nwItemLayout.NOTE + # Convert Folders to Documents + # ============================ + + projView.setSelectedHandle(hNovelNote) + assert projView.projTree.newTreeItem(nwItemType.FOLDER) is True + projView.setSelectedHandle(hNewFolderOne) + assert projView.projTree.newTreeItem(nwItemType.FILE) is True + + projView.setSelectedHandle(hNovelNote) + assert projView.projTree.newTreeItem(nwItemType.FOLDER) is True + projView.setSelectedHandle(hNewFolderTwo) + assert projView.projTree.newTreeItem(nwItemType.FILE, isNote=True) is True + + # Click no on the dialog + with monkeypatch.context() as mp: + mp.setattr(QMessageBox, "question", lambda *a: QMessageBox.No) + projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT) + assert nwGUI.theProject.tree[hNewFolderOne].isFolderType() + + # Convert the first folder to a document + projTree._covertFolderToFile(hNewFolderOne, nwItemLayout.DOCUMENT) + assert nwGUI.theProject.tree[hNewFolderOne].isFileType() + assert nwGUI.theProject.tree[hNewFolderOne].isDocumentLayout() + + # Convert the second folder to a note + projTree._covertFolderToFile(hNewFolderTwo, nwItemLayout.NOTE) + assert nwGUI.theProject.tree[hNewFolderTwo].isFileType() + assert nwGUI.theProject.tree[hNewFolderTwo].isNoteLayout() + # qtbot.stop() # END Test testGuiProjTree_ContextMenu + + +@pytest.mark.gui +def testGuiProjTree_MergeDocuments(qtbot, monkeypatch, nwGUI, fncDir, mockRnd, ipsumText): + """Test the merge document function. + """ + mergeData = {} + + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + + monkeypatch.setattr(GuiDocMerge, "__init__", lambda *a: None) + monkeypatch.setattr(GuiDocMerge, "exec_", lambda *a: None) + monkeypatch.setattr(GuiDocMerge, "result", lambda *a: QDialog.Accepted) + monkeypatch.setattr(GuiDocMerge, "getData", lambda *a: mergeData) + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree + + mergedDoc1 = "0000000000014" + + # Create File to Merge + hChapter1 = theProject.newFile("Chapter 1", C.hNovelRoot) + hSceneOne11 = theProject.newFile("Scene 1.1", hChapter1) + hSceneOne12 = theProject.newFile("Scene 1.2", hChapter1) + hSceneOne13 = theProject.newFile("Scene 1.3", hChapter1) + + docText1 = "\n\n".join(ipsumText[0:2]) + "\n\n" + docText2 = "\n\n".join(ipsumText[1:3]) + "\n\n" + docText3 = "\n\n".join(ipsumText[2:4]) + "\n\n" + docText4 = "\n\n".join(ipsumText[3:5]) + "\n\n" + + lenText1 = len(docText1) + lenText2 = len(docText2) + lenText3 = len(docText3) + lenText4 = len(docText4) + lenAll = lenText1 + lenText2 + lenText3 + lenText4 + + theProject.writeNewFile(hChapter1, 2, True, docText1) + theProject.writeNewFile(hSceneOne11, 3, True, docText2) + theProject.writeNewFile(hSceneOne12, 3, True, docText3) + theProject.writeNewFile(hSceneOne13, 3, True, docText4) + + projTree.revealNewTreeItem(hChapter1) + projTree.revealNewTreeItem(hSceneOne11) + projTree.revealNewTreeItem(hSceneOne12) + projTree.revealNewTreeItem(hSceneOne13) + + # Invalid file handle + assert projTree._mergeDocuments(C.hInvalid, False) is False + + # Cannot merge root item + assert projTree._mergeDocuments(C.hNovelRoot, False) is False + + # Merge to new file, but there is now merge data + mergeData.clear() + assert projTree._mergeDocuments(hChapter1, True) is False + + # Merge to New Doc + # ================ + + # Set merge job for new documents + mergeData["finalItems"] = [hChapter1, hSceneOne11, hSceneOne12, hSceneOne13] + mergeData["moveToTrash"] = False + + # User cancels merge + with monkeypatch.context() as mp: + mp.setattr(GuiDocMerge, "result", lambda *a: QDialog.Rejected) + assert projTree._mergeDocuments(hChapter1, True) is False + + # The merge goes through + assert projTree._mergeDocuments(hChapter1, True) is True + assert len(NWDoc(theProject, mergedDoc1).readDocument()) > lenAll + + # Merge to Existing Doc + # ===================== + + # Set merge job for parent document + mergeData["finalItems"] = [hSceneOne11, hSceneOne12, hSceneOne13] + mergeData["moveToTrash"] = False + + # Merging to a folder is not allowed + assert projTree._mergeDocuments(C.hChapterDir, False) is False + + # Block writing and check error handling + with monkeypatch.context() as mp: + mp.setattr("builtins.open", causeOSError) + assert projTree._mergeDocuments(hChapter1, False) is False + + # Successful merge, and move to trash + mergeData["moveToTrash"] = True + assert len(NWDoc(theProject, hChapter1).readDocument()) < lenAll + assert projTree._mergeDocuments(hChapter1, False) is True + assert len(NWDoc(theProject, hChapter1).readDocument()) > lenAll + + assert theProject.tree.isTrash(hSceneOne11) + assert theProject.tree.isTrash(hSceneOne12) + assert theProject.tree.isTrash(hSceneOne13) + + # qtbot.stop() + +# END Test testGuiProjTree_MergeDocuments + + +@pytest.mark.gui +def testGuiProjTree_SplitDocument(qtbot, monkeypatch, nwGUI, fncDir, mockRnd, ipsumText): + """Test the split document function. + """ + splitData = {} + splitText = [] + + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + + monkeypatch.setattr(GuiDocSplit, "__init__", lambda *a: None) + monkeypatch.setattr(GuiDocSplit, "exec_", lambda *a: None) + monkeypatch.setattr(GuiDocSplit, "result", lambda *a: QDialog.Accepted) + monkeypatch.setattr(GuiDocSplit, "getData", lambda *a: (splitData, splitText)) + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + theProject = nwGUI.theProject + projTree = nwGUI.projView.projTree + + docText = ( + "Text\n\n" + "##! Prologue\n\nText\n\n" + "## Chapter One\n\nText\n\n" + "### Scene One\n\nText\n\n" + "### Scene Two\n\nText\n\n" + "## Chapter Two\n\nText\n\n" + "### Scene Three\n\nText\n\n" + "### Scene Four\n\nText\n\n" + "#! New Title\n\nText\n\n" + "## New Chapter\n\nText\n\n" + "### New Scene\n\nText\n\n" + "#### New Section\n\nText\n\n" + ) + + hSplitDoc = theProject.newFile("Split Doc", C.hNovelRoot) + theProject.writeNewFile(hSplitDoc, 1, True, docText) + projTree.revealNewTreeItem(hSplitDoc, nHandle=C.hNovelRoot, wordCount=True) + + docText = f"# Split Doc\n\n{docText}" + splitData["headerList"] = [ + (0, 1, "Split Doc"), + (4, 2, "Prologue"), + (8, 2, "Chapter One"), + (12, 3, "Scene One"), + (16, 3, "Scene Two"), + (20, 2, "Chapter Two"), + (24, 3, "Scene Three"), + (28, 3, "Scene Four"), + (32, 1, "New Title"), + (36, 2, "New Chapter"), + (40, 3, "New Scene"), + (44, 4, "New Section"), + ] + + fstSet = [ + "0000000000011", "0000000000012", "0000000000013", "0000000000014", + "0000000000015", "0000000000016", "0000000000017", "0000000000018", + "0000000000019", "000000000001a", "000000000001b", "000000000001c", + ] + sndSet = [ + "000000000001d", "000000000001e", "000000000001f", "0000000000020", + "0000000000021", "0000000000022", "0000000000023", "0000000000024", + "0000000000025", "0000000000026", "0000000000027", "0000000000028", + ] + trdSet = [ + "000000000002a", "000000000002b", "000000000002c", "000000000002d", + "000000000002e", "000000000002f", "0000000000030", "0000000000031", + "0000000000032", "0000000000033", "0000000000034", "0000000000035", + ] + + # Try to split an invalid document and a non-document + assert projTree._splitDocument(C.hInvalid) is False + assert projTree._splitDocument(C.hNovelRoot) is False + + # Split into same root folder + splitData["intoFolder"] = False + + # Writing fails + with monkeypatch.context() as mp: + mp.setattr("builtins.open", causeOSError) + assert projTree._splitDocument(hSplitDoc) is True + for tHandle in fstSet: + assert tHandle in theProject.tree + assert not os.path.isfile(os.path.join(prjDir, "content", f"{tHandle}.nwd")) + + # Writing succeeds + assert projTree._splitDocument(hSplitDoc) is True + for tHandle in sndSet: + assert tHandle in theProject.tree + assert os.path.isfile(os.path.join(prjDir, "content", f"{tHandle}.nwd")) + + # Add to a folder + splitData["intoFolder"] = True + assert projTree._splitDocument(hSplitDoc) is True + assert "0000000000029" in theProject.tree # The folder + for tHandle in trdSet: + assert tHandle in theProject.tree + assert os.path.isfile(os.path.join(prjDir, "content", f"{tHandle}.nwd")) + + # Cancelled by user + with monkeypatch.context() as mp: + mp.setattr(GuiDocSplit, "result", lambda *a: QDialog.Rejected) + assert projTree._splitDocument(hSplitDoc) is False + + # qtbot.stop() + +# END Test testGuiProjTree_SplitDocument + + +@pytest.mark.gui +def testGuiProjTree_Other(qtbot, monkeypatch, nwGUI, fncDir, mockRnd): + """Test various parts of the project tree class not covered by + other tests. + """ + # Block message box + monkeypatch.setattr(QMessageBox, "warning", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "critical", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) + monkeypatch.setattr(QMessageBox, "information", lambda *a: QMessageBox.Yes) + + # Create a project + prjDir = os.path.join(fncDir, "project") + buildTestProject(nwGUI, prjDir) + + projView = nwGUI.projView + projTree = nwGUI.projView.projTree + + # Method: initSettings + # ==================== + + # Test that the scrollbar setting works + nwGUI.mainConf.hideVScroll = True + nwGUI.mainConf.hideHScroll = True + projView.initSettings() + assert projTree.verticalScrollBarPolicy() == Qt.ScrollBarAlwaysOff + assert projTree.horizontalScrollBarPolicy() == Qt.ScrollBarAlwaysOff + + nwGUI.mainConf.hideVScroll = False + nwGUI.mainConf.hideHScroll = False + projView.initSettings() + assert projTree.verticalScrollBarPolicy() == Qt.ScrollBarAsNeeded + assert projTree.horizontalScrollBarPolicy() == Qt.ScrollBarAsNeeded + + # Method: revealNewTreeItem + # ========================= + + # Send invalid handle + assert projTree.revealNewTreeItem(C.hInvalid) is False + + # Try to add an oprhaned file to the tree + nHandle = nwGUI.theProject.newFile("Test", C.hNovelRoot) + nwGUI.theProject.tree[nHandle].setParent(None) + assert projTree.revealNewTreeItem(nHandle) is False + + # Method: undoLastMove + # ==================== + + # Nothing to move + assert projTree.undoLastMove() is False + + projTree._lastMove["item"] = QTreeWidgetItem() + projTree._lastMove["parent"] = QTreeWidgetItem() + projTree._lastMove["index"] = 0 + assert projTree.undoLastMove() is False + + projTree._lastMove["item"] = projTree._treeMap[C.hTitlePage] + projTree._lastMove["parent"] = QTreeWidgetItem() + projTree._lastMove["index"] = 0 + assert projTree.undoLastMove() is False + + # Slot: _treeDoubleClick + # ====================== + + # Try to open a file with nothings selected + projTree.clearSelection() + projTree._treeDoubleClick(QTreeWidgetItem(), 0) + assert nwGUI.docEditor.docHandle() is None + + # When the item cannot be found + projTree._getTreeItem(C.hTitlePage).setSelected(True) + with monkeypatch.context() as mp: + mp.setattr("novelwriter.core.tree.NWTree.__getitem__", lambda *a: None) + projTree._treeDoubleClick(QTreeWidgetItem(), 0) + assert nwGUI.docEditor.docHandle() is None + + # Successfully open a file + projTree._treeDoubleClick(projTree._getTreeItem(C.hTitlePage), 0) + assert nwGUI.docEditor.docHandle() == C.hTitlePage + projTree._getTreeItem(C.hTitlePage).setSelected(False) + + # A non-file item should be expanded instead + projTree._getTreeItem(C.hNovelRoot).setExpanded(False) + projTree._getTreeItem(C.hNovelRoot).setSelected(True) + projTree._treeDoubleClick(projTree._getTreeItem(C.hNovelRoot), 1) + assert nwGUI.docEditor.docHandle() == C.hTitlePage + assert projTree._getTreeItem(C.hNovelRoot).isExpanded() is True + + # qtbot.stop() + +# END Test testGuiProjTree_Other diff --git a/tests/test_gui/test_gui_statusbar.py b/tests/test_gui/test_gui_statusbar.py index 0c6b1e81..6c99642f 100644 --- a/tests/test_gui/test_gui_statusbar.py +++ b/tests/test_gui/test_gui_statusbar.py @@ -22,12 +22,12 @@ along with this program. If not, see . import time import pytest -from tools import buildTestProject +from tools import C, buildTestProject from PyQt5.QtWidgets import QMessageBox -from novelwriter.core import NWDoc from novelwriter.enum import nwState +from novelwriter.core.document import NWDoc @pytest.mark.gui @@ -37,7 +37,7 @@ def testGuiStatusBar_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): monkeypatch.setattr(QMessageBox, "question", lambda *a: QMessageBox.Yes) buildTestProject(nwGUI, fncProj) - cHandle = nwGUI.theProject.newFile("A Note", "000000000000a") + cHandle = nwGUI.theProject.newFile("A Note", C.hCharRoot) newDoc = NWDoc(nwGUI.theProject, cHandle) newDoc.writeDocument("# A Note\n\n") nwGUI.projView.revealNewTreeItem(cHandle) @@ -45,57 +45,57 @@ def testGuiStatusBar_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): # Reference Time refTime = time.time() - nwGUI.statusBar.setRefTime(refTime) - assert nwGUI.statusBar.refTime == refTime + nwGUI.mainStatus.setRefTime(refTime) + assert nwGUI.mainStatus.refTime == refTime # Project Status - nwGUI.statusBar.setProjectStatus(nwState.NONE) - assert nwGUI.statusBar.projIcon._theCol == nwGUI.statusBar.projIcon._colNone - nwGUI.statusBar.setProjectStatus(nwState.BAD) - assert nwGUI.statusBar.projIcon._theCol == nwGUI.statusBar.projIcon._colBad - nwGUI.statusBar.setProjectStatus(nwState.GOOD) - assert nwGUI.statusBar.projIcon._theCol == nwGUI.statusBar.projIcon._colGood + nwGUI.mainStatus.setProjectStatus(nwState.NONE) + assert nwGUI.mainStatus.projIcon._theCol == nwGUI.mainStatus.projIcon._colNone + nwGUI.mainStatus.setProjectStatus(nwState.BAD) + assert nwGUI.mainStatus.projIcon._theCol == nwGUI.mainStatus.projIcon._colBad + nwGUI.mainStatus.setProjectStatus(nwState.GOOD) + assert nwGUI.mainStatus.projIcon._theCol == nwGUI.mainStatus.projIcon._colGood # Document Status - nwGUI.statusBar.setDocumentStatus(nwState.NONE) - assert nwGUI.statusBar.docIcon._theCol == nwGUI.statusBar.docIcon._colNone - nwGUI.statusBar.setDocumentStatus(nwState.BAD) - assert nwGUI.statusBar.docIcon._theCol == nwGUI.statusBar.docIcon._colBad - nwGUI.statusBar.setDocumentStatus(nwState.GOOD) - assert nwGUI.statusBar.docIcon._theCol == nwGUI.statusBar.docIcon._colGood + nwGUI.mainStatus.setDocumentStatus(nwState.NONE) + assert nwGUI.mainStatus.docIcon._theCol == nwGUI.mainStatus.docIcon._colNone + nwGUI.mainStatus.setDocumentStatus(nwState.BAD) + assert nwGUI.mainStatus.docIcon._theCol == nwGUI.mainStatus.docIcon._colBad + nwGUI.mainStatus.setDocumentStatus(nwState.GOOD) + assert nwGUI.mainStatus.docIcon._theCol == nwGUI.mainStatus.docIcon._colGood # Idle Status - nwGUI.statusBar.mainConf.stopWhenIdle = False - nwGUI.statusBar.setUserIdle(True) - nwGUI.statusBar.updateTime() - assert nwGUI.statusBar.userIdle is False - assert nwGUI.statusBar.timeText.text() == "00:00:00" + nwGUI.mainStatus.mainConf.stopWhenIdle = False + nwGUI.mainStatus.setUserIdle(True) + nwGUI.mainStatus.updateTime() + assert nwGUI.mainStatus.userIdle is False + assert nwGUI.mainStatus.timeText.text() == "00:00:00" - nwGUI.statusBar.mainConf.stopWhenIdle = True - nwGUI.statusBar.setUserIdle(True) - nwGUI.statusBar.updateTime(5) - assert nwGUI.statusBar.userIdle is True - assert nwGUI.statusBar.timeText.text() != "00:00:00" + nwGUI.mainStatus.mainConf.stopWhenIdle = True + nwGUI.mainStatus.setUserIdle(True) + nwGUI.mainStatus.updateTime(5) + assert nwGUI.mainStatus.userIdle is True + assert nwGUI.mainStatus.timeText.text() != "00:00:00" - nwGUI.statusBar.setUserIdle(False) - nwGUI.statusBar.updateTime(5) - assert nwGUI.statusBar.userIdle is False - assert nwGUI.statusBar.timeText.text() != "00:00:00" + nwGUI.mainStatus.setUserIdle(False) + nwGUI.mainStatus.updateTime(5) + assert nwGUI.mainStatus.userIdle is False + assert nwGUI.mainStatus.timeText.text() != "00:00:00" # Language - nwGUI.statusBar.setLanguage("None", "None") - assert nwGUI.statusBar.langText.text() == "None" - nwGUI.statusBar.setLanguage("en", "None") - assert nwGUI.statusBar.langText.text() == "American English" + nwGUI.mainStatus.setLanguage("None", "None") + assert nwGUI.mainStatus.langText.text() == "None" + nwGUI.mainStatus.setLanguage("en", "None") + assert nwGUI.mainStatus.langText.text() == "American English" # Project Stats - nwGUI.statusBar.mainConf.incNotesWCount = False + nwGUI.mainStatus.mainConf.incNotesWCount = False nwGUI._updateStatusWordCount() - assert nwGUI.statusBar.statsText.text() == "Words: 9 (+9)" - nwGUI.statusBar.mainConf.incNotesWCount = True + assert nwGUI.mainStatus.statsText.text() == "Words: 9 (+9)" + nwGUI.mainStatus.mainConf.incNotesWCount = True nwGUI._updateStatusWordCount() - assert nwGUI.statusBar.statsText.text() == "Words: 11 (+11)" + assert nwGUI.mainStatus.statsText.text() == "Words: 11 (+11)" - # qtbot.stopForInteraction() + # qtbot.stop() # END Test testGuiStatusBar_Init diff --git a/tests/test_tools/test_tools_lipsum.py b/tests/test_tools/test_tools_lipsum.py index 629deb56..de70a428 100644 --- a/tests/test_tools/test_tools_lipsum.py +++ b/tests/test_tools/test_tools_lipsum.py @@ -21,7 +21,7 @@ along with this program. If not, see . import pytest -from tools import getGuiItem, buildTestProject +from tools import C, getGuiItem, buildTestProject from PyQt5.QtWidgets import QAction, QMessageBox @@ -41,7 +41,7 @@ def testToolLipsum_Main(qtbot, monkeypatch, nwGUI, fncProj, mockRnd): # Create a new project buildTestProject(nwGUI, fncProj) - assert nwGUI.openDocument("000000000000f") is True + assert nwGUI.openDocument(C.hSceneDoc) is True assert len(nwGUI.docEditor.getText()) == 15 # Open the tool diff --git a/tests/test_tools/test_tools_projwizard.py b/tests/test_tools/test_tools_projwizard.py index 8839964e..afe720ff 100644 --- a/tests/test_tools/test_tools_projwizard.py +++ b/tests/test_tools/test_tools_projwizard.py @@ -202,6 +202,14 @@ def testToolProjectWizard_Run(qtbot, monkeypatch, nwGUI, fncDir, prjType): assert isinstance(customPage, ProjWizardCustomPage) assert nwWiz.button(QWizard.NextButton).isEnabled() + # Make sure the fourth option is also turned off + customPage.addPlot.setChecked(False) + customPage.addChar.setChecked(False) + customPage.addWorld.setChecked(False) + customPage._syncSwitches() + assert not customPage.addNotes.isChecked() + + # Switch everything back on again customPage.addPlot.setChecked(True) customPage.addChar.setChecked(True) customPage.addWorld.setChecked(True) diff --git a/tests/tools.py b/tests/tools.py index fcdd3817..4744d472 100644 --- a/tests/tools.py +++ b/tests/tools.py @@ -28,6 +28,22 @@ from PyQt5.QtWidgets import qApp XML_IGNORE = ("> By Jane DOe <<\n") + aDoc.writeDocument("#! New Novel\n\n>> By Jane Doe <<\n") + theProject.index.reIndexHandle(xHandle[5]) aDoc = NWDoc(theProject, xHandle[7]) aDoc.writeDocument("## %s\n\n" % theProject.tr("New Chapter")) + theProject.index.reIndexHandle(xHandle[7]) aDoc = NWDoc(theProject, xHandle[8]) aDoc.writeDocument("### %s\n\n" % theProject.tr("New Scene")) + theProject.index.reIndexHandle(xHandle[8]) theProject.projOpened = time.time() theProject.setProjectChanged(True) @@ -172,6 +191,5 @@ def buildTestProject(theObject, projPath): if theGUI is not None: theGUI.hasProject = True theGUI.rebuildTrees() - theGUI.rebuildIndex(beQuiet=True) return