miggor-StreamGraph/classes/util.gd
Lera Elvoé ac6ede2b41 make the default library group location be based on the executable location (#164)
closes #163

Reviewed-on: https://codeberg.org/StreamGraph/StreamGraph/pulls/164
Co-authored-by: Lera Elvoé <yagich@poto.cafe>
Co-committed-by: Lera Elvoé <yagich@poto.cafe>
2024-05-26 16:05:22 +00:00

67 lines
2.6 KiB
GDScript

# (c) 2023-present Eroax
# (c) 2023-present Yagich
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
class_name Util
## A class with commonly used methods.
static var _batches: Dictionary # Dictionary[StringName, BatchConnection]
## Connects the [param p_func] to [param p_signal] if that connection doesn't already exist.
static func safe_connect(p_signal: Signal, p_func: Callable) -> void:
if is_instance_valid(p_signal.get_object()) and is_instance_valid(p_func.get_object()) and not p_signal.is_null() and p_func.is_valid() and not p_signal.is_connected(p_func):
p_signal.connect(p_func)
## Disconnects the [param p_func] from [param p_signal] if that connection exists.
static func safe_disconnect(p_signal: Signal, p_func: Callable) -> void:
if is_instance_valid(p_signal.get_object()) and is_instance_valid(p_func.get_object()) and not p_signal.is_null() and p_func.is_valid() and p_signal.is_connected(p_func):
p_signal.disconnect(p_func)
## Returns a new [Util.BatchConnection] object.
static func batch_begin() -> BatchConnection:
return BatchConnection.new()
## Adds the [param batch] object to storage, to be retrieved later with [param key].
static func push_batch(batch: BatchConnection, key: StringName) -> void:
_batches[key] = batch
## Disconnects the signals in a batch connection stored at [param key]. See [method push_batch].
static func pop_batch(key: StringName) -> void:
var b: BatchConnection = _batches.get(key, null)
if not b:
return
b._pop()
_batches.erase(key)
## Customized version of [method ProjectSettings.globalize_path] that handles
## a [code]$PWD[/code] template which points to the current working folder.
static func globalize_path(path: String) -> String:
var pwd: String = ProjectSettings.globalize_path("res://").trim_suffix("/") if OS.has_feature("editor") else OS.get_executable_path().get_base_dir()
return path.format({"$PWD": pwd})
## An object representing multiple connections.
##
## Useful when there's a need to connect multiple signals in one operation, to be disconnected later.
class BatchConnection:
var _connections := {} # Dictionary[Signal, Array[Callable]]
## Add a new connection from [param p_signal] to [param p_func]. Uses [method Util.safe_connect].
func add(p_signal: Signal, p_func: Callable) -> void:
var arr: Array = _connections.get(p_signal, [])
arr.append(p_func)
_connections[p_signal] = arr
Util.safe_connect(p_signal, p_func)
func _pop() -> void:
for sig: Signal in _connections:
for f in _connections[sig]:
Util.safe_disconnect(sig, f)