Skip to content

Commit

Permalink
Fix build formatting and font handling (#1891)
Browse files Browse the repository at this point in the history
  • Loading branch information
vkbo committed May 23, 2024
2 parents e95d330 + 69b362b commit f92c22c
Show file tree
Hide file tree
Showing 36 changed files with 318 additions and 263 deletions.
2 changes: 2 additions & 0 deletions novelwriter/assets/icons/typicons_dark/icons.conf
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ fmt_strike-md = nw_tb-strike-md.svg
fmt_subscript = nw_tb-subscript.svg
fmt_superscript = nw_tb-superscript.svg
fmt_underline = nw_tb-underline.svg
font = nw_font.svg
forward = typ_chevron-right.svg
import = mixed_import.svg
list = typ_th-list.svg
Expand All @@ -78,6 +79,7 @@ proj_scene = mixed_document-scene.svg
proj_section = mixed_document-section.svg
proj_stats = typ_chart-bar-grey.svg
proj_title = mixed_document-title.svg
quote = nw_quote.svg
refresh = typ_refresh.svg
remove = typ_minus.svg
revert = typ_refresh-flipped.svg
Expand Down
4 changes: 4 additions & 0 deletions novelwriter/assets/icons/typicons_dark/nw_font.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions novelwriter/assets/icons/typicons_dark/nw_quote.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 2 additions & 0 deletions novelwriter/assets/icons/typicons_light/icons.conf
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ fmt_strike-md = nw_tb-strike-md.svg
fmt_subscript = nw_tb-subscript.svg
fmt_superscript = nw_tb-superscript.svg
fmt_underline = nw_tb-underline.svg
font = nw_font.svg
forward = typ_chevron-right.svg
import = mixed_import.svg
list = typ_th-list.svg
Expand All @@ -78,6 +79,7 @@ proj_scene = mixed_document-scene.svg
proj_section = mixed_document-section.svg
proj_stats = typ_chart-bar-grey.svg
proj_title = mixed_document-title.svg
quote = nw_quote.svg
refresh = typ_refresh.svg
remove = typ_minus.svg
revert = typ_refresh-flipped.svg
Expand Down
4 changes: 4 additions & 0 deletions novelwriter/assets/icons/typicons_light/nw_font.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions novelwriter/assets/icons/typicons_light/nw_quote.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 3 additions & 1 deletion novelwriter/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,9 @@ def describeFont(font: QFont) -> str:
"""Describe a font in a way that can be displayed on the GUI."""
if isinstance(font, QFont):
info = QFontInfo(font)
return f"{font.family()} {info.styleName()} @ {font.pointSize()} pt"
family = info.family()
styles = [v for v in info.styleName().split() if v not in family]
return " ".join([f"{info.pointSize()} pt", family] + styles)
return "Error"


Expand Down
3 changes: 3 additions & 0 deletions novelwriter/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@ def __init__(self) -> None:
self.hideVScroll = False # Hide vertical scroll bars on main widgets
self.hideHScroll = False # Hide horizontal scroll bars on main widgets
self.lastNotes = "0x0" # The latest release notes that have been shown
self.nativeFont = True # Use native font dialog

# Size Settings
self._mainWinSize = [1200, 650] # Last size of the main GUI window
Expand Down Expand Up @@ -598,6 +599,7 @@ def loadConfig(self) -> bool:
self.hideVScroll = conf.rdBool(sec, "hidevscroll", self.hideVScroll)
self.hideHScroll = conf.rdBool(sec, "hidehscroll", self.hideHScroll)
self.lastNotes = conf.rdStr(sec, "lastnotes", self.lastNotes)
self.nativeFont = conf.rdBool(sec, "nativefont", self.nativeFont)
self._lastPath = conf.rdPath(sec, "lastpath", self._lastPath)

# Sizes
Expand Down Expand Up @@ -707,6 +709,7 @@ def saveConfig(self) -> bool:
"hidevscroll": str(self.hideVScroll),
"hidehscroll": str(self.hideHScroll),
"lastnotes": str(self.lastNotes),
"nativefont": str(self.nativeFont),
"lastpath": str(self._lastPath),
}

Expand Down
12 changes: 4 additions & 8 deletions novelwriter/core/buildsettings.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,12 +76,12 @@
"text.includeBodyText": (bool, True),
"text.ignoredKeywords": (str, ""),
"text.addNoteHeadings": (bool, True),
"format.textFont": (str, CONFIG.textFont.family()),
"format.textSize": (int, 12),
"format.textFont": (str, CONFIG.textFont.toString()),
"format.lineHeight": (float, 1.15, 0.75, 3.0),
"format.justifyText": (bool, False),
"format.stripUnicode": (bool, False),
"format.replaceTabs": (bool, False),
"format.keepBreaks": (bool, True),
"format.firstLineIndent": (bool, False),
"format.firstIndentWidth": (float, 1.4),
"format.indentFirstPar": (bool, False),
Expand All @@ -96,7 +96,6 @@
"odt.addColours": (bool, True),
"odt.pageHeader": (str, nwHeadFmt.ODT_AUTO),
"odt.pageCountOffset": (int, 0),
"md.preserveBreaks": (bool, True),
"html.addStyles": (bool, True),
"html.preserveTabs": (bool, False),
}
Expand Down Expand Up @@ -125,13 +124,13 @@
"text.addNoteHeadings": QT_TRANSLATE_NOOP("Builds", "Add Titles for Notes"),

"format.grpFormat": QT_TRANSLATE_NOOP("Builds", "Text Format"),
"format.textFont": QT_TRANSLATE_NOOP("Builds", "Font Family"),
"format.textSize": QT_TRANSLATE_NOOP("Builds", "Font Size"),
"format.textFont": QT_TRANSLATE_NOOP("Builds", "Text Font"),
"format.lineHeight": QT_TRANSLATE_NOOP("Builds", "Line Height"),
"format.grpOptions": QT_TRANSLATE_NOOP("Builds", "Text Options"),
"format.justifyText": QT_TRANSLATE_NOOP("Builds", "Justify Text Margins"),
"format.stripUnicode": QT_TRANSLATE_NOOP("Builds", "Replace Unicode Characters"),
"format.replaceTabs": QT_TRANSLATE_NOOP("Builds", "Replace Tabs with Spaces"),
"format.keepBreaks": QT_TRANSLATE_NOOP("Builds", "Preserve Hard Line Breaks"),

"format.grpParIndent": QT_TRANSLATE_NOOP("Builds", "First Line Indent"),
"format.firstLineIndent": QT_TRANSLATE_NOOP("Builds", "Enable Indent"),
Expand All @@ -153,9 +152,6 @@
"odt.pageHeader": QT_TRANSLATE_NOOP("Builds", "Page Header"),
"odt.pageCountOffset": QT_TRANSLATE_NOOP("Builds", "Page Counter Offset"),

"md": QT_TRANSLATE_NOOP("Builds", "Markdown (.md)"),
"md.preserveBreaks": QT_TRANSLATE_NOOP("Builds", "Preserve Hard Line Breaks"),

"html": QT_TRANSLATE_NOOP("Builds", "HTML (.html)"),
"html.addStyles": QT_TRANSLATE_NOOP("Builds", "Add CSS Styles"),
"html.preserveTabs": QT_TRANSLATE_NOOP("Builds", "Preserve Tab Characters"),
Expand Down
22 changes: 6 additions & 16 deletions novelwriter/core/docbuild.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from collections.abc import Iterable
from pathlib import Path

from PyQt5.QtGui import QFont, QFontInfo
from PyQt5.QtGui import QFont

from novelwriter import CONFIG
from novelwriter.constants import nwLabels
Expand Down Expand Up @@ -216,16 +216,10 @@ def iterBuildMarkdown(self, path: Path, extendedMd: bool) -> Iterable[tuple[int,
makeObj = ToMarkdown(self._project)
filtered = self._setupBuild(makeObj)

if extendedMd:
makeObj.setExtendedMarkdown()
else:
makeObj.setStandardMarkdown()

makeObj.setExtendedMarkdown(extendedMd)
if self._build.getBool("format.replaceTabs"):
makeObj.replaceTabs(nSpaces=4, spaceChar=" ")

makeObj.setPreserveBreaks(self._build.getBool("md.preserveBreaks"))

for i, tHandle in enumerate(self._queue):
self._error = None
if filtered.get(tHandle, (False, 0))[0]:
Expand Down Expand Up @@ -285,13 +279,9 @@ def iterBuildNWD(self, path: Path | None, asJson: bool = False) -> Iterable[tupl
def _setupBuild(self, bldObj: Tokenizer) -> dict:
"""Configure the build object."""
# Get Settings
textFont = self._build.getStr("format.textFont")
textSize = self._build.getInt("format.textSize")

fontFamily = textFont or CONFIG.textFont.family()
bldFont = QFont(fontFamily, textSize)
fontInfo = QFontInfo(bldFont)
textFixed = fontInfo.fixedPitch()
textFont = QFont(CONFIG.textFont)
textFont.fromString(self._build.getStr("format.textFont"))
bldObj.setFont(textFont)

bldObj.setTitleFormat(
self._build.getStr("headings.fmtTitle"),
Expand Down Expand Up @@ -330,9 +320,9 @@ def _setupBuild(self, bldObj: Tokenizer) -> dict:
self._build.getBool("headings.breakScene")
)

bldObj.setFont(fontFamily, textSize, textFixed)
bldObj.setJustify(self._build.getBool("format.justifyText"))
bldObj.setLineHeight(self._build.getFloat("format.lineHeight"))
bldObj.setKeepLineBreaks(self._build.getBool("format.keepBreaks"))
bldObj.setFirstLineIndent(
self._build.getBool("format.firstLineIndent"),
self._build.getFloat("format.firstIndentWidth"),
Expand Down
13 changes: 11 additions & 2 deletions novelwriter/core/tohtml.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from novelwriter.constants import nwHeadFmt, nwHtmlUnicode, nwKeyWords, nwLabels
from novelwriter.core.project import NWProject
from novelwriter.core.tokenizer import T_Formats, Tokenizer, stripEscape
from novelwriter.types import FONT_STYLE, FONT_WEIGHTS

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -373,8 +374,16 @@ def getStyleSheet(self) -> list[str]:
mScale = self._lineHeight/1.15

styles = []
styles.append("body {{font-family: '{0:s}'; font-size: {1:d}pt;}}".format(
self._textFont, self._textSize
font = self._textFont
styles.append((
"body {{"
"font-family: '{0:s}'; font-size: {1:d}pt; "
"font-weight: {2:d}; font-style: {3:s};"
"}}"
).format(
font.family(), font.pointSize(),
FONT_WEIGHTS.get(font.weight(), 400),
FONT_STYLE.get(font.style(), "normal"),
))
styles.append((
"p {{"
Expand Down
11 changes: 4 additions & 7 deletions novelwriter/core/tokenizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from time import time

from PyQt5.QtCore import QCoreApplication, QRegularExpression
from PyQt5.QtGui import QFont

from novelwriter.common import checkInt, formatTimeStamp, numberToRoman
from novelwriter.constants import (
Expand Down Expand Up @@ -139,9 +140,7 @@ def __init__(self, project: NWProject) -> None:
self._markdown: list[str] = []

# User Settings
self._textFont = "Serif" # Output text font
self._textSize = 11 # Output text size
self._textFixed = False # Fixed width text
self._textFont = QFont("Serif", 11) # Output text font
self._lineHeight = 1.15 # Line height in units of em
self._blockIndent = 4.00 # Block indent in units of em
self._firstIndent = False # Enable first line indent
Expand Down Expand Up @@ -315,11 +314,9 @@ def setSceneStyle(self, center: bool, pageBreak: bool) -> None:
)
return

def setFont(self, family: str, size: int, isFixed: bool = False) -> None:
def setFont(self, font: QFont) -> None:
"""Set the build font."""
self._textFont = family
self._textSize = round(int(size))
self._textFixed = isFixed
self._textFont = font
return

def setLineHeight(self, height: float) -> None:
Expand Down
30 changes: 8 additions & 22 deletions novelwriter/core/tomarkdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,15 +81,11 @@ class ToMarkdown(Tokenizer):
supports concatenating novelWriter markup files.
"""

M_STD = 0 # Standard Markdown
M_EXT = 1 # Extended Markdown

def __init__(self, project: NWProject) -> None:
super().__init__(project)
self._genMode = self.M_STD
self._fullMD: list[str] = []
self._preserveBreaks = True
self._usedNotes: dict[str, int] = {}
self._extended = True
return

##
Expand All @@ -105,19 +101,9 @@ def fullMD(self) -> list[str]:
# Setters
##

def setStandardMarkdown(self) -> None:
"""Set the converter to use standard Markdown formatting."""
self._genMode = self.M_STD
return

def setExtendedMarkdown(self) -> None:
def setExtendedMarkdown(self, state: bool) -> None:
"""Set the converter to use Extended Markdown formatting."""
self._genMode = self.M_EXT
return

def setPreserveBreaks(self, state: bool) -> None:
"""Preserve line breaks in paragraphs."""
self._preserveBreaks = state
self._extended = state
return

##
Expand All @@ -132,12 +118,12 @@ def doConvert(self) -> None:
"""Convert the list of text tokens into a Markdown document."""
self._result = ""

if self._genMode == self.M_STD:
mTags = STD_MD
cSkip = ""
else:
if self._extended:
mTags = EXT_MD
cSkip = nwUnicode.U_MMSP
else:
mTags = STD_MD
cSkip = ""

lines = []
for tType, _, tText, tFormat, tStyle in self._tokens:
Expand Down Expand Up @@ -195,7 +181,7 @@ def doConvert(self) -> None:
def appendFootnotes(self) -> None:
"""Append the footnotes in the buffer."""
if self._usedNotes:
tags = STD_MD if self._genMode == self.M_STD else EXT_MD
tags = EXT_MD if self._extended else STD_MD
footnotes = self._localLookup("Footnotes")

lines = []
Expand Down
Loading

0 comments on commit f92c22c

Please sign in to comment.