Gracefully handle non-UTF8 characters in xsane output

Thanks to Peter for the fix
This commit is contained in:
Piotr Chmura 2025-04-20 16:28:05 +10:00 committed by RunasSudo
parent df8c4042c4
commit dd0809b0eb
Signed by: RunasSudo
GPG Key ID: 7234E476BF21C61A
2 changed files with 17 additions and 21 deletions

1
CONTRIBUTORS Normal file
View File

@ -0,0 +1 @@
Piotr Chmura

View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# GIMP 3.0 plug-in for scanning via XSane # GIMP 3.0 plug-in for scanning via XSane
# Copyright (C) 2024-2025 Lee Yingtong Li (RunasSudo) # Copyright (C) 2024-2025 Lee Yingtong Li (RunasSudo) and CONTRIBUTORS
# #
# This program is free software: you can redistribute it and/or modify # 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 # it under the terms of the GNU General Public License as published by
@ -52,29 +52,24 @@ def xsanecli_run(procedure, config, run_data, *args):
args = ['xsane', '--save', '--no-mode-selection', '--force-filename', png_out, '--print-filenames'] + ([DEVICE_NAME] if DEVICE_NAME else []) args = ['xsane', '--save', '--no-mode-selection', '--force-filename', png_out, '--print-filenames'] + ([DEVICE_NAME] if DEVICE_NAME else [])
proc = subprocess.Popen(args, stdout=subprocess.PIPE, encoding='utf-8', env=xsane_env) proc = subprocess.Popen(args, stdout=subprocess.PIPE, encoding='utf-8', env=xsane_env)
while True: while proc.poll() is None:
# Wait until XSane prints the name of the scanned file, indicating scanning is finished # Wait until XSane prints the name of the scanned file, indicating scanning is finished
# This blocks Python but that is ok because GIMP UI is not affected # This blocks Python but that is ok because GIMP UI is not affected
result = proc.stdout.readline().strip() try:
result = proc.stdout.readline().strip()
except UnicodeDecodeError as e:
result = ''
if result == '': if result == 'XSANE_IMAGE_FILENAME: ' + png_out:
# XSane was closed # Open image
break image = Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, Gio.File.new_for_path(png_out))
Gimp.Display.new(image)
if result != 'XSANE_IMAGE_FILENAME: ' + png_out: # Remove temporary files
Gimp.message('Unexpected XSane result') os.unlink(png_out)
return Gimp.ValueArray.new_from_values([GObject.Value(Gimp.PDBStatusType, Gimp.PDBStatusType.EXECUTION_ERROR)])
# Open image if not SCAN_MULTIPLE:
image = Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, Gio.File.new_for_path(png_out)) proc.terminate()
Gimp.Display.new(image)
# Remove temporary files
os.unlink(png_out)
if not SCAN_MULTIPLE:
proc.terminate()
break
os.rmdir(tempdir) os.rmdir(tempdir)