Skip to content

Commit

Permalink
Minor refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Răzvan C. Rădulescu committed May 18, 2021
1 parent d732aad commit b20e8c7
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 49 deletions.
60 changes: 33 additions & 27 deletions project/PexelsQD/PexelsQD.gd
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
extends Control

const MESSAGES := {
const NOTIFICATIONS := {
"filesystem": "ERROR\nCan't open the config file!",
"search": "ERROR\nStopping! Search string has less than {0} letters."
"search": "ERROR\nStopping! Search string has less than {0} letters.",
"color": "{0} copied to clipboard."
}
const LAST := 3
const PB_COLORS := {
Expand All @@ -16,7 +17,14 @@ const PCNotification := preload("res://PexelsQD/PanelContainerNotification.tscn"
var _is_first := true
var _session: Session = null
var _tr_image_placeholder: StreamTexture = null
var _tween_funcs := {}
var _tr_image_alpha := {
true: 1,
false: 0.01
}
var _tween_funcs := {
true: "resume_all",
false: "stop_all"
}

onready var pc_intro: PanelContainer = $PanelContainerIntro
onready var tb_next: TextureButton = $PanelContainerIntro/CenterContainer/VBoxContainer/HBoxContainerControls/TextureButtonNext
Expand Down Expand Up @@ -47,9 +55,7 @@ func _ready() -> void:
var config_file := _load_config()
_session = Session.new(config_file, http_request)
_tr_image_placeholder = tr_image.texture
_tween_funcs[true] = funcref(tween, "start")
_tween_funcs[false] = funcref(tween, "stop_all")
MESSAGES.search = MESSAGES.search.format([Constants.MIN_SEARCH_LENGTH])
NOTIFICATIONS.search = NOTIFICATIONS.search.format([Constants.MIN_SEARCH_LENGTH])

pc_intro.connect("notified", self, "_notify")
tb_next.connect("pressed", vbc_main, "set_visible", [true])
Expand All @@ -76,7 +82,9 @@ func _ready() -> void:
pc_intro.setup(config_file)
rtl_help.bbcode_text = rtl_help.bbcode_text.format([Constants.DELTA])

var api_key: String = config_file.get_value(Constants.CONFIG_FILE.section, Constants.CONFIG_FILE.key, "")
var api_key: String = config_file.get_value(
Constants.CONFIG_FILE.section, Constants.CONFIG_FILE.key, ""
)
pc_intro.visible = api_key.empty()
vbc_main.visible = not pc_intro.visible

Expand All @@ -103,11 +111,8 @@ func _on_LineEditSearch_text_validated(new_text: String) -> void:


func _on_TextureButtonPlayPaused_toggled(is_button_pressed: bool) -> void:
_tween_funcs[is_button_pressed].call_func()
tr_image.modulate.a = 1 if is_button_pressed else 0.01
if _is_first:
_tween_funcs[true] = funcref(tween, "resume_all")
_is_first = not _is_first
tween.call(_tween_funcs[is_button_pressed])
tr_image.modulate.a = _tr_image_alpha[is_button_pressed]


func _on_TextureButtonStop_pressed() -> void:
Expand All @@ -122,36 +127,37 @@ func _on_TextureButtonStop_pressed() -> void:
func _on_PanelContainerInfoColorRect_gui_input(event: InputEvent) -> void:
if event.is_action_pressed("left_click"):
OS.clipboard = pc_info.html_color
_notify("{0} copied to clipboard!".format([OS.clipboard]))
_notify(NOTIFICATIONS.color.format([OS.clipboard]))


func _load_config() -> ConfigFile:
var config_file := ConfigFile.new()
if config_file.load(Constants.CONFIG_FILE.path) != OK:
if config_file.save(Constants.CONFIG_FILE.path) != OK:
emit_signal(MESSAGES.filesystem)
emit_signal(NOTIFICATIONS.filesystem)
return config_file


func _search() -> void:
if le_search.text.length() < Constants.MIN_SEARCH_LENGTH:
_notify(MESSAGES.search)
_notify(NOTIFICATIONS.search)
tb_stop.emit_signal("pressed")
return

var photo = yield(_session.search(le_search.text), "completed")
if not photo.has("error") and tb_play_pause.pressed:
tween.remove_all()
pc_info.refresh(photo)
tr_image.texture = photo.texture
pb.max_value = sb_time_input.value
tween.interpolate_property(pb, "value", pb.min_value, pb.max_value, sb_time_input.value)
tween.interpolate_property(pb, "modulate", PB_COLORS.begin, PB_COLORS.end, sb_time_input.value - LAST, Tween.TRANS_SINE, Tween.EASE_IN)
tween.interpolate_property(pb, "modulate", PB_COLORS.end, PB_COLORS.last, LAST, Tween.TRANS_LINEAR, Tween.EASE_IN, sb_time_input.value - LAST)
tween.start()
elif photo.has("error"):
_notify(photo.error)
tb_stop.emit_signal("pressed")
match [photo, tb_play_pause.pressed]:
[{"texture": var texture, ..}, true]:
tween.remove_all()
pc_info.refresh(photo)
tr_image.texture = texture
pb.max_value = sb_time_input.value
tween.interpolate_property(pb, "value", pb.min_value, pb.max_value, sb_time_input.value)
tween.interpolate_property(pb, "modulate", PB_COLORS.begin, PB_COLORS.end, sb_time_input.value - LAST, Tween.TRANS_SINE, Tween.EASE_IN)
tween.interpolate_property(pb, "modulate", PB_COLORS.end, PB_COLORS.last, LAST, Tween.TRANS_LINEAR, Tween.EASE_IN, sb_time_input.value - LAST)
tween.start()
[{"error": var error}, _]:
_notify(error)
tb_stop.emit_signal("pressed")


func _seek(delta: float, is_relative := true) -> void:
Expand Down
53 changes: 31 additions & 22 deletions project/PexelsQD/Session.gd
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
class_name Session

const MESSAGES := {
const NOTIFICATIONS := {
"http": "ERROR\nresult: {0}\nrequest_code: {1}\nbody: {3}",
"json": "ERROR\nerror: {0}\nerror_line: {1}\nerror_string: {2}",
"result": "ERROR\nerror: {0}",
"zero": "ERROR\nCouldn't find any results for `{0}`, please try a again!",
"unsupported": "ERROR\n Skipping! Fetched an unsupported image type from {0}.",
"unknown": "ERROR\n Something went wrong!"
"unsupported": "ERROR\nGot an unsupported image type from {0}.",
"unknown": "ERROR\nSomething went wrong!"
}
const PHOTO := {
"base_url": "https://api.pexels.com/v1",
Expand All @@ -24,12 +24,11 @@ var _rng := RandomNumberGenerator.new()
var _regex := RegEx.new()
var _total_results := 0
var _previous_query := ""
var _image := Image.new()
var _image_funcs := {
"jpg": funcref(_image, "load_jpg_from_buffer"),
"png": funcref(_image, "load_png_from_buffer"),
"tga": funcref(_image, "load_tga_from_buffer"),
"webp": funcref(_image, "load_webp_from_buffer")
"jpg": "load_jpg_from_buffer",
"png": "load_png_from_buffer",
"tga": "load_tga_from_buffer",
"webp": "load_webp_from_buffer"
}
var _config_file: ConfigFile = null
var _http_request: HTTPRequest = null
Expand All @@ -54,20 +53,22 @@ func search(query: String) -> Dictionary:
"page": 1 if is_first else _rng.randi_range(1, _total_results)
}

var api_key: String = _config_file.get_value(Constants.CONFIG_FILE.section, Constants.CONFIG_FILE.key, "")
var api_key: String = _config_file.get_value(
Constants.CONFIG_FILE.section, Constants.CONFIG_FILE.key, ""
)
PHOTO.headers[-1] = PHOTO.headers[-1].format({"api_key": api_key})
_http_request.request(PHOTO.search.format(params), PHOTO.headers)
var result: Array = yield(_http_request, "request_completed")
var ret: Array = yield(_http_request, "request_completed")

if result[0] != HTTPRequest.RESULT_SUCCESS or not result[1] in [HTTPClient.RESPONSE_OK, HTTPClient.RESPONSE_UNAUTHORIZED]:
return {"error": MESSAGES.http.format(result)}
if not _is_result_ok(ret[0], ret[1]):
return {"error": NOTIFICATIONS.http.format(ret)}

var body := JSON.parse(result[3].get_string_from_utf8())
var body := JSON.parse(ret[3].get_string_from_utf8())
if body.error != OK:
return {"error": MESSAGES.json.format([body.error, body.error_line, body.error_string])}
return {"error": NOTIFICATIONS.json.format([body.error, body.error_line, body.error_string])}

if body.result.has("error"):
return {"error": MESSAGES.result.format([body.result.error])}
return {"error": NOTIFICATIONS.result.format([body.result.error])}

if is_first:
_total_results = body.result.total_results
Expand All @@ -79,19 +80,27 @@ func search(query: String) -> Dictionary:
if regex_result != null:
var type := regex_result.get_string(1)
_http_request.request(src)
result = yield(_http_request, "request_completed")
ret = yield(_http_request, "request_completed")

if result[0] != HTTPRequest.RESULT_SUCCESS or not result[1] in [HTTPClient.RESPONSE_OK, HTTPClient.RESPONSE_UNAUTHORIZED]:
return {"error": MESSAGES.http.format(result)}
if not _is_result_ok(ret[0], ret[1]):
return {"error": NOTIFICATIONS.http.format(ret)}

_image_funcs[type].call_func(result[3])
var _image := Image.new()
_image.call(_image_funcs[type], ret[3])
photo.texture = ImageTexture.new()
photo.texture.create_from_image(_image)
return photo
else:
return {"error": MESSAGES.unsupported.format(src)}
return {"error": NOTIFICATIONS.unsupported.format(src)}
else:
return {"error": MESSAGES.zero.format([query])}
return {"error": NOTIFICATIONS.zero.format([query])}

# Function should never reach this code
return MESSAGES.unknown
return NOTIFICATIONS.unknown


static func _is_result_ok(result: int, response: int) -> bool:
return (
result == HTTPRequest.RESULT_SUCCESS
and response in [HTTPClient.RESPONSE_OK, HTTPClient.RESPONSE_UNAUTHORIZED]
)

0 comments on commit b20e8c7

Please sign in to comment.