More pylint improvements

This commit is contained in:
Nick Hall 2016-06-03 23:46:23 +01:00
parent f049dca048
commit 306f3abd01
3 changed files with 126 additions and 106 deletions

View File

@ -23,25 +23,22 @@
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# #
#------------------------------------------------------------------------ """
# ACSII document generator.
# python modules """
#
#------------------------------------------------------------------------
import sys
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Gramps modules # Gramps modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.plug.docgen import (BaseDoc, TextDoc, from gramps.gen.plug.docgen import (BaseDoc, TextDoc,
PARA_ALIGN_RIGHT, PARA_ALIGN_CENTER) PARA_ALIGN_RIGHT, PARA_ALIGN_CENTER)
from gramps.gen.errors import ReportError from gramps.gen.errors import ReportError
from gramps.gen.plug.menu import NumberOption from gramps.gen.plug.menu import NumberOption
from gramps.gen.plug.report import DocOptions from gramps.gen.plug.report import DocOptions
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -133,9 +130,11 @@ def reformat_para(para='', left=0, right=72, just=LEFT, right_pad=0, first=0):
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
class AsciiDoc(BaseDoc, TextDoc): class AsciiDoc(BaseDoc, TextDoc):
"""
def __init__(self, styles, type, options=None): ASCII document generator.
BaseDoc.__init__(self, styles, type) """
def __init__(self, styles, paper_style, options=None):
BaseDoc.__init__(self, styles, paper_style)
self.__note_format = False self.__note_format = False
self._cpl = 72 # characters per line, in case the options are ignored self._cpl = 72 # characters per line, in case the options are ignored
@ -143,6 +142,22 @@ class AsciiDoc(BaseDoc, TextDoc):
menu = options.menu menu = options.menu
self._cpl = menu.get_option_by_name('linechars').get_value() self._cpl = menu.get_option_by_name('linechars').get_value()
self.file = None
self.filename = ''
self.text = ''
self.para = None
self.leader = None
self.tbl_style = None
self.in_cell = None
self.ncols = 0
self.cellpars = []
self.cell_lines = []
self.cell_widths = []
self.cellnum = -1
self.maxlines = 0
#-------------------------------------------------------------------- #--------------------------------------------------------------------
# #
# Opens the file, resets the text buffer. # Opens the file, resets the text buffer.
@ -155,7 +170,7 @@ class AsciiDoc(BaseDoc, TextDoc):
self.filename = filename self.filename = filename
try: try:
self.f = open(self.filename, "w", errors = 'backslashreplace') self.file = open(self.filename, "w", errors='backslashreplace')
except Exception as msg: except Exception as msg:
errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg) errmsg = "%s\n%s" % (_("Could not create %s") % self.filename, msg)
raise ReportError(errmsg) raise ReportError(errmsg)
@ -169,9 +184,12 @@ class AsciiDoc(BaseDoc, TextDoc):
# #
#-------------------------------------------------------------------- #--------------------------------------------------------------------
def close(self): def close(self):
self.f.close() self.file.close()
def get_usable_width(self): def get_usable_width(self):
"""
Return the usable width of the document in characters.
"""
return self._cpl return self._cpl
#-------------------------------------------------------------------- #--------------------------------------------------------------------
@ -180,7 +198,7 @@ class AsciiDoc(BaseDoc, TextDoc):
# #
#-------------------------------------------------------------------- #--------------------------------------------------------------------
def page_break(self): def page_break(self):
self.f.write('\012') self.file.write('\012')
def start_bold(self): def start_bold(self):
pass pass
@ -201,7 +219,7 @@ class AsciiDoc(BaseDoc, TextDoc):
#-------------------------------------------------------------------- #--------------------------------------------------------------------
def start_paragraph(self, style_name, leader=None): def start_paragraph(self, style_name, leader=None):
styles = self.get_style_sheet() styles = self.get_style_sheet()
self.p = styles.get_paragraph_style(style_name) self.para = styles.get_paragraph_style(style_name)
self.leader = leader self.leader = leader
#-------------------------------------------------------------------- #--------------------------------------------------------------------
@ -212,9 +230,9 @@ class AsciiDoc(BaseDoc, TextDoc):
# #
#-------------------------------------------------------------------- #--------------------------------------------------------------------
def end_paragraph(self): def end_paragraph(self):
if self.p.get_alignment() == PARA_ALIGN_RIGHT: if self.para.get_alignment() == PARA_ALIGN_RIGHT:
fmt = RIGHT fmt = RIGHT
elif self.p.get_alignment() == PARA_ALIGN_CENTER: elif self.para.get_alignment() == PARA_ALIGN_CENTER:
fmt = CENTER fmt = CENTER
else: else:
fmt = LEFT fmt = LEFT
@ -227,10 +245,10 @@ class AsciiDoc(BaseDoc, TextDoc):
# Compute indents in characters. Keep first_indent relative! # Compute indents in characters. Keep first_indent relative!
regular_indent = 0 regular_indent = 0
first_indent = 0 first_indent = 0
if self.p.get_left_margin(): if self.para.get_left_margin():
regular_indent = int(4*self.p.get_left_margin()) regular_indent = int(4*self.para.get_left_margin())
if self.p.get_first_indent(): if self.para.get_first_indent():
first_indent = int(4*self.p.get_first_indent()) first_indent = int(4*self.para.get_first_indent())
if self.in_cell and self.cellnum < self.ncols - 1: if self.in_cell and self.cellnum < self.ncols - 1:
right_pad = 1 right_pad = 1
@ -247,7 +265,8 @@ class AsciiDoc(BaseDoc, TextDoc):
# Do not reformat if preformatted notes # Do not reformat if preformatted notes
if not self.__note_format: if not self.__note_format:
self.leader += ' ' self.leader += ' '
start_at = regular_indent + min(len(self.leader)+first_indent, 0) start_at = regular_indent + min(len(self.leader)+first_indent,
0)
this_text = reformat_para(self.text, regular_indent, right, fmt, this_text = reformat_para(self.text, regular_indent, right, fmt,
right_pad) right_pad)
this_text = (' ' * (regular_indent+first_indent) + this_text = (' ' * (regular_indent+first_indent) +
@ -277,7 +296,7 @@ class AsciiDoc(BaseDoc, TextDoc):
if self.in_cell: if self.in_cell:
self.cellpars[self.cellnum] += this_text self.cellpars[self.cellnum] += this_text
else: else:
self.f.write(this_text) self.file.write(this_text)
self.text = "" self.text = ""
@ -312,10 +331,11 @@ class AsciiDoc(BaseDoc, TextDoc):
self.cell_widths = [0] * self.ncols self.cell_widths = [0] * self.ncols
self.cellnum = -1 self.cellnum = -1
self.maxlines = 0 self.maxlines = 0
table_width = self.get_usable_width() * self.tbl_style.get_width() / 100.0 table_width = (self.get_usable_width() *
self.tbl_style.get_width() / 100.0)
for cell in range(self.ncols): for cell in range(self.ncols):
self.cell_widths[cell] = int(table_width * self.cell_widths[cell] = int(
self.tbl_style.get_column_width(cell) / 100.0) table_width * self.tbl_style.get_column_width(cell) / 100.0)
#-------------------------------------------------------------------- #--------------------------------------------------------------------
# #
@ -337,8 +357,8 @@ class AsciiDoc(BaseDoc, TextDoc):
for line in range(self.maxlines): for line in range(self.maxlines):
for cell in range(self.ncols): for cell in range(self.ncols):
if self.cell_widths[cell]: if self.cell_widths[cell]:
self.f.write(cell_text[cell][line]) self.file.write(cell_text[cell][line])
self.f.write('\n') self.file.write('\n')
#-------------------------------------------------------------------- #--------------------------------------------------------------------
# #
@ -370,13 +390,13 @@ class AsciiDoc(BaseDoc, TextDoc):
if self.cell_lines[self.cellnum] > self.maxlines: if self.cell_lines[self.cellnum] > self.maxlines:
self.maxlines = self.cell_lines[self.cellnum] self.maxlines = self.cell_lines[self.cellnum]
def add_media(self, name, align, w_cm, h_cm, alt='', def add_media(self, name, align, w_cm, h_cm, alt='', style_name=None,
style_name=None, crop=None): crop=None):
this_text = '(photo)' this_text = '(photo)'
if self.in_cell: if self.in_cell:
self.cellpars[self.cellnum] += this_text self.cellpars[self.cellnum] += this_text
else: else:
self.f.write(this_text) self.file.write(this_text)
def write_styled_note(self, styledtext, format, style_name, def write_styled_note(self, styledtext, format, style_name,
contains_html=False, links=False): contains_html=False, links=False):

View File

@ -28,7 +28,15 @@
# Python modules # Python modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import sys import logging
#-------------------------------------------------------------------------
#
# GTK modules
#
#-------------------------------------------------------------------------
from gi.repository import Pango, PangoCairo
import cairo
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
@ -40,23 +48,14 @@ from gramps.gen.plug.docgen import INDEX_TYPE_ALP, INDEX_TYPE_TOC
from gramps.gen.errors import ReportError from gramps.gen.errors import ReportError
from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext _ = glocale.translation.gettext
from gramps.gen.constfunc import lin
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Set up logging # Set up logging
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import logging
LOG = logging.getLogger(".cairodoc") LOG = logging.getLogger(".cairodoc")
#-------------------------------------------------------------------------
#
# GTK modules
#
#-------------------------------------------------------------------------
from gi.repository import Pango, PangoCairo
import cairo
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Constants # Constants

View File

@ -31,33 +31,32 @@ Report output generator for html documents, based on Html and HtmlBackend
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# python modules # Python modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import os import os
import shutil import shutil
import time import logging
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Gramps modules # Gramps modules
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from gramps.gen.utils.image import resize_to_jpeg from gramps.gen.utils.image import resize_to_jpeg
from gramps.gen.const import DATA_DIR, IMAGE_DIR, PROGRAM_NAME, URL_HOMEPAGE from gramps.gen.const import DATA_DIR, IMAGE_DIR, PROGRAM_NAME, URL_HOMEPAGE
from gramps.version import VERSION from gramps.version import VERSION
from gramps.gen.plug.docgen import BaseDoc, TextDoc, FONT_SANS_SERIF, URL_PATTERN from gramps.gen.plug.docgen import BaseDoc, TextDoc, URL_PATTERN
from gramps.plugins.lib.libhtmlbackend import HtmlBackend, process_spaces from gramps.plugins.lib.libhtmlbackend import HtmlBackend, process_spaces
from gramps.plugins.lib.libhtml import Html from gramps.plugins.lib.libhtml import Html
from gramps.gen.const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
#------------------------------------------------------------------------ #------------------------------------------------------------------------
# #
# Set up logging # Set up logging
# #
#------------------------------------------------------------------------ #------------------------------------------------------------------------
import logging
LOG = logging.getLogger(".htmldoc") LOG = logging.getLogger(".htmldoc")
_TEXTDOCSCREEN = 'grampstextdoc.css' _TEXTDOCSCREEN = 'grampstextdoc.css'
@ -107,6 +106,7 @@ class HtmlDoc(BaseDoc, TextDoc):
self.__title_written = -1 # -1 = not written, 0 = writing, 1 = written self.__title_written = -1 # -1 = not written, 0 = writing, 1 = written
self.__link_attrs = {} # additional link attrs, eg {"style": "...", "class": "..."} self.__link_attrs = {} # additional link attrs, eg {"style": "...", "class": "..."}
self.use_table_headers = False # th, td self.use_table_headers = False # th, td
self.first_row = True
def set_css_filename(self, css_filename): def set_css_filename(self, css_filename):
""" """
@ -136,8 +136,8 @@ class HtmlDoc(BaseDoc, TextDoc):
""" """
# add additional meta tags and stylesheet links to head section # add additional meta tags and stylesheet links to head section
# create additional meta tags # create additional meta tags
_meta1 = 'name="generator" content="%s %s %s"' % (PROGRAM_NAME, _meta1 = 'name="generator" content="%s %s %s"' % (
VERSION, URL_HOMEPAGE) PROGRAM_NAME, VERSION, URL_HOMEPAGE)
meta = Html('meta', attr=_meta1) meta = Html('meta', attr=_meta1)
#set styles of the report as inline css #set styles of the report as inline css
@ -152,12 +152,11 @@ class HtmlDoc(BaseDoc, TextDoc):
# links for GRAMPS favicon and stylesheets # links for GRAMPS favicon and stylesheets
links = Html('link', rel='shortcut icon', href=fname1, links = Html('link', rel='shortcut icon', href=fname1,
type='image/x-icon') + ( type='image/x-icon') + (
Html('link', rel='stylesheet', href=fname2, type='text/css', Html('link', rel='stylesheet', href=fname2,
media='screen', indent=False),) type='text/css', media='screen', indent=False),)
if self.css_filename: if self.css_filename:
links += (Html('link', rel='stylesheet', href=fname3, links += (Html('link', rel='stylesheet', href=fname3,
type='text/css', media='screen', indent=False), type='text/css', media='screen', indent=False),)
)
self._backend.html_header += (meta, links) self._backend.html_header += (meta, links)
def build_style_declaration(self, id="grampstextdoc"): def build_style_declaration(self, id="grampstextdoc"):
@ -251,8 +250,8 @@ class HtmlDoc(BaseDoc, TextDoc):
def copy_file(self, from_fname, to_fname, to_dir=''): def copy_file(self, from_fname, to_fname, to_dir=''):
""" """
Copy a file from a source to a (report) destination. Copy a file from a source to a (report) destination. If to_dir is not
If to_dir is not present, then the destination directory will be created. present, then the destination directory will be created.
Normally 'to_fname' will be just a filename, without directory path. Normally 'to_fname' will be just a filename, without directory path.
@ -285,7 +284,8 @@ class HtmlDoc(BaseDoc, TextDoc):
Copy support files to the datadir that needs to hold them Copy support files to the datadir that needs to hold them
""" """
#css of textdoc styles #css of textdoc styles
with open(os.path.join(self._backend.datadirfull(), _TEXTDOCSCREEN), 'w') as tdfile: with open(os.path.join(self._backend.datadirfull(),
_TEXTDOCSCREEN), 'w') as tdfile:
tdfile.write(self.style_declaration) tdfile.write(self.style_declaration)
#css file #css file
if self.css_filename: if self.css_filename:
@ -317,7 +317,7 @@ class HtmlDoc(BaseDoc, TextDoc):
text = self._backend.ESCAPE_FUNC()(text) text = self._backend.ESCAPE_FUNC()(text)
if self.__title_written == 0: if self.__title_written == 0:
self.title += text self.title += text
if links == True: if links is True:
import re import re
text = re.sub(URL_PATTERN, _CLICKABLE, text) text = re.sub(URL_PATTERN, _CLICKABLE, text)
self.htmllist[-1] += text self.htmllist[-1] += text
@ -384,8 +384,7 @@ class HtmlDoc(BaseDoc, TextDoc):
tag = "td" tag = "td"
self._empty = 1 self._empty = 1
if span > 1: if span > 1:
self.htmllist += (Html(tag, colspan=str(span), self.htmllist += (Html(tag, colspan=str(span), class_=style_name),)
class_=style_name),)
self._col += span self._col += span
else: else:
self.htmllist += (Html(tag, colspan=str(span), self.htmllist += (Html(tag, colspan=str(span),
@ -506,7 +505,7 @@ class HtmlDoc(BaseDoc, TextDoc):
for line in markuptext.split('\n'): for line in markuptext.split('\n'):
[line, sigcount] = process_spaces(line, format) [line, sigcount] = process_spaces(line, format)
if sigcount == 0: if sigcount == 0:
if inpara == False: if inpara is False:
# needed for runs of three or more newlines # needed for runs of three or more newlines
self.start_paragraph(style_name) self.start_paragraph(style_name)
inpara = True inpara = True
@ -515,7 +514,7 @@ class HtmlDoc(BaseDoc, TextDoc):
inpara = False inpara = False
linenb = 1 linenb = 1
else: else:
if inpara == False: if inpara is False:
self.start_paragraph(style_name) self.start_paragraph(style_name)
inpara = True inpara = True
self._empty = 1 # para is empty self._empty = 1 # para is empty
@ -524,19 +523,20 @@ class HtmlDoc(BaseDoc, TextDoc):
self.__write_text(line, markup=True, links=links) self.__write_text(line, markup=True, links=links)
self._empty = 0 # para is not empty self._empty = 0 # para is not empty
linenb += 1 linenb += 1
if inpara == True: if inpara is True:
self.end_paragraph() self.end_paragraph()
if sigcount == 0: if sigcount == 0:
# if the last line was blank, then as well as outputting the previous para, # if the last line was blank, then as well as outputting the
# which we have just done, # previous para, which we have just done, we also output a new
# we also output a new blank para # blank para
self.start_paragraph(style_name) self.start_paragraph(style_name)
self._empty = 1 # para is empty self._empty = 1 # para is empty
self.end_paragraph() self.end_paragraph()
#end div element #end div element
self.__reduce_list() self.__reduce_list()
def add_media(self, name, pos, w_cm, h_cm, alt='', style_name=None, crop=None): def add_media(self, name, pos, w_cm, h_cm, alt='', style_name=None,
crop=None):
""" """
Overwrite base method Overwrite base method
""" """
@ -547,10 +547,11 @@ class HtmlDoc(BaseDoc, TextDoc):
imdir = self._backend.datadirfull() imdir = self._backend.datadirfull()
try: try:
resize_to_jpeg(name, imdir + os.sep + refname, size, size, crop=crop) resize_to_jpeg(name, imdir + os.sep + refname, size, size,
crop=crop)
except: except:
LOG.warn(_("Could not create jpeg version of image %(name)s") % LOG.warning(_("Could not create jpeg version of image %(name)s"),
{'name' : name}) name)
return return
if len(alt): if len(alt):
@ -568,11 +569,11 @@ class HtmlDoc(BaseDoc, TextDoc):
border='0', alt=alt) border='0', alt=alt)
else: else:
if len(alt): if len(alt):
self.htmllist[-1] += Html('div', style_="float: %s; padding: 5px; margin: 0;" % pos) + ( self.htmllist[-1] += Html(
Html('img', src= imdir + os.sep + refname, 'div', style_="float: %s; padding: 5px; margin: 0;" % pos
) + (Html('img', src=imdir + os.sep + refname,
border='0', alt=alt), border='0', alt=alt),
Html('p', class_="DDR-Caption") + alt Html('p', class_="DDR-Caption") + alt)
)
else: else:
self.htmllist[-1] += Html('img', src=imdir + os.sep + refname, self.htmllist[-1] += Html('img', src=imdir + os.sep + refname,
border='0', alt=alt, align=pos) border='0', alt=alt, align=pos)