Refactor signature path logic
Dieser Commit ist enthalten in:
Ursprung
17ccf8b527
Commit
bcc37b0929
1 geänderte Dateien mit 58 neuen und 51 gelöschten Zeilen
109
pdf-sign
109
pdf-sign
|
@ -65,41 +65,44 @@ def main(args):
|
||||||
return outFile
|
return outFile
|
||||||
pageSize=Cell(lambda: pdfGetSize(pagePDF()))
|
pageSize=Cell(lambda: pdfGetSize(pagePDF()))
|
||||||
# The chosen signature
|
# The chosen signature
|
||||||
if args.batch:
|
if args.signature:
|
||||||
if not args.signature and not args.text:
|
if args.text:
|
||||||
|
die('--signature and --text cannot be specified together.')
|
||||||
|
if not os.path.exists(args.signature):
|
||||||
|
die(f'File not found: {args.signature}')
|
||||||
|
signatures=[('file', args.signature, args.signature)]
|
||||||
|
elif args.batch:
|
||||||
|
assert not args.signature
|
||||||
|
if not args.text:
|
||||||
die('In batch mode, --signature or --text must be specified.')
|
die('In batch mode, --signature or --text must be specified.')
|
||||||
if args.text and len(args.text) > 1:
|
if len(args.text) > 1:
|
||||||
die('In batch mode, --text must be given only once.')
|
die('In batch mode, --text must be given only once.')
|
||||||
if args.signature and args.text:
|
validateText(args.text[0], True)
|
||||||
die('--signature and --text cannot be specified together.')
|
signatures=[('text', textLabel(args.text[0]), args.text[0])]
|
||||||
if args.signature and not os.path.exists(args.signature):
|
else:
|
||||||
die(f'File not found: {args.signature}')
|
(signatureDir, signatureDirHelp)=getSignatureDirAndHelp()
|
||||||
if args.text:
|
signatures=([('file', x, os.path.join(signatureDir, x))
|
||||||
assert(len(args.text) > 0)
|
for x in filter(isPdfFilename, os.listdir(signatureDir))]
|
||||||
latin1_chars=set([*range(0x20, 0x7f), *range(0xa0, 0x100)])
|
if signatureDir else [])
|
||||||
for text in args.text:
|
signatures.sort()
|
||||||
text_chars=set(map(ord, text))
|
if not signatures and not args.text:
|
||||||
if not text_chars.issubset(latin1_chars):
|
die('Could not find any usable signatures. No --signature, no --text, and ' +
|
||||||
die("Error: Only non-control latin-1 characters are supported in --text." +
|
('no .pdf files found in {signatureDir}.'
|
||||||
" Unsupported characters: " + ', '.join(map(hex, text_chars - latin1_chars)))
|
if signatureDir else
|
||||||
signatureDir=getSignatureDir()
|
f'no signature directory. The options considered for signature directory are: {signatureDirHelp}'))
|
||||||
signatures=[('file', x) for x in filter(isPdfFilename, os.listdir(signatureDir))] if not args.signature else [None]
|
if args.text:
|
||||||
if not signatures and not args.text:
|
assert(len(args.text) > 0)
|
||||||
die(f'Could not find anything usable as signature, since no .pdf files found in {signatureDir} and no --text option given.')
|
for text in args.text:
|
||||||
signatures.sort()
|
validateText(text, True)
|
||||||
if args.text:
|
signatures=[('text', textLabel(x), x) for x in args.text] + signatures
|
||||||
signatures=[('text', x) for x in args.text] + signatures
|
|
||||||
signatureIndex=Cell(0)
|
signatureIndex=Cell(0)
|
||||||
customText=Cell(('text', time.strftime('%Y-%m-%d')))
|
|
||||||
@Cell
|
@Cell
|
||||||
def signaturePath():
|
def signaturePath():
|
||||||
if args.signature:
|
(signType, _, content)=signatures[signatureIndex()]
|
||||||
return args.signature
|
|
||||||
(signType, content)=signatures[signatureIndex()]
|
|
||||||
if signType=='cell':
|
if signType=='cell':
|
||||||
(signType, content)=content()
|
(signType, _, content)=content()
|
||||||
if signType=='file':
|
if signType=='file':
|
||||||
return os.path.join(signatureDir, content)
|
return content
|
||||||
assert signType=='text'
|
assert signType=='text'
|
||||||
cache = signaturePath._cache
|
cache = signaturePath._cache
|
||||||
if content in cache:
|
if content in cache:
|
||||||
|
@ -220,6 +223,7 @@ def main(args):
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
die('Cannot find Python module `tkinter`, which is needed for interactive use.')
|
die('Cannot find Python module `tkinter`, which is needed for interactive use.')
|
||||||
doSign=False
|
doSign=False
|
||||||
|
customText=Cell(('text', None, time.strftime('%Y-%m-%d')))
|
||||||
customTextIndex = len(signatures)
|
customTextIndex = len(signatures)
|
||||||
# Commands
|
# Commands
|
||||||
def uf(fun):
|
def uf(fun):
|
||||||
|
@ -260,32 +264,25 @@ def main(args):
|
||||||
text = simpledialog.askstring(
|
text = simpledialog.askstring(
|
||||||
"Custom Text",
|
"Custom Text",
|
||||||
"Input the text you want to stamp this PDF file with",
|
"Input the text you want to stamp this PDF file with",
|
||||||
initialvalue=customText()[1])
|
initialvalue=customText()[2])
|
||||||
if text == None:
|
if text == None:
|
||||||
return
|
return
|
||||||
# Validate text
|
# Validate text
|
||||||
text_chars=set(map(ord, text))
|
validateMsg = validateText(text, False)
|
||||||
latin1_chars=set([*range(0x20, 0x7f), *range(0xa0, 0x100)])
|
if validateMsg:
|
||||||
if not text_chars.issubset(latin1_chars):
|
|
||||||
simpledialog.messagebox.showerror(
|
simpledialog.messagebox.showerror(
|
||||||
parent=root,
|
parent=root,
|
||||||
title="Invalid text",
|
title="Invalid text",
|
||||||
message=f"Only non-control latin-1 characters are supported. Unsupported characters: {', '.join(map(hex, text_chars - latin1_chars))}"
|
message=validateMsg
|
||||||
)
|
|
||||||
return
|
|
||||||
if not (1 <= len(text) and len(text) <= 100):
|
|
||||||
simpledialog.messagebox.showerror(
|
|
||||||
parent=root,
|
|
||||||
title="Invalid text",
|
|
||||||
message="Text must be between 1 and 100 characters long."
|
|
||||||
)
|
)
|
||||||
return
|
return
|
||||||
# Set text
|
# Set text
|
||||||
customText(('text', text))
|
customText(('text', None, text))
|
||||||
signatureIndex(customTextIndex)
|
signatureIndex(customTextIndex)
|
||||||
label='Custom text: ' + (text if len(text) <= 20 else (text[:17] + '...'))
|
label='Custom text: ' + textLabel(text)
|
||||||
placemenu.entryconfig(len(signatures) + 2, label=label)
|
placemenu.entryconfig(len(signatures) + 2, label=label)
|
||||||
update()
|
update()
|
||||||
|
def textLabel(text): return f'"{text}"' if len(text) <= 20 else f'Custom text: "{text[:17]}"...'
|
||||||
def cmd_abort():
|
def cmd_abort():
|
||||||
root.destroy()
|
root.destroy()
|
||||||
def cmd_sign():
|
def cmd_sign():
|
||||||
|
@ -323,18 +320,18 @@ def main(args):
|
||||||
if root.signatureControlVar.get() != signatureIndex():
|
if root.signatureControlVar.get() != signatureIndex():
|
||||||
signatureIndex(root.signatureControlVar.get())
|
signatureIndex(root.signatureControlVar.get())
|
||||||
update()
|
update()
|
||||||
for index, (_, signature) in enumerate(signatures):
|
for index, (_, signatureText, _) in enumerate(signatures):
|
||||||
placemenu.add_radiobutton(
|
placemenu.add_radiobutton(
|
||||||
value=index,
|
value=index,
|
||||||
label=f'{index+1}: {signature}',
|
label=f'{index+1}: {signatureText}',
|
||||||
underline=0 if index<9 else None,
|
underline=0 if index<9 else None,
|
||||||
variable=root.signatureControlVar,
|
variable=root.signatureControlVar,
|
||||||
accelerator=(str(index+1) if index<9 else None),
|
accelerator=(str(index+1) if index<9 else None),
|
||||||
command=updateFromSignatureRadio)
|
command=updateFromSignatureRadio)
|
||||||
signatures.append(('cell', customText))
|
signatures.append(('cell', None, customText))
|
||||||
placemenu.add_radiobutton(
|
placemenu.add_radiobutton(
|
||||||
value=customTextIndex,
|
value=customTextIndex,
|
||||||
label='Custom text: ' + customText()[1],
|
label='Custom text: ' + textLabel(customText()[2]),
|
||||||
underline=7,
|
underline=7,
|
||||||
variable=root.signatureControlVar,
|
variable=root.signatureControlVar,
|
||||||
accelerator='T',
|
accelerator='T',
|
||||||
|
@ -487,11 +484,21 @@ def qpdfOrPdftk(qpdfCmd, pdftkCmd):
|
||||||
subprocess.run(cmd, check=True)
|
subprocess.run(cmd, check=True)
|
||||||
return True # Some lambdas above rely on this
|
return True # Some lambdas above rely on this
|
||||||
|
|
||||||
def getSignatureDir():
|
def validateText(text, do_die):
|
||||||
(path, helptxt) = getSignatureDirAndHelp()
|
latin1_chars=set([*range(0x20, 0x7f), *range(0xa0, 0x100)])
|
||||||
if not path:
|
text_chars=set(map(ord, text))
|
||||||
die(f"Could not find a valid signature directory. The options considered are: {helptxt}")
|
msg = ""
|
||||||
return path
|
if not text_chars.issubset(latin1_chars):
|
||||||
|
msg = ("Error: Only non-control latin-1 characters are supported" +
|
||||||
|
(" in --text" if do_die else "") +
|
||||||
|
". Unsupported characters: " + ', '.join(map(hex, text_chars - latin1_chars)))
|
||||||
|
elif not (1 <= len(text) and len(text) <= 100):
|
||||||
|
msg = "Text must be between 1 and 100 characters long."
|
||||||
|
if not msg:
|
||||||
|
return None
|
||||||
|
if do_die:
|
||||||
|
die(msg)
|
||||||
|
return msg
|
||||||
|
|
||||||
def getSignatureDirAndHelp():
|
def getSignatureDirAndHelp():
|
||||||
def candidate(prevpath, prevhelptxt, nr, lbl, envvar, path):
|
def candidate(prevpath, prevhelptxt, nr, lbl, envvar, path):
|
||||||
|
|
Laden …
Tabelle hinzufügen
In neuem Issue referenzieren