fallback to timg if chafa fails to load an image

This commit is contained in:
Ploum 2023-12-22 18:50:03 +01:00
parent 426161e35d
commit 6d7c45188f
2 changed files with 25 additions and 16 deletions

View File

@ -5,6 +5,7 @@
- netcache : solve an infinite gemini loop with code 6X (see also bug #31)
- ansicat: added support for <video> HTML-element
- ansicat: if chafa fails to load an image, fallback to timg is available
## 2.1 - December 15th 2023
- freshly updated gemtext/rss links are highlighted ("new_link" theme option)

View File

@ -106,7 +106,8 @@ def inline_image(img_file,width):
if not os.path.exists(img_file):
return ""
#Chafa is faster than timg inline. Let use that one by default
inline = None
#But we keep a list of "inlines" in case chafa fails
inlines = []
ansi_img = ""
#We avoid errors by not trying to render non-image files
if shutil.which("file"):
@ -120,32 +121,39 @@ def inline_image(img_file,width):
if hasattr(img_obj,"n_frames") and img_obj.n_frames > 1:
# we remove all frames but the first one
img_obj.save(img_file,format="gif",save_all=False)
inline = "chafa --bg white -s %s -f symbols"
inlines.append("chafa --bg white -s %s -f symbols")
elif _NEW_CHAFA:
inline = "chafa --bg white -t 1 -s %s -f symbols --animate=off"
if not inline and _NEW_TIMG:
inline = "timg --frames=1 -p q -g %sx1000"
if inline:
cmd = inline%width + " %s"
inlines.append("chafa --bg white -t 1 -s %s -f symbols --animate=off")
if _NEW_TIMG:
inlines.append("timg --frames=1 -p q -g %sx1000")
image_success = False
while not image_success and len(inlines)>0:
cmd = inlines.pop(0)%width + " %s"
try:
ansi_img = run(cmd, parameter=img_file)
image_succes = True
except Exception as err:
ansi_img = "***IMAGE ERROR: wrong or undisplayable picture***\n" %err
ansi_img = "***IMAGE ERROR***\n%s\n%s" %(str(err)[:50],str(err)[-50:])
return ansi_img
def terminal_image(img_file):
#Render by timg is better than old chafa.
# it is also centered
cmd = None
cmds = []
if _NEW_CHAFA:
cmd = "chafa -C on -d 0 --bg white -t 1 -w 1"
elif _NEW_TIMG:
cmd = "timg --loops=1 -C"
cmds.append("chafa -C on -d 0 --bg white -t 1 -w 1")
elif _HAS_CHAFA:
cmd = "chafa -d 0 --bg white -t 1 -w 1"
if cmd:
cmd = cmd + " %s"
run(cmd, parameter=img_file, direct_output=True)
cmds.append("chafa -d 0 --bg white -t 1 -w 1")
if _NEW_TIMG:
cmds.append("timg --loops=1 -C")
image_success = False
while not image_success and len(cmds) > 0:
cmd = cmds.pop(0) + " %s"
try:
run(cmd, parameter=img_file, direct_output=True)
image_success = True
except Exception as err:
print(err)
# First, we define the different content->text renderers, outside of the rest