miggor-StreamGraph/classes/util.gd

61 lines
2 KiB
GDScript3
Raw Normal View History

# (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 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 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)
## 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)