FAbrowser/scripts/URLImage.gd
2024-07-22 11:06:25 -04:00

78 lines
2.4 KiB
GDScript

extends TextureRect
class_name URLRect
# script to make TextureRect load and display thumbnail of image on FA.
# and cache it
var http = HTTPRequest.new()
export var url:String = "" #the image url should not start empty
var requested:bool = false
var loaded:bool = false
var lock_aspect_ratio:bool = false
var img:Image
export var ignore_global_busy:bool = false
signal image_scaled
func _ready():
add_child(http)
http.connect("request_completed",self,"complete")
func _process(delta):
# if not loaded and not Global.busy and not url.empty():
if not url.empty() and not requested:
var c = File.new()
var cache_dir = Global.cache_dir+url.md5_text()
if c.file_exists(cache_dir):
c.open(cache_dir,File.READ)
complete(0,0,[],c.get_buffer(c.get_len()),true)
c.close()
requested = true
elif not requested and (ignore_global_busy or Global.busy < 3):
texture = preload("res://loading.png")
Global.busy += 1
http.request(url)
requested = true
# Global.busy = true
if lock_aspect_ratio and loaded:
rect_min_size.x = rect_min_size.y * (float(img.get_width()) / float(img.get_height()))
expand = true
func complete(result, response_code, headers, body:PoolByteArray, cached = false):
loaded = true
Global.stuff_loaded += 1
if not (cached or ignore_global_busy):
Global.busy -= 1
img = Image.new()
if result != 0:
printerr("Error fetching content " + url)
texture = preload("res://errorimg.png")
return
elif img.load_jpg_from_buffer(body) == 0 or img.load_png_from_buffer(body) == 0:
# print("Succesfully loaded " + url)
pass
else:
printerr("Error loading image from HTTP response " + url)
texture = preload("res://errorimg.png")
hint_tooltip = "Thumbnail file type is unspported."
return
var imgtex = ImageTexture.new()
imgtex.create_from_image(img,imgtex.FLAG_FILTER | imgtex.FLAG_MIPMAPS)
#imgtex.create_from_image(img,imgtex.FLAG_FILTER)
texture = imgtex
var parent = get_parent()
if parent is Button:
parent.icon = imgtex
queue_free()
# save cache
if not cached:
var c = File.new()
c.open(Global.cache_dir+url.md5_text(),File.WRITE)
c.store_buffer(body)
c.close()
# check if image is resized by FA and emit signal. only used in the SubViewer
if max(img.get_height(),img.get_width()) == 1280 or true:
# analyze file for metadata created by FA when resizing.
if body.subarray(33,39) == "gd-jpeg".to_ascii():
emit_signal("image_scaled")