From b07509c1f66b2c91bab88a458b8aa7f739ee5f21 Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Sun, 11 Jul 2021 14:50:27 +0200 Subject: [PATCH 1/7] Fix pdf export when a locale is set --- .../import_export/pdf_plugin/pdf_exporter.py | 137 ++++++++++-------- 1 file changed, 78 insertions(+), 59 deletions(-) diff --git a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py index 523c8b05..47b5b3e8 100644 --- a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py +++ b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py @@ -1,28 +1,18 @@ import math import os.path -import re import tempfile -import types -import webbrowser import xml.sax.saxutils from gettext import ngettext from io import BytesIO +from typing import List, Optional, Tuple, Union -import reportlab -import reportlab.lib.colors as colors -import reportlab.lib.fonts as fonts -import reportlab.lib.pagesizes as pagesizes -import reportlab.lib.styles as styles -import reportlab.lib.units as units -import reportlab.platypus as platypus from gi.repository import Gtk +from reportlab import platypus +from reportlab.lib import colors, pagesizes, styles from reportlab.lib.units import inch, mm -from reportlab.pdfbase import pdfmetrics -from reportlab.pdfgen import canvas -from reportlab.platypus.flowables import ParagraphAndImage import gourmet.exporters.exporter as exporter -from gourmet import convert, gglobals, image_utils +from gourmet import convert, gglobals from gourmet.gtk_extras import cb_extras from gourmet.gtk_extras import dialog_extras as de from gourmet.gtk_extras import optionTable @@ -31,7 +21,16 @@ from .page_drawer import PageDrawer -DEFAULT_PDF_ARGS = {'bottom_margin': 72, 'pagesize': 'letter', 'right_margin': 72, 'top_margin': 72, 'left_margin': 72, 'pagemode': 'portrait', 'base_font_size': 10, 'mode': ('column', 1)} +DEFAULT_PDF_ARGS = { + 'bottom_margin': 72, + 'pagesize': 'letter', + 'right_margin': 72, + 'top_margin': 72, + 'left_margin': 72, + 'pagemode': 'portrait', + 'base_font_size': 10, + 'mode': ('column', 1) +} # Code for MCLine from: # http://two.pairlist.net/pipermail/reportlab-users/2005-February/003695.html @@ -217,7 +216,7 @@ def draw(self): class PdfWriter: - def __init__ (self, allrecs=[]): + def __init__ (self, allrecs=None): pass def setup_document (self, file, mode=('column',1), size='default', pagesize='letter', @@ -226,9 +225,9 @@ def setup_document (self, file, mode=('column',1), size='default', pagesize='let bottom_margin=inch, base_font_size=10 ): - frames = self.setup_frames(mode,size,pagesize,pagemode, - left_margin,right_margin,top_margin, - bottom_margin,base_font_size) + frames = self.setup_frames(mode, size,pagesize, pagemode, + left_margin, right_margin, top_margin, + bottom_margin, base_font_size) pt = platypus.PageTemplate(frames=frames) self.doc = platypus.BaseDocTemplate(file,pagesize=self.pagesize, pageTemplates=[pt],) @@ -240,24 +239,34 @@ def setup_document (self, file, mode=('column',1), size='default', pagesize='let self.scale_stylesheet(perc_scale) self.txt = [] - def setup_frames (self,mode=('column',1), size='default', pagesize='letter', - pagemode='portrait',left_margin=inch,right_margin=inch, - top_margin=inch, - bottom_margin=inch, - base_font_size=10): - if not isinstance(mode, tuple): - raise Exception("What is this mode! %s" % str(mode)) + def setup_frames(self, + mode: Optional[Tuple[str, int]] = None, + size: str = 'default', + pagesize: Union[str, Tuple] = 'LETTER', + pagemode: str = 'portrait', + left_margin: float = inch, + right_margin: float = inch, + top_margin: float = inch, + bottom_margin: float = inch, + base_font_size: Optional[int] = 10) -> List['Frame']: if isinstance(pagesize, str): - self.pagesize = getattr(pagesizes,pagemode)(getattr(pagesizes,pagesize)) + pagesize = getattr(pagesizes, pagesize) + + self.pagesize = getattr(pagesizes, pagemode)(pagesize) + self.margins = (left_margin, right_margin, top_margin, bottom_margin) + + if mode is not None: + mode, count = mode else: - self.pagesize = getattr(pagesizes,pagemode)(pagesize) - self.margins = (left_margin,right_margin,top_margin,bottom_margin) - if mode[0] == 'column': - frames = self.setup_column_frames(mode[1]) - elif mode[0] == 'index_cards': - frames = self.setup_multiple_index_cards(mode[1]) + mode, count = 'column', 1 + + if mode == 'column': + frames = self.setup_column_frames(count) + elif mode == 'index_cards': + frames = self.setup_multiple_index_cards(count) else: - raise Exception("WTF - mode = %s" % str(mode)) + raise ValueError(f'Expected mode to be "column" or "index_cards" ' + f'not {mode}') return frames def scale_stylesheet (self, perc): @@ -400,10 +409,13 @@ class PdfExporter (exporter.exporter_mult, PdfWriter): def __init__ (self, rd, r, out, doc=None, styleSheet=None, - txt=[], - pdf_args=DEFAULT_PDF_ARGS, - all_recipes=[], # For learning about references... + txt=None, + pdf_args=None, + all_recipes=None, # For learning about references... **kwargs): + txt = txt if txt is not None else [] + pdf_args = pdf_args if pdf_args is not None else DEFAULT_PDF_ARGS + all_recipes = all_recipes if all_recipes is not None else [] self.all_recipes = all_recipes PdfWriter.__init__(self) if isinstance(out, str): @@ -682,11 +694,11 @@ def write_footer (self): self.close() self.output_file.close() -class Sizer (PdfWriter): - def get_size (self, *args, **kwargs): +class Sizer(PdfWriter): + def get_size(self, *args, **kwargs): frames = self.setup_frames(*args,**kwargs) - return self.pagesize,frames + return self.pagesize, frames def get_pagesize_and_frames_for_widget (self, *args, **kwargs): ps,ff = self.get_size(*args,**kwargs) @@ -830,22 +842,20 @@ class PdfPrefGetter: 'B0':'B0','B1':'B1','B2':'B2','B3':'B3','B4':'B4','B5':'B5','B6':'B6', } - INDEX_CARDS = [(3.5*inch,5*inch),(4*inch,6*inch),(5*inch,8*inch),(74*mm,105*mm)] + INDEX_CARDS = [(3.5*inch, 5*inch), + (4*inch, 6*inch), + (5*inch, 8*inch), + (74*mm, 105*mm)] INDEX_CARD_LAYOUTS = [_('Index Cards (3.5x5)'), _('Index Cards (4x6)'), - _('Index Cards (A7)'), - ] - layouts = { - _('Plain'):('column',1), - _('Index Cards (3.5x5)'):('index_cards',(5*inch,3.5*inch)), - _('Index Cards (4x6)'):('index_cards',(6*inch,4*inch)), - _('Index Cards (A7)'):('index_cards',(105*mm,74*mm)), - } + _('Index Cards (A7)')] + layouts = {_('Plain'): ('column', 1), + _('Index Cards (3.5x5)'): ('index_cards', (5*inch, 3.5*inch)), + _('Index Cards (4x6)'): ('index_cards', (6*inch, 4*inch)), + _('Index Cards (A7)'): ('index_cards', (105*mm, 74*mm))} - page_modes = { - _('Portrait'):'portrait', - _('Landscape'):'landscape', - } + page_modes = {_('Portrait'): 'portrait', + _('Landscape'): 'landscape'} OPT_PS,OPT_PO,OPT_FS,OPT_PL,OPT_LM,OPT_RM,OPT_TM,OPT_BM = list(range(8)) @@ -911,15 +921,23 @@ def run (self): self.pd.run() return self.get_args_from_opts(self.opts) - def get_args_from_opts (self, opts): + def get_args_from_opts(self, opts): args = {} prefs = self.prefs.get('PDF_EXP', {}) - args['pagesize'] = self.page_sizes[opts[self.OPT_PS][1]] # PAGE SIZE + args['pagesize'] = self.page_sizes[opts[self.OPT_PS][1]] prefs['page_size'] = self.page_sizes_r[args['pagesize']] - args['pagemode'] = self.page_modes[opts[self.OPT_PO][1]] # PAGE MODE + + try: + mode = self.page_modes[opts[self.OPT_PO][-1]] + except KeyError: # the value was not set in the export dialog + mode = list(self.page_modes.items())[0][-1] + args['pagemode'] = mode + prefs['orientation'] = self.page_modes_r[args['pagemode']] - prefs['font_size'] = args['base_font_size'] = opts[self.OPT_FS][1] # FONT SIZE - args['mode'] = self.layouts[opts[self.OPT_PL][1]] # LAYOUT/MODE + + prefs['font_size'] = args['base_font_size'] = opts[self.OPT_FS][1] + + args['mode'] = self.layouts[opts[self.OPT_PL][1]] prefs['page_layout'] = self.layouts_r[args['mode']] prefs['left_margin'] = args['left_margin'] = opts[self.OPT_LM][1] prefs['right_margin'] = args['right_margin'] = opts[self.OPT_RM][1] @@ -1046,8 +1064,9 @@ def get_pdf_prefs (defaults=None): Gtk.main() raise Exception("Hell") - from tempfile import tempdir import os.path + from tempfile import tempdir + #opts = get_pdf_prefs(); print opts test_3_x_5() From 93bd237680f284866bb9a2d2eceb62a7c1f2b76d Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Sun, 11 Jul 2021 15:06:34 +0200 Subject: [PATCH 2/7] Clarify variable names --- .../nutritional_information/nutrition.py | 2 +- src/gourmet/reccard.py | 18 +++++++++--------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/gourmet/plugins/nutritional_information/nutrition.py b/src/gourmet/plugins/nutritional_information/nutrition.py index 38992cbb..34ca1180 100644 --- a/src/gourmet/plugins/nutritional_information/nutrition.py +++ b/src/gourmet/plugins/nutritional_information/nutrition.py @@ -71,7 +71,7 @@ def set_conversion (self, key, unit, factor): else: self.db.do_add(self.db.nutritionconversions_table,{'ingkey':key,'unit':unit,'factor':factor}) - def get_matches (self, key, max=50): + def get_matches(self, key, max=50): """Handed a string, get a list of likely USDA database matches. We return a list of lists: diff --git a/src/gourmet/reccard.py b/src/gourmet/reccard.py index 3ddf0010..9f4dbd55 100644 --- a/src/gourmet/reccard.py +++ b/src/gourmet/reccard.py @@ -33,20 +33,20 @@ from gourmet.plugins.clipboard_exporter import ClipboardExporter from gourmet.recindex import RecIndex -from .image_utils import load_pixbuf_from_resource - -def find_entry(w) -> Optional[Gtk.Entry]: - if isinstance(w, Gtk.Entry): - return w +def find_entry(widget) -> Optional[Gtk.Entry]: + """Recurse through all the children widgets to find the first Gtk.Entry.""" + if isinstance(widget, Gtk.Entry): + return widget else: - if not hasattr(w,'get_children'): + if not hasattr(widget, 'get_children'): return - for child in w.get_children(): + for child in widget.get_children(): e = find_entry(child) if e is not None: return e + class RecRef: def __init__ (self, refid, title): self.refid = refid @@ -369,7 +369,7 @@ def reflow_on_allocate_cb (self, sw, allocation): # Main GUI setup def setup_main_window (self): self.window = Gtk.Window() - self.window.set_icon(load_pixbuf_from_resource('reccard.png')) + self.window.set_icon(iu.load_pixbuf_from_resource('reccard.png')) self.window.connect('delete-event',self.hide) self.conf.append(WidgetSaver.WindowSaver(self.window, self.prefs.get('reccard_window_%s'%self.current_rec.id, @@ -960,7 +960,7 @@ def show_module(self, module_name: str) -> None: def setup_main_interface (self): self.window = Gtk.Window() - self.window.set_icon(load_pixbuf_from_resource('reccard_edit.png')) + self.window.set_icon(iu.load_pixbuf_from_resource('reccard_edit.png')) title = ((self.current_rec and self.current_rec.title) or _('New Recipe')) + ' (%s)'%_('Edit') self.window.set_title(title) self.window.connect('delete-event', From 8762b0ca0964d13903eabdd846fec4c979ad0aa5 Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Mon, 12 Jul 2021 17:03:05 +0200 Subject: [PATCH 3/7] Store PDF export settings in locale-agnostic format --- .../import_export/pdf_plugin/pdf_exporter.py | 77 +++++++++++++------ 1 file changed, 53 insertions(+), 24 deletions(-) diff --git a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py index 47b5b3e8..f7e8eef8 100644 --- a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py +++ b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py @@ -4,7 +4,7 @@ import xml.sax.saxutils from gettext import ngettext from io import BytesIO -from typing import List, Optional, Tuple, Union +from typing import Dict, List, Optional, Tuple, Union from gi.repository import Gtk from reportlab import platypus @@ -829,6 +829,7 @@ def change_cb (other_cuo): self.__quiet__ = False cuo.connect('changed',change_cb) + class PdfPrefGetter: page_sizes = { _('11x17"'):'elevenSeventeen', @@ -854,6 +855,15 @@ class PdfPrefGetter: _('Index Cards (4x6)'): ('index_cards', (6*inch, 4*inch)), _('Index Cards (A7)'): ('index_cards', (105*mm, 74*mm))} + # These two dictionaries are here to be able to store the preferences in the persistent toml file. + # This allows us to have a locale-agnostic GUI. + _layouts_to_settings = {_('Plain'): 'plain', + _('Index Cards (3.5x5)'): 'index_cards_35_5', + _('Index Cards (4x6)'): 'index_cards_4_6', + _('Index Cards (A7)'): 'a7'} + + _settings_to_layout = {v: k for k, v in _layouts_to_settings.items()} + page_modes = {_('Portrait'): 'portrait', _('Landscape'): 'landscape'} @@ -879,19 +889,36 @@ def __init__(self): if mm is not m: m.sync_to_other_cuo(mm) - self.opts = [ - [_('Paper _Size')+':',(defaults.get('page_size',PDF_PREF_DEFAULT['page_size']), - self.size_strings)], - [_('_Orientation')+':',(defaults.get('orientation',PDF_PREF_DEFAULT['orientation']), - list(self.page_modes.keys()))], - [_('_Font Size')+':',int(defaults.get('font_size',PDF_PREF_DEFAULT['font_size']))], - [_('Page _Layout'),(defaults.get('page_layout',PDF_PREF_DEFAULT['page_layout']), - self.layout_strings)], - [_('Left Margin')+':',margin_widgets[0]], - [_('Right Margin')+':',margin_widgets[1]], - [_('Top Margin')+':',margin_widgets[2]], - [_('Bottom Margin')+':',margin_widgets[3]], - ] + default_page_size = defaults.get('page_size', + PDF_PREF_DEFAULT['page_size']) + default_page_size = self.page_sizes_r[default_page_size] + page_size = [_('Paper _Size')+':', + (default_page_size, self.size_strings)] + + default_orientation = defaults.get('orientation', + PDF_PREF_DEFAULT['orientation']) + default_orientation = self.page_modes_r[default_orientation] + orientation = [_('_Orientation')+':', + (default_orientation, list(self.page_modes.keys()))] + + default_layout = defaults.get('page_layout', + PDF_PREF_DEFAULT['page_layout']) + default_layout = self._settings_to_layout[default_layout] + # default_layout = self.layouts_r[default_layout] + layout = [_('Page _Layout'), + (default_layout, self.layout_strings)] + + self.opts = ( + page_size, + orientation, + [_('_Font Size')+':', + int(defaults.get('font_size', PDF_PREF_DEFAULT['font_size']))], + layout, + [_('Left Margin')+':', margin_widgets[0]], + [_('Right Margin')+':', margin_widgets[1]], + [_('Top Margin')+':', margin_widgets[2]], + [_('Bottom Margin')+':', margin_widgets[3]], + ) self.page_drawer = PdfPageDrawer(yalign=0.0) self.in_ccb = False @@ -921,24 +948,26 @@ def run (self): self.pd.run() return self.get_args_from_opts(self.opts) - def get_args_from_opts(self, opts): + def get_args_from_opts(self, opts: Tuple[List]) -> Dict[str, Union[str, int, float]]: + """Get information from the dialog. + + As the information is retrieved from the dialog and converted into + system values, they are also saved to the persistent preferences. + """ args = {} prefs = self.prefs.get('PDF_EXP', {}) args['pagesize'] = self.page_sizes[opts[self.OPT_PS][1]] - prefs['page_size'] = self.page_sizes_r[args['pagesize']] - - try: - mode = self.page_modes[opts[self.OPT_PO][-1]] - except KeyError: # the value was not set in the export dialog - mode = list(self.page_modes.items())[0][-1] - args['pagemode'] = mode + prefs['page_size'] = args['pagesize'] - prefs['orientation'] = self.page_modes_r[args['pagemode']] + args['pagemode'] = self.page_modes[opts[self.OPT_PO][1]] + prefs['orientation'] = args['pagemode'] prefs['font_size'] = args['base_font_size'] = opts[self.OPT_FS][1] args['mode'] = self.layouts[opts[self.OPT_PL][1]] - prefs['page_layout'] = self.layouts_r[args['mode']] + layout = self.layouts_r[args['mode']] + layout = self._layouts_to_settings[layout] + prefs['page_layout'] = layout prefs['left_margin'] = args['left_margin'] = opts[self.OPT_LM][1] prefs['right_margin'] = args['right_margin'] = opts[self.OPT_RM][1] prefs['top_margin'] = args['top_margin'] = opts[self.OPT_TM][1] From a951f9c2c8656953718f394858b33f3d6b29c1b2 Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Mon, 12 Jul 2021 17:04:32 +0200 Subject: [PATCH 4/7] Remove not needed self.prefs attribute of PdfPrefGetter --- .../import_export/pdf_plugin/pdf_exporter.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py index f7e8eef8..333378cc 100644 --- a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py +++ b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py @@ -870,8 +870,6 @@ class PdfPrefGetter: OPT_PS,OPT_PO,OPT_FS,OPT_PL,OPT_LM,OPT_RM,OPT_TM,OPT_BM = list(range(8)) def __init__(self): - self.prefs = Prefs.instance() - defaults = self.prefs.get('PDF_EXP', PDF_PREF_DEFAULT) self.size_strings = list(self.page_sizes.keys()) self.size_strings.sort() for n in range(2,5): @@ -879,10 +877,12 @@ def __init__(self): self.make_reverse_dicts() self.layout_strings = list(self.layouts.keys()) self.layout_strings.sort() - margin_widgets = [ - CustomUnitOption(defaults.get(pref,PDF_PREF_DEFAULT[pref])) - for pref in ['left_margin','right_margin','top_margin','bottom_margin'] - ] + + defaults = Prefs.instance().get('PDF_EXP', PDF_PREF_DEFAULT) + + margin_widgets = [CustomUnitOption(defaults.get(pref, PDF_PREF_DEFAULT[pref])) + for pref in ['left_margin', 'right_margin', 'top_margin', 'bottom_margin'] + ] # Make unit changes to one widget affect all the others! for m in margin_widgets: for mm in margin_widgets: @@ -955,7 +955,7 @@ def get_args_from_opts(self, opts: Tuple[List]) -> Dict[str, Union[str, int, flo system values, they are also saved to the persistent preferences. """ args = {} - prefs = self.prefs.get('PDF_EXP', {}) + prefs = Prefs.instance().get('PDF_EXP', {}) args['pagesize'] = self.page_sizes[opts[self.OPT_PS][1]] prefs['page_size'] = args['pagesize'] From 5b495b7b6fbacd155f1f60aedfb51f4f1baa6efa Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Mon, 12 Jul 2021 17:05:13 +0200 Subject: [PATCH 5/7] Remove PdfPrefGetter.make_reverse_dicts function --- .../import_export/pdf_plugin/pdf_exporter.py | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py index 333378cc..dd67a614 100644 --- a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py +++ b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py @@ -874,7 +874,11 @@ def __init__(self): self.size_strings.sort() for n in range(2,5): self.layouts[ngettext('%s Column','%s Columns',n)%n]=('column',n) - self.make_reverse_dicts() + + self.page_sizes_r = {v: k for k, v in self.page_sizes.items()} + self.layouts_r = {v: k for k, v in self.layouts.items()} + self.page_modes_r = {v: k for k, v in self.page_modes.items()} + self.layout_strings = list(self.layouts.keys()) self.layout_strings.sort() @@ -928,14 +932,6 @@ def __init__(self): self.page_drawer.set_size_request(200,100) self.page_drawer.show() - def make_reverse_dicts (self): - self.page_sizes_r = {}; self.layouts_r = {}; self.page_modes_r = {} - for dict,dict_r in [ - (self.page_sizes,self.page_sizes_r), - (self.layouts,self.layouts_r), - (self.page_modes,self.page_modes_r)]: - for k,v in list(dict.items()): dict_r[v]=k - def setup_widgets (self): self.pd = de.PreferencesDialog(self.opts,option_label=None,value_label=None, label=_('PDF Options'), From 57c4e7b17f7ab1f225aeef40fd5657a8467e2d95 Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Mon, 12 Jul 2021 17:05:47 +0200 Subject: [PATCH 6/7] Flake PdfPrefGetter attributes definitions --- .../import_export/pdf_plugin/pdf_exporter.py | 64 +++++++++++-------- 1 file changed, 38 insertions(+), 26 deletions(-) diff --git a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py index dd67a614..caefba95 100644 --- a/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py +++ b/src/gourmet/plugins/import_export/pdf_plugin/pdf_exporter.py @@ -721,14 +721,14 @@ def set_page (self, *args, **kwargs): self.set_page_area(size[0],size[1],areas) PDF_PREF_DEFAULT={ - 'page_size':_('Letter'), - 'orientation':_('Portrait'), - 'font_size':10, - 'page_layout':_('Plain'), - 'left_margin':1.0*inch, - 'right_margin':1.0*inch, - 'top_margin':1.0*inch, - 'bottom_margin':1.0*inch, + 'page_size': 'letter', + 'orientation': 'portrait', + 'font_size': 10, + 'page_layout': 'plain', + 'left_margin': 1.0 * inch, + 'right_margin': 1.0 * inch, + 'top_margin': 1.0 * inch, + 'bottom_margin': 1.0 * inch, } class CustomUnitOption (optionTable.CustomOption): @@ -832,28 +832,40 @@ def change_cb (other_cuo): class PdfPrefGetter: page_sizes = { - _('11x17"'):'elevenSeventeen', - _('Index Card (3.5x5")'):(3.5*inch,5*inch), - _('Index Card (4x6")'):(4*inch,6*inch), - _('Index Card (5x8")'):(5*inch,8*inch), - _('Index Card (A7)'):(74*mm,105*mm), - _('Letter'):'letter', - _('Legal'):'legal', - 'A0':'A0','A1':'A1','A2':'A2','A3':'A3','A4':'A4','A5':'A5','A6':'A6', - 'B0':'B0','B1':'B1','B2':'B2','B3':'B3','B4':'B4','B5':'B5','B6':'B6', + _('11x17"'): 'elevenSeventeen', + _('Index Card (3.5x5")'): (3.5 * inch, 5 * inch), + _('Index Card (4x6")'): (4 * inch, 6 * inch), + _('Index Card (5x8")'): (5 * inch, 8 * inch), + _('Index Card (A7)'): (74 * mm, 105 * mm), + _('Letter'): 'letter', + _('Legal'): 'legal', + 'A0': 'A0', + 'A1': 'A1', + 'A2': 'A2', + 'A3': 'A3', + 'A4': 'A4', + 'A5': 'A5', + 'A6': 'A6', + 'B0': 'B0', + 'B1': 'B1', + 'B2': 'B2', + 'B3': 'B3', + 'B4': 'B4', + 'B5': 'B5', + 'B6': 'B6', } - INDEX_CARDS = [(3.5*inch, 5*inch), - (4*inch, 6*inch), - (5*inch, 8*inch), - (74*mm, 105*mm)] + INDEX_CARDS = [(3.5 * inch, 5 * inch), + (4 * inch, 6 * inch), + (5 * inch, 8 * inch), + (74 * mm, 105 * mm)] INDEX_CARD_LAYOUTS = [_('Index Cards (3.5x5)'), _('Index Cards (4x6)'), _('Index Cards (A7)')] layouts = {_('Plain'): ('column', 1), - _('Index Cards (3.5x5)'): ('index_cards', (5*inch, 3.5*inch)), - _('Index Cards (4x6)'): ('index_cards', (6*inch, 4*inch)), - _('Index Cards (A7)'): ('index_cards', (105*mm, 74*mm))} + _('Index Cards (3.5x5)'): ('index_cards', (5 * inch, 3.5 * inch)), + _('Index Cards (4x6)'): ('index_cards', (6 * inch, 4 * inch)), + _('Index Cards (A7)'): ('index_cards', (105 * mm, 74 * mm))} # These two dictionaries are here to be able to store the preferences in the persistent toml file. # This allows us to have a locale-agnostic GUI. @@ -867,7 +879,7 @@ class PdfPrefGetter: page_modes = {_('Portrait'): 'portrait', _('Landscape'): 'landscape'} - OPT_PS,OPT_PO,OPT_FS,OPT_PL,OPT_LM,OPT_RM,OPT_TM,OPT_BM = list(range(8)) + OPT_PS, OPT_PO, OPT_FS, OPT_PL, OPT_LM, OPT_RM, OPT_TM, OPT_BM = list(range(8)) def __init__(self): self.size_strings = list(self.page_sizes.keys()) @@ -970,7 +982,7 @@ def get_args_from_opts(self, opts: Tuple[List]) -> Dict[str, Union[str, int, flo prefs['bottom_margin'] = args['bottom_margin'] = opts[self.OPT_BM][1] return args - def change_cb (self, option_table, *args,**kwargs): + def change_cb(self, option_table, *args,**kwargs): if self.in_ccb: return self.in_ccb = True option_table.apply() From a1546f4f4606b8537ec2b89c6886a383bd849516 Mon Sep 17 00:00:00 2001 From: Cyril Danilevski Date: Mon, 12 Jul 2021 17:11:46 +0200 Subject: [PATCH 7/7] Add test for locale-agnostic PDF preferences --- .github/workflows/tests.yml | 2 +- tests/test_pdf_exporter.py | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/test_pdf_exporter.py diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 045cdfbf..661f6159 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -36,7 +36,7 @@ jobs: run: sudo pip3 install -r development.in - name: Test with pytest - run: xvfb-run -a pytest -vv tests/test_* + run: LANGUAGE=de_DE.utf-8 xvfb-run -a pytest -vv tests/test_* - name: Check imports ordering run: > diff --git a/tests/test_pdf_exporter.py b/tests/test_pdf_exporter.py new file mode 100644 index 00000000..32bba89c --- /dev/null +++ b/tests/test_pdf_exporter.py @@ -0,0 +1,32 @@ +"""This test may leave marks in the user preferences file.""" +import os +os.environ['LANGUAGE'] = 'de_DE.utf-8' # must happend before Gourmet import + +from gourmet.gglobals import gourmetdir +from gourmet.plugins.import_export.pdf_plugin.pdf_exporter import PdfPrefGetter # noqa: import not at top of file + +def test_get_args_from_opts(tmp_path): + gourmetdir = tmp_path + pref_getter = PdfPrefGetter() + + options = (['Papiergröße:', 'Letter'], + ['_Ausrichtung:', 'Hochformat'], + ['_Schriftgröße:', 10], + ['Seiten-Layout', 'Eben'], + ['Linker Rand:', 70.86614173228347], + ['Rechter Rand:', 70.86614173228347], + ['Oberer Rand:', 70.86614173228347], + ['Unterer Rand:', 70.86614173228347]) + + expected = {'pagesize': 'letter', + 'pagemode': 'portrait', + 'base_font_size': 10, + 'mode': ('column', 1), + 'left_margin': 70.86614173228347, + 'right_margin': 70.86614173228347, + 'top_margin': 70.86614173228347, + 'bottom_margin': 70.86614173228347} + + ret = pref_getter.get_args_from_opts(options) + + assert ret == expected