diff --git a/.gitattributes b/.gitattributes
index 1f7887f..66e603c 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -25,3 +25,5 @@
/LICENSE export-ignore
/README.md export-ignore
/CODE_OF_CONDUCT.md export-ignore
+
+* text=auto eol=lf
diff --git a/.gutconfig.json b/.gutconfig.json
deleted file mode 100644
index 10b60bf..0000000
--- a/.gutconfig.json
+++ /dev/null
@@ -1,16 +0,0 @@
-{
- "dirs":["res://test/unit/"],
- "double_strategy":"partial",
- "ignore_pause":false,
- "include_subdirs":true,
- "inner_class":"",
- "log_level":3,
- "opacity":100,
- "prefix":"test_",
- "selected":"",
- "should_exit":true,
- "should_maximize":true,
- "suffix":".gd",
- "tests": [],
- "unit_test_name": ""
-}
diff --git a/README.md b/README.md
index 14d0278..e33b49d 100644
--- a/README.md
+++ b/README.md
@@ -14,11 +14,11 @@ godotnuts@gmail.com
The following individuals and many more have contributed significantly to this project. If you would like to support this project's further development, consider supporting them.
-- [Kyle Szklenski](https://github.com/WolfgangSenff) (creator) ([buy me a coffee](https://ko-fi.com/kyleszklenski))
-- [Nicolò Santilio](https://github.com/fenix-hub) (creator)
-- [Chuck Lindblom](https://github.com/BearDooks) (creator)
-- [SIsilicon](https://github.com/SISilicon) (creator)
-- [Luke Hollenback](https://github.com/lukehollenback) ([buy me a coffee](https://ko-fi.com/lukehollenback))
+- [Kyle Szklenski](https://github.com/WolfgangSenff) (creator - original, Database, Functions, several features) ([buy me a coffee](https://ko-fi.com/kyleszklenski))
+- [Nicolò Santilio](https://github.com/fenix-hub) (creator - Firestore, several features)
+- [Chuck Lindblom](https://github.com/BearDooks) (creator - several features across the board)
+- [SIsilicon](https://github.com/SISilicon) (creator - Firestore, a few other features)
+- [Luke Hollenback](https://github.com/lukehollenback) (unit testing) ([buy me a coffee](https://ko-fi.com/lukehollenback))
## :arrow_down: Cloning
SSH:
diff --git a/addons/godot-firebase/Utilities.gd b/addons/godot-firebase/Utilities.gd
new file mode 100644
index 0000000..d9ae3b5
--- /dev/null
+++ b/addons/godot-firebase/Utilities.gd
@@ -0,0 +1,346 @@
+extends Node
+class_name Utilities
+
+static func get_json_data(value):
+ if value is PackedByteArray:
+ value = value.get_string_from_utf8()
+ var json = JSON.new()
+ var json_parse_result = json.parse(value)
+ if json_parse_result == OK:
+ return json.data
+
+ return null
+
+
+# Pass a dictionary { 'key' : 'value' } to format it in a APIs usable .fields
+# Field Path3D using the "dot" (`.`) notation are supported:
+# ex. { "PATH.TO.SUBKEY" : "VALUE" } ==> { "PATH" : { "TO" : { "SUBKEY" : "VALUE" } } }
+static func dict2fields(dict : Dictionary) -> Dictionary:
+ var fields = {}
+ var var_type : String = ""
+ for field in dict.keys():
+ var field_value = dict[field]
+ if field is String and "." in field:
+ var keys: Array = field.split(".")
+ field = keys.pop_front()
+ keys.reverse()
+ for key in keys:
+ field_value = { key : field_value }
+
+ match typeof(field_value):
+ TYPE_NIL: var_type = "nullValue"
+ TYPE_BOOL: var_type = "booleanValue"
+ TYPE_INT: var_type = "integerValue"
+ TYPE_FLOAT: var_type = "doubleValue"
+ TYPE_STRING: var_type = "stringValue"
+ TYPE_DICTIONARY:
+ if is_field_timestamp(field_value):
+ var_type = "timestampValue"
+ field_value = dict2timestamp(field_value)
+ else:
+ var_type = "mapValue"
+ field_value = dict2fields(field_value)
+ TYPE_ARRAY:
+ var_type = "arrayValue"
+ field_value = {"values": array2fields(field_value)}
+
+ if fields.has(field) and fields[field].has("mapValue") and field_value.has("fields"):
+ for key in field_value["fields"].keys():
+ fields[field]["mapValue"]["fields"][key] = field_value["fields"][key]
+ else:
+ fields[field] = { var_type : field_value }
+
+ return {'fields' : fields}
+
+
+class FirebaseTypeConverter extends RefCounted:
+ var converters = {
+ "nullValue": _to_null,
+ "booleanValue": _to_bool,
+ "integerValue": _to_int,
+ "doubleValue": _to_float
+ }
+
+ func convert_value(type, value):
+ if converters.has(type):
+ return converters[type].call(value)
+
+ return value
+
+ func _to_null(value):
+ return null
+
+ func _to_bool(value):
+ return bool(value)
+
+ func _to_int(value):
+ return int(value)
+
+ func _to_float(value):
+ return float(value)
+
+static func from_firebase_type(value):
+ if value == null:
+ return null
+
+ if value.has("mapValue"):
+ value = fields2dict(value.values()[0])
+ elif value.has("arrayValue"):
+ value = fields2array(value.values()[0])
+ elif value.has("timestampValue"):
+ value = Time.get_datetime_dict_from_datetime_string(value.values()[0], false)
+ else:
+ var converter = FirebaseTypeConverter.new()
+ value = converter.convert_value(value.keys()[0], value.values()[0])
+
+ return value
+
+
+static func to_firebase_type(value : Variant) -> Dictionary:
+ var var_type : String = ""
+
+ match typeof(value):
+ TYPE_NIL: var_type = "nullValue"
+ TYPE_BOOL: var_type = "booleanValue"
+ TYPE_INT: var_type = "integerValue"
+ TYPE_FLOAT: var_type = "doubleValue"
+ TYPE_STRING: var_type = "stringValue"
+ TYPE_DICTIONARY:
+ if is_field_timestamp(value):
+ var_type = "timestampValue"
+ value = dict2timestamp(value)
+ else:
+ var_type = "mapValue"
+ value = dict2fields(value)
+ TYPE_ARRAY:
+ var_type = "arrayValue"
+ value = {"values": array2fields(value)}
+
+ return { var_type : value }
+
+# Pass the .fields inside a Firestore Document to print out the Dictionary { 'key' : 'value' }
+static func fields2dict(doc) -> Dictionary:
+ var dict = {}
+ if doc.has("fields"):
+ var fields = doc["fields"]
+
+ for field in fields.keys():
+ if fields[field].has("mapValue"):
+ dict[field] = (fields2dict(fields[field].mapValue))
+ elif fields[field].has("timestampValue"):
+ dict[field] = timestamp2dict(fields[field].timestampValue)
+ elif fields[field].has("arrayValue"):
+ dict[field] = fields2array(fields[field].arrayValue)
+ elif fields[field].has("integerValue"):
+ dict[field] = fields[field].values()[0] as int
+ elif fields[field].has("doubleValue"):
+ dict[field] = fields[field].values()[0] as float
+ elif fields[field].has("booleanValue"):
+ dict[field] = fields[field].values()[0] as bool
+ elif fields[field].has("nullValue"):
+ dict[field] = null
+ else:
+ dict[field] = fields[field].values()[0]
+ return dict
+
+# Pass an Array to parse it to a Firebase arrayValue
+static func array2fields(array : Array) -> Array:
+ var fields : Array = []
+ var var_type : String = ""
+ for field in array:
+ match typeof(field):
+ TYPE_DICTIONARY:
+ if is_field_timestamp(field):
+ var_type = "timestampValue"
+ field = dict2timestamp(field)
+ else:
+ var_type = "mapValue"
+ field = dict2fields(field)
+ TYPE_NIL: var_type = "nullValue"
+ TYPE_BOOL: var_type = "booleanValue"
+ TYPE_INT: var_type = "integerValue"
+ TYPE_FLOAT: var_type = "doubleValue"
+ TYPE_STRING: var_type = "stringValue"
+ TYPE_ARRAY: var_type = "arrayValue"
+ _: var_type = "FieldTransform"
+ fields.append({ var_type : field })
+ return fields
+
+# Pass a Firebase arrayValue Dictionary to convert it back to an Array
+static func fields2array(array : Dictionary) -> Array:
+ var fields : Array = []
+ if array.has("values"):
+ for field in array.values:
+ var item
+ match field.keys()[0]:
+ "mapValue":
+ item = fields2dict(field.mapValue)
+ "arrayValue":
+ item = fields2array(field.arrayValue)
+ "integerValue":
+ item = field.values()[0] as int
+ "doubleValue":
+ item = field.values()[0] as float
+ "booleanValue":
+ item = field.values()[0] as bool
+ "timestampValue":
+ item = timestamp2dict(field.timestampValue)
+ "nullValue":
+ item = null
+ _:
+ item = field.values()[0]
+ fields.append(item)
+ return fields
+
+# Converts a gdscript Dictionary (most likely obtained with Time.get_datetime_dict_from_system()) to a Firebase Timestamp
+static func dict2timestamp(dict : Dictionary) -> String:
+ #dict.erase('weekday')
+ #dict.erase('dst')
+ #var dict_values : Array = dict.values()
+ var time = Time.get_datetime_string_from_datetime_dict(dict, false)
+ return time
+ #return "%04d-%02d-%02dT%02d:%02d:%02d.00Z" % dict_values
+
+# Converts a Firebase Timestamp back to a gdscript Dictionary
+static func timestamp2dict(timestamp : String) -> Dictionary:
+ return Time.get_datetime_dict_from_datetime_string(timestamp, false)
+ #var datetime : Dictionary = {year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0}
+ #var dict : PackedStringArray = timestamp.split("T")[0].split("-")
+ #dict.append_array(timestamp.split("T")[1].split(":"))
+ #for value in dict.size():
+ #datetime[datetime.keys()[value]] = int(dict[value])
+ #return datetime
+
+static func is_field_timestamp(field : Dictionary) -> bool:
+ return field.has_all(['year','month','day','hour','minute','second'])
+
+
+# HTTPRequeust seems to have an issue in Web exports where the body returns empty
+# This appears to be caused by the gzip compression being unsupported, so we
+# disable it when web export is detected.
+static func fix_http_request(http_request):
+ if is_web():
+ http_request.accept_gzip = false
+
+static func is_web() -> bool:
+ return OS.get_name() in ["HTML5", "Web"]
+
+
+class MultiSignal extends RefCounted:
+ signal completed(with_signal)
+ signal all_completed()
+
+ var _has_signaled := false
+ var _early_exit := false
+
+ var signal_count := 0
+
+ func _init(sigs : Array[Signal], early_exit := true, should_oneshot := true) -> void:
+ _early_exit = early_exit
+ for sig in sigs:
+ add_signal(sig, should_oneshot)
+
+ func add_signal(sig : Signal, should_oneshot) -> void:
+ signal_count += 1
+ sig.connect(
+ func():
+ if not _has_signaled and _early_exit:
+ completed.emit(sig)
+ _has_signaled = true
+ elif not _early_exit:
+ completed.emit(sig)
+ signal_count -= 1
+ if signal_count <= 0: # Not sure how it could be less than
+ all_completed.emit()
+ , CONNECT_ONE_SHOT if should_oneshot else CONNECT_REFERENCE_COUNTED
+ )
+
+class SignalReducer extends RefCounted: # No need for a node, as this deals strictly with signals, which can be on any object.
+ signal completed
+
+ var awaiters : Array[Signal] = []
+
+ var reducers = {
+ 0 : func(): completed.emit(),
+ 1 : func(p): completed.emit(),
+ 2 : func(p1, p2): completed.emit(),
+ 3 : func(p1, p2, p3): completed.emit(),
+ 4 : func(p1, p2, p3, p4): completed.emit()
+ }
+
+ func add_signal(sig : Signal, param_count : int = 0) -> void:
+ assert(param_count < 5, "Too many parameters to reduce, just add more!")
+ sig.connect(reducers[param_count], CONNECT_ONE_SHOT) # May wish to not just one-shot, but instead track all of them firing
+
+class SignalReducerWithResult extends RefCounted: # No need for a node, as this deals strictly with signals, which can be on any object.
+ signal completed(result)
+
+ var awaiters : Array[Signal] = []
+
+ var reducers = {
+ 0 : func(): completed.emit(),
+ 1 : func(p): completed.emit({1 : p}),
+ 2 : func(p1, p2): completed.emit({ 1 : p1, 2 : p2 }),
+ 3 : func(p1, p2, p3): completed.emit({ 1 : p1, 2 : p2, 3 : p3 }),
+ 4 : func(p1, p2, p3, p4): completed.emit({ 1 : p1, 2 : p2, 3 : p3, 4 : p4 })
+ }
+
+ func add_signal(sig : Signal, param_count : int = 0) -> void:
+ assert(param_count < 5, "Too many parameters to reduce, just add more!")
+ sig.connect(reducers[param_count], CONNECT_ONE_SHOT) # May wish to not just one-shot, but instead track all of them firing
+
+class ObservableDictionary extends RefCounted:
+ signal keys_changed()
+
+ var _internal : Dictionary
+ var is_notifying := true
+
+ func _init(copy : Dictionary = {}) -> void:
+ _internal = copy
+
+ func add(key : Variant, value : Variant) -> void:
+ _internal[key] = value
+ if is_notifying:
+ keys_changed.emit()
+
+ func update(key : Variant, value : Variant) -> void:
+ _internal[key] = value
+ if is_notifying:
+ keys_changed.emit()
+
+ func has(key : Variant) -> bool:
+ return _internal.has(key)
+
+ func keys():
+ return _internal.keys()
+
+ func values():
+ return _internal.values()
+
+ func erase(key : Variant) -> bool:
+ var result = _internal.erase(key)
+ if is_notifying:
+ keys_changed.emit()
+
+ return result
+
+ func get_value(key : Variant) -> Variant:
+ return _internal[key]
+
+ func _get(property: StringName) -> Variant:
+ if _internal.has(property):
+ return _internal[property]
+
+ return false
+
+ func _set(property: StringName, value: Variant) -> bool:
+ update(property, value)
+ return true
+
+class AwaitDetachable extends Node2D:
+ var awaiter : Signal
+
+ func _init(freeable_node, await_signal : Signal) -> void:
+ awaiter = await_signal
+ add_child(freeable_node)
+ awaiter.connect(queue_free)
diff --git a/addons/godot-firebase/auth/auth.gd b/addons/godot-firebase/auth/auth.gd
index bf3d98b..8eefcef 100644
--- a/addons/godot-firebase/auth/auth.gd
+++ b/addons/godot-firebase/auth/auth.gd
@@ -2,13 +2,12 @@
## @meta-version 2.5
## The authentication API for Firebase.
## Documentation TODO.
-tool
+@tool
class_name FirebaseAuth
extends HTTPRequest
-
-const _API_VERSION: String = "v1"
-const _INAPP_PLUGIN: String = "GodotSvc"
+const _API_VERSION : String = "v1"
+const _INAPP_PLUGIN : String = "GodotSvc"
# Emitted for each Auth request issued.
# `result_code` -> Either `1` if auth succeeded or `error_code` if unsuccessful auth request
@@ -24,194 +23,203 @@ signal token_exchanged(successful)
signal token_refresh_succeeded(auth_result)
signal logged_out()
-const RESPONSE_SIGNUP: String = "identitytoolkit#SignupNewUserResponse"
-const RESPONSE_SIGNIN: String = "identitytoolkit#VerifyPasswordResponse"
-const RESPONSE_ASSERTION: String = "identitytoolkit#VerifyAssertionResponse"
-const RESPONSE_USERDATA: String = "identitytoolkit#GetAccountInfoResponse"
-const RESPONSE_CUSTOM_TOKEN: String = "identitytoolkit#VerifyCustomTokenResponse"
+const RESPONSE_SIGNUP : String = "identitytoolkit#SignupNewUserResponse"
+const RESPONSE_SIGNIN : String = "identitytoolkit#VerifyPasswordResponse"
+const RESPONSE_ASSERTION : String = "identitytoolkit#VerifyAssertionResponse"
+const RESPONSE_USERDATA : String = "identitytoolkit#GetAccountInfoResponse"
+const RESPONSE_CUSTOM_TOKEN : String = "identitytoolkit#VerifyCustomTokenResponse"
-var _base_url: String = ""
+var _base_url : String = ""
var _refresh_request_base_url = ""
-var _signup_request_url: String = "accounts:signUp?key=%s"
-var _signin_with_oauth_request_url: String = "accounts:signInWithIdp?key=%s"
-var _signin_request_url: String = "accounts:signInWithPassword?key=%s"
-var _signin_custom_token_url: String = "accounts:signInWithCustomToken?key=%s"
-var _userdata_request_url: String = "accounts:lookup?key=%s"
-var _oobcode_request_url: String = "accounts:sendOobCode?key=%s"
-var _delete_account_request_url: String = "accounts:delete?key=%s"
-var _update_account_request_url: String = "accounts:update?key=%s"
-
-var _refresh_request_url: String = "/v1/token?key=%s"
-var _google_auth_request_url: String = "https://accounts.google.com/o/oauth2/v2/auth?"
-
-var _config: Dictionary = {}
-var auth: Dictionary = {}
-var _needs_refresh: bool = false
-var is_busy: bool = false
-var has_child: bool = false
-
-var tcp_server: TCP_Server = TCP_Server.new()
-var tcp_timer: Timer = Timer.new()
-var tcp_timeout: float = 0.5
-
-var _headers: PoolStringArray = [
- "Content-Type: application/json",
- "Accept: application/json",
+var _signup_request_url : String = "accounts:signUp?key=%s"
+var _signin_with_oauth_request_url : String = "accounts:signInWithIdp?key=%s"
+var _signin_request_url : String = "accounts:signInWithPassword?key=%s"
+var _signin_custom_token_url : String = "accounts:signInWithCustomToken?key=%s"
+var _userdata_request_url : String = "accounts:lookup?key=%s"
+var _oobcode_request_url : String = "accounts:sendOobCode?key=%s"
+var _delete_account_request_url : String = "accounts:delete?key=%s"
+var _update_account_request_url : String = "accounts:update?key=%s"
+
+var _refresh_request_url : String = "/v1/token?key=%s"
+var _google_auth_request_url : String = "https://accounts.google.com/o/oauth2/v2/auth?"
+
+var _config : Dictionary = {}
+var auth : Dictionary = {}
+var _needs_refresh : bool = false
+var is_busy : bool = false
+var has_child : bool = false
+var is_oauth_login: bool = false
+
+
+var tcp_server : TCPServer = TCPServer.new()
+var tcp_timer : Timer = Timer.new()
+var tcp_timeout : float = 0.5
+
+var _headers : PackedStringArray = [
+ "Content-Type: application/json",
+ "Accept: application/json",
]
-var requesting: int = -1
+var requesting : int = -1
enum Requests {
- NONE = -1,
- EXCHANGE_TOKEN,
- LOGIN_WITH_OAUTH,
+ NONE = -1,
+ EXCHANGE_TOKEN,
+ LOGIN_WITH_OAUTH
}
-var auth_request_type: int = -1
+var auth_request_type : int = -1
enum Auth_Type {
- NONE = -1,
- LOGIN_EP,
- LOGIN_ANON,
- LOGIN_CT,
- LOGIN_OAUTH,
- SIGNUP_EP,
+ NONE = -1,
+ LOGIN_EP,
+ LOGIN_ANON,
+ LOGIN_CT,
+ LOGIN_OAUTH,
+ SIGNUP_EP
}
-var _login_request_body: Dictionary = {
- "email": "",
- "password": "",
- "returnSecureToken": true,
+var _login_request_body : Dictionary = {
+ "email":"",
+ "password":"",
+ "returnSecureToken": true,
}
-var _oauth_login_request_body: Dictionary = {
- "postBody": "",
- "requestUri": "",
- "returnIdpCredential": false,
- "returnSecureToken": true,
+var _oauth_login_request_body : Dictionary = {
+ "postBody":"",
+ "requestUri":"",
+ "returnIdpCredential":false,
+ "returnSecureToken":true
}
-var _anonymous_login_request_body: Dictionary = {
- "returnSecureToken": true,
+var _anonymous_login_request_body : Dictionary = {
+ "returnSecureToken":true
}
-var _refresh_request_body: Dictionary = {
- "grant_type": "refresh_token",
- "refresh_token": "",
+var _refresh_request_body : Dictionary = {
+ "grant_type":"refresh_token",
+ "refresh_token":"",
}
-var _custom_token_body: Dictionary = {
- "token": "",
- "returnSecureToken": true,
+var _custom_token_body : Dictionary = {
+ "token":"",
+ "returnSecureToken":true
}
-var _password_reset_body: Dictionary = {
- "requestType": "password_reset",
- "email": "",
+var _password_reset_body : Dictionary = {
+ "requestType":"password_reset",
+ "email":"",
}
-var _change_email_body: Dictionary = {
- "idToken": "",
- "email": "",
- "returnSecureToken": true,
-}
-var _change_password_body: Dictionary = {
- "idToken": "",
- "password": "",
- "returnSecureToken": true,
+var _change_email_body : Dictionary = {
+ "idToken":"",
+ "email":"",
+ "returnSecureToken": true,
}
-var _account_verification_body: Dictionary = {
- "requestType": "verify_email",
- "idToken": "",
+
+var _change_password_body : Dictionary = {
+ "idToken":"",
+ "password":"",
+ "returnSecureToken": true,
}
-var _update_profile_body: Dictionary = {
- "idToken": "",
- "displayName": "",
- "photoUrl": "",
- "deleteAttribute": "",
- "returnSecureToken": true,
+
+var _account_verification_body : Dictionary = {
+ "requestType":"verify_email",
+ "idToken":"",
}
-var _local_port: int = 8060
-var _local_uri: String = "http://localhost:%s/" % _local_port
-var _local_provider: AuthProvider = AuthProvider.new()
+var _update_profile_body : Dictionary = {
+ "idToken":"",
+ "displayName":"",
+ "photoUrl":"",
+ "deleteAttribute":"",
+ "returnSecureToken":true
+}
+
+var _local_port : int = 8060
+var _local_uri : String = "http://localhost:%s/"%_local_port
+var _local_provider : AuthProvider = AuthProvider.new()
func _ready() -> void:
- tcp_timer.wait_time = tcp_timeout
- tcp_timer.connect("timeout", self, "_tcp_stream_timer")
+ tcp_timer.wait_time = tcp_timeout
+ tcp_timer.timeout.connect(_tcp_stream_timer)
- if OS.get_name() == "HTML5":
- _local_uri += "tmp_js_export.html"
+ Utilities.fix_http_request(self)
+ if Utilities.is_web():
+ _local_uri += "tmp_js_export.html"
# Sets the configuration needed for the plugin to talk to Firebase
# These settings come from the Firebase.gd script automatically
-func _set_config(config_json: Dictionary) -> void:
- _config = config_json
- _signup_request_url %= _config.apiKey
- _signin_request_url %= _config.apiKey
- _signin_custom_token_url %= _config.apiKey
- _signin_with_oauth_request_url %= _config.apiKey
- _userdata_request_url %= _config.apiKey
- _refresh_request_url %= _config.apiKey
- _oobcode_request_url %= _config.apiKey
- _delete_account_request_url %= _config.apiKey
- _update_account_request_url %= _config.apiKey
-
- connect("request_completed", self, "_on_FirebaseAuth_request_completed")
- _check_emulating()
-
-
-func _check_emulating() -> void:
- ## Check emulating
- if not Firebase.emulating:
- _base_url = "https://identitytoolkit.googleapis.com/{version}/".format({version = _API_VERSION})
- _refresh_request_base_url = "https://securetoken.googleapis.com"
- else:
- var port: String = _config.emulators.ports.authentication
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Authentication has not been configured.")
- else:
- _base_url = "http://localhost:{port}/identitytoolkit.googleapis.com/{version}/".format({version = _API_VERSION, port = port})
- _refresh_request_base_url = "http://localhost:{port}/securetoken.googleapis.com".format({port = port})
+func _set_config(config_json : Dictionary) -> void:
+ _config = config_json
+ _signup_request_url %= _config.apiKey
+ _signin_request_url %= _config.apiKey
+ _signin_custom_token_url %= _config.apiKey
+ _signin_with_oauth_request_url %= _config.apiKey
+ _userdata_request_url %= _config.apiKey
+ _refresh_request_url %= _config.apiKey
+ _oobcode_request_url %= _config.apiKey
+ _delete_account_request_url %= _config.apiKey
+ _update_account_request_url %= _config.apiKey
+
+ request_completed.connect(_on_FirebaseAuth_request_completed)
+ _check_emulating()
+
+
+func _check_emulating() -> void :
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = "https://identitytoolkit.googleapis.com/{version}/".format({ version = _API_VERSION })
+ _refresh_request_base_url = "https://securetoken.googleapis.com"
+ else:
+ var port : String = _config.emulators.ports.authentication
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Authentication has not been configured.")
+ else:
+ _base_url = "http://localhost:{port}/identitytoolkit.googleapis.com/{version}/".format({ version = _API_VERSION ,port = port })
+ _refresh_request_base_url = "http://localhost:{port}/securetoken.googleapis.com".format({port = port})
# Function is used to check if the auth script is ready to process a request. Returns true if it is not currently processing
# If false it will print an error
func _is_ready() -> bool:
- if is_busy:
- Firebase._printerr("Firebase Auth is currently busy and cannot process this request")
- return false
- else:
- return true
-
+ if is_busy:
+ Firebase._printerr("Firebase Auth is currently busy and cannot process this request")
+ return false
+ else:
+ return true
# Function cleans the URI and replaces spaces with %20
# As of right now we only replace spaces
-# We may need to decide to use the percent_encode() String function
+# We may need to decide to use the uri_encode() String function
func _clean_url(_url):
- _url = _url.replace(" ", "%20")
- return _url
-
+ _url = _url.replace(' ','%20')
+ return _url
# Synchronous call to check if any user is already logged in.
func is_logged_in() -> bool:
- return auth != null and auth.has("idtoken")
+ return auth != null and auth.has("idtoken")
# Called with Firebase.Auth.signup_with_email_and_password(email, password)
# You must pass in the email and password to this function for it to work correctly
-func signup_with_email_and_password(email: String, password: String) -> void:
- if _is_ready():
- is_busy = true
- _login_request_body.email = email
- _login_request_body.password = password
- auth_request_type = Auth_Type.SIGNUP_EP
- request(_base_url + _signup_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_login_request_body))
+func signup_with_email_and_password(email : String, password : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _login_request_body.email = email
+ _login_request_body.password = password
+ auth_request_type = Auth_Type.SIGNUP_EP
+ var err = request(_base_url + _signup_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_login_request_body))
+ _login_request_body.email = ""
+ _login_request_body.password = ""
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error signing up with password and email: %s" % err)
# Called with Firebase.Auth.anonymous_login()
@@ -219,398 +227,448 @@ func signup_with_email_and_password(email: String, password: String) -> void:
# The response contains the Firebase ID token and refresh token associated with the anonymous user.
# The 'mail' field will be empty since no email is linked to an anonymous user
func login_anonymous() -> void:
- if _is_ready():
- is_busy = true
- auth_request_type = Auth_Type.LOGIN_ANON
- request(_base_url + _signup_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_anonymous_login_request_body))
-
+ if _is_ready():
+ is_busy = true
+ auth_request_type = Auth_Type.LOGIN_ANON
+ var err = request(_base_url + _signup_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_anonymous_login_request_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error logging in as anonymous: %s" % err)
# Called with Firebase.Auth.login_with_email_and_password(email, password)
# You must pass in the email and password to this function for it to work correctly
# If the login fails it will return an error code through the function _on_FirebaseAuth_request_completed
-func login_with_email_and_password(email: String, password: String) -> void:
- if _is_ready():
- is_busy = true
- _login_request_body.email = email
- _login_request_body.password = password
- auth_request_type = Auth_Type.LOGIN_EP
- request(_base_url + _signin_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_login_request_body))
-
+func login_with_email_and_password(email : String, password : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _login_request_body.email = email
+ _login_request_body.password = password
+ auth_request_type = Auth_Type.LOGIN_EP
+ var err = request(_base_url + _signin_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_login_request_body))
+ _login_request_body.email = ""
+ _login_request_body.password = ""
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error logging in with password and email: %s" % err)
# Login with a custom valid token
# The token needs to be generated using an external service/function
-func login_with_custom_token(token: String) -> void:
- if _is_ready():
- is_busy = true
- _custom_token_body.token = token
- auth_request_type = Auth_Type.LOGIN_CT
- request(_base_url + _signin_custom_token_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_custom_token_body))
-
+func login_with_custom_token(token : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _custom_token_body.token = token
+ auth_request_type = Auth_Type.LOGIN_CT
+ var err = request(_base_url + _signin_custom_token_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_custom_token_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error logging in with custom token: %s" % err)
# Open a web page in browser redirecting to Google oAuth2 page for the current project
# Once given user's authorization, a token will be generated.
# NOTE** the generated token will be automatically captured and a login request will be made if the token is correct
-func get_auth_localhost(provider: AuthProvider = get_GoogleProvider(), port: int = _local_port):
- get_auth_with_redirect(provider)
- yield(get_tree().create_timer(0.5),"timeout")
- if has_child == false:
- add_child(tcp_timer)
- has_child = true
- tcp_timer.start()
- tcp_server.listen(port, "*")
+func get_auth_localhost(provider: AuthProvider = get_GoogleProvider(), port : int = _local_port):
+ get_auth_with_redirect(provider)
+ await get_tree().create_timer(0.5).timeout
+ if has_child == false:
+ add_child(tcp_timer)
+ has_child = true
+ tcp_timer.start()
+ tcp_server.listen(port, "*")
func get_auth_with_redirect(provider: AuthProvider) -> void:
- var url_endpoint: String = provider.redirect_uri
- for key in provider.params.keys():
- url_endpoint += key + "=" + provider.params[key] + "&"
- url_endpoint += provider.params.redirect_type + "=" + _local_uri
- url_endpoint = _clean_url(url_endpoint)
- if OS.get_name() == "HTML5" and OS.has_feature("JavaScript"):
- JavaScript.eval('window.location.replace("' + url_endpoint + '")')
- elif Engine.has_singleton(_INAPP_PLUGIN) and OS.get_name() == "iOS":
- # in app for ios if the iOS plugin exists
- set_local_provider(provider)
- Engine.get_singleton(_INAPP_PLUGIN).popup(url_endpoint)
- else:
- set_local_provider(provider)
- OS.shell_open(url_endpoint)
- print(url_endpoint)
+ var url_endpoint: String = provider.redirect_uri
+ for key in provider.params.keys():
+ url_endpoint+=key+"="+provider.params[key]+"&"
+ url_endpoint += provider.params.redirect_type+"="+_local_uri
+ url_endpoint = _clean_url(url_endpoint)
+ if Utilities.is_web() and OS.has_feature("JavaScript"):
+ JavaScriptBridge.eval('window.location.replace("' + url_endpoint + '")')
+ elif Engine.has_singleton(_INAPP_PLUGIN) and OS.get_name() == "iOS":
+ #in app for ios if the iOS plugin exists
+ set_local_provider(provider)
+ Engine.get_singleton(_INAPP_PLUGIN).popup(url_endpoint)
+ else:
+ set_local_provider(provider)
+ OS.shell_open(url_endpoint)
# Login with Google oAuth2.
# A token is automatically obtained using an authorization code using @get_google_auth()
# @provider_id and @request_uri can be changed
func login_with_oauth(_token: String, provider: AuthProvider) -> void:
- var token: String = _token.percent_decode()
- print(token)
- var is_successful: bool = true
- if provider.should_exchange:
- exchange_token(token, _local_uri, provider.access_token_uri, provider.get_client_id(), provider.get_client_secret())
- is_successful = yield(self, "token_exchanged")
- token = auth.accesstoken
- if is_successful and _is_ready():
- is_busy = true
- _oauth_login_request_body.postBody = "access_token=" + token + "&providerId=" + provider.provider_id
- _oauth_login_request_body.requestUri = _local_uri
- requesting = Requests.LOGIN_WITH_OAUTH
- auth_request_type = Auth_Type.LOGIN_OAUTH
- request(_base_url + _signin_with_oauth_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_oauth_login_request_body))
-
+ if _token:
+ is_oauth_login = true
+ var token : String = _token.uri_decode()
+ var is_successful: bool = true
+ if provider.should_exchange:
+ exchange_token(token, _local_uri, provider.access_token_uri, provider.get_client_id(), provider.get_client_secret())
+ is_successful = await self.token_exchanged
+ token = auth.accesstoken
+ if is_successful and _is_ready():
+ is_busy = true
+ _oauth_login_request_body.postBody = "access_token="+token+"&providerId="+provider.provider_id
+ _oauth_login_request_body.requestUri = _local_uri
+ requesting = Requests.LOGIN_WITH_OAUTH
+ auth_request_type = Auth_Type.LOGIN_OAUTH
+ var err = request(_base_url + _signin_with_oauth_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_oauth_login_request_body))
+ _oauth_login_request_body.postBody = ""
+ _oauth_login_request_body.requestUri = ""
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error logging in with oauth: %s" % err)
# Exchange the authorization oAuth2 code obtained from browser with a proper access id_token
-func exchange_token(code: String, redirect_uri: String, request_url: String, _client_id: String, _client_secret: String) -> void:
- if _is_ready():
- is_busy = true
- var exchange_token_body: Dictionary = {
- code = code,
- redirect_uri = redirect_uri,
- client_id = _client_id,
- client_secret = _client_secret,
- grant_type = "authorization_code",
- }
- requesting = Requests.EXCHANGE_TOKEN
- request(request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(exchange_token_body))
-
+func exchange_token(code : String, redirect_uri : String, request_url: String, _client_id: String, _client_secret: String) -> void:
+ if _is_ready():
+ is_busy = true
+ var exchange_token_body : Dictionary = {
+ code = code,
+ redirect_uri = redirect_uri,
+ client_id = _client_id,
+ client_secret = _client_secret,
+ grant_type = "authorization_code",
+ }
+ requesting = Requests.EXCHANGE_TOKEN
+ var err = request(request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(exchange_token_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error exchanging tokens: %s" % err)
# Open a web page in browser redirecting to Google oAuth2 page for the current project
# Once given user's authorization, a token will be generated.
# NOTE** with this method, the authorization process will be copy-pasted
func get_google_auth_manual(provider: AuthProvider = _local_provider) -> void:
- provider.params.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
- get_auth_with_redirect(provider)
-
+ provider.params.redirect_uri = "urn:ietf:wg:oauth:2.0:oob"
+ get_auth_with_redirect(provider)
-# A timer used to listen through TCP on the redirect uri of the request
+# A timer used to listen through TCP checked the redirect uri of the request
func _tcp_stream_timer() -> void:
- var peer : StreamPeer = tcp_server.take_connection()
- if peer != null:
- var raw_result: String = peer.get_utf8_string(400)
- if raw_result != "" and raw_result.begins_with("GET"):
- tcp_timer.stop()
- remove_child(tcp_timer)
- has_child = false
- var token: String = ""
- for value in raw_result.split(" ")[1].lstrip("/?").split("&"):
- var splitted: PoolStringArray = value.split("=")
- if _local_provider.params.response_type in splitted[0]:
- token = splitted[1]
- break
- if token == "":
- emit_signal("login_failed")
- peer.disconnect_from_host()
- tcp_server.stop()
- var data : PoolByteArray = '
🔥 You can close this window now. 🔥
'.to_ascii()
- peer.put_data(("HTTP/1.1 200 OK\n").to_ascii())
- peer.put_data(("Server: Godot Firebase SDK\n").to_ascii())
- peer.put_data(("Content-Length: %d\n" % data.size()).to_ascii())
- peer.put_data("Connection: close\n".to_ascii())
- peer.put_data(("Content-Type: text/html; charset=UTF-8\n\n").to_ascii())
- peer.put_data(data)
- login_with_oauth(token, _local_provider)
- yield(self, "login_succeeded")
- peer.disconnect_from_host()
- tcp_server.stop()
-
-
-# Function used to logout of the system, this will also remove the local encrypted auth file if there is one
+ var peer : StreamPeer = tcp_server.take_connection()
+ if peer != null:
+ var raw_result : String = peer.get_utf8_string(441)
+ if raw_result != "" and raw_result.begins_with("GET"):
+ tcp_timer.stop()
+ remove_child(tcp_timer)
+ has_child = false
+ var token : String = ""
+ for value in raw_result.split(" ")[1].lstrip("/?").split("&"):
+ var splitted: PackedStringArray = value.split("=")
+ if _local_provider.params.response_type in splitted[0]:
+ token = splitted[1]
+ break
+
+ if token == "":
+ login_failed.emit()
+ peer.disconnect_from_host()
+ tcp_server.stop()
+ return
+
+ var data : PackedByteArray = '🔥 You can close this window now. 🔥
'.to_ascii_buffer()
+ peer.put_data(("HTTP/1.1 200 OK\n").to_ascii_buffer())
+ peer.put_data(("Server: Godot Firebase SDK\n").to_ascii_buffer())
+ peer.put_data(("Content-Length: %d\n" % data.size()).to_ascii_buffer())
+ peer.put_data("Connection: close\n".to_ascii_buffer())
+ peer.put_data(("Content-Type: text/html; charset=UTF-8\n\n").to_ascii_buffer())
+ peer.put_data(data)
+ login_with_oauth(token, _local_provider)
+ await self.login_succeeded
+ peer.disconnect_from_host()
+ tcp_server.stop()
+
+
+# Function used to logout of the system, this will also remove_at the local encrypted auth file if there is one
func logout() -> void:
- auth = {}
- remove_auth()
- emit_signal("logged_out")
+ auth = {}
+ remove_auth()
+ logged_out.emit()
+# Checks to see if we need a hard login
+func needs_login() -> bool:
+ var encrypted_file = FileAccess.open_encrypted_with_pass("user://user.auth", FileAccess.READ, _config.apiKey)
+ var err = encrypted_file == null
+ return err
# Function is called when requesting a manual token refresh
func manual_token_refresh(auth_data):
- auth = auth_data
- var refresh_token = null
- auth = get_clean_keys(auth)
- if auth.has("refreshtoken"):
- refresh_token = auth.refreshtoken
- elif auth.has("refresh_token"):
- refresh_token = auth.refresh_token
- _needs_refresh = true
- _refresh_request_body.refresh_token = refresh_token
- request(_refresh_request_base_url + _refresh_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_refresh_request_body))
+ auth = auth_data
+ var refresh_token = null
+ auth = get_clean_keys(auth)
+ if auth.has("refreshtoken"):
+ refresh_token = auth.refreshtoken
+ elif auth.has("refresh_token"):
+ refresh_token = auth.refresh_token
+ _needs_refresh = true
+ _refresh_request_body.refresh_token = refresh_token
+ var err = request(_refresh_request_base_url + _refresh_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_refresh_request_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error manually refreshing token: %s" % err)
# This function is called whenever there is an authentication request to Firebase
# On an error, this function with emit the signal 'login_failed' and print the error to the console
-func _on_FirebaseAuth_request_completed(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray) -> void:
- print_debug(JSON.parse(body.get_string_from_utf8()).result)
- is_busy = false
- var res
- if response_code == 0:
- # Mocked error results to trigger the correct signal.
- # Can occur if there is no internet connection, or the service is down,
- # in which case there is no json_body (and thus parsing would fail).
- res = {"error": {
- "code": "Connection error",
- "message": "Error connecting to auth service"}}
- else:
- var bod = body.get_string_from_utf8()
- var json_result = JSON.parse(bod)
- if json_result.error != OK:
- Firebase._printerr("Error while parsing auth body json")
- emit_signal("auth_request", ERR_PARSE_ERROR, "Error while parsing auth body json")
- return
- res = json_result.result
-
- if response_code == HTTPClient.RESPONSE_OK:
- if not res.has("kind"):
- auth = get_clean_keys(res)
- match requesting:
- Requests.EXCHANGE_TOKEN:
- emit_signal("token_exchanged", true)
- begin_refresh_countdown()
- # Refresh token countdown
- emit_signal("auth_request", 1, auth)
- else:
- match res.kind:
- RESPONSE_SIGNUP:
- auth = get_clean_keys(res)
- emit_signal("signup_succeeded", auth)
- begin_refresh_countdown()
- RESPONSE_SIGNIN, RESPONSE_ASSERTION, RESPONSE_CUSTOM_TOKEN:
- auth = get_clean_keys(res)
- emit_signal("login_succeeded", auth)
- begin_refresh_countdown()
- RESPONSE_USERDATA:
- var userdata = FirebaseUserData.new(res.users[0])
- emit_signal("userdata_received", userdata)
- emit_signal("auth_request", 1, auth)
- else:
- # error message would be INVALID_EMAIL, EMAIL_NOT_FOUND, INVALID_PASSWORD, USER_DISABLED or WEAK_PASSWORD
- if requesting == Requests.EXCHANGE_TOKEN:
- emit_signal("token_exchanged", false)
- emit_signal("login_failed", res.error, res.error_description)
- emit_signal("auth_request", res.error, res.error_description)
- else:
- var sig = "signup_failed" if auth_request_type == Auth_Type.SIGNUP_EP else "login_failed"
- emit_signal(sig, res.error.code, res.error.message)
- emit_signal("auth_request", res.error.code, res.error.message)
- requesting = Requests.NONE
- auth_request_type = Auth_Type.NONE
+func _on_FirebaseAuth_request_completed(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ var json = Utilities.get_json_data(body.get_string_from_utf8())
+ is_busy = false
+ var res
+ if response_code == 0:
+ # Mocked error results to trigger the correct signal.
+ # Can occur if there is no internet connection, or the service is down,
+ # in which case there is no json_body (and thus parsing would fail).
+ res = {"error": {
+ "code": "Connection error",
+ "message": "Error connecting to auth service"}}
+ else:
+ if json == null:
+ Firebase._printerr("Error while parsing auth body json")
+ auth_request.emit(ERR_PARSE_ERROR, "Error while parsing auth body json")
+ return
+
+ res = json
+ if response_code == HTTPClient.RESPONSE_OK:
+ if not res.has("kind"):
+ auth = get_clean_keys(res)
+ match requesting:
+ Requests.EXCHANGE_TOKEN:
+ token_exchanged.emit(true)
+ begin_refresh_countdown()
+ # Refresh token countdown
+ auth_request.emit(1, auth)
+
+ if _needs_refresh:
+ _needs_refresh = false
+ if not is_oauth_login: login_succeeded.emit(auth)
+ else:
+ match res.kind:
+ RESPONSE_SIGNUP:
+ auth = get_clean_keys(res)
+ signup_succeeded.emit(auth)
+ begin_refresh_countdown()
+ RESPONSE_SIGNIN, RESPONSE_ASSERTION, RESPONSE_CUSTOM_TOKEN:
+ auth = get_clean_keys(res)
+ login_succeeded.emit(auth)
+ begin_refresh_countdown()
+ RESPONSE_USERDATA:
+ var userdata = FirebaseUserData.new(res.users[0])
+ userdata_received.emit(userdata)
+ auth_request.emit(1, auth)
+ else:
+ # error message would be INVALID_EMAIL, EMAIL_NOT_FOUND, INVALID_PASSWORD, USER_DISABLED or WEAK_PASSWORD
+ if requesting == Requests.EXCHANGE_TOKEN:
+ token_exchanged.emit(false)
+ login_failed.emit(res.error, res.error_description)
+ auth_request.emit(res.error, res.error_description)
+ else:
+ var sig = signup_failed if auth_request_type == Auth_Type.SIGNUP_EP else login_failed
+ sig.emit(res.error.code, res.error.message)
+ auth_request.emit(res.error.code, res.error.message)
+ requesting = Requests.NONE
+ auth_request_type = Auth_Type.NONE
+ is_oauth_login = false
+
# Function used to save the auth data provided by Firebase into an encrypted file
# Note this does not work in HTML5 or UWP
-func save_auth(auth: Dictionary) -> void:
- var encrypted_file = File.new()
- var err = encrypted_file.open_encrypted_with_pass("user://user.auth", File.WRITE, _config.apiKey)
- if err != OK:
- Firebase._printerr("Error Opening File. Error Code: " + String(err))
- else:
- encrypted_file.store_line(to_json(auth))
- encrypted_file.close()
+func save_auth(auth : Dictionary) -> bool:
+ var encrypted_file = FileAccess.open_encrypted_with_pass("user://user.auth", FileAccess.WRITE, _config.apiKey)
+ var err = encrypted_file == null
+ if err:
+ Firebase._printerr("Error Opening File. Error Code: " + str(FileAccess.get_open_error()))
+ else:
+ encrypted_file.store_line(JSON.stringify(auth))
+ return not err
# Function used to load the auth data file that has been stored locally
# Note this does not work in HTML5 or UWP
-func load_auth() -> void:
- var encrypted_file = File.new()
- var err = encrypted_file.open_encrypted_with_pass("user://user.auth", File.READ, _config.apiKey)
- if err != OK:
- Firebase._printerr("Error Opening Firebase Auth File. Error Code: " + str(err))
- emit_signal("auth_request", err, "Error Opening Firebase Auth File.")
- else:
- var encrypted_file_data = parse_json(encrypted_file.get_line())
- manual_token_refresh(encrypted_file_data)
-
-
-# Function used to remove the local encrypted auth file
+func load_auth() -> bool:
+ var encrypted_file = FileAccess.open_encrypted_with_pass("user://user.auth", FileAccess.READ, _config.apiKey)
+ var err = encrypted_file == null
+ if err:
+ Firebase._printerr("Error Opening Firebase Auth File. Error Code: " + str(FileAccess.get_open_error()))
+ auth_request.emit(err, "Error Opening Firebase Auth File.")
+ else:
+ var json = JSON.new()
+ var json_parse_result = json.parse(encrypted_file.get_line())
+ if json_parse_result == OK:
+ var encrypted_file_data = json.data
+ manual_token_refresh(encrypted_file_data)
+ return not err
+
+# Function used to remove_at the local encrypted auth file
func remove_auth() -> void:
- var dir = Directory.new()
- if dir.file_exists("user://user.auth"):
- dir.remove("user://user.auth")
- else:
- Firebase._printerr("No encrypted auth file exists")
+ if (FileAccess.file_exists("user://user.auth")):
+ DirAccess.remove_absolute("user://user.auth")
+ else:
+ Firebase._printerr("No encrypted auth file exists")
# Function to check if there is an encrypted auth data file
# If there is, the game will load it and refresh the token
-func check_auth_file() -> void:
- var dir = Directory.new()
- if dir.file_exists("user://user.auth"):
- # Will ensure "auth_request" emitted
- load_auth()
- else:
- Firebase._printerr("Encrypted Firebase Auth file does not exist")
- emit_signal("auth_request", ERR_DOES_NOT_EXIST, "Encrypted Firebase Auth file does not exist")
+func check_auth_file() -> bool:
+ if (FileAccess.file_exists("user://user.auth")):
+ # Will ensure "auth_request" emitted
+ return load_auth()
+ else:
+ Firebase._printerr("Encrypted Firebase Auth file does not exist")
+ auth_request.emit(ERR_DOES_NOT_EXIST, "Encrypted Firebase Auth file does not exist")
+ return false
# Function used to change the email account for the currently logged in user
-func change_user_email(email: String) -> void:
- if _is_ready():
- is_busy = true
- _change_email_body.email = email
- _change_email_body.idToken = auth.idtoken
- request(_base_url + _update_account_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_change_email_body))
+func change_user_email(email : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _change_email_body.email = email
+ _change_email_body.idToken = auth.idtoken
+ var err = request(_base_url + _update_account_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_change_email_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error changing user email: %s" % err)
# Function used to change the password for the currently logged in user
-func change_user_password(password: String) -> void:
- if _is_ready():
- is_busy = true
- _change_password_body.password = password
- _change_password_body.idToken = auth.idtoken
- request(_base_url + _update_account_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_change_password_body))
+func change_user_password(password : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _change_password_body.password = password
+ _change_password_body.idToken = auth.idtoken
+ var err = request(_base_url + _update_account_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_change_password_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error changing user password: %s" % err)
# User Profile handlers
-func update_account(idToken: String, displayName: String, photoUrl: String, deleteAttribute: PoolStringArray, returnSecureToken: bool) -> void:
- if _is_ready():
- is_busy = true
- _update_profile_body.idToken = idToken
- _update_profile_body.displayName = displayName
- _update_profile_body.photoUrl = photoUrl
- _update_profile_body.deleteAttribute = deleteAttribute
- _update_profile_body.returnSecureToken = returnSecureToken
- request(_base_url + _update_account_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_update_profile_body))
+func update_account(idToken : String, displayName : String, photoUrl : String, deleteAttribute : PackedStringArray, returnSecureToken : bool) -> void:
+ if _is_ready():
+ is_busy = true
+ _update_profile_body.idToken = idToken
+ _update_profile_body.displayName = displayName
+ _update_profile_body.photoUrl = photoUrl
+ _update_profile_body.deleteAttribute = deleteAttribute
+ _update_profile_body.returnSecureToken = returnSecureToken
+ var err = request(_base_url + _update_account_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_update_profile_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error updating account: %s" % err)
# Function to send a account verification email
func send_account_verification_email() -> void:
- if _is_ready():
- is_busy = true
- _account_verification_body.idToken = auth.idtoken
- request(_base_url + _oobcode_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_account_verification_body))
+ if _is_ready():
+ is_busy = true
+ _account_verification_body.idToken = auth.idtoken
+ var err = request(_base_url + _oobcode_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_account_verification_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error sending account verification email: %s" % err)
# Function used to reset the password for a user who has forgotten in.
# This will send the users account an email with a password reset link
-func send_password_reset_email(email: String) -> void:
- if _is_ready():
- is_busy = true
- _password_reset_body.email = email
- request(_base_url + _oobcode_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_password_reset_body))
+func send_password_reset_email(email : String) -> void:
+ if _is_ready():
+ is_busy = true
+ _password_reset_body.email = email
+ var err = request(_base_url + _oobcode_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_password_reset_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error sending password reset email: %s" % err)
# Function called to get all
func get_user_data() -> void:
- if _is_ready():
- is_busy = true
- if not is_logged_in():
- print_debug("Not logged in")
- is_busy = false
- return
+ if _is_ready():
+ is_busy = true
+ if not is_logged_in():
+ print_debug("Not logged in")
+ is_busy = false
+ return
- request(_base_url + _userdata_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print({"idToken": auth.idtoken}))
+ var err = request(_base_url + _userdata_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify({"idToken":auth.idtoken}))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error getting user data: %s" % err)
# Function used to delete the account of the currently authenticated user
func delete_user_account() -> void:
- if _is_ready():
- is_busy = true
- request(_base_url + _delete_account_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print({"idToken": auth.idtoken}))
+ if _is_ready():
+ is_busy = true
+ var err = request(_base_url + _delete_account_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify({"idToken":auth.idtoken}))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error deleting user: %s" % err)
+ else:
+ remove_auth()
# Function is called when a new token is issued to a user. The function will yield until the token has expired, and then request a new one.
func begin_refresh_countdown() -> void:
- var refresh_token = null
- var expires_in = 1000
- auth = get_clean_keys(auth)
- if auth.has("refreshtoken"):
- refresh_token = auth.refreshtoken
- expires_in = auth.expiresin
- elif auth.has("refresh_token"):
- refresh_token = auth.refresh_token
- expires_in = auth.expires_in
- if auth.has("userid"):
- auth["localid"] = auth.userid
- _needs_refresh = true
- emit_signal("token_refresh_succeeded", auth)
- yield(get_tree().create_timer(float(expires_in)), "timeout")
- _refresh_request_body.refresh_token = refresh_token
- request(_refresh_request_base_url + _refresh_request_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_refresh_request_body))
+ var refresh_token = null
+ var expires_in = 1000
+ auth = get_clean_keys(auth)
+ if auth.has("refreshtoken"):
+ refresh_token = auth.refreshtoken
+ expires_in = auth.expiresin
+ elif auth.has("refresh_token"):
+ refresh_token = auth.refresh_token
+ expires_in = auth.expires_in
+ if auth.has("userid"):
+ auth["localid"] = auth.userid
+ _needs_refresh = true
+ token_refresh_succeeded.emit(auth)
+ await get_tree().create_timer(float(expires_in)).timeout
+ _refresh_request_body.refresh_token = refresh_token
+ var err = request(_refresh_request_base_url + _refresh_request_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_refresh_request_body))
+ if err != OK:
+ is_busy = false
+ Firebase._printerr("Error refreshing via countdown: %s" % err)
func get_token_from_url(provider: AuthProvider):
- var token_type: String = provider.params.response_type if provider.params.response_type == "code" else "access_token"
- if OS.has_feature('JavaScript'):
- var token = JavaScript.eval("""
- var url_string = window.location.href.replaceAll('?#', '?');
- var url = new URL(url_string);
- url.searchParams.get('"""+token_type+"""');
- """)
- JavaScript.eval("""window.history.pushState({}, null, location.href.split('?')[0]);""")
- return token
- return null
-
+ var token_type: String = provider.params.response_type if provider.params.response_type == "code" else "access_token"
+ if OS.has_feature('web'):
+ var token = JavaScriptBridge.eval("""
+ var url_string = window.location.href.replaceAll('?#', '?');
+ var url = new URL(url_string);
+ url.searchParams.get('"""+token_type+"""');
+ """)
+ JavaScriptBridge.eval("""window.history.pushState({}, null, location.href.split('?')[0]);""")
+ return token
+ return null
-func set_redirect_uri(redirect_uri: String) -> void:
- self._local_uri = redirect_uri
+func set_redirect_uri(redirect_uri : String) -> void:
+ self._local_uri = redirect_uri
-func set_local_provider(provider: AuthProvider) -> void:
- self._local_provider = provider
-
+func set_local_provider(provider : AuthProvider) -> void:
+ self._local_provider = provider
# This function is used to make all keys lowercase
-# This is only used to cut down on processing errors from Firebase
+# This is only used to cut down checked processing errors from Firebase
# This is due to Google have inconsistencies in the API that we are trying to fix
-func get_clean_keys(auth_result: Dictionary) -> Dictionary:
- var cleaned = {}
- for key in auth_result.keys():
- cleaned[key.replace("_", "").to_lower()] = auth_result[key]
- return cleaned
-
+func get_clean_keys(auth_result : Dictionary) -> Dictionary:
+ var cleaned = {}
+ for key in auth_result.keys():
+ cleaned[key.replace("_", "").to_lower()] = auth_result[key]
+ return cleaned
# --------------------
# PROVIDERS
# --------------------
func get_GoogleProvider() -> GoogleProvider:
- return GoogleProvider.new(_config.clientId, _config.clientSecret)
-
+ return GoogleProvider.new(_config.clientId, _config.clientSecret)
func get_FacebookProvider() -> FacebookProvider:
- return FacebookProvider.new(_config.auth_providers.facebook_id, _config.auth_providers.facebook_secret)
-
+ return FacebookProvider.new(_config.auth_providers.facebook_id, _config.auth_providers.facebook_secret)
func get_GitHubProvider() -> GitHubProvider:
- return GitHubProvider.new(_config.auth_providers.github_id, _config.auth_providers.github_secret)
-
+ return GitHubProvider.new(_config.auth_providers.github_id, _config.auth_providers.github_secret)
func get_TwitterProvider() -> TwitterProvider:
- return TwitterProvider.new(_config.auth_providers.twitter_id, _config.auth_providers.twitter_secret)
+ return TwitterProvider.new(_config.auth_providers.twitter_id, _config.auth_providers.twitter_secret)
diff --git a/addons/godot-firebase/auth/auth_provider.gd b/addons/godot-firebase/auth/auth_provider.gd
index 2f0fd0b..288cf2d 100644
--- a/addons/godot-firebase/auth/auth_provider.gd
+++ b/addons/godot-firebase/auth/auth_provider.gd
@@ -1,7 +1,6 @@
-tool
+@tool
class_name AuthProvider
-extends Reference
-
+extends RefCounted
var redirect_uri: String = ""
var access_token_uri: String = ""
@@ -20,18 +19,14 @@ var should_exchange: bool = false
func set_client_id(client_id: String) -> void:
self.params.client_id = client_id
-
func set_client_secret(client_secret: String) -> void:
self.client_secret = client_secret
-
func get_client_id() -> String:
return self.params.client_id
-
func get_client_secret() -> String:
return self.client_secret
-
func get_oauth_params() -> String:
return ""
diff --git a/addons/godot-firebase/auth/providers/facebook.gd b/addons/godot-firebase/auth/providers/facebook.gd
index b5e59fb..35e8dd8 100644
--- a/addons/godot-firebase/auth/providers/facebook.gd
+++ b/addons/godot-firebase/auth/providers/facebook.gd
@@ -1,20 +1,21 @@
-class_name FacebookProvider
+class_name FacebookProvider
extends AuthProvider
-
-func _init(client_id: String, client_secret: String) -> void:
- randomize()
- set_client_id(client_id)
- set_client_secret(client_secret)
-
- self.redirect_uri = "https://www.facebook.com/v13.0/dialog/oauth?"
- self.access_token_uri = "https://graph.facebook.com/v13.0/oauth/access_token"
- self.provider_id = "facebook.com"
- self.params.scope = "public_profile"
- self.params.state = str(rand_range(0, 1))
- if OS.get_name() == "HTML5":
- self.should_exchange = false
- self.params.response_type = "token"
- else:
- self.should_exchange = true
- self.params.response_type = "code"
+func _init(client_id: String,client_secret: String):
+ randomize()
+ set_client_id(client_id)
+ set_client_secret(client_secret)
+
+ self.redirect_uri = "https://www.facebook.com/v13.0/dialog/oauth?"
+ self.access_token_uri = "https://graph.facebook.com/v13.0/oauth/access_token"
+ self.provider_id = "facebook.com"
+ self.params.scope = "public_profile"
+ self.params.state = str(randf_range(0, 1))
+ if Utilities.is_web():
+ self.should_exchange = false
+ self.params.response_type = "token"
+ else:
+ self.should_exchange = true
+ self.params.response_type = "code"
+
+
diff --git a/addons/godot-firebase/auth/providers/github.gd b/addons/godot-firebase/auth/providers/github.gd
index 0c77272..bab073a 100644
--- a/addons/godot-firebase/auth/providers/github.gd
+++ b/addons/godot-firebase/auth/providers/github.gd
@@ -1,8 +1,7 @@
-class_name GitHubProvider
+class_name GitHubProvider
extends AuthProvider
-
-func _init(client_id: String, client_secret: String) -> void:
+func _init(client_id: String,client_secret: String):
randomize()
set_client_id(client_id)
set_client_secret(client_secret)
@@ -11,5 +10,5 @@ func _init(client_id: String, client_secret: String) -> void:
self.access_token_uri = "https://github.com/login/oauth/access_token"
self.provider_id = "github.com"
self.params.scope = "user:read"
- self.params.state = str(rand_range(0, 1))
+ self.params.state = str(randf_range(0, 1))
self.params.response_type = "code"
diff --git a/addons/godot-firebase/auth/providers/google.gd b/addons/godot-firebase/auth/providers/google.gd
index 15ac362..152a5cc 100644
--- a/addons/godot-firebase/auth/providers/google.gd
+++ b/addons/godot-firebase/auth/providers/google.gd
@@ -1,14 +1,13 @@
class_name GoogleProvider
extends AuthProvider
-
-func _init(client_id: String, client_secret: String) -> void:
- set_client_id(client_id)
- set_client_secret(client_secret)
- self.should_exchange = true
- self.redirect_uri = "https://accounts.google.com/o/oauth2/v2/auth?"
- self.access_token_uri = "https://oauth2.googleapis.com/token"
- self.provider_id = "google.com"
- self.params.response_type = "code"
- self.params.scope = "email openid profile"
- self.params.response_type = "code"
+func _init(client_id: String,client_secret: String):
+ set_client_id(client_id)
+ set_client_secret(client_secret)
+ self.should_exchange = true
+ self.redirect_uri = "https://accounts.google.com/o/oauth2/v2/auth?"
+ self.access_token_uri = "https://oauth2.googleapis.com/token"
+ self.provider_id = "google.com"
+ self.params.response_type = "code"
+ self.params.scope = "email openid profile"
+ self.params.response_type = "code"
diff --git a/addons/godot-firebase/auth/providers/twitter.gd b/addons/godot-firebase/auth/providers/twitter.gd
index b7675c9..1ec11cf 100644
--- a/addons/godot-firebase/auth/providers/twitter.gd
+++ b/addons/godot-firebase/auth/providers/twitter.gd
@@ -1,29 +1,28 @@
-class_name TwitterProvider
+class_name TwitterProvider
extends AuthProvider
-
var request_token_endpoint: String = "https://api.twitter.com/oauth/access_token?oauth_callback="
var oauth_header: Dictionary = {
- oauth_callback = "",
- oauth_consumer_key = "",
- oauth_nonce = "",
- oauth_signature = "",
- oauth_signature_method = "HMAC-SHA1",
- oauth_timestamp = "",
- oauth_version = "1.0"
+ oauth_callback="",
+ oauth_consumer_key="",
+ oauth_nonce="",
+ oauth_signature="",
+ oauth_signature_method="HMAC-SHA1",
+ oauth_timestamp="",
+ oauth_version="1.0"
}
-
-func _init(client_id: String, client_secret: String) -> void:
+func _init(client_id: String,client_secret: String):
randomize()
set_client_id(client_id)
set_client_secret(client_secret)
-
+
self.oauth_header.oauth_consumer_key = client_id
- self.oauth_header.oauth_nonce = OS.get_ticks_usec()
- self.oauth_header.oauth_timestamp = OS.get_ticks_msec()
-
+ self.oauth_header.oauth_nonce = Time.get_ticks_usec()
+ self.oauth_header.oauth_timestamp = Time.get_ticks_msec()
+
+
self.should_exchange = true
self.redirect_uri = "https://twitter.com/i/oauth2/authorize?"
self.access_token_uri = "https://api.twitter.com/2/oauth2/token"
@@ -31,11 +30,10 @@ func _init(client_id: String, client_secret: String) -> void:
self.params.redirect_type = "redirect_uri"
self.params.response_type = "code"
self.params.scope = "users.read"
- self.params.state = str(rand_range(0, 1))
-
+ self.params.state = str(randf_range(0, 1))
func get_oauth_params() -> String:
- var params: PoolStringArray = []
+ var params: PackedStringArray = []
for key in self.oauth.keys():
- params.append(key + "=" + self.oauth.get(key))
- return params.join("&")
+ params.append(key+"="+self.oauth.get(key))
+ return "&".join(params)
diff --git a/addons/godot-firebase/auth/user_data.gd b/addons/godot-firebase/auth/user_data.gd
index 62e0d57..c76e515 100644
--- a/addons/godot-firebase/auth/user_data.gd
+++ b/addons/godot-firebase/auth/user_data.gd
@@ -2,25 +2,23 @@
## @meta-version 2.3
## Authentication user data.
## Documentation TODO.
-tool
+@tool
class_name FirebaseUserData
-extends Reference
+extends RefCounted
+var local_id : String = "" # The uid of the current user.
+var email : String = ""
+var email_verified := false # Whether or not the account's email has been verified.
+var password_updated_at : float = 0 # The timestamp, in milliseconds, that the account password was last changed.
+var last_login_at : float = 0 # The timestamp, in milliseconds, that the account last logged in at.
+var created_at : float = 0 # The timestamp, in milliseconds, that the account was created at.
+var provider_user_info : Array = []
-var local_id: String = "" # The uid of the current user.
-var email: String = ""
-var email_verified := false # Whether or not the account's email has been verified.
-var password_updated_at: float = 0 # The timestamp, in milliseconds, that the account password was last changed.
-var last_login_at: float = 0 # The timestamp, in milliseconds, that the account last logged in at.
-var created_at: float = 0 # The timestamp, in milliseconds, that the account was created at.
-var provider_user_info: Array = []
+var provider_id : String = ""
+var display_name : String = ""
+var photo_url : String = ""
-var provider_id: String = ""
-var display_name: String = ""
-var photo_url: String = ""
-
-
-func _init(p_userdata: Dictionary) -> void:
+func _init(p_userdata : Dictionary):
local_id = p_userdata.get("localId", "")
email = p_userdata.get("email", "")
email_verified = p_userdata.get("emailVerified", false)
@@ -29,16 +27,14 @@ func _init(p_userdata: Dictionary) -> void:
password_updated_at = float(p_userdata.get("passwordUpdatedAt", 0))
display_name = p_userdata.get("displayName", "")
provider_user_info = p_userdata.get("providerUserInfo", [])
- if not provider_user_info.empty():
+ if not provider_user_info.is_empty():
provider_id = provider_user_info[0].get("providerId", "")
photo_url = provider_user_info[0].get("photoUrl", "")
display_name = provider_user_info[0].get("displayName", "")
-
func as_text() -> String:
return _to_string()
-
func _to_string() -> String:
var txt = "local_id : %s\n" % local_id
txt += "email : %s\n" % email
diff --git a/addons/godot-firebase/database/database.gd b/addons/godot-firebase/database/database.gd
index de736be..3391518 100644
--- a/addons/godot-firebase/database/database.gd
+++ b/addons/godot-firebase/database/database.gd
@@ -2,57 +2,50 @@
## @meta-version 2.2
## The Realtime Database API for Firebase.
## Documentation TODO.
-tool
+@tool
class_name FirebaseDatabase
extends Node
+var _base_url : String = ""
-var _base_url: String = ""
+var _config : Dictionary = {}
-var _config: Dictionary = {}
+var _auth : Dictionary = {}
-var _auth: Dictionary = {}
+func _set_config(config_json : Dictionary) -> void:
+ _config = config_json
+ _check_emulating()
+func _check_emulating() -> void :
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = _config.databaseURL
+ else:
+ var port : String = _config.emulators.ports.realtimeDatabase
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Realtime Database has not been configured.")
+ else:
+ _base_url = "http://localhost"
-func _set_config(config_json: Dictionary) -> void:
- _config = config_json
- _check_emulating()
-
-
-func _check_emulating() -> void:
- ## Check emulating
- if not Firebase.emulating:
- _base_url = _config.databaseURL
- else:
- var port: String = _config.emulators.ports.realtimeDatabase
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Realtime Database has not been configured.")
- else:
- _base_url = "http://localhost"
-
-
-func _on_FirebaseAuth_login_succeeded(auth_result: Dictionary) -> void:
- _auth = auth_result
-
-
-func _on_FirebaseAuth_token_refresh_succeeded(auth_result: Dictionary) -> void:
- _auth = auth_result
+func _on_FirebaseAuth_login_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
+func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
func _on_FirebaseAuth_logout() -> void:
- _auth = {}
-
-
-func get_database_reference(path: String, filter: Dictionary = {}) -> FirebaseDatabaseReference:
- var firebase_reference: FirebaseDatabaseReference = FirebaseDatabaseReference.new()
- var pusher: HTTPRequest = HTTPRequest.new()
- var listener: Node = Node.new()
- listener.set_script(load("res://addons/http-sse-client/HTTPSSEClient.gd"))
- var store: FirebaseDatabaseStore = FirebaseDatabaseStore.new()
- firebase_reference.set_db_path(path, filter)
- firebase_reference.set_auth_and_config(_auth, _config)
- firebase_reference.set_pusher(pusher)
- firebase_reference.set_listener(listener)
- firebase_reference.set_store(store)
- add_child(firebase_reference)
- return firebase_reference
+ _auth = {}
+
+func get_database_reference(path : String, filter : Dictionary = {}) -> FirebaseDatabaseReference:
+ var firebase_reference = load("res://addons/godot-firebase/database/firebase_database_reference.tscn").instantiate()
+ firebase_reference.set_db_path(path, filter)
+ firebase_reference.set_auth_and_config(_auth, _config)
+ add_child(firebase_reference)
+ return firebase_reference
+
+func get_once_database_reference(path : String, filter : Dictionary = {}) -> FirebaseOnceDatabaseReference:
+ var firebase_reference = load("res://addons/godot-firebase/database/firebase_once_database_reference.tscn").instantiate()
+ firebase_reference.set_db_path(path, filter)
+ firebase_reference.set_auth_and_config(_auth, _config)
+ add_child(firebase_reference)
+ return firebase_reference
diff --git a/addons/godot-firebase/database/database_store.gd b/addons/godot-firebase/database/database_store.gd
index 07b6753..a407241 100644
--- a/addons/godot-firebase/database/database_store.gd
+++ b/addons/godot-firebase/database/database_store.gd
@@ -1,8 +1,8 @@
## @meta-authors TODO
## @meta-version 2.2
## Data structure that holds the currently-known data at a given path (a.k.a. reference) in a Firebase Realtime Database.
-## Can process both puts and patches into the data based on realtime events received from the service.
-tool
+## Can process both puts and patches into the data based checked realtime events received from the service.
+@tool
class_name FirebaseDatabaseStore
extends Node
@@ -19,91 +19,91 @@ var _data : Dictionary = { }
## Puts a new payload into this data store at the given path. Any existing values in this data store
## at the specified path will be completely erased.
func put(path : String, payload) -> void:
- _update_data(path, payload, false)
+ _update_data(path, payload, false)
## @args path, payload
## Patches an update payload into this data store at the specified path.
## NOTE: When patching in updates to arrays, payload should contain the entire new array! Updating single elements/indexes of an array is not supported. Sometimes when manually mutating array data directly from the Firebase Realtime Database console, single-element patches will be sent out which can cause issues here.
func patch(path : String, payload) -> void:
- _update_data(path, payload, true)
+ _update_data(path, payload, true)
## @args path, payload
## Deletes data at the reference point provided
## NOTE: This will delete without warning, so make sure the reference is pointed to the level you want and not the root or you will lose everything
func delete(path : String, payload) -> void:
- _update_data(path, payload, true)
+ _update_data(path, payload, true)
## Returns a deep copy of this data store's payload.
func get_data() -> Dictionary:
- return _data[_ROOT].duplicate(true)
+ return _data[_ROOT].duplicate(true)
#
# Updates this data store by either putting or patching the provided payload into it at the given
# path. The provided payload can technically be any value.
#
func _update_data(path: String, payload, patch: bool) -> void:
- if debug:
- print("Updating data store (patch = %s) (%s = %s)..." % [patch, path, payload])
+ if debug:
+ print("Updating data store (patch = %s) (%s = %s)..." % [patch, path, payload])
- #
- # Remove any leading separators.
- #
- path = path.lstrip(_DELIMITER)
+ #
+ # Remove any leading separators.
+ #
+ path = path.lstrip(_DELIMITER)
- #
- # Traverse the path.
- #
- var dict = _data
- var keys = PoolStringArray([_ROOT])
+ #
+ # Traverse the path.
+ #
+ var dict = _data
+ var keys = PackedStringArray([_ROOT])
- keys.append_array(path.split(_DELIMITER, false))
+ keys.append_array(path.split(_DELIMITER, false))
- var final_key_idx = (keys.size() - 1)
- var final_key = (keys[final_key_idx])
+ var final_key_idx = (keys.size() - 1)
+ var final_key = (keys[final_key_idx])
- keys.remove(final_key_idx)
+ keys.remove_at(final_key_idx)
- for key in keys:
- if !dict.has(key):
- dict[key] = { }
+ for key in keys:
+ if !dict.has(key):
+ dict[key] = { }
- dict = dict[key]
+ dict = dict[key]
- #
- # Handle non-patch (a.k.a. put) mode and then update the destination value.
- #
- var new_type = typeof(payload)
+ #
+ # Handle non-patch (a.k.a. put) mode and then update the destination value.
+ #
+ var new_type = typeof(payload)
- if !patch:
- dict.erase(final_key)
+ if !patch:
+ dict.erase(final_key)
- if new_type == TYPE_NIL:
- dict.erase(final_key)
- elif new_type == TYPE_DICTIONARY:
- if !dict.has(final_key):
- dict[final_key] = { }
+ if new_type == TYPE_NIL:
+ dict.erase(final_key)
+ elif new_type == TYPE_DICTIONARY:
+ if !dict.has(final_key):
+ dict[final_key] = { }
- _update_dictionary(dict[final_key], payload)
- else:
- dict[final_key] = payload
+ _update_dictionary(dict[final_key], payload)
+ else:
+ dict[final_key] = payload
- if debug:
- print("...Data store updated (%s)." % _data)
+ if debug:
+ print("...Data store updated (%s)." % _data)
#
# Helper method to "blit" changes in an update dictionary payload onto an original dictionary.
# Parameters are directly changed via reference.
#
func _update_dictionary(original_dict: Dictionary, update_payload: Dictionary) -> void:
- for key in update_payload.keys():
- var val_type = typeof(update_payload[key])
-
- if val_type == TYPE_NIL:
- original_dict.erase(key)
- elif val_type == TYPE_DICTIONARY:
- if !original_dict.has(key):
- original_dict[key] = { }
-
- _update_dictionary(original_dict[key], update_payload[key])
- else:
- original_dict[key] = update_payload[key]
+ for key in update_payload.keys():
+ var val_type = typeof(update_payload[key])
+
+ if val_type == TYPE_NIL:
+ original_dict.erase(key)
+ elif val_type == TYPE_DICTIONARY:
+ if !original_dict.has(key):
+ original_dict[key] = { }
+
+ _update_dictionary(original_dict[key], update_payload[key])
+ else:
+ original_dict[key] = update_payload[key]
diff --git a/addons/godot-firebase/database/firebase_database_reference.tscn b/addons/godot-firebase/database/firebase_database_reference.tscn
new file mode 100644
index 0000000..27abf89
--- /dev/null
+++ b/addons/godot-firebase/database/firebase_database_reference.tscn
@@ -0,0 +1,17 @@
+[gd_scene load_steps=5 format=3 uid="uid://btltp52tywbe4"]
+
+[ext_resource type="Script" path="res://addons/godot-firebase/database/reference.gd" id="1_l3oy5"]
+[ext_resource type="PackedScene" uid="uid://ctb4l7plg8kqg" path="res://addons/godot-firebase/queues/queueable_http_request.tscn" id="2_0qpk7"]
+[ext_resource type="Script" path="res://addons/http-sse-client/HTTPSSEClient.gd" id="2_4l0io"]
+[ext_resource type="Script" path="res://addons/godot-firebase/database/database_store.gd" id="3_c3r2w"]
+
+[node name="FirebaseDatabaseReference" type="Node"]
+script = ExtResource("1_l3oy5")
+
+[node name="Pusher" parent="." instance=ExtResource("2_0qpk7")]
+
+[node name="Listener" type="Node" parent="."]
+script = ExtResource("2_4l0io")
+
+[node name="DataStore" type="Node" parent="."]
+script = ExtResource("3_c3r2w")
diff --git a/addons/godot-firebase/database/firebase_once_database_reference.tscn b/addons/godot-firebase/database/firebase_once_database_reference.tscn
new file mode 100644
index 0000000..c1e2913
--- /dev/null
+++ b/addons/godot-firebase/database/firebase_once_database_reference.tscn
@@ -0,0 +1,16 @@
+[gd_scene load_steps=3 format=3 uid="uid://d1u1bxp2fd60e"]
+
+[ext_resource type="Script" path="res://addons/godot-firebase/database/once_reference.gd" id="1_hq5s2"]
+[ext_resource type="PackedScene" uid="uid://ctb4l7plg8kqg" path="res://addons/godot-firebase/queues/queueable_http_request.tscn" id="2_t2f32"]
+
+[node name="FirebaseOnceDatabaseReference" type="Node"]
+script = ExtResource("1_hq5s2")
+
+[node name="Pusher" parent="." instance=ExtResource("2_t2f32")]
+accept_gzip = false
+
+[node name="Oncer" parent="." instance=ExtResource("2_t2f32")]
+accept_gzip = false
+
+[connection signal="queue_request_completed" from="Pusher" to="." method="on_push_request_complete"]
+[connection signal="queue_request_completed" from="Oncer" to="." method="on_get_request_complete"]
diff --git a/addons/godot-firebase/database/once_reference.gd b/addons/godot-firebase/database/once_reference.gd
new file mode 100644
index 0000000..ac816e4
--- /dev/null
+++ b/addons/godot-firebase/database/once_reference.gd
@@ -0,0 +1,124 @@
+class_name FirebaseOnceDatabaseReference
+extends Node
+
+
+## @meta-authors BackAt50Ft
+## @meta-version 1.0
+## A once off reference to a location in the Realtime Database.
+## Documentation TODO.
+
+signal once_successful(dataSnapshot)
+signal once_failed()
+
+signal push_successful()
+signal push_failed()
+
+const ORDER_BY : String = "orderBy"
+const LIMIT_TO_FIRST : String = "limitToFirst"
+const LIMIT_TO_LAST : String = "limitToLast"
+const START_AT : String = "startAt"
+const END_AT : String = "endAt"
+const EQUAL_TO : String = "equalTo"
+
+@onready var _oncer = $Oncer
+@onready var _pusher = $Pusher
+
+var _auth : Dictionary
+var _config : Dictionary
+var _filter_query : Dictionary
+var _db_path : String
+
+const _separator : String = "/"
+const _json_list_tag : String = ".json"
+const _query_tag : String = "?"
+const _auth_tag : String = "auth="
+
+const _auth_variable_begin : String = "["
+const _auth_variable_end : String = "]"
+const _filter_tag : String = "&"
+const _escaped_quote : String = '"'
+const _equal_tag : String = "="
+const _key_filter_tag : String = "$key"
+
+var _headers : PackedStringArray = []
+
+func set_db_path(path : String, filter_query_dict : Dictionary) -> void:
+ _db_path = path
+ _filter_query = filter_query_dict
+
+func set_auth_and_config(auth_ref : Dictionary, config_ref : Dictionary) -> void:
+ _auth = auth_ref
+ _config = config_ref
+
+#
+# Gets a data snapshot once at the position passed in
+#
+func once(reference : String) -> void:
+ var ref_pos = _get_list_url() + _db_path + _separator + reference + _get_remaining_path()
+ _oncer.request(ref_pos, _headers, HTTPClient.METHOD_GET, "")
+
+func _get_remaining_path(is_push : bool = true) -> String:
+ var remaining_path = ""
+ if _filter_query_empty() or is_push:
+ remaining_path = _json_list_tag + _query_tag + _auth_tag + Firebase.Auth.auth.idtoken
+ else:
+ remaining_path = _json_list_tag + _query_tag + _get_filter() + _filter_tag + _auth_tag + Firebase.Auth.auth.idtoken
+
+ if Firebase.emulating:
+ remaining_path += "&ns="+_config.projectId+"-default-rtdb"
+
+ return remaining_path
+
+func _get_list_url(with_port:bool = true) -> String:
+ var url = Firebase.Database._base_url.trim_suffix(_separator)
+ if with_port and Firebase.emulating:
+ url += ":" + _config.emulators.ports.realtimeDatabase
+ return url + _separator
+
+
+func _get_filter():
+ if _filter_query_empty():
+ return ""
+
+ var filter = ""
+
+ if _filter_query.has(ORDER_BY):
+ filter += ORDER_BY + _equal_tag + _escaped_quote + _filter_query[ORDER_BY] + _escaped_quote
+ _filter_query.erase(ORDER_BY)
+ else:
+ filter += ORDER_BY + _equal_tag + _escaped_quote + _key_filter_tag + _escaped_quote # Presumptuous, but to get it to work at all...
+
+ for key in _filter_query.keys():
+ filter += _filter_tag + key + _equal_tag + _filter_query[key]
+
+ return filter
+
+func _filter_query_empty() -> bool:
+ return _filter_query == null or _filter_query.is_empty()
+
+func on_get_request_complete(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ if response_code == HTTPClient.RESPONSE_OK:
+ var bod = Utilities.get_json_data(body)
+ once_successful.emit(bod)
+ else:
+ once_failed.emit()
+
+func on_push_request_complete(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ if response_code == HTTPClient.RESPONSE_OK:
+ push_successful.emit()
+ else:
+ push_failed.emit()
+
+func push(data : Dictionary) -> void:
+ var to_push = JSON.stringify(data)
+ _pusher.request(_get_list_url() + _db_path + _get_remaining_path(true), _headers, HTTPClient.METHOD_POST, to_push)
+
+func update(path : String, data : Dictionary) -> void:
+ path = path.strip_edges(true, true)
+
+ if path == _separator:
+ path = ""
+
+ var to_update = JSON.stringify(data)
+ var resolved_path = (_get_list_url() + _db_path + "/" + path + _get_remaining_path())
+ _pusher.request(resolved_path, _headers, HTTPClient.METHOD_PATCH, to_update)
diff --git a/addons/godot-firebase/database/reference.gd b/addons/godot-firebase/database/reference.gd
index 464e5c1..0429b92 100644
--- a/addons/godot-firebase/database/reference.gd
+++ b/addons/godot-firebase/database/reference.gd
@@ -1,211 +1,176 @@
-## @meta-authors TODO
-## @meta-version 2.3
+## @meta-authors BackAt50Ft
+## @meta-version 2.4
## A reference to a location in the Realtime Database.
## Documentation TODO.
-tool
+@tool
class_name FirebaseDatabaseReference
extends Node
-
signal new_data_update(data)
signal patch_data_update(data)
signal delete_data_update(data)
+signal once_successful(dataSnapshot)
+signal once_failed()
+
signal push_successful()
signal push_failed()
-const ORDER_BY: String = "orderBy"
-const LIMIT_TO_FIRST: String = "limitToFirst"
-const LIMIT_TO_LAST: String = "limitToLast"
-const START_AT: String = "startAt"
-const END_AT: String = "endAt"
-const EQUAL_TO: String = "equalTo"
-
-var _pusher: HTTPRequest
-var _listener: Node
-var _store: FirebaseDatabaseStore
-var _auth: Dictionary
-var _config: Dictionary
-var _filter_query: Dictionary
-var _db_path: String
-var _cached_filter: String
-var _push_queue: Array = []
-var _update_queue: Array = []
-var _delete_queue: Array = []
-var _can_connect_to_host: bool = false
-
-const _put_tag: String = "put"
-const _patch_tag: String = "patch"
-const _delete_tag: String = "delete"
-const _separator: String = "/"
-const _json_list_tag: String = ".json"
-const _query_tag: String = "?"
-const _auth_tag: String = "auth="
-const _accept_header: String = "accept: text/event-stream"
-const _auth_variable_begin: String = "["
-const _auth_variable_end: String = "]"
-const _filter_tag: String = "&"
-const _escaped_quote: String = '"'
-const _equal_tag: String = "="
-const _key_filter_tag: String = "$key"
-
-var _headers: PoolStringArray = []
-
-
-func set_db_path(path: String, filter_query_dict: Dictionary) -> void:
- _db_path = path
- _filter_query = filter_query_dict
-
-
-func set_auth_and_config(auth_ref: Dictionary, config_ref: Dictionary) -> void:
- _auth = auth_ref
- _config = config_ref
-
-
-func set_pusher(pusher_ref: HTTPRequest) -> void:
- if not _pusher:
- _pusher = pusher_ref
- add_child(_pusher)
- _pusher.connect("request_completed", self, "on_push_request_complete")
-
-
-func set_listener(listener_ref: Node) -> void:
- if not _listener:
- _listener = listener_ref
- add_child(_listener)
- _listener.connect("new_sse_event", self, "on_new_sse_event")
- var base_url = _get_list_url(false).trim_suffix(_separator)
- var extended_url = _separator + _db_path + _get_remaining_path(false)
- var port = -1
- if Firebase.emulating:
- port = int(_config.emulators.ports.realtimeDatabase)
- _listener.connect_to_host(base_url, extended_url, port)
-
-
-func on_new_sse_event(headers: Dictionary, event: String, data: Dictionary) -> void:
- if data:
- var command = event
- if command and command != "keep-alive":
- _route_data(command, data.path, data.data)
- if command == _put_tag:
- if data.path == _separator and data.data and data.data.keys().size() > 0:
- for key in data.data.keys():
- emit_signal("new_data_update", FirebaseResource.new(_separator + key, data.data[key]))
- elif data.path != _separator:
- emit_signal("new_data_update", FirebaseResource.new(data.path, data.data))
- elif command == _patch_tag:
- emit_signal("patch_data_update", FirebaseResource.new(data.path, data.data))
- elif command == _delete_tag:
- emit_signal("delete_data_update", FirebaseResource.new(data.path, data.data))
- pass
-
-
-func set_store(store_ref: FirebaseDatabaseStore) -> void:
- if not _store:
- _store = store_ref
- add_child(_store)
-
-
-func update(path: String, data: Dictionary) -> void:
- path = path.strip_edges(true, true)
-
- if path == _separator:
- path = ""
-
- var to_update = JSON.print(data)
- var status = _pusher.get_http_client_status()
- if status == HTTPClient.STATUS_DISCONNECTED or status != HTTPClient.STATUS_REQUESTING:
- var resolved_path = _get_list_url() + _db_path + "/" + path + _get_remaining_path()
-
- _pusher.request(resolved_path, _headers, true, HTTPClient.METHOD_PATCH, to_update)
- else:
- _update_queue.append({"path": path, "data": data})
-
-
-func push(data: Dictionary) -> void:
- var to_push = JSON.print(data)
- if _pusher.get_http_client_status() == HTTPClient.STATUS_DISCONNECTED:
- _pusher.request(_get_list_url() + _db_path + _get_remaining_path(), _headers, true, HTTPClient.METHOD_POST, to_push)
- else:
- _push_queue.append(data)
-
-
-func delete(reference: String) -> void:
- if _pusher.get_http_client_status() == HTTPClient.STATUS_DISCONNECTED:
- _pusher.request(_get_list_url() + _db_path + _separator + reference + _get_remaining_path(), _headers, true, HTTPClient.METHOD_DELETE, "")
- else:
- _delete_queue.append(reference)
-
-
-## Returns a deep copy of the current local copy of the data stored at this reference in the Firebase
-## Realtime Database.
-func get_data() -> Dictionary:
- if _store == null:
- return {}
-
- return _store.get_data()
+const ORDER_BY : String = "orderBy"
+const LIMIT_TO_FIRST : String = "limitToFirst"
+const LIMIT_TO_LAST : String = "limitToLast"
+const START_AT : String = "startAt"
+const END_AT : String = "endAt"
+const EQUAL_TO : String = "equalTo"
+
+@onready var _pusher := $Pusher
+@onready var _listener := $Listener
+@onready var _store := $DataStore
+
+var _auth : Dictionary
+var _config : Dictionary
+var _filter_query : Dictionary
+var _db_path : String
+var _cached_filter : String
+var _can_connect_to_host : bool = false
+
+const _put_tag : String = "put"
+const _patch_tag : String = "patch"
+const _delete_tag : String = "delete"
+const _separator : String = "/"
+const _json_list_tag : String = ".json"
+const _query_tag : String = "?"
+const _auth_tag : String = "auth="
+const _accept_header : String = "accept: text/event-stream"
+const _auth_variable_begin : String = "["
+const _auth_variable_end : String = "]"
+const _filter_tag : String = "&"
+const _escaped_quote : String = '"'
+const _equal_tag : String = "="
+const _key_filter_tag : String = "$key"
+
+var _headers : PackedStringArray = []
+
+func _ready() -> void:
+#region Set Listener info
+ $Listener.new_sse_event.connect(on_new_sse_event)
+ var base_url = _get_list_url(false).trim_suffix(_separator)
+ var extended_url = _separator + _db_path + _get_remaining_path(false)
+ var port = -1
+ if Firebase.emulating:
+ port = int(_config.emulators.ports.realtimeDatabase)
+ $Listener.connect_to_host(base_url, extended_url, port)
+#endregion Set Listener info
+
+#region Set Pusher info
+ $Pusher.queue_request_completed.connect(on_push_request_complete)
+#endregion Set Pusher info
+
+func set_db_path(path : String, filter_query_dict : Dictionary) -> void:
+ _db_path = path
+ _filter_query = filter_query_dict
+
+func set_auth_and_config(auth_ref : Dictionary, config_ref : Dictionary) -> void:
+ _auth = auth_ref
+ _config = config_ref
+
+func on_new_sse_event(headers : Dictionary, event : String, data : Dictionary) -> void:
+ if data:
+ var command = event
+ if command and command != "keep-alive":
+ _route_data(command, data.path, data.data)
+ if command == _put_tag:
+ if data.path == _separator and data.data and data.data.keys().size() > 0:
+ for key in data.data.keys():
+ new_data_update.emit(FirebaseResource.new(_separator + key, data.data[key]))
+ elif data.path != _separator:
+ new_data_update.emit(FirebaseResource.new(data.path, data.data))
+ elif command == _patch_tag:
+ patch_data_update.emit(FirebaseResource.new(data.path, data.data))
+ elif command == _delete_tag:
+ delete_data_update.emit(FirebaseResource.new(data.path, data.data))
+
+func update(path : String, data : Dictionary) -> void:
+ path = path.strip_edges(true, true)
+
+ if path == _separator:
+ path = ""
+
+ var to_update = JSON.stringify(data)
+
+ var resolved_path = (_get_list_url() + _db_path + "/" + path + _get_remaining_path())
+ _pusher.request(resolved_path, _headers, HTTPClient.METHOD_PATCH, to_update)
+
+func push(data : Dictionary) -> void:
+ var to_push = JSON.stringify(data)
+ _pusher.request(_get_list_url() + _db_path + _get_remaining_path(), _headers, HTTPClient.METHOD_POST, to_push)
+
+func delete(reference : String) -> void:
+ _pusher.request(_get_list_url() + _db_path + _separator + reference + _get_remaining_path(), _headers, HTTPClient.METHOD_DELETE, "")
+
+#
+# Returns a deep copy of the current local copy of the data stored at this reference in the Firebase
+# Realtime Database.
+#
+func get_data() -> Dictionary:
+ if _store == null:
+ return { }
-func _get_remaining_path(is_push: bool = true) -> String:
- var remaining_path = ""
- if not _filter_query or is_push:
- remaining_path = _json_list_tag + _query_tag + _auth_tag + Firebase.Auth.auth.idtoken
- else:
- remaining_path = _json_list_tag + _query_tag + _get_filter() + _filter_tag + _auth_tag + Firebase.Auth.auth.idtoken
+ return _store.get_data()
- if Firebase.emulating:
- remaining_path += "&ns=" + _config.projectId + "-default-rtdb"
+func _get_remaining_path(is_push : bool = true) -> String:
+ var remaining_path = ""
+ if _filter_query_empty() or is_push:
+ remaining_path = _json_list_tag + _query_tag + _auth_tag + Firebase.Auth.auth.idtoken
+ else:
+ remaining_path = _json_list_tag + _query_tag + _get_filter() + _filter_tag + _auth_tag + Firebase.Auth.auth.idtoken
- return remaining_path
+ if Firebase.emulating:
+ remaining_path += "&ns="+_config.projectId+"-default-rtdb"
+ return remaining_path
-func _get_list_url(with_port: bool = true) -> String:
- var url = Firebase.Database._base_url.trim_suffix(_separator)
- if with_port and Firebase.emulating:
- url += ":" + _config.emulators.ports.realtimeDatabase
- return url + _separator
+func _get_list_url(with_port:bool = true) -> String:
+ var url = Firebase.Database._base_url.trim_suffix(_separator)
+ if with_port and Firebase.emulating:
+ url += ":" + _config.emulators.ports.realtimeDatabase
+ return url + _separator
func _get_filter():
- if not _filter_query:
- return ""
- # At the moment, this means you can't dynamically change your filter; I think it's okay to specify that in the rules.
- if not _cached_filter:
- _cached_filter = ""
- if _filter_query.has(ORDER_BY):
- _cached_filter += ORDER_BY + _equal_tag + _escaped_quote + _filter_query[ORDER_BY] + _escaped_quote
- _filter_query.erase(ORDER_BY)
- else:
- _cached_filter += ORDER_BY + _equal_tag + _escaped_quote + _key_filter_tag + _escaped_quote # Presumptuous, but to get it to work at all...
- for key in _filter_query.keys():
- _cached_filter += _filter_tag + key + _equal_tag + _filter_query[key]
-
- return _cached_filter
-
-
-## Appropriately updates the current local copy of the data stored at this reference in the Firebase
-## Realtime Database.
-func _route_data(command: String, path: String, data) -> void:
- if command == _put_tag:
- _store.put(path, data)
- elif command == _patch_tag:
- _store.patch(path, data)
- elif command == _delete_tag:
- _store.delete(path, data)
-
-
-func on_push_request_complete(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray) -> void:
- if response_code == HTTPClient.RESPONSE_OK:
- emit_signal("push_successful")
- else:
- emit_signal("push_failed")
-
- if _push_queue.size() > 0:
- push(_push_queue.pop_front())
- return
- if _update_queue.size() > 0:
- var e = _update_queue.pop_front()
- update(e["path"], e["data"])
- return
- if _delete_queue.size() > 0:
- delete(_delete_queue.pop_front())
+ if _filter_query_empty():
+ return ""
+ # At the moment, this means you can't dynamically change your filter; I think it's okay to specify that in the rules.
+ if _cached_filter != "":
+ _cached_filter = ""
+ if _filter_query.has(ORDER_BY):
+ _cached_filter += ORDER_BY + _equal_tag + _escaped_quote + _filter_query[ORDER_BY] + _escaped_quote
+ _filter_query.erase(ORDER_BY)
+ else:
+ _cached_filter += ORDER_BY + _equal_tag + _escaped_quote + _key_filter_tag + _escaped_quote # Presumptuous, but to get it to work at all...
+ for key in _filter_query.keys():
+ _cached_filter += _filter_tag + key + _equal_tag + _filter_query[key]
+
+ return _cached_filter
+
+func _filter_query_empty() -> bool:
+ return _filter_query == null or _filter_query.is_empty()
+
+#
+# Appropriately updates the current local copy of the data stored at this reference in the Firebase
+# Realtime Database.
+#
+func _route_data(command : String, path : String, data) -> void:
+ if command == _put_tag:
+ _store.put(path, data)
+ elif command == _patch_tag:
+ _store.patch(path, data)
+ elif command == _delete_tag:
+ _store.delete(path, data)
+
+func on_push_request_complete(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ if response_code == HTTPClient.RESPONSE_OK:
+ push_successful.emit()
+ else:
+ push_failed.emit()
diff --git a/addons/godot-firebase/database/resource.gd b/addons/godot-firebase/database/resource.gd
index 9b7e82d..ff8a620 100644
--- a/addons/godot-firebase/database/resource.gd
+++ b/addons/godot-firebase/database/resource.gd
@@ -1,19 +1,16 @@
## @meta-authors SIsilicon, fenix-hub
## @meta-version 2.2
## A generic resource used by Firebase Database.
-tool
+@tool
class_name FirebaseResource
extends Resource
-
-var key: String
+var key : String
var data
-
-func _init(key: String, data) -> void:
- self.key = key.lstrip("/")
- self.data = data
-
+func _init(key : String,data):
+ self.key = key.lstrip("/")
+ self.data = data
func _to_string():
- return "{ key:{key}, data:{data} }".format({key = key, data = data})
+ return "{ key:{key}, data:{data} }".format({key = key, data = data})
diff --git a/addons/godot-firebase/dynamiclinks/dynamiclinks.gd b/addons/godot-firebase/dynamiclinks/dynamiclinks.gd
index d749458..8f7a6c7 100644
--- a/addons/godot-firebase/dynamiclinks/dynamiclinks.gd
+++ b/addons/godot-firebase/dynamiclinks/dynamiclinks.gd
@@ -3,112 +3,107 @@
## @meta-version 1.1
## The dynamic links API for Firebase
## Documentation TODO.
-tool
+@tool
class_name FirebaseDynamicLinks
extends Node
-
signal dynamic_link_generated(link_result)
signal generate_dynamic_link_error(error)
-const _AUTHORIZATION_HEADER: String = "Authorization: Bearer "
-const _API_VERSION: String = "v1"
+const _AUTHORIZATION_HEADER : String = "Authorization: Bearer "
+const _API_VERSION : String = "v1"
-var request: int = -1
+var request : int = -1
-var _base_url: String = ""
+var _base_url : String = ""
-var _config: Dictionary = {}
+var _config : Dictionary = {}
-var _auth: Dictionary
-var _request_list_node: HTTPRequest
+var _auth : Dictionary
+var _request_list_node : HTTPRequest
-var _headers: PoolStringArray = []
+var _headers : PackedStringArray = []
enum Requests {
- NONE = -1,
- GENERATE
-}
-
-
-func _set_config(config_json: Dictionary) -> void:
- _config = config_json
- _request_list_node = HTTPRequest.new()
- _request_list_node.connect("request_completed", self, "_on_request_completed")
- add_child(_request_list_node)
- _check_emulating()
-
-
-func _check_emulating() -> void:
- ## Check emulating
- if not Firebase.emulating:
- _base_url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=%s"
- _base_url %= _config.apiKey
- else:
- var port: String = _config.emulators.ports.dynamicLinks
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Dynamic Links has not been configured.")
- else:
- _base_url = "http://localhost:{port}/{version}/".format({version = _API_VERSION, port = port})
-
-
-var _link_request_body: Dictionary = {
- "dynamicLinkInfo": {
- "domainUriPrefix": "",
- "link": "",
- "androidInfo": {
- "androidPackageName": ""
- },
- "iosInfo": {
- "iosBundleId": ""
- }
- },
- "suffix": {
- "option": ""
- }
+ NONE = -1,
+ GENERATE
+ }
+
+func _set_config(config_json : Dictionary) -> void:
+ _config = config_json
+ _request_list_node = HTTPRequest.new()
+ Utilities.fix_http_request(_request_list_node)
+ _request_list_node.request_completed.connect(_on_request_completed)
+ add_child(_request_list_node)
+ _check_emulating()
+
+
+func _check_emulating() -> void :
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = "https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=%s"
+ _base_url %= _config.apiKey
+ else:
+ var port : String = _config.emulators.ports.dynamicLinks
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Dynamic Links has not been configured.")
+ else:
+ _base_url = "http://localhost:{port}/{version}/".format({ version = _API_VERSION, port = port })
+
+
+var _link_request_body : Dictionary = {
+ "dynamicLinkInfo": {
+ "domainUriPrefix": "",
+ "link": "",
+ "androidInfo": {
+ "androidPackageName": ""
+ },
+ "iosInfo": {
+ "iosBundleId": ""
+ }
+ },
+ "suffix": {
+ "option": ""
+ }
}
-
## @args log_link, APN, IBI, is_unguessable
## This function is used to generate a dynamic link using the Firebase REST API
## It will return a JSON with the shortened link
-func generate_dynamic_link(long_link: String, APN: String, IBI: String, is_unguessable: bool) -> void:
- if not _config.domainUriPrefix or _config.domainUriPrefix == "":
- emit_signal("generate_dynamic_link_error", "You're missing the domainUriPrefix in config file! Error!")
- Firebase._printerr("You're missing the domainUriPrefix in config file! Error!")
- return
-
- request = Requests.GENERATE
- _link_request_body.dynamicLinkInfo.domainUriPrefix = _config.domainUriPrefix
- _link_request_body.dynamicLinkInfo.link = long_link
- _link_request_body.dynamicLinkInfo.androidInfo.androidPackageName = APN
- _link_request_body.dynamicLinkInfo.iosInfo.iosBundleId = IBI
- if is_unguessable:
- _link_request_body.suffix.option = "UNGUESSABLE"
- else:
- _link_request_body.suffix.option = "SHORT"
- _request_list_node.request(_base_url, _headers, true, HTTPClient.METHOD_POST, JSON.print(_link_request_body))
-
-
-func _on_request_completed(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray) -> void:
- var result_body = JSON.parse(body.get_string_from_utf8())
- if result_body.error:
- emit_signal("generate_dynamic_link_error", result_body.error_string)
- return
- else:
- result_body = result_body.result
-
- emit_signal("dynamic_link_generated", result_body.shortLink)
- request = Requests.NONE
-
-
-func _on_FirebaseAuth_login_succeeded(auth_result: Dictionary) -> void:
- _auth = auth_result
-
-
-func _on_FirebaseAuth_token_refresh_succeeded(auth_result: Dictionary) -> void:
- _auth = auth_result
-
+func generate_dynamic_link(long_link : String, APN : String, IBI : String, is_unguessable : bool) -> void:
+ if not _config.domainUriPrefix or _config.domainUriPrefix == "":
+ generate_dynamic_link_error.emit("Error: Missing domainUriPrefix in config file. Parameter is required.")
+ Firebase._printerr("Error: Missing domainUriPrefix in config file. Parameter is required.")
+ return
+
+ request = Requests.GENERATE
+ _link_request_body.dynamicLinkInfo.domainUriPrefix = _config.domainUriPrefix
+ _link_request_body.dynamicLinkInfo.link = long_link
+ _link_request_body.dynamicLinkInfo.androidInfo.androidPackageName = APN
+ _link_request_body.dynamicLinkInfo.iosInfo.iosBundleId = IBI
+ if is_unguessable:
+ _link_request_body.suffix.option = "UNGUESSABLE"
+ else:
+ _link_request_body.suffix.option = "SHORT"
+ _request_list_node.request(_base_url, _headers, HTTPClient.METHOD_POST, JSON.stringify(_link_request_body))
+
+func _on_request_completed(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ var json = JSON.new()
+ var json_parse_result = json.parse(body.get_string_from_utf8())
+ if json_parse_result == OK:
+ var result_body = json.data.result # Check this
+ dynamic_link_generated.emit(result_body.shortLink)
+ else:
+ generate_dynamic_link_error.emit(json.get_error_message())
+ # This used to return immediately when above, but it should still clear the request, so removing it
+
+ request = Requests.NONE
+
+func _on_FirebaseAuth_login_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
+
+func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
func _on_FirebaseAuth_logout() -> void:
- _auth = {}
+ _auth = {}
diff --git a/addons/godot-firebase/example.env b/addons/godot-firebase/example.env
new file mode 100644
index 0000000..e35f66a
--- /dev/null
+++ b/addons/godot-firebase/example.env
@@ -0,0 +1,24 @@
+[firebase/environment_variables]
+
+"apiKey"="",
+"authDomain"="",
+"databaseURL"="",
+"projectId"="",
+"storageBucket"="",
+"messagingSenderId"="",
+"appId"="",
+"measurementId"=""
+"clientId"=""
+"clientSecret"=""
+"domainUriPrefix"=""
+"functionsGeoZone"=""
+"cacheLocation"=""
+
+[firebase/emulators/ports]
+
+authentication=""
+firestore=""
+realtimeDatabase=""
+functions=""
+storage=""
+dynamicLinks=""
diff --git a/addons/godot-firebase/firebase/firebase.gd b/addons/godot-firebase/firebase/firebase.gd
index e8cd0ec..f2eed9f 100644
--- a/addons/godot-firebase/firebase/firebase.gd
+++ b/addons/godot-firebase/firebase/firebase.gd
@@ -1,147 +1,144 @@
## @meta-authors Kyle Szklenski
-## @meta-version 2.5
+## @meta-version 2.6
## The Firebase Godot API.
## This singleton gives you access to your Firebase project and its capabilities. Using this requires you to fill out some Firebase configuration settings. It currently comes with four modules.
## - [code]Auth[/code]: Manages user authentication (logging and out, etc...)
## - [code]Database[/code]: A NonSQL realtime database for managing data in JSON structures.
## - [code]Firestore[/code]: Similar to Database, but stores data in collections and documents, among other things.
## - [code]Storage[/code]: Gives access to Cloud Storage; perfect for storing files like images and other assets.
+## - [code]RemoteConfig[/code]: Gives access to Remote Config functionality; allows you to download your app's configuration from Firebase, do A/B testing, and more.
##
## @tutorial https://github.com/GodotNuts/GodotFirebase/wiki
-tool
+@tool
extends Node
-
-const _ENVIRONMENT_VARIABLES: String = "firebase/environment_variables"
-const _EMULATORS_PORTS: String = "firebase/emulators/ports"
-const _AUTH_PROVIDERS: String = "firebase/auth_providers"
+const _ENVIRONMENT_VARIABLES : String = "firebase/environment_variables"
+const _EMULATORS_PORTS : String = "firebase/emulators/ports"
+const _AUTH_PROVIDERS : String = "firebase/auth_providers"
## @type FirebaseAuth
## The Firebase Authentication API.
-onready var Auth: FirebaseAuth = $Auth
+@onready var Auth := $Auth
## @type FirebaseFirestore
## The Firebase Firestore API.
-onready var Firestore: FirebaseFirestore = $Firestore
+@onready var Firestore := $Firestore
## @type FirebaseDatabase
## The Firebase Realtime Database API.
-onready var Database: FirebaseDatabase = $Database
+@onready var Database := $Database
## @type FirebaseStorage
## The Firebase Storage API.
-onready var Storage: FirebaseStorage = $Storage
+@onready var Storage := $Storage
## @type FirebaseDynamicLinks
## The Firebase Dynamic Links API.
-onready var DynamicLinks: FirebaseDynamicLinks = $DynamicLinks
+@onready var DynamicLinks := $DynamicLinks
## @type FirebaseFunctions
## The Firebase Cloud Functions API
-onready var Functions: FirebaseFunctions = $Functions
+@onready var Functions := $Functions
+
+## @type FirebaseRemoteConfig
+## The Firebase Remote Config API
+@onready var RemoteConfigAPI := $RemoteConfig
-export var emulating: bool = false
+@export var emulating : bool = false
# Configuration used by all files in this project
# These values can be found in your Firebase Project
-# See the README on Github for how to access
-var _config: Dictionary = {
- "apiKey": "",
- "authDomain": "",
- "databaseURL": "",
- "projectId": "",
- "storageBucket": "",
- "messagingSenderId": "",
- "appId": "",
- "measurementId": "",
- "clientId": "",
- "clientSecret": "",
- "domainUriPrefix": "",
- "functionsGeoZone": "",
- "cacheLocation": "user://.firebase_cache",
- "emulators": {
- "ports": {
- "authentication": "",
- "firestore": "",
- "realtimeDatabase": "",
- "functions": "",
- "storage": "",
- "dynamicLinks": ""
- }
- },
- "workarounds": {
- "database_connection_closed_issue": false, # fixes https://github.com/firebase/firebase-tools/issues/3329
- },
- "auth_providers": {
- "facebook_id": "",
- "facebook_secret": "",
- "github_id": "",
- "github_secret": "",
- "twitter_id": "",
- "twitter_secret": ""
- }
+# See the README checked Github for how to access
+var _config : Dictionary = {
+ "apiKey": "",
+ "authDomain": "",
+ "databaseURL": "",
+ "projectId": "",
+ "storageBucket": "",
+ "messagingSenderId": "",
+ "appId": "",
+ "measurementId": "",
+ "clientId": "",
+ "clientSecret" : "",
+ "domainUriPrefix" : "",
+ "functionsGeoZone" : "",
+ "cacheLocation":"",
+ "emulators": {
+ "ports" : {
+ "authentication" : "",
+ "firestore" : "",
+ "realtimeDatabase" : "",
+ "functions" : "",
+ "storage" : "",
+ "dynamicLinks" : ""
+ }
+ },
+ "workarounds":{
+ "database_connection_closed_issue": false, # fixes https://github.com/firebase/firebase-tools/issues/3329
+ },
+ "auth_providers": {
+ "facebook_id":"",
+ "facebook_secret":"",
+ "github_id":"",
+ "github_secret":"",
+ "twitter_id":"",
+ "twitter_secret":""
+ }
}
-
func _ready() -> void:
- _load_config()
-
+ _load_config()
-func set_emulated(emulating: bool = true) -> void:
- self.emulating = emulating
- _check_emulating()
+func set_emulated(emulating : bool = true) -> void:
+ self.emulating = emulating
+ _check_emulating()
func _check_emulating() -> void:
- if emulating:
- print("[Firebase] You are now in 'emulated' mode: the services you are using will try to connect to your local emulators, if available.")
- for module in get_children():
- if module.has_method("_check_emulating"):
- module._check_emulating()
-
+ if emulating:
+ print("[Firebase] You are now in 'emulated' mode: the services you are using will try to connect to your local emulators, if available.")
+ for module in get_children():
+ if module.has_method("_check_emulating"):
+ module._check_emulating()
func _load_config() -> void:
- if _config.apiKey != "" and _config.authDomain != "":
- pass
- else:
- var env = ConfigFile.new()
- var err = env.load("res://addons/godot-firebase/.env")
- if err == OK:
- for key in _config.keys():
- if key == "emulators":
- for port in _config[key]["ports"].keys():
- _config[key]["ports"][port] = env.get_value(_EMULATORS_PORTS, port, "")
- if key == "auth_providers":
- for provider in _config[key].keys():
- _config[key][provider] = env.get_value(_AUTH_PROVIDERS, provider)
- else:
- var value: String = env.get_value(_ENVIRONMENT_VARIABLES, key, "")
- if value == "":
- _print("The value for `%s` is not configured. If you are not planning to use it, ignore this message." % key)
- else:
- _config[key] = value
- else:
- _printerr("Unable to read .env file at path 'res://addons/godot-firebase/.env'")
-
- _setup_modules()
-
+ if not (_config.apiKey != "" and _config.authDomain != ""):
+ var env = ConfigFile.new()
+ var err = env.load("res://addons/godot-firebase/.env")
+ if err == OK:
+ for key in _config.keys():
+ var config_value = _config[key]
+ if key == "emulators" and config_value.has("ports"):
+ for port in config_value["ports"].keys():
+ config_value["ports"][port] = env.get_value(_EMULATORS_PORTS, port, "")
+ if key == "auth_providers":
+ for provider in config_value.keys():
+ config_value[provider] = env.get_value(_AUTH_PROVIDERS, provider, "")
+ else:
+ var value : String = env.get_value(_ENVIRONMENT_VARIABLES, key, "")
+ if value == "":
+ _print("The value for `%s` is not configured. If you are not planning to use it, ignore this message." % key)
+ else:
+ _config[key] = value
+ else:
+ _printerr("Unable to read .env file at path 'res://addons/godot-firebase/.env'")
+
+ _setup_modules()
func _setup_modules() -> void:
- for module in get_children():
- module._set_config(_config)
- if not module.has_method("_on_FirebaseAuth_login_succeeded"):
- continue
- Auth.connect("login_succeeded", module, "_on_FirebaseAuth_login_succeeded")
- Auth.connect("signup_succeeded", module, "_on_FirebaseAuth_login_succeeded")
- Auth.connect("token_refresh_succeeded", module, "_on_FirebaseAuth_token_refresh_succeeded")
- Auth.connect("logged_out", module, "_on_FirebaseAuth_logout")
-
+ for module in get_children():
+ module._set_config(_config)
+ if not module.has_method("_on_FirebaseAuth_login_succeeded"):
+ continue
+ Auth.login_succeeded.connect(module._on_FirebaseAuth_login_succeeded)
+ Auth.signup_succeeded.connect(module._on_FirebaseAuth_login_succeeded)
+ Auth.token_refresh_succeeded.connect(module._on_FirebaseAuth_token_refresh_succeeded)
+ Auth.logged_out.connect(module._on_FirebaseAuth_logout)
# -------------
-func _printerr(error: String) -> void:
- printerr("[Firebase Error] >> " + error)
-
+func _printerr(error : String) -> void:
+ printerr("[Firebase Error] >> " + error)
-func _print(msg: String) -> void:
- print("[Firebase] >> " + msg)
+func _print(msg : String) -> void:
+ print("[Firebase] >> " + str(msg))
diff --git a/addons/godot-firebase/firebase/firebase.tscn b/addons/godot-firebase/firebase/firebase.tscn
index 6b86131..31f5b56 100644
--- a/addons/godot-firebase/firebase/firebase.tscn
+++ b/addons/godot-firebase/firebase/firebase.tscn
@@ -1,31 +1,36 @@
-[gd_scene load_steps=8 format=2]
+[gd_scene load_steps=9 format=3 uid="uid://cvb26atjckwlq"]
-[ext_resource path="res://addons/godot-firebase/database/database.gd" type="Script" id=1]
-[ext_resource path="res://addons/godot-firebase/firestore/firestore.gd" type="Script" id=2]
-[ext_resource path="res://addons/godot-firebase/firebase/firebase.gd" type="Script" id=3]
-[ext_resource path="res://addons/godot-firebase/auth/auth.gd" type="Script" id=4]
-[ext_resource path="res://addons/godot-firebase/storage/storage.gd" type="Script" id=5]
-[ext_resource path="res://addons/godot-firebase/dynamiclinks/dynamiclinks.gd" type="Script" id=6]
-[ext_resource path="res://addons/godot-firebase/functions/functions.gd" type="Script" id=7]
+[ext_resource type="Script" path="res://addons/godot-firebase/database/database.gd" id="1"]
+[ext_resource type="Script" path="res://addons/godot-firebase/firestore/firestore.gd" id="2"]
+[ext_resource type="Script" path="res://addons/godot-firebase/firebase/firebase.gd" id="3"]
+[ext_resource type="Script" path="res://addons/godot-firebase/auth/auth.gd" id="4"]
+[ext_resource type="Script" path="res://addons/godot-firebase/storage/storage.gd" id="5"]
+[ext_resource type="Script" path="res://addons/godot-firebase/dynamiclinks/dynamiclinks.gd" id="6"]
+[ext_resource type="Script" path="res://addons/godot-firebase/functions/functions.gd" id="7"]
+[ext_resource type="PackedScene" uid="uid://5xa6ulbllkjk" path="res://addons/godot-firebase/remote_config/firebase_remote_config.tscn" id="8_mvdf4"]
[node name="Firebase" type="Node"]
-pause_mode = 2
-script = ExtResource( 3 )
+script = ExtResource("3")
[node name="Auth" type="HTTPRequest" parent="."]
-script = ExtResource( 4 )
+max_redirects = 12
+timeout = 10.0
+script = ExtResource("4")
[node name="Firestore" type="Node" parent="."]
-script = ExtResource( 2 )
+script = ExtResource("2")
[node name="Database" type="Node" parent="."]
-script = ExtResource( 1 )
+script = ExtResource("1")
[node name="Storage" type="Node" parent="."]
-script = ExtResource( 5 )
+script = ExtResource("5")
[node name="DynamicLinks" type="Node" parent="."]
-script = ExtResource( 6 )
+script = ExtResource("6")
[node name="Functions" type="Node" parent="."]
-script = ExtResource( 7 )
+script = ExtResource("7")
+
+[node name="RemoteConfig" parent="." instance=ExtResource("8_mvdf4")]
+accept_gzip = false
diff --git a/addons/godot-firebase/firestore/field_transform.gd b/addons/godot-firebase/firestore/field_transform.gd
new file mode 100644
index 0000000..b69395b
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transform.gd
@@ -0,0 +1,22 @@
+extends FirestoreTransform
+class_name FieldTransform
+
+enum TransformType { SetToServerValue, Maximum, Minimum, Increment, AppendMissingElements, RemoveAllFromArray }
+
+const transtype_string_map = {
+ TransformType.SetToServerValue : "setToServerValue",
+ TransformType.Increment : "increment",
+ TransformType.Maximum : "maximum",
+ TransformType.Minimum : "minimum",
+ TransformType.AppendMissingElements : "appendMissingElements",
+ TransformType.RemoveAllFromArray : "removeAllFromArray"
+}
+
+var document_exists : bool
+var document_name : String
+var field_path : String
+var transform_type : TransformType
+var value : Variant
+
+func get_transform_type() -> String:
+ return transtype_string_map[transform_type]
diff --git a/addons/godot-firebase/firestore/field_transform_array.gd b/addons/godot-firebase/firestore/field_transform_array.gd
new file mode 100644
index 0000000..72552e9
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transform_array.gd
@@ -0,0 +1,35 @@
+class_name FieldTransformArray
+extends RefCounted
+
+var transforms = []
+
+var _extended_url
+var _collection_name
+const _separator = "/"
+
+func set_config(config : Dictionary):
+ _extended_url = config.extended_url
+ _collection_name = config.collection_name
+
+func push_back(transform : FieldTransform) -> void:
+ transforms.push_back(transform)
+
+func serialize() -> Dictionary:
+ var body = {}
+ var writes_array = []
+ for transform in transforms:
+ writes_array.push_back({
+ "currentDocument": { "exists" : transform.document_exists },
+ "transform" : {
+ "document": _extended_url + _collection_name + _separator + transform.document_name,
+ "fieldTransforms": [
+ {
+ "fieldPath": transform.field_path,
+ transform.get_transform_type(): transform.value
+ }]
+ }
+ })
+
+ body = { "writes": writes_array }
+
+ return body
diff --git a/addons/godot-firebase/firestore/field_transforms/decrement_transform.gd b/addons/godot-firebase/firestore/field_transforms/decrement_transform.gd
new file mode 100644
index 0000000..ed7f4b7
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transforms/decrement_transform.gd
@@ -0,0 +1,19 @@
+class_name DecrementTransform
+extends FieldTransform
+
+func _init(doc_name : String, doc_must_exist : bool, path_to_field : String, by_this_much : Variant) -> void:
+ document_name = doc_name
+ document_exists = doc_must_exist
+ field_path = path_to_field
+
+ transform_type = FieldTransform.TransformType.Increment
+
+ var value_type = typeof(by_this_much)
+ if value_type == TYPE_INT:
+ self.value = {
+ "integerValue": -by_this_much
+ }
+ elif value_type == TYPE_FLOAT:
+ self.value = {
+ "doubleValue": -by_this_much
+ }
diff --git a/addons/godot-firebase/firestore/field_transforms/increment_transform.gd b/addons/godot-firebase/firestore/field_transforms/increment_transform.gd
new file mode 100644
index 0000000..5c7a38c
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transforms/increment_transform.gd
@@ -0,0 +1,19 @@
+class_name IncrementTransform
+extends FieldTransform
+
+func _init(doc_name : String, doc_must_exist : bool, path_to_field : String, by_this_much : Variant) -> void:
+ document_name = doc_name
+ document_exists = doc_must_exist
+ field_path = path_to_field
+
+ transform_type = FieldTransform.TransformType.Increment
+
+ var value_type = typeof(by_this_much)
+ if value_type == TYPE_INT:
+ self.value = {
+ "integerValue": by_this_much
+ }
+ elif value_type == TYPE_FLOAT:
+ self.value = {
+ "doubleValue": by_this_much
+ }
diff --git a/addons/godot-firebase/firestore/field_transforms/max_transform.gd b/addons/godot-firebase/firestore/field_transforms/max_transform.gd
new file mode 100644
index 0000000..a10c87e
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transforms/max_transform.gd
@@ -0,0 +1,19 @@
+class_name MaxTransform
+extends FieldTransform
+
+func _init(doc_name : String, doc_must_exist : bool, path_to_field : String, value : Variant) -> void:
+ document_name = doc_name
+ document_exists = doc_must_exist
+ field_path = path_to_field
+
+ transform_type = FieldTransform.TransformType.Maximum
+
+ var value_type = typeof(value)
+ if value_type == TYPE_INT:
+ self.value = {
+ "integerValue": value
+ }
+ elif value_type == TYPE_FLOAT:
+ self.value = {
+ "doubleValue": value
+ }
diff --git a/addons/godot-firebase/firestore/field_transforms/min_transform.gd b/addons/godot-firebase/firestore/field_transforms/min_transform.gd
new file mode 100644
index 0000000..82fd8e4
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transforms/min_transform.gd
@@ -0,0 +1,19 @@
+class_name MinTransform
+extends FieldTransform
+
+func _init(doc_name : String, doc_must_exist : bool, path_to_field : String, value : Variant) -> void:
+ document_name = doc_name
+ document_exists = doc_must_exist
+ field_path = path_to_field
+
+ transform_type = FieldTransform.TransformType.Minimum
+
+ var value_type = typeof(value)
+ if value_type == TYPE_INT:
+ self.value = {
+ "integerValue": value
+ }
+ elif value_type == TYPE_FLOAT:
+ self.value = {
+ "doubleValue": value
+ }
diff --git a/addons/godot-firebase/firestore/field_transforms/server_timestamp_transform.gd b/addons/godot-firebase/firestore/field_transforms/server_timestamp_transform.gd
new file mode 100644
index 0000000..7c7c380
--- /dev/null
+++ b/addons/godot-firebase/firestore/field_transforms/server_timestamp_transform.gd
@@ -0,0 +1,10 @@
+class_name ServerTimestampTransform
+extends FieldTransform
+
+func _init(doc_name : String, doc_must_exist : bool, path_to_field : String) -> void:
+ document_name = doc_name
+ document_exists = doc_must_exist
+ field_path = path_to_field
+
+ transform_type = FieldTransform.TransformType.SetToServerValue
+ value = "REQUEST_TIME"
diff --git a/addons/godot-firebase/firestore/firestore.gd b/addons/godot-firebase/firestore/firestore.gd
index 156a645..1676d3a 100644
--- a/addons/godot-firebase/firestore/firestore.gd
+++ b/addons/godot-firebase/firestore/firestore.gd
@@ -12,27 +12,19 @@
## (source: [url=https://firebase.google.com/docs/firestore]Firestore[/url])
##
## @tutorial https://github.com/GodotNuts/GodotFirebase/wiki/Firestore
-tool
+@tool
class_name FirebaseFirestore
extends Node
const _API_VERSION : String = "v1"
-## Emitted when a [code]list()[/code] request is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types Array
-signal listed_documents(documents)
-## Emitted when a [code]query()[/code] request is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types Array
-signal result_query(result)
-## Emitted when a [code]query()[/code] request is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types Array
## Emitted when a [code]list()[/code] or [code]query()[/code] request is [b]not[/b] successfully completed.
-signal task_error(code,status,message)
+signal error(code, status, message)
enum Requests {
- NONE = -1, ## Firestore is not processing any request.
- LIST, ## Firestore is processing a [code]list()[/code] request on a collection.
- QUERY ## Firestore is processing a [code]query()[/code] request on a collection.
+ NONE = -1, ## Firestore is not processing any request.
+ LIST, ## Firestore is processing a [code]list()[/code] request checked a collection.
+ QUERY ## Firestore is processing a [code]query()[/code] request checked a collection.
}
# TODO: Implement cache size limit
@@ -48,333 +40,204 @@ const _MAX_POOLED_REQUEST_AGE = 30
## The code indicating the request Firestore is processing.
## See @[enum FirebaseFirestore.Requests] to get a full list of codes identifiers.
## @enum Requests
-var request : int = -1
-
-## Whether cache files can be used and generated.
-## @default true
-var persistence_enabled : bool = true
-
-## Whether an internet connection can be used.
-## @default true
-var networking: bool = true setget set_networking
-
-## A Dictionary containing all collections currently referenced.
-## @type Dictionary
-var collections : Dictionary = {}
+var request: int = -1
## A Dictionary containing all authentication fields for the current logged user.
## @type Dictionary
-var auth : Dictionary
+var auth: Dictionary
-var _config : Dictionary = {}
+var _config: Dictionary = {}
var _cache_loc: String
-var _encrypt_key := "5vg76n90345f7w390346" if OS.get_name() in ["HTML5", "UWP"] else OS.get_unique_id()
+var _encrypt_key := "5vg76n90345f7w390346" if Utilities.is_web() else OS.get_unique_id()
-var _base_url : String = ""
-var _extended_url : String = "projects/[PROJECT_ID]/databases/(default)/documents/"
-var _query_suffix : String = ":runQuery"
+var _base_url: String = ""
+var _extended_url: String = "projects/[PROJECT_ID]/databases/(default)/documents/"
+var _query_suffix: String = ":runQuery"
+var _agg_query_suffix: String = ":runAggregationQuery"
#var _connect_check_node : HTTPRequest
-var _request_list_node : HTTPRequest
-var _requests_queue : Array = []
-var _current_query : FirestoreQuery
-
-var _http_request_pool := []
-
-var _offline: bool = false setget _set_offline
-
-func _ready() -> void:
- pass
-
-func _process(delta : float) -> void:
- for i in range(_http_request_pool.size() - 1, -1, -1):
- var request = _http_request_pool[i]
- if not request.get_meta("requesting"):
- var lifetime: float = request.get_meta("lifetime") + delta
- if lifetime > _MAX_POOLED_REQUEST_AGE:
- request.queue_free()
- _http_request_pool.remove(i)
- request.set_meta("lifetime", lifetime)
-
+var _request_list_node: HTTPRequest
+var _requests_queue: Array = []
+var _current_query: FirestoreQuery
## Returns a reference collection by its [i]path[/i].
##
## The returned object will be of [code]FirestoreCollection[/code] type.
-## If saved into a variable, it can be used to issue requests on the collection itself.
+## If saved into a variable, it can be used to issue requests checked the collection itself.
## @args path
## @return FirestoreCollection
func collection(path : String) -> FirestoreCollection:
- if not collections.has(path):
- var coll : FirestoreCollection = FirestoreCollection.new()
- coll._extended_url = _extended_url
- coll._base_url = _base_url
- coll._config = _config
- coll.auth = auth
- coll.collection_name = path
- coll.firestore = self
- collections[path] = coll
- return coll
- else:
- return collections[path]
-
-
-## Issue a query on your Firestore database.
+ for coll in get_children():
+ if coll is FirestoreCollection:
+ if coll.collection_name == path:
+ return coll
+
+ var coll : FirestoreCollection = FirestoreCollection.new()
+ coll._extended_url = _extended_url
+ coll._base_url = _base_url
+ coll._config = _config
+ coll.auth = auth
+ coll.collection_name = path
+ add_child(coll)
+ return coll
+
+
+## Issue a query checked your Firestore database.
##
## [b]Note:[/b] a [code]FirestoreQuery[/code] object needs to be created to issue the query.
-## This method will return a [code]FirestoreTask[/code] object, representing a reference to the request issued.
-## If saved into a variable, the [code]FirestoreTask[/code] object can be used to yield on the [code]result_query(result)[/code] signal, or the more generic [code]task_finished(result)[/code] signal.
+## When awaited, this function returns the resulting array from the query.
##
## ex.
-## [code]var query_task : FirestoreTask = Firebase.Firestore.query(FirestoreQuery.new())[/code]
-## [code]yield(query_task, "task_finished")[/code]
-## Since the emitted signal is holding an argument, it can be directly retrieved as a return variable from the [code]yield()[/code] function.
-##
-## ex.
-## [code]var result : Array = yield(query_task, "task_finished")[/code]
+## [code]var query_results = await Firebase.Firestore.query(FirestoreQuery.new())[/code]
##
## [b]Warning:[/b] It currently does not work offline!
##
## @args query
## @arg-types FirestoreQuery
-## @return FirestoreTask
-func query(query : FirestoreQuery) -> FirestoreTask:
- var firestore_task : FirestoreTask = FirestoreTask.new()
- firestore_task.connect("result_query", self, "_on_result_query")
- firestore_task.connect("task_error", self, "_on_task_error")
- firestore_task.action = FirestoreTask.Task.TASK_QUERY
- var body : Dictionary = { structuredQuery = query.query }
- var url : String = _base_url + _extended_url + _query_suffix
-
- firestore_task.data = query
- firestore_task._fields = JSON.print(body)
- firestore_task._url = url
- _pooled_request(firestore_task)
- return firestore_task
-
-
-## Request a list of contents (documents and/or collections) inside a collection, specified by its [i]id[/i]. This method will return a [code]FirestoreTask[/code] object, representing a reference to the request issued. If saved into a variable, the [code]FirestoreTask[/code] object can be used to yield on the [code]result_query(result)[/code] signal, or the more generic [code]task_finished(result)[/code] signal.
-## [b]Note:[/b] [code]order_by[/code] does not work in offline mode.
-## ex.
-## [code]var query_task : FirestoreTask = Firebase.Firestore.query(FirestoreQuery.new())[/code]
-## [code]yield(query_task, "task_finished")[/code]
-## Since the emitted signal is holding an argument, it can be directly retrieved as a return variable from the [code]yield()[/code] function.
+## @return Array[FirestoreDocument]
+func query(query : FirestoreQuery) -> Array:
+ if query.aggregations.size() > 0:
+ Firebase._printerr("Aggregation query sent with normal query call: " + str(query))
+ return []
+
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_QUERY
+ var body: Dictionary = { structuredQuery = query.query }
+ var url: String = _base_url + _extended_url + _query_suffix
+
+ task.data = query
+ task._fields = JSON.stringify(body)
+ task._url = url
+ _pooled_request(task)
+ return await _handle_task_finished(task)
+
+## Issue an aggregation query (sum, average, count) against your Firestore database;
+## cheaper than a normal query and counting (for instance) values directly.
+##
+## [b]Note:[/b] a [code]FirestoreQuery[/code] object needs to be created to issue the query.
+## When awaited, this function returns the result from the aggregation query.
##
## ex.
-## [code]var result : Array = yield(query_task, "task_finished")[/code]
+## [code]var query_results = await Firebase.Firestore.query(FirestoreQuery.new())[/code]
##
+## [b]Warning:[/b] It currently does not work offline!
+##
+## @args query
+## @arg-types FirestoreQuery
+## @return Variant representing the array results of the aggregation query
+func aggregation_query(query : FirestoreQuery) -> Variant:
+ if query.aggregations.size() == 0:
+ Firebase._printerr("Aggregation query sent with no aggregation values: " + str(query))
+ return 0
+
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_AGG_QUERY
+
+ var body: Dictionary = { structuredAggregationQuery = { structuredQuery = query.query, aggregations = query.aggregations } }
+ var url: String = _base_url + _extended_url + _agg_query_suffix
+
+ task.data = query
+ task._fields = JSON.stringify(body)
+ task._url = url
+ _pooled_request(task)
+ var result = await _handle_task_finished(task)
+ return result
+
+## Request a list of contents (documents and/or collections) inside a collection, specified by its [i]id[/i]. This method will return an Array[FirestoreDocument]
## @args collection_id, page_size, page_token, order_by
## @arg-types String, int, String, String
## @arg-defaults , 0, "", ""
-## @return FirestoreTask
-func list(path : String = "", page_size : int = 0, page_token : String = "", order_by : String = "") -> FirestoreTask:
- var firestore_task : FirestoreTask = FirestoreTask.new()
- firestore_task.connect("listed_documents", self, "_on_listed_documents")
- firestore_task.connect("task_error", self, "_on_task_error")
- firestore_task.action = FirestoreTask.Task.TASK_LIST
- var url : String = _base_url + _extended_url + path
- if page_size != 0:
- url+="?pageSize="+str(page_size)
- if page_token != "":
- url+="&pageToken="+page_token
- if order_by != "":
- url+="&orderBy="+order_by
-
- firestore_task.data = [path, page_size, page_token, order_by]
- firestore_task._url = url
- _pooled_request(firestore_task)
- return firestore_task
-
-
-func set_networking(value: bool) -> void:
- if value:
- enable_networking()
- else:
- disable_networking()
-
-
-func enable_networking() -> void:
- if networking:
- return
- networking = true
- _base_url = _base_url.replace("storeoffline", "firestore")
- for key in collections:
- collections[key]._base_url = _base_url
-
-
-func disable_networking() -> void:
- if not networking:
- return
- networking = false
- # Pointing to an invalid url should do the trick.
- _base_url = _base_url.replace("firestore", "storeoffline")
- for key in collections:
- collections[key]._base_url = _base_url
-
-
-func _set_offline(value: bool) -> void:
- if value == _offline:
- return
-
- _offline = value
- if not persistence_enabled:
- return
-
- var event_record_path: String = _config["cacheLocation"].plus_file(_CACHE_RECORD_FILE)
- if not value:
- var offline_time := 2147483647 # Maximum signed 32-bit integer
- var file := File.new()
- if file.open_encrypted_with_pass(event_record_path, File.READ, _encrypt_key) == OK:
- offline_time = int(file.get_buffer(file.get_len()).get_string_from_utf8()) - 2
- file.close()
-
- var cache_dir := Directory.new()
- var cache_files := []
- if cache_dir.open(_cache_loc) == OK:
- cache_dir.list_dir_begin(true)
- var file_name = cache_dir.get_next()
- while file_name != "":
- if not cache_dir.current_is_dir() and file_name.ends_with(_CACHE_EXTENSION):
- if file.get_modified_time(_cache_loc.plus_file(file_name)) >= offline_time:
- cache_files.append(_cache_loc.plus_file(file_name))
-# else:
-# print("%s is old! It's time is %d, but the time offline was %d." % [file_name, file.get_modified_time(_cache_loc.plus_file(file_name)), offline_time])
- file_name = cache_dir.get_next()
- cache_dir.list_dir_end()
-
- cache_files.erase(event_record_path)
- cache_dir.remove(event_record_path)
-
- for cache in cache_files:
- var deleted := false
- if file.open_encrypted_with_pass(cache, File.READ, _encrypt_key) == OK:
- var name := file.get_line()
- var content := file.get_line()
- var collection_id := name.left(name.find_last("/"))
- var document_id := name.right(name.find_last("/") + 1)
-
- var collection := collection(collection_id)
- if content == "--deleted--":
- collection.delete(document_id)
- deleted = true
- else:
- collection.update(document_id, FirestoreDocument.fields2dict(JSON.parse(content).result))
- else:
- Firebase._printerr("Failed to retrieve cache %s! Error code: %d" % [cache, file.get_error()])
- file.close()
- if deleted:
- cache_dir.remove(cache)
-
- else:
- var file := File.new()
- if file.open_encrypted_with_pass(event_record_path, File.WRITE, _encrypt_key) == OK:
- file.store_buffer(str(OS.get_unix_time()).to_utf8())
- file.close()
+## @return Array[FirestoreDocument]
+func list(path : String = "", page_size : int = 0, page_token : String = "", order_by : String = "") -> Array:
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_LIST
+ var url : String = _base_url + _extended_url + path
+ if page_size != 0:
+ url+="?pageSize="+str(page_size)
+ if page_token != "":
+ url+="&pageToken="+page_token
+ if order_by != "":
+ url+="&orderBy="+order_by
+
+ task.data = [path, page_size, page_token, order_by]
+ task._url = url
+ _pooled_request(task)
+
+ return await _handle_task_finished(task)
func _set_config(config_json : Dictionary) -> void:
- _config = config_json
- _cache_loc = _config["cacheLocation"]
- _extended_url = _extended_url.replace("[PROJECT_ID]", _config.projectId)
-
- var file := File.new()
- if file.file_exists(_cache_loc.plus_file(_CACHE_RECORD_FILE)):
- _offline = true
- else:
- _offline = false
+ _config = config_json
+ _cache_loc = _config["cacheLocation"]
+ _extended_url = _extended_url.replace("[PROJECT_ID]", _config.projectId)
- _check_emulating()
+ # Since caching is causing a lot of issues, I'm removing this check for now. We will revisit this in the future, once we have some time to investigate why the cache is being corrupted.
+ _check_emulating()
func _check_emulating() -> void :
- ## Check emulating
- if not Firebase.emulating:
- _base_url = "https://firestore.googleapis.com/{version}/".format({ version = _API_VERSION })
- else:
- var port : String = _config.emulators.ports.firestore
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Firestore has not been configured.")
- else:
- _base_url = "http://localhost:{port}/{version}/".format({ version = _API_VERSION, port = port })
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = "https://firestore.googleapis.com/{version}/".format({ version = _API_VERSION })
+ else:
+ var port : String = _config.emulators.ports.firestore
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Firestore has not been configured.")
+ else:
+ _base_url = "http://localhost:{port}/{version}/".format({ version = _API_VERSION, port = port })
func _pooled_request(task : FirestoreTask) -> void:
- if _offline:
- task._on_request_completed(HTTPRequest.RESULT_CANT_CONNECT, 404, PoolStringArray(), PoolByteArray())
- return
-
- if not auth and not Firebase.emulating:
- Firebase._print("Unauthenticated request issued...")
- Firebase.Auth.login_anonymous()
- var result : Array = yield(Firebase.Auth, "auth_request")
- if result[0] != 1:
- _check_auth_error(result[0], result[1])
- Firebase._print("Client connected as Anonymous")
-
- if not Firebase.emulating:
- task._headers = PoolStringArray([_AUTHORIZATION_HEADER + auth.idtoken])
-
- var http_request : HTTPRequest
- for request in _http_request_pool:
- if not request.get_meta("requesting"):
- http_request = request
- break
-
- if not http_request:
- http_request = HTTPRequest.new()
- http_request.timeout = 5
- _http_request_pool.append(http_request)
- add_child(http_request)
- http_request.connect("request_completed", self, "_on_pooled_request_completed", [http_request])
-
- http_request.set_meta("requesting", true)
- http_request.set_meta("lifetime", 0.0)
- http_request.set_meta("task", task)
- http_request.request(task._url, task._headers, !Firebase.emulating, task._method, task._fields)
-
-
-# -------------
-
-
-func _on_listed_documents(listed_documents : Array):
- emit_signal("listed_documents", listed_documents)
-
-
-func _on_result_query(result : Array):
- emit_signal("result_query", result)
-
-func _on_task_error(code : int, status : String, message : String, task : int):
- emit_signal("task_error", code, status, message)
- Firebase._printerr(message)
+ if (auth == null or auth.is_empty()) and not Firebase.emulating:
+ Firebase._print("Unauthenticated request issued...")
+ Firebase.Auth.login_anonymous()
+ var result : Array = await Firebase.Auth.auth_request
+ if result[0] != 1:
+ _check_auth_error(result[0], result[1])
+ Firebase._print("Client connected as Anonymous")
+
+ if not Firebase.emulating:
+ task._headers = PackedStringArray([_AUTHORIZATION_HEADER + auth.idtoken])
+
+ var http_request = HTTPRequest.new()
+ http_request.timeout = 5
+ Utilities.fix_http_request(http_request)
+ add_child(http_request)
+ http_request.request_completed.connect(
+ func(result, response_code, headers, body):
+ task._on_request_completed(result, response_code, headers, body)
+ http_request.queue_free()
+ )
+
+ http_request.request(task._url, task._headers, task._method, task._fields)
func _on_FirebaseAuth_login_succeeded(auth_result : Dictionary) -> void:
- auth = auth_result
- for key in collections:
- collections[key].auth = auth
-
+ auth = auth_result
+ for coll in get_children():
+ if coll is FirestoreCollection:
+ coll.auth = auth
func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
- auth = auth_result
- for key in collections:
- collections[key].auth = auth
-
-
-func _on_pooled_request_completed(result : int, response_code : int, headers : PoolStringArray, body : PoolByteArray, request : HTTPRequest) -> void:
- request.get_meta("task")._on_request_completed(result, response_code, headers, body)
- request.set_meta("requesting", false)
-
-
-func _on_connect_check_request_completed(result : int, _response_code, _headers, _body) -> void:
- _set_offline(result != HTTPRequest.RESULT_SUCCESS)
- #_connect_check_node.request(_base_url)
-
+ auth = auth_result
+ for coll in get_children():
+ if coll is FirestoreCollection:
+ coll.auth = auth
func _on_FirebaseAuth_logout() -> void:
- auth = {}
+ auth = {}
func _check_auth_error(code : int, message : String) -> void:
- var err : String
- match code:
- 400: err = "Please enable the Anonymous Sign-in method, or Authenticate the Client before issuing a request"
- Firebase._printerr(err)
- Firebase._printerr(message)
+ var err : String
+ match code:
+ 400: err = "Please enable the Anonymous Sign-in method, or Authenticate the Client before issuing a request"
+ Firebase._printerr(err)
+ Firebase._printerr(message)
+
+func _handle_task_finished(task : FirestoreTask):
+ await task.task_finished
+
+ if task.error.keys().size() > 0:
+ error.emit(task.error)
+
+ return task.data
diff --git a/addons/godot-firebase/firestore/firestore_collection.gd b/addons/godot-firebase/firestore/firestore_collection.gd
index 7903318..4883f87 100644
--- a/addons/godot-firebase/firestore/firestore_collection.gd
+++ b/addons/godot-firebase/firestore/firestore_collection.gd
@@ -3,15 +3,11 @@
## @meta-version 2.3
## A reference to a Firestore Collection.
## Documentation TODO.
-tool
+@tool
class_name FirestoreCollection
-extends Reference
+extends Node
-signal add_document(doc)
-signal get_document(doc)
-signal update_document(doc)
-signal delete_document()
-signal error(code,status,message)
+signal error(error_result)
const _AUTHORIZATION_HEADER : String = "Authorization: Bearer "
@@ -21,124 +17,162 @@ const _documentId_tag : String = "documentId="
var auth : Dictionary
var collection_name : String
-var firestore # FirebaseFirestore (can't static type due to cyclic reference)
var _base_url : String
var _extended_url : String
var _config : Dictionary
var _documents := {}
-var _request_queues := {}
# ----------------------- Requests
## @args document_id
## @return FirestoreTask
## used to GET a document from the collection, specify @document_id
-func get(document_id : String) -> FirestoreTask:
- var task : FirestoreTask = FirestoreTask.new()
- task.action = FirestoreTask.Task.TASK_GET
- task.data = collection_name + "/" + document_id
- var url = _get_request_url() + _separator + document_id.replace(" ", "%20")
-
- task.connect("get_document", self, "_on_get_document")
- task.connect("task_finished", self, "_on_task_finished", [document_id], CONNECT_DEFERRED)
- _process_request(task, document_id, url)
- return task
+func get_doc(document_id : String, from_cache : bool = false, is_listener : bool = false) -> FirestoreDocument:
+ if from_cache:
+ # for now, just return the child directly; in the future, make it smarter so there's a default, if long, polling time for this
+ for child in get_children():
+ if child.doc_name == document_id:
+ return child
+
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_GET
+ task.data = collection_name + "/" + document_id
+ var url = _get_request_url() + _separator + document_id.replace(" ", "%20")
+
+ _process_request(task, document_id, url)
+ var result = await Firebase.Firestore._handle_task_finished(task)
+ if result != null:
+ for child in get_children():
+ if child.doc_name == document_id:
+ child.replace(result, true)
+ result = child
+ break
+ else:
+ print("get_document returned null for %s %s" % [collection_name, document_id])
+
+ return result
## @args document_id, fields
## @arg-defaults , {}
-## @return FirestoreTask
-## used to SAVE/ADD a new document to the collection, specify @documentID and @fields
-func add(document_id : String, fields : Dictionary = {}) -> FirestoreTask:
- var task : FirestoreTask = FirestoreTask.new()
- task.action = FirestoreTask.Task.TASK_POST
- task.data = collection_name + "/" + document_id
- var url = _get_request_url() + _query_tag + _documentId_tag + document_id
-
- task.connect("add_document", self, "_on_add_document")
- task.connect("task_finished", self, "_on_task_finished", [document_id], CONNECT_DEFERRED)
- _process_request(task, document_id, url, JSON.print(FirestoreDocument.dict2fields(fields)))
- return task
-
-## @args document_id, fields
-## @arg-defaults , {}
-## @return FirestoreTask
-# used to UPDATE a document, specify @documentID and @fields
-func update(document_id : String, fields : Dictionary = {}) -> FirestoreTask:
- var task : FirestoreTask = FirestoreTask.new()
- task.action = FirestoreTask.Task.TASK_PATCH
- task.data = collection_name + "/" + document_id
- var url = _get_request_url() + _separator + document_id.replace(" ", "%20") + "?"
- for key in fields.keys():
- url+="updateMask.fieldPaths={key}&".format({key = key})
- url = url.rstrip("&")
-
- task.connect("update_document", self, "_on_update_document")
- task.connect("task_finished", self, "_on_task_finished", [document_id], CONNECT_DEFERRED)
- _process_request(task, document_id, url, JSON.print(FirestoreDocument.dict2fields(fields)))
- return task
+## @return FirestoreDocument
+## used to ADD a new document to the collection, specify @documentID and @data
+func add(document_id : String, data : Dictionary = {}) -> FirestoreDocument:
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_POST
+ task.data = collection_name + "/" + document_id
+ var url = _get_request_url() + _query_tag + _documentId_tag + document_id
+
+ _process_request(task, document_id, url, JSON.stringify(Utilities.dict2fields(data)))
+ var result = await Firebase.Firestore._handle_task_finished(task)
+ if result != null:
+ for child in get_children():
+ if child.doc_name == document_id:
+ child.free() # Consider throwing an error for this since it shouldn't already exist
+ break
+
+ result.collection_name = collection_name
+ add_child(result, true)
+ return result
+
+## @args document
+## @return FirestoreDocument
+# used to UPDATE a document, specify the document
+func update(document : FirestoreDocument) -> FirestoreDocument:
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_PATCH
+ task.data = collection_name + "/" + document.doc_name
+ var url = _get_request_url() + _separator + document.doc_name.replace(" ", "%20") + "?"
+ for key in document.keys():
+ url+="updateMask.fieldPaths={key}&".format({key = key})
+
+ url = url.rstrip("&")
+
+ for key in document.keys():
+ if document.get_value(key) == null:
+ document._erase(key)
+
+ var temp_transforms
+ if document._transforms != null:
+ temp_transforms = document._transforms
+ document._transforms = null
+
+ var body = JSON.stringify({"fields": document.document})
+
+ _process_request(task, document.doc_name, url, body)
+ var result = await Firebase.Firestore._handle_task_finished(task)
+ if result != null:
+ for child in get_children():
+ if child.doc_name == result.doc_name:
+ child.replace(result, true)
+ break
+
+ if temp_transforms != null:
+ result._transforms = temp_transforms
+
+ return result
+
+
+## @args document
+## @return Dictionary
+# Used to commit changes from transforms, specify the document with the transforms
+func commit(document : FirestoreDocument) -> Dictionary:
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_COMMIT
+ var url = get_database_url("commit")
+
+ document._transforms.set_config(
+ {
+ "extended_url": _extended_url,
+ "collection_name": collection_name
+ }
+ ) # Only place we can set this is here, oofness
+
+ var body = document._transforms.serialize()
+ document.clear_field_transforms()
+ _process_request(task, document.doc_name, url, JSON.stringify(body))
+
+ return await Firebase.Firestore._handle_task_finished(task) # Not implementing the follow-up get here as user may have a listener that's already listening for changes, but user should call get if they don't
## @args document_id
## @return FirestoreTask
-# used to DELETE a document, specify @document_id
-func delete(document_id : String) -> FirestoreTask:
- var task : FirestoreTask = FirestoreTask.new()
- task.action = FirestoreTask.Task.TASK_DELETE
- task.data = collection_name + "/" + document_id
- var url = _get_request_url() + _separator + document_id.replace(" ", "%20")
-
- task.connect("delete_document", self, "_on_delete_document")
- task.connect("task_finished", self, "_on_task_finished", [document_id], CONNECT_DEFERRED)
- _process_request(task, document_id, url)
- return task
-
-# ----------------- Functions
-func _get_request_url() -> String:
- return _base_url + _extended_url + collection_name
+# used to DELETE a document, specify the document
+func delete(document : FirestoreDocument) -> bool:
+ var doc_name = document.doc_name
+ var task : FirestoreTask = FirestoreTask.new()
+ task.action = FirestoreTask.Task.TASK_DELETE
+ task.data = document.collection_name + "/" + doc_name
+ var url = _get_request_url() + _separator + doc_name.replace(" ", "%20")
+ _process_request(task, doc_name, url)
+ var result = await Firebase.Firestore._handle_task_finished(task)
+
+ # Clean up the cache
+ if result:
+ for node in get_children():
+ if node.doc_name == doc_name:
+ node.free() # Should be only one
+ break
+
+ return result
+func _get_request_url() -> String:
+ return _base_url + _extended_url + collection_name
func _process_request(task : FirestoreTask, document_id : String, url : String, fields := "") -> void:
- task.connect("task_error", self, "_on_error")
-
- if not auth:
- Firebase._print("Unauthenticated request issued...")
- Firebase.Auth.login_anonymous()
- var result : Array = yield(Firebase.Auth, "auth_request")
- if result[0] != 1:
- Firebase.Firestore._check_auth_error(result[0], result[1])
- return null
- Firebase._print("Client authenticated as Anonymous User.")
-
- task._url = url
- task._fields = fields
- task._headers = PoolStringArray([_AUTHORIZATION_HEADER + auth.idtoken])
- if _request_queues.has(document_id) and not _request_queues[document_id].empty():
- _request_queues[document_id].append(task)
- else:
- _request_queues[document_id] = []
- firestore._pooled_request(task)
-# task._push_request(url, , fields)
-
-
-func _on_task_finished(task : FirestoreTask, document_id : String) -> void:
- if not _request_queues[document_id].empty():
- task._push_request(task._url, _AUTHORIZATION_HEADER + auth.idtoken, task._fields)
-
-
-# -------------------- Higher level of communication with signals
-func _on_get_document(document : FirestoreDocument):
- emit_signal("get_document", document )
-
-func _on_add_document(document : FirestoreDocument):
- emit_signal("add_document", document )
-
-func _on_update_document(document : FirestoreDocument):
- emit_signal("update_document", document )
-
-func _on_delete_document():
- emit_signal("delete_document")
-
-func _on_error(code, status, message, task):
- emit_signal("error", code, status, message)
- Firebase._printerr(message)
+ if auth == null or auth.is_empty():
+ Firebase._print("Unauthenticated request issued...")
+ Firebase.Auth.login_anonymous()
+ var result : Array = await Firebase.Auth.auth_request
+ if result[0] != 1:
+ Firebase.Firestore._check_auth_error(result[0], result[1])
+ return
+ Firebase._print("Client authenticated as Anonymous User.")
+
+ task._url = url
+ task._fields = fields
+ task._headers = PackedStringArray([_AUTHORIZATION_HEADER + auth.idtoken])
+ Firebase.Firestore._pooled_request(task)
+
+func get_database_url(append) -> String:
+ return _base_url + _extended_url.rstrip("/") + ":" + append
diff --git a/addons/godot-firebase/firestore/firestore_document.gd b/addons/godot-firebase/firestore/firestore_document.gd
index 3411eba..2475276 100644
--- a/addons/godot-firebase/firestore/firestore_document.gd
+++ b/addons/godot-firebase/firestore/firestore_document.gd
@@ -2,168 +2,145 @@
## @meta-version 2.2
## A reference to a Firestore Document.
## Documentation TODO.
-tool
+@tool
class_name FirestoreDocument
-extends Reference
-
+extends Node
# A FirestoreDocument objects that holds all important values for a Firestore Document,
# @doc_name = name of the Firestore Document, which is the request PATH
# @doc_fields = fields held by Firestore Document, in APIs format
# created when requested from a `collection().get()` call
-var document: Dictionary # the Document itself
-var doc_fields: Dictionary # only .fields
-var doc_name: String # only .name
-var create_time: String # createTime
-
-
-func _init(doc: Dictionary = {}, _doc_name: String = "", _doc_fields: Dictionary = {}) -> void:
- self.document = doc
- self.doc_name = doc.name
- if self.doc_name.count("/") > 2:
- self.doc_name = (self.doc_name.split("/") as Array).back()
- self.doc_fields = fields2dict(self.document)
- self.create_time = doc.createTime
-
-
-# Pass a dictionary { 'key' : 'value' } to format it in a APIs usable .fields
-# Field Path using the "dot" (`.`) notation are supported:
-# ex. { "PATH.TO.SUBKEY" : "VALUE" } ==> { "PATH" : { "TO" : { "SUBKEY" : "VALUE" } } }
-static func dict2fields(dict: Dictionary) -> Dictionary:
- var fields: Dictionary = {}
- var var_type: String = ""
- for field in dict.keys():
- var field_value = dict[field]
- if "." in field:
- var keys: Array = field.split(".")
- field = keys.pop_front()
- keys.invert()
- for key in keys:
- field_value = {key: field_value}
- match typeof(field_value):
- TYPE_NIL: var_type = "nullValue"
- TYPE_BOOL: var_type = "booleanValue"
- TYPE_INT: var_type = "integerValue"
- TYPE_REAL: var_type = "doubleValue"
- TYPE_STRING: var_type = "stringValue"
- TYPE_DICTIONARY:
- if is_field_timestamp(field_value):
- var_type = "timestampValue"
- field_value = dict2timestamp(field_value)
- else:
- var_type = "mapValue"
- field_value = dict2fields(field_value)
- TYPE_ARRAY:
- var_type = "arrayValue"
- field_value = {"values": array2fields(field_value)}
-
- if fields.has(field) and fields[field].has("mapValue") and field_value.has("fields"):
- for key in field_value["fields"].keys():
- fields[field]["mapValue"]["fields"][key] = field_value["fields"][key]
- else:
- fields[field] = {var_type: field_value}
- return {"fields": fields}
-
-
-# Pass the .fields inside a Firestore Document to print out the Dictionary { 'key' : 'value' }
-static func fields2dict(doc: Dictionary) -> Dictionary:
- var dict: Dictionary = {}
- if doc.has("fields"):
- for field in doc.fields.keys():
- if doc.fields[field].has("mapValue"):
- dict[field] = fields2dict(doc.fields[field].mapValue)
- elif doc.fields[field].has("timestampValue"):
- dict[field] = timestamp2dict(doc.fields[field].timestampValue)
- elif doc.fields[field].has("arrayValue"):
- dict[field] = fields2array(doc.fields[field].arrayValue)
- elif doc.fields[field].has("integerValue"):
- dict[field] = doc.fields[field].values()[0] as int
- elif doc.fields[field].has("doubleValue"):
- dict[field] = doc.fields[field].values()[0] as float
- elif doc.fields[field].has("booleanValue"):
- dict[field] = doc.fields[field].values()[0] as bool
- elif doc.fields[field].has("nullValue"):
- dict[field] = null
- else:
- dict[field] = doc.fields[field].values()[0]
- return dict
-
-
-# Pass an Array to parse it to a Firebase arrayValue
-static func array2fields(array: Array) -> Array:
- var fields: Array = []
- var var_type: String = ""
- for field in array:
- match typeof(field):
- TYPE_DICTIONARY:
- if is_field_timestamp(field):
- var_type = "timestampValue"
- field = dict2timestamp(field)
- else:
- var_type = "mapValue"
- field = dict2fields(field)
- TYPE_NIL: var_type = "nullValue"
- TYPE_BOOL: var_type = "booleanValue"
- TYPE_INT: var_type = "integerValue"
- TYPE_REAL: var_type = "doubleValue"
- TYPE_STRING: var_type = "stringValue"
- TYPE_ARRAY: var_type = "arrayValue"
-
- fields.append({var_type: field})
- return fields
-
-
-# Pass a Firebase arrayValue Dictionary to convert it back to an Array
-static func fields2array(array: Dictionary) -> Array:
- var fields: Array = []
- if array.has("values"):
- for field in array.values:
- var item
- match field.keys()[0]:
- "mapValue":
- item = fields2dict(field.mapValue)
- "arrayValue":
- item = fields2array(field.arrayValue)
- "integerValue":
- item = field.values()[0] as int
- "doubleValue":
- item = field.values()[0] as float
- "booleanValue":
- item = field.values()[0] as bool
- "timestampValue":
- item = timestamp2dict(field.timestampValue)
- "nullValue":
- item = null
- _:
- item = field.values()[0]
- fields.append(item)
- return fields
-
-
-# Converts a gdscript Dictionary (most likely obtained with OS.get_datetime()) to a Firebase Timestamp
-static func dict2timestamp(dict: Dictionary) -> String:
- dict.erase("weekday")
- dict.erase("dst")
- var dict_values: Array = dict.values()
- return "%04d-%02d-%02dT%02d:%02d:%02d.00Z" % dict_values
-
-
-# Converts a Firebase Timestamp back to a gdscript Dictionary
-static func timestamp2dict(timestamp: String) -> Dictionary:
- var datetime: Dictionary = {year = 0, month = 0, day = 0, hour = 0, minute = 0, second = 0}
- var dict: PoolStringArray = timestamp.split("T")[0].split("-")
- dict.append_array(timestamp.split("T")[1].split(":"))
- for value in dict.size():
- datetime[datetime.keys()[value]] = int(dict[value])
- return datetime
-
-
-static func is_field_timestamp(field: Dictionary) -> bool:
- return field.has_all(["year", "month", "day", "hour", "minute", "second"])
+var document : Dictionary # the Document itself
+var doc_name : String # only .name
+var create_time : String # createTime
+var collection_name : String # Name of the collection to which it belongs
+var _transforms : FieldTransformArray # The transforms to apply
+signal changed(changes)
+
+func _init(doc : Dictionary = {}):
+ _transforms = FieldTransformArray.new()
+
+ if doc.has("fields"):
+ document = doc.fields
+ if doc.has("name"):
+ doc_name = doc.name
+ if doc_name.count("/") > 2:
+ doc_name = (doc_name.split("/") as Array).back()
+
+ self.create_time = doc.createTime
+
+func replace(with : FirestoreDocument, is_listener := false) -> void:
+ var current = document.duplicate()
+ document = with.document
+
+ var changes = {
+ "added": [], "removed": [], "updated": [], "is_listener": is_listener
+ }
+
+ for key in current.keys():
+ if not document.has(key):
+ changes.removed.push_back({ "key" : key })
+ else:
+ var new_value = Utilities.from_firebase_type(document[key])
+ var old_value = Utilities.from_firebase_type(current[key])
+ if new_value != old_value:
+ if old_value == null:
+ changes.removed.push_back({ "key" : key }) # ??
+ else:
+ changes.updated.push_back({ "key" : key, "old": old_value, "new" : new_value })
+
+ for key in document.keys():
+ if not current.has(key):
+ changes.added.push_back({ "key" : key, "new" : Utilities.from_firebase_type(document[key]) })
+
+ if not (changes.added.is_empty() and changes.removed.is_empty() and changes.updated.is_empty()):
+ changed.emit(changes)
+
+func is_null_value(key) -> bool:
+ return document.has(key) and Utilities.from_firebase_type(document[key]) == null
+
+# As of right now, we do not track these with track changes; instead, they'll come back when the document updates from the server.
+# Until that time, it's expected if you want to track these types of changes that you commit for the transforms and then get the document yourself.
+func add_field_transform(transform : FieldTransform) -> void:
+ _transforms.push_back(transform)
+
+func remove_field_transform(transform : FieldTransform) -> void:
+ _transforms.erase(transform)
+
+func clear_field_transforms() -> void:
+ _transforms.transforms.clear()
+
+func remove_field(field_path : String) -> void:
+ if document.has(field_path):
+ document[field_path] = Utilities.to_firebase_type(null)
+
+ var changes = {
+ "added": [], "removed": [], "updated": [], "is_listener": false
+ }
+
+ changes.removed.push_back({ "key" : field_path })
+ changed.emit(changes)
+
+func _erase(field_path : String) -> void:
+ document.erase(field_path)
+
+func add_or_update_field(field_path : String, value : Variant) -> void:
+ var changes = {
+ "added": [], "removed": [], "updated": [], "is_listener": false
+ }
+
+ var existing_value = get_value(field_path)
+ var has_field_path = existing_value != null and not is_null_value(field_path)
+
+ var converted_value = Utilities.to_firebase_type(value)
+ document[field_path] = converted_value
+
+ if has_field_path:
+ changes.updated.push_back({ "key" : field_path, "old" : existing_value, "new" : value })
+ else:
+ changes.added.push_back({ "key" : field_path, "new" : value })
+
+ changed.emit(changes)
+
+func on_snapshot(when_called : Callable, poll_time : float = 1.0) -> FirestoreListener.FirestoreListenerConnection:
+ if get_child_count() >= 1: # Only one listener per
+ assert(false, "Multiple listeners not allowed for the same document yet")
+ return
+
+ changed.connect(when_called, CONNECT_REFERENCE_COUNTED)
+ var listener = preload("res://addons/godot-firebase/firestore/firestore_listener.tscn").instantiate()
+ add_child(listener)
+ listener.initialize_listener(collection_name, doc_name, poll_time)
+ listener.owner = self
+ var result = listener.enable_connection()
+ return result
+
+func get_value(property : StringName) -> Variant:
+ if property == "doc_name":
+ return doc_name
+ elif property == "collection_name":
+ return collection_name
+ elif property == "create_time":
+ return create_time
+
+ if document.has(property):
+ var result = Utilities.from_firebase_type(document[property])
+
+ return result
+
+ return null
+
+func _set(property: StringName, value: Variant) -> bool:
+ document[property] = Utilities.to_firebase_type(value)
+ return true
+
+func keys():
+ return document.keys()
# Call print(document) to return directly this document formatted
func _to_string() -> String:
- return "doc_name: {doc_name}, \ndoc_fields: {doc_fields}, \ncreate_time: {create_time}\n".format(
- {doc_name = self.doc_name, doc_fields = self.doc_fields, create_time = self.create_time}
- )
+ return ("doc_name: {doc_name}, \ndata: {data}, \ncreate_time: {create_time}\n").format(
+ {doc_name = self.doc_name,
+ data = document,
+ create_time = self.create_time})
diff --git a/addons/godot-firebase/firestore/firestore_listener.gd b/addons/godot-firebase/firestore/firestore_listener.gd
new file mode 100644
index 0000000..7808a5c
--- /dev/null
+++ b/addons/godot-firebase/firestore/firestore_listener.gd
@@ -0,0 +1,47 @@
+class_name FirestoreListener
+extends Node
+
+const MinPollTime = 60 * 2 # seconds, so 2 minutes
+
+var _doc_name : String
+var _poll_time : float
+var _collection : FirestoreCollection
+
+var _total_time = 0.0
+var _enabled := false
+
+func initialize_listener(collection_name : String, doc_name : String, poll_time : float) -> void:
+ _poll_time = max(poll_time, MinPollTime)
+ _doc_name = doc_name
+ _collection = Firebase.Firestore.collection(collection_name)
+
+func enable_connection() -> FirestoreListenerConnection:
+ _enabled = true
+ set_process(true)
+ return FirestoreListenerConnection.new(self)
+
+func _process(delta: float) -> void:
+ if _enabled:
+ _total_time += delta
+ if _total_time >= _poll_time:
+ _check_for_server_updates()
+ _total_time = 0.0
+
+func _check_for_server_updates() -> void:
+ var executor = func():
+ var doc = await _collection.get_doc(_doc_name, false, true)
+ if doc == null:
+ set_process(false) # Document was deleted out from under us, so stop updating
+
+ executor.call() # Hack to work around the await here, otherwise would have to call with await in _process and that's no bueno
+
+class FirestoreListenerConnection extends RefCounted:
+ var connection
+
+ func _init(connection_node):
+ connection = connection_node
+
+ func stop():
+ if connection != null and is_instance_valid(connection):
+ connection.set_process(false)
+ connection.free()
diff --git a/addons/godot-firebase/firestore/firestore_listener.tscn b/addons/godot-firebase/firestore/firestore_listener.tscn
new file mode 100644
index 0000000..9f5e246
--- /dev/null
+++ b/addons/godot-firebase/firestore/firestore_listener.tscn
@@ -0,0 +1,6 @@
+[gd_scene load_steps=2 format=3 uid="uid://bwv7vtgssc0n5"]
+
+[ext_resource type="Script" path="res://addons/godot-firebase/firestore/firestore_listener.gd" id="1_qlaei"]
+
+[node name="FirestoreListener" type="Node"]
+script = ExtResource("1_qlaei")
diff --git a/addons/godot-firebase/firestore/firestore_query.gd b/addons/godot-firebase/firestore/firestore_query.gd
index a75a692..bdebbe6 100644
--- a/addons/godot-firebase/firestore/firestore_query.gd
+++ b/addons/godot-firebase/firestore/firestore_query.gd
@@ -1,105 +1,101 @@
-## @meta-authors NicolĂł 'fenix' Santilio
+## @meta-authors NicolĂł 'fenix' Santilio, Kyle Szklenski
## @meta-version 1.4
## A firestore query.
## Documentation TODO.
-tool
-extends Reference
+@tool
+extends RefCounted
class_name FirestoreQuery
class Order:
- var obj : Dictionary
+ var obj: Dictionary
class Cursor:
- var values : Array
- var before : bool
+ var values: Array
+ var before: bool
- func _init(v : Array, b : bool):
- values = v
- before = b
+ func _init(v : Array,b : bool):
+ values = v
+ before = b
signal query_result(query_result)
-const TEMPLATE_QUERY : Dictionary = {
- select = {},
- from = [],
- where = {},
- orderBy = [],
- startAt = {},
- endAt = {},
- offset = 0,
- limit = 0
+const TEMPLATE_QUERY: Dictionary = {
+ select = {},
+ from = [],
+ where = {},
+ orderBy = [],
+ startAt = {},
+ endAt = {},
+ offset = 0,
+ limit = 0
}
-var query : Dictionary = {}
+var query: Dictionary = {}
+var aggregations: Array[Dictionary] = []
enum OPERATOR {
- # Standard operators
- OPERATOR_NSPECIFIED,
- LESS_THAN,
- LESS_THAN_OR_EQUAL,
- GREATER_THAN,
- GREATER_THAN_OR_EQUAL,
- EQUAL,
- NOT_EQUAL,
- ARRAY_CONTAINS,
- ARRAY_CONTAINS_ANY,
- IN,
- NOT_IN,
-
- # Unary operators
- IS_NAN,
- IS_NULL,
- IS_NOT_NAN,
- IS_NOT_NULL,
-
- # Complex operators
- AND,
- OR
+ # Standard operators
+ OPERATOR_UNSPECIFIED,
+ LESS_THAN,
+ LESS_THAN_OR_EQUAL,
+ GREATER_THAN,
+ GREATER_THAN_OR_EQUAL,
+ EQUAL,
+ NOT_EQUAL,
+ ARRAY_CONTAINS,
+ ARRAY_CONTAINS_ANY,
+ IN,
+ NOT_IN,
+
+ # Unary operators
+ IS_NAN,
+ IS_NULL,
+ IS_NOT_NAN,
+ IS_NOT_NULL,
+
+ # Complex operators
+ AND,
+ OR
}
enum DIRECTION {
- DIRECTION_UNSPECIFIED,
- ASCENDING,
- DESCENDING
+ DIRECTION_UNSPECIFIED,
+ ASCENDING,
+ DESCENDING
}
-func _init():
- return self
-
# Select which fields you want to return as a reflection from your query.
# Fields must be added inside a list. Only a field is accepted inside the list
# Leave the Array empty if you want to return the whole document
func select(fields) -> FirestoreQuery:
- match typeof(fields):
- TYPE_STRING:
- query["select"] = { fields = { fieldPath = fields } }
- TYPE_ARRAY:
- for field in fields:
- field = ({ fieldPath = field })
- query["select"] = { fields = fields }
- _:
- print("Type of 'fields' is not accepted.")
- return self
+ match typeof(fields):
+ TYPE_STRING:
+ query["select"] = { fields = { fieldPath = fields } }
+ TYPE_ARRAY:
+ for field in fields:
+ field = ({ fieldPath = field })
+ query["select"] = { fields = fields }
+ _:
+ print("Type of 'fields' is not accepted.")
+ return self
# Select the collection you want to return the query result from
# if @all_descendants also sub-collections will be returned. If false, only documents will be returned
func from(collection_id : String, all_descendants : bool = true) -> FirestoreQuery:
- query["from"] = [{collectionId = collection_id, allDescendants = all_descendants}]
- return self
-
-
+ query["from"] = [{collectionId = collection_id, allDescendants = all_descendants}]
+ return self
# @collections_array MUST be an Array of Arrays with this structure
# [ ["collection_id", true/false] ]
func from_many(collections_array : Array) -> FirestoreQuery:
- var collections : Array = []
- for collection in collections_array:
- collections.append({collectionId = collection[0], allDescendants = collection[1]})
- query["from"] = collections.duplicate(true)
- return self
+ var collections : Array = []
+ for collection in collections_array:
+ collections.append({collectionId = collection[0], allDescendants = collection[1]})
+ query["from"] = collections.duplicate(true)
+ return self
# Query the value of a field you want to match
@@ -107,45 +103,45 @@ func from_many(collections_array : Array) -> FirestoreQuery:
# @operator : from FirestoreQuery.OPERATOR
# @value : can be any type - String, int, bool, float
# @chain : from FirestoreQuery.OPERATOR.[OR/AND], use it only if you want to chain "AND" or "OR" logic with futher where() calls
-# eg. .where("name", OPERATOR.EQUAL, "Matt", OPERATOR.AND).where("age", OPERATOR.LESS_THAN, 20)
+# eg. super.where("name", OPERATOR.EQUAL, "Matt", OPERATOR.AND).where("age", OPERATOR.LESS_THAN, 20)
func where(field : String, operator : int, value = null, chain : int = -1):
- if operator in [OPERATOR.IS_NAN, OPERATOR.IS_NULL, OPERATOR.IS_NOT_NAN, OPERATOR.IS_NOT_NULL]:
- if (chain in [OPERATOR.AND, OPERATOR.OR]) or (query.has("where") and query.where.has("compositeFilter")):
- var filters : Array = []
- if query.has("where") and query.where.has("compositeFilter"):
- if chain == -1:
- filters = query.where.compositeFilter.filters.duplicate(true)
- chain = OPERATOR.get(query.where.compositeFilter.op)
- else:
- filters.append(query.where)
- filters.append(create_unary_filter(field, operator))
- query["where"] = create_composite_filter(chain, filters)
- else:
- query["where"] = create_unary_filter(field, operator)
- else:
- if value == null:
- print("A value must be defined to match the field: {field}".format({field = field}))
- else:
- if (chain in [OPERATOR.AND, OPERATOR.OR]) or (query.has("where") and query.where.has("compositeFilter")):
- var filters : Array = []
- if query.has("where") and query.where.has("compositeFilter"):
- if chain == -1:
- filters = query.where.compositeFilter.filters.duplicate(true)
- chain = OPERATOR.get(query.where.compositeFilter.op)
- else:
- filters.append(query.where)
- filters.append(create_field_filter(field, operator, value))
- query["where"] = create_composite_filter(chain, filters)
- else:
- query["where"] = create_field_filter(field, operator, value)
- return self
+ if operator in [OPERATOR.IS_NAN, OPERATOR.IS_NULL, OPERATOR.IS_NOT_NAN, OPERATOR.IS_NOT_NULL]:
+ if (chain in [OPERATOR.AND, OPERATOR.OR]) or (query.has("where") and query.where.has("compositeFilter")):
+ var filters : Array = []
+ if query.has("where") and query.where.has("compositeFilter"):
+ if chain == -1:
+ filters = query.where.compositeFilter.filters.duplicate(true)
+ chain = OPERATOR.get(query.where.compositeFilter.op)
+ else:
+ filters.append(query.where)
+ filters.append(create_unary_filter(field, operator))
+ query["where"] = create_composite_filter(chain, filters)
+ else:
+ query["where"] = create_unary_filter(field, operator)
+ else:
+ if value == null:
+ print("A value must be defined to match the field: {field}".format({field = field}))
+ else:
+ if (chain in [OPERATOR.AND, OPERATOR.OR]) or (query.has("where") and query.where.has("compositeFilter")):
+ var filters : Array = []
+ if query.has("where") and query.where.has("compositeFilter"):
+ if chain == -1:
+ filters = query.where.compositeFilter.filters.duplicate(true)
+ chain = OPERATOR.get(query.where.compositeFilter.op)
+ else:
+ filters.append(query.where)
+ filters.append(create_field_filter(field, operator, value))
+ query["where"] = create_composite_filter(chain, filters)
+ else:
+ query["where"] = create_field_filter(field, operator, value)
+ return self
# Order by a field, defining its name and the order direction
# default directoin = Ascending
func order_by(field : String, direction : int = DIRECTION.ASCENDING) -> FirestoreQuery:
- query["orderBy"] = [_order_object(field, direction).obj]
- return self
+ query["orderBy"] = [_order_object(field, direction).obj]
+ return self
# Order by a set of fields and directions
@@ -153,88 +149,106 @@ func order_by(field : String, direction : int = DIRECTION.ASCENDING) -> Firestor
# [@field_name , @DIRECTION.[direction]]
# else, order_object() can be called to return an already parsed Dictionary
func order_by_fields(order_field_list : Array) -> FirestoreQuery:
- var order_list : Array = []
- for order in order_field_list:
- if order is Array:
- order_list.append(_order_object(order[0], order[1]).obj)
- elif order is Order:
- order_list.append(order.obj)
- query["orderBy"] = order_list
- return self
-
-
+ var order_list : Array = []
+ for order in order_field_list:
+ if order is Array:
+ order_list.append(_order_object(order[0], order[1]).obj)
+ elif order is Order:
+ order_list.append(order.obj)
+ query["orderBy"] = order_list
+ return self
func start_at(value, before : bool) -> FirestoreQuery:
- var cursor : Cursor = _cursor_object(value, before)
- query["startAt"] = { values = cursor.values, before = cursor.before }
- print(query["startAt"])
- return self
+ var cursor : Cursor = _cursor_object(value, before)
+ query["startAt"] = { values = cursor.values, before = cursor.before }
+ print(query["startAt"])
+ return self
func end_at(value, before : bool) -> FirestoreQuery:
- var cursor : Cursor = _cursor_object(value, before)
- query["startAt"] = { values = cursor.values, before = cursor.before }
- print(query["startAt"])
- return self
+ var cursor : Cursor = _cursor_object(value, before)
+ query["startAt"] = { values = cursor.values, before = cursor.before }
+ print(query["startAt"])
+ return self
func offset(offset : int) -> FirestoreQuery:
- if offset < 0:
- print("If specified, offset must be >= 0")
- else:
- query["offset"] = offset
- return self
+ if offset < 0:
+ print("If specified, offset must be >= 0")
+ else:
+ query["offset"] = offset
+ return self
func limit(limit : int) -> FirestoreQuery:
- if limit < 0:
- print("If specified, offset must be >= 0")
- else:
- query["limit"] = limit
- return self
-
-
+ if limit < 0:
+ print("If specified, offset must be >= 0")
+ else:
+ query["limit"] = limit
+ return self
+
+
+func aggregate() -> FirestoreAggregation:
+ return FirestoreAggregation.new(self)
+
+class FirestoreAggregation extends RefCounted:
+ var _query: FirestoreQuery
+
+ func _init(query: FirestoreQuery) -> void:
+ _query = query
+
+ func sum(field: String) -> FirestoreQuery:
+ _query.aggregations.push_back({ sum = { field = { fieldPath = field }}})
+ return _query
+
+ func count(up_to: int) -> FirestoreQuery:
+ _query.aggregations.push_back({ count = { upTo = up_to }})
+ return _query
+
+ func average(field: String) -> FirestoreQuery:
+ _query.aggregations.push_back({ avg = { field = { fieldPath = field }}})
+ return _query
# UTILITIES ----------------------------------------
static func _cursor_object(value, before : bool) -> Cursor:
- var parse : Dictionary = FirestoreDocument.dict2fields({value = value}).fields.value
- var cursor : Cursor = Cursor.new(parse.arrayValue.values if parse.has("arrayValue") else [parse], before)
- return cursor
+ var parse : Dictionary = Utilities.dict2fields({value = value}).fields.value
+ var cursor : Cursor = Cursor.new(parse.arrayValue.values if parse.has("arrayValue") else [parse], before)
+ return cursor
static func _order_object(field : String, direction : int) -> Order:
- var order : Order = Order.new()
- order.obj = { field = { fieldPath = field }, direction = DIRECTION.keys()[direction] }
- return order
+ var order : Order = Order.new()
+ order.obj = { field = { fieldPath = field }, direction = DIRECTION.keys()[direction] }
+ return order
func create_field_filter(field : String, operator : int, value) -> Dictionary:
- return {
- fieldFilter = {
- field = { fieldPath = field },
- op = OPERATOR.keys()[operator],
- value = FirestoreDocument.dict2fields({value = value}).fields.value
- } }
+ return {
+ fieldFilter = {
+ field = { fieldPath = field },
+ op = OPERATOR.keys()[operator],
+ value = Utilities.dict2fields({value = value}).fields.value
+ } }
func create_unary_filter(field : String, operator : int) -> Dictionary:
- return {
- unaryFilter = {
- field = { fieldPath = field },
- op = OPERATOR.keys()[operator],
- } }
+ return {
+ unaryFilter = {
+ field = { fieldPath = field },
+ op = OPERATOR.keys()[operator],
+ } }
func create_composite_filter(operator : int, filters : Array) -> Dictionary:
- return {
- compositeFilter = {
- op = OPERATOR.keys()[operator],
- filters = filters
- } }
+ return {
+ compositeFilter = {
+ op = OPERATOR.keys()[operator],
+ filters = filters
+ } }
func clean() -> void:
- query = { }
+ query = { }
func _to_string() -> String:
- var pretty : String = "QUERY:\n"
- for key in query.keys():
- pretty += "- {key} = {value}\n".format({key = key, value = query.get(key)})
- return pretty
+ var pretty : String = "QUERY:\n"
+ for key in query.keys():
+ pretty += "- {key} = {value}\n".format({key = key, value = query.get(key)})
+ return pretty
diff --git a/addons/godot-firebase/firestore/firestore_task.gd b/addons/godot-firebase/firestore/firestore_task.gd
index ad65f03..8122ae5 100644
--- a/addons/godot-firebase/firestore/firestore_task.gd
+++ b/addons/godot-firebase/firestore/firestore_task.gd
@@ -4,369 +4,185 @@
## A [code]FirestoreTask[/code] is an independent node inheriting [code]HTTPRequest[/code] that processes a [code]Firestore[/code] request.
## Once the Task is completed (both if successfully or not) it will emit the relative signal (or a general purpose signal [code]task_finished()[/code]) and will destroy automatically.
##
-## Being a [code]Node[/code] it can be stored in a variable to yield on it, and receive its result as a callback.
+## Being a [code]Node[/code] it can be stored in a variable to yield checked it, and receive its result as a callback.
## All signals emitted by a [code]FirestoreTask[/code] represent a direct level of signal communication, which can be high ([code]get_document(document), result_query(result)[/code]) or low ([code]task_finished(result)[/code]).
## An indirect level of communication with Tasks is also provided, redirecting signals to the [class FirebaseFirestore] module.
##
## ex.
## [code]var task : FirestoreTask = Firebase.Firestore.query(query)[/code]
-## [code]var result : Array = yield(task, "task_finished")[/code]
-## [code]var result : Array = yield(task, "result_query")[/code]
-## [code]var result : Array = yield(Firebase.Firestore, "task_finished")[/code]
-## [code]var result : Array = yield(Firebase.Firestore, "result_query")[/code]
+## [code]var result : Array = await task.task_finished[/code]
+## [code]var result : Array = await task.result_query[/code]
+## [code]var result : Array = await Firebase.Firestore.task_finished[/code]
+## [code]var result : Array = await Firebase.Firestore.result_query[/code]
##
## @tutorial https://github.com/GodotNuts/GodotFirebase/wiki/Firestore#FirestoreTask
-tool
+@tool
class_name FirestoreTask
-extends Reference
+extends RefCounted
## Emitted when a request is completed. The request can be successful or not successful: if not, an [code]error[/code] Dictionary will be passed as a result.
## @arg-types Variant
-signal task_finished(task)
-## Emitted when a [code]add(document)[/code] request on a [class FirebaseCollection] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types FirestoreDocument
-signal add_document(doc)
-## Emitted when a [code]get(document)[/code] request on a [class FirebaseCollection] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types FirestoreDocument
-signal get_document(doc)
-## Emitted when a [code]update(document)[/code] request on a [class FirebaseCollection] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types FirestoreDocument
-signal update_document(doc)
-## Emitted when a [code]delete(document)[/code] request on a [class FirebaseCollection] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types FirestoreDocument
-signal delete_document()
-## Emitted when a [code]list(collection_id)[/code] request on [class FirebaseFirestore] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types Array
-signal listed_documents(documents)
-## Emitted when a [code]query(collection_id)[/code] request on [class FirebaseFirestore] is successfully completed. [code]error()[/code] signal will be emitted otherwise.
-## @arg-types Array
-signal result_query(result)
-## Emitted when a request is [b]not[/b] successfully completed.
-## @arg-types Dictionary
-signal task_error(code, status, message, task)
+signal task_finished()
enum Task {
- TASK_GET, ## A GET Request Task, processing a get() request
- TASK_POST, ## A POST Request Task, processing add() request
- TASK_PATCH, ## A PATCH Request Task, processing a update() request
- TASK_DELETE, ## A DELETE Request Task, processing a delete() request
- TASK_QUERY, ## A POST Request Task, processing a query() request
- TASK_LIST ## A POST Request Task, processing a list() request
+ TASK_GET, ## A GET Request Task, processing a get() request
+ TASK_POST, ## A POST Request Task, processing add() request
+ TASK_PATCH, ## A PATCH Request Task, processing a update() request
+ TASK_DELETE, ## A DELETE Request Task, processing a delete() request
+ TASK_QUERY, ## A POST Request Task, processing a query() request
+ TASK_AGG_QUERY, ## A POST Request Task, processing an aggregation_query() request
+ TASK_LIST, ## A POST Request Task, processing a list() request
+ TASK_COMMIT ## A POST Request Task that hits the write api
+}
+
+## Mapping of Task enum values to descriptions for use in printing user-friendly error codes.
+const TASK_MAP = {
+ Task.TASK_GET: "GET DOCUMENT",
+ Task.TASK_POST: "ADD DOCUMENT",
+ Task.TASK_PATCH: "UPDATE DOCUMENT",
+ Task.TASK_DELETE: "DELETE DOCUMENT",
+ Task.TASK_QUERY: "QUERY COLLECTION",
+ Task.TASK_LIST: "LIST DOCUMENTS",
+ Task.TASK_COMMIT: "COMMIT DOCUMENT",
+ Task.TASK_AGG_QUERY: "AGG QUERY COLLECTION"
}
## The code indicating the request Firestore is processing.
## See @[enum FirebaseFirestore.Requests] to get a full list of codes identifiers.
## @setter set_action
-var action : int = -1 setget set_action
+var action : int = -1 : set = set_action
## A variable, temporary holding the result of the request.
var data
-var error : Dictionary
-var document : FirestoreDocument
-## Whether the data came from cache.
-var from_cache : bool = false
-
-var _response_headers : PoolStringArray = PoolStringArray()
-var _response_code : int = 0
-
-var _method : int = -1
-var _url : String = ""
-var _fields : String = ""
-var _headers : PoolStringArray = []
-
-#func _ready() -> void:
-# connect("request_completed", self, "_on_request_completed")
-
-
-#func _push_request(url := "", headers := "", fields := "") -> void:
-# _url = url
-# _fields = fields
-# var temp_header : Array = []
-# temp_header.append(headers)
-# _headers = PoolStringArray(temp_header)
-#
-# if Firebase.Firestore._offline:
-# call_deferred("_on_request_completed", -1, 404, PoolStringArray(), PoolByteArray())
-# else:
-# request(_url, _headers, true, _method, _fields)
-
-
-func _on_request_completed(result : int, response_code : int, headers : PoolStringArray, body : PoolByteArray) -> void:
- var bod
- if validate_json(body.get_string_from_utf8()).empty():
- bod = JSON.parse(body.get_string_from_utf8()).result
-
- var offline: bool = typeof(bod) == TYPE_NIL
- var failed: bool = bod is Dictionary and bod.has("error") and response_code != HTTPClient.RESPONSE_OK
- from_cache = offline
-
- Firebase.Firestore._set_offline(offline)
-
- var cache_path : String = Firebase._config["cacheLocation"]
- if not cache_path.empty() and not failed and Firebase.Firestore.persistence_enabled:
- var encrypt_key: String = Firebase.Firestore._encrypt_key
- var full_path : String
- var url_segment : String
- match action:
- Task.TASK_LIST:
- url_segment = data[0]
- full_path = cache_path
- Task.TASK_QUERY:
- url_segment = JSON.print(data.query)
- full_path = cache_path
- _:
- url_segment = to_json(data)
- full_path = _get_doc_file(cache_path, url_segment, encrypt_key)
- bod = _handle_cache(offline, data, encrypt_key, full_path, bod)
- if not bod.empty() and offline:
- response_code = HTTPClient.RESPONSE_OK
-
- if response_code == HTTPClient.RESPONSE_OK:
- data = bod
- match action:
- Task.TASK_POST:
- document = FirestoreDocument.new(bod)
- emit_signal("add_document", document)
- Task.TASK_GET:
- document = FirestoreDocument.new(bod)
- emit_signal("get_document", document)
- Task.TASK_PATCH:
- document = FirestoreDocument.new(bod)
- emit_signal("update_document", document)
- Task.TASK_DELETE:
- emit_signal("delete_document")
- Task.TASK_QUERY:
- data = []
- for doc in bod:
- if doc.has('document'):
- data.append(FirestoreDocument.new(doc.document))
- emit_signal("result_query", data)
- Task.TASK_LIST:
- data = []
- if bod.has('documents'):
- for doc in bod.documents:
- data.append(FirestoreDocument.new(doc))
- if bod.has("nextPageToken"):
- data.append(bod.nextPageToken)
- emit_signal("listed_documents", data)
- else:
- Firebase._printerr("Action in error was: " + str(action))
- emit_error("task_error", bod, action)
-
- emit_signal("task_finished", self)
-
-func emit_error(signal_name : String, bod, task) -> void:
- if bod:
- if bod is Array and bod.size() > 0 and bod[0].has("error"):
- error = bod[0].error
- elif bod is Dictionary and bod.keys().size() > 0 and bod.has("error"):
- error = bod.error
-
- emit_signal(signal_name, error.code, error.status, error.message, task)
-
- return
-
- emit_signal(signal_name, 1, 0, "Unknown error", task)
+var error: Dictionary
+var document: FirestoreDocument
+
+var _response_headers: PackedStringArray = PackedStringArray()
+var _response_code: int = 0
+
+var _method: int = -1
+var _url: String = ""
+var _fields: String = ""
+var _headers: PackedStringArray = []
+
+func _on_request_completed(result: int, response_code: int, headers: PackedStringArray, body: PackedByteArray) -> void:
+ var bod = body.get_string_from_utf8()
+ if bod != "":
+ bod = Utilities.get_json_data(bod)
+
+ var failed: bool = bod is Dictionary and bod.has("error") and response_code != HTTPClient.RESPONSE_OK
+ # Probably going to regret this...
+ if response_code == HTTPClient.RESPONSE_OK:
+ match action:
+ Task.TASK_POST, Task.TASK_GET, Task.TASK_PATCH:
+ document = FirestoreDocument.new(bod)
+ data = document
+ Task.TASK_DELETE:
+ data = true
+ Task.TASK_QUERY:
+ data = []
+ for doc in bod:
+ if doc.has('document'):
+ data.append(FirestoreDocument.new(doc.document))
+ Task.TASK_AGG_QUERY:
+ var agg_results = []
+ for agg_result in bod:
+ var idx = 0
+ var query_results = {}
+ for field_value in agg_result.result.aggregateFields.keys():
+ var agg = data.aggregations[idx]
+ var field = agg_result.result.aggregateFields[field_value]
+ query_results[agg.keys()[0]] = Utilities.from_firebase_type(field)
+ idx += 1
+ agg_results.push_back(query_results)
+ data = agg_results
+ Task.TASK_LIST:
+ data = []
+ if bod.has('documents'):
+ for doc in bod.documents:
+ data.append(FirestoreDocument.new(doc))
+ if bod.has("nextPageToken"):
+ data.append(bod.nextPageToken)
+ Task.TASK_COMMIT:
+ data = bod # Commit's response is not a full document, so don't treat it as such
+ else:
+ var description = ""
+ if TASK_MAP.has(action):
+ description = "(" + TASK_MAP[action] + ")"
+
+ Firebase._printerr("Action in error was: " + str(action) + " " + description)
+ build_error(bod, action, description)
+
+ task_finished.emit()
+
+func build_error(_error, action, description) -> void:
+ if _error:
+ if _error is Array and _error.size() > 0 and _error[0].has("error"):
+ _error = _error[0].error
+ elif _error is Dictionary and _error.keys().size() > 0 and _error.has("error"):
+ _error = _error.error
+
+ error = _error
+ else:
+ #error.code, error.status, error.message
+ error = { "error": {
+ "code": 0,
+ "status": "Unknown Error",
+ "message": "Error: %s - %s" % [action, description]
+ }
+ }
+
+ data = null
func set_action(value : int) -> void:
- action = value
- match action:
- Task.TASK_GET, Task.TASK_LIST:
- _method = HTTPClient.METHOD_GET
- Task.TASK_POST, Task.TASK_QUERY:
- _method = HTTPClient.METHOD_POST
- Task.TASK_PATCH:
- _method = HTTPClient.METHOD_PATCH
- Task.TASK_DELETE:
- _method = HTTPClient.METHOD_DELETE
-
-
-func _handle_cache(offline : bool, data, encrypt_key : String, cache_path : String, body) -> Dictionary:
- var body_return := {}
-
- var dir := Directory.new()
- dir.make_dir_recursive(cache_path)
- var file := File.new()
- match action:
- Task.TASK_POST:
- if offline:
- var save: Dictionary
- if offline:
- save = {
- "name": "projects/%s/databases/(default)/documents/%s" % [Firebase._config["storageBucket"], data],
- "fields": JSON.parse(_fields).result["fields"],
- "createTime": "from_cache_file",
- "updateTime": "from_cache_file"
- }
- else:
- save = body.duplicate()
-
- if file.open_encrypted_with_pass(cache_path, File.READ, encrypt_key) == OK:
- file.store_line(data)
- file.store_line(JSON.print(save))
- body_return = save
- else:
- Firebase._printerr("Error saving cache file! Error code: %d" % file.get_error())
- file.close()
-
- Task.TASK_PATCH:
- if offline:
- var save := {
- "fields": {}
- }
- if offline:
- var mod: Dictionary
- mod = {
- "name": "projects/%s/databases/(default)/documents/%s" % [Firebase._config["storageBucket"], data],
- "fields": JSON.parse(_fields).result["fields"],
- "createTime": "from_cache_file",
- "updateTime": "from_cache_file"
- }
-
- if file.file_exists(cache_path):
- if file.open_encrypted_with_pass(cache_path, File.READ, encrypt_key) == OK:
- if file.get_len():
- assert(data == file.get_line())
- var content := file.get_line()
- if content != "--deleted--":
- save = JSON.parse(content).result
- else:
- Firebase._printerr("Error updating cache file! Error code: %d" % file.get_error())
- file.close()
-
- save.fields = FirestoreDocument.dict2fields(_merge_dict(
- FirestoreDocument.fields2dict({"fields": save.fields}),
- FirestoreDocument.fields2dict({"fields": mod.fields}),
- not offline
- )).fields
- save.name = mod.name
- save.createTime = mod.createTime
- save.updateTime = mod.updateTime
- else:
- save = body.duplicate()
-
-
- if file.open_encrypted_with_pass(cache_path, File.WRITE, encrypt_key) == OK:
- file.store_line(data)
- file.store_line(JSON.print(save))
- body_return = save
- else:
- Firebase._printerr("Error updating cache file! Error code: %d" % file.get_error())
- file.close()
-
- Task.TASK_GET:
- if offline and file.file_exists(cache_path):
- if file.open_encrypted_with_pass(cache_path, File.READ, encrypt_key) == OK:
- assert(data == file.get_line())
- var content := file.get_line()
- if content != "--deleted--":
- body_return = JSON.parse(content).result
- else:
- Firebase._printerr("Error reading cache file! Error code: %d" % file.get_error())
- file.close()
-
- Task.TASK_DELETE:
- if offline:
- if file.open_encrypted_with_pass(cache_path, File.WRITE, encrypt_key) == OK:
- file.store_line(data)
- file.store_line("--deleted--")
- body_return = {"deleted": true}
- else:
- Firebase._printerr("Error \"deleting\" cache file! Error code: %d" % file.get_error())
- file.close()
- else:
- dir.remove(cache_path)
-
- Task.TASK_LIST:
- if offline:
- var cache_dir := Directory.new()
- var cache_files := []
- if cache_dir.open(cache_path) == OK:
- cache_dir.list_dir_begin(true)
- var file_name = cache_dir.get_next()
- while file_name != "":
- if not cache_dir.current_is_dir() and file_name.ends_with(Firebase.Firestore._CACHE_EXTENSION):
- cache_files.append(cache_path.plus_file(file_name))
- file_name = cache_dir.get_next()
- cache_dir.list_dir_end()
- cache_files.erase(cache_path.plus_file(Firebase.Firestore._CACHE_RECORD_FILE))
- cache_dir.remove(cache_path.plus_file(Firebase.Firestore._CACHE_RECORD_FILE))
- print(cache_files)
-
- body_return.documents = []
- for cache in cache_files:
- if file.open_encrypted_with_pass(cache, File.READ, encrypt_key) == OK:
- if file.get_line().begins_with(data[0]):
- body_return.documents.append(JSON.parse(file.get_line()).result)
- else:
- Firebase._printerr("Error opening cache file for listing! Error code: %d" % file.get_error())
- file.close()
- body_return.documents.resize(min(data[1], body_return.documents.size()))
- body_return.nextPageToken = ""
-
- Task.TASK_QUERY:
- if offline:
- Firebase._printerr("Offline queries are currently unsupported!")
-
- if not offline:
- return body
- else:
- return body_return
+ action = value
+ match action:
+ Task.TASK_GET, Task.TASK_LIST:
+ _method = HTTPClient.METHOD_GET
+ Task.TASK_POST, Task.TASK_QUERY, Task.TASK_AGG_QUERY:
+ _method = HTTPClient.METHOD_POST
+ Task.TASK_PATCH:
+ _method = HTTPClient.METHOD_PATCH
+ Task.TASK_DELETE:
+ _method = HTTPClient.METHOD_DELETE
+ Task.TASK_COMMIT:
+ _method = HTTPClient.METHOD_POST
+ _:
+ assert(false)
func _merge_dict(dic_a : Dictionary, dic_b : Dictionary, nullify := false) -> Dictionary:
- var ret := dic_a.duplicate(true)
- for key in dic_b:
- var val = dic_b[key]
+ var ret := dic_a.duplicate(true)
+ for key in dic_b:
+ var val = dic_b[key]
- if val == null and nullify:
- ret.erase(key)
- elif val is Array:
- ret[key] = _merge_array(ret.get(key) if ret.get(key) else [], val)
- elif val is Dictionary:
- ret[key] = _merge_dict(ret.get(key) if ret.get(key) else {}, val)
- else:
- ret[key] = val
- return ret
+ if val == null and nullify:
+ ret.erase(key)
+ elif val is Array:
+ ret[key] = _merge_array(ret.get(key) if ret.get(key) else [], val)
+ elif val is Dictionary:
+ ret[key] = _merge_dict(ret.get(key) if ret.get(key) else {}, val)
+ else:
+ ret[key] = val
+ return ret
func _merge_array(arr_a : Array, arr_b : Array, nullify := false) -> Array:
- var ret := arr_a.duplicate(true)
- ret.resize(len(arr_b))
-
- var deletions := 0
- for i in len(arr_b):
- var index : int = i - deletions
- var val = arr_b[index]
- if val == null and nullify:
- ret.remove(index)
- deletions += i
- elif val is Array:
- ret[index] = _merge_array(ret[index] if ret[index] else [], val)
- elif val is Dictionary:
- ret[index] = _merge_dict(ret[index] if ret[index] else {}, val)
- else:
- ret[index] = val
- return ret
-
-
-static func _get_doc_file(cache_path : String, document_id : String, encrypt_key : String) -> String:
- var file := File.new()
- var path := ""
- var i = 0
- while i < 256:
- path = cache_path.plus_file("%s-%d.fscache" % [str(document_id.hash()).pad_zeros(10), i])
- if file.file_exists(path):
- var is_file := false
- if file.open_encrypted_with_pass(path, File.READ, encrypt_key) == OK:
- is_file = file.get_line() == document_id
- file.close()
-
- if is_file:
- return path
- else:
- i += 1
- else:
- return path
- return path
+ var ret := arr_a.duplicate(true)
+ ret.resize(len(arr_b))
+
+ var deletions := 0
+ for i in len(arr_b):
+ var index : int = i - deletions
+ var val = arr_b[index]
+ if val == null and nullify:
+ ret.remove_at(index)
+ deletions += i
+ elif val is Array:
+ ret[index] = _merge_array(ret[index] if ret[index] else [], val)
+ elif val is Dictionary:
+ ret[index] = _merge_dict(ret[index] if ret[index] else {}, val)
+ else:
+ ret[index] = val
+ return ret
diff --git a/addons/godot-firebase/firestore/firestore_transform.gd b/addons/godot-firebase/firestore/firestore_transform.gd
new file mode 100644
index 0000000..6de6597
--- /dev/null
+++ b/addons/godot-firebase/firestore/firestore_transform.gd
@@ -0,0 +1,3 @@
+class_name FirestoreTransform
+extends RefCounted
+
diff --git a/addons/godot-firebase/functions/function_task.gd b/addons/godot-firebase/functions/function_task.gd
index 461e005..96a6222 100644
--- a/addons/godot-firebase/functions/function_task.gd
+++ b/addons/godot-firebase/functions/function_task.gd
@@ -3,16 +3,16 @@
##
## ex.
## [code]var task : FirestoreTask = Firebase.Firestore.query(query)[/code]
-## [code]var result : Array = yield(task, "task_finished")[/code]
-## [code]var result : Array = yield(task, "result_query")[/code]
-## [code]var result : Array = yield(Firebase.Firestore, "task_finished")[/code]
-## [code]var result : Array = yield(Firebase.Firestore, "result_query")[/code]
+## [code]var result : Array = await task.task_finished[/code]
+## [code]var result : Array = await task.result_query[/code]
+## [code]var result : Array = await Firebase.Firestore.task_finished[/code]
+## [code]var result : Array = await Firebase.Firestore.result_query[/code]
##
## @tutorial https://github.com/GodotNuts/GodotFirebase/wiki/Firestore#FirestoreTask
-tool
-class_name FunctionTask
-extends Reference
+@tool
+class_name FunctionTask
+extends RefCounted
## Emitted when a request is completed. The request can be successful or not successful: if not, an [code]error[/code] Dictionary will be passed as a result.
## @arg-types Variant
@@ -31,42 +31,29 @@ var data: Dictionary
var error: Dictionary
## Whether the data came from cache.
-var from_cache: bool = false
-
-var _response_headers: PoolStringArray = PoolStringArray()
-var _response_code: int = 0
-
-var _method: int = -1
-var _url: String = ""
-var _fields: String = ""
-var _headers: PoolStringArray = []
-
+var from_cache : bool = false
-func _on_request_completed(result: int, response_code: int, headers: PoolStringArray, body: PoolByteArray) -> void:
- var bod
- if validate_json(body.get_string_from_utf8()).empty():
- bod = JSON.parse(body.get_string_from_utf8()).result
- else:
- bod = {content = body.get_string_from_utf8()}
+var _response_headers : PackedStringArray = PackedStringArray()
+var _response_code : int = 0
- var offline: bool = typeof(bod) == TYPE_NIL
- from_cache = offline
+var _method : int = -1
+var _url : String = ""
+var _fields : String = ""
+var _headers : PackedStringArray = []
- data = bod
- if response_code == HTTPClient.RESPONSE_OK and data != null:
- emit_signal("function_executed", result, data)
- else:
- error = {result = result, response_code = response_code, data = data}
- emit_signal("task_error", result, response_code, str(data))
+func _on_request_completed(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray) -> void:
+ var bod = Utilities.get_json_data(body)
+ if bod == null:
+ bod = {content = body.get_string_from_utf8()} # I don't understand what this line does at all. What the hell?!
- emit_signal("task_finished", data)
+ var offline: bool = typeof(bod) == TYPE_NIL
+ from_cache = offline
+ data = bod
+ if response_code == HTTPClient.RESPONSE_OK and data!=null:
+ function_executed.emit(result, data)
+ else:
+ error = {result=result, response_code=response_code, data=data}
+ task_error.emit(result, response_code, str(data))
-#func _handle_cache(offline : bool, data, encrypt_key : String, cache_path : String, body) -> Dictionary:
-# if offline:
-# Firebase._printerr("Offline queries are currently unsupported!")
-#
-# if not offline:
-# return body
-# else:
-# return body_return
+ task_finished.emit(data)
diff --git a/addons/godot-firebase/functions/functions.gd b/addons/godot-firebase/functions/functions.gd
index 0bb600e..8ccfa97 100644
--- a/addons/godot-firebase/functions/functions.gd
+++ b/addons/godot-firebase/functions/functions.gd
@@ -4,7 +4,7 @@
## (source: [url=https://firebase.google.com/docs/functions]Functions[/url])
##
## @tutorial https://github.com/GodotNuts/GodotFirebase/wiki/Functions
-tool
+@tool
class_name FirebaseFunctions
extends Node
@@ -30,11 +30,11 @@ var request : int = -1
## Whether cache files can be used and generated.
## @default true
-var persistence_enabled : bool = true
+var persistence_enabled : bool = false
## Whether an internet connection can be used.
## @default true
-var networking: bool = true setget set_networking
+var networking: bool = true : set = set_networking
## A Dictionary containing all authentication fields for the current logged user.
## @type Dictionary
@@ -42,177 +42,178 @@ var auth : Dictionary
var _config : Dictionary = {}
var _cache_loc: String
-var _encrypt_key: String = "" if OS.get_name() in ["HTML5", "UWP"] else OS.get_unique_id()
+var _encrypt_key: String = "" if Utilities.is_web() else OS.get_unique_id()
var _base_url : String = ""
var _http_request_pool : Array = []
-var _offline: bool = false setget _set_offline
+var _offline: bool = false : set = _set_offline
func _ready() -> void:
- pass
+ set_process(false)
func _process(delta : float) -> void:
- for i in range(_http_request_pool.size() - 1, -1, -1):
- var request = _http_request_pool[i]
- if not request.get_meta("requesting"):
- var lifetime: float = request.get_meta("lifetime") + delta
- if lifetime > _MAX_POOLED_REQUEST_AGE:
- request.queue_free()
- _http_request_pool.remove(i)
- request.set_meta("lifetime", lifetime)
+ for i in range(_http_request_pool.size() - 1, -1, -1):
+ var request = _http_request_pool[i]
+ if not request.get_meta("requesting"):
+ var lifetime: float = request.get_meta("lifetime") + delta
+ if lifetime > _MAX_POOLED_REQUEST_AGE:
+ request.queue_free()
+ _http_request_pool.remove_at(i)
+ return # Prevent setting a value on request after it's already been queue_freed
+ request.set_meta("lifetime", lifetime)
## @args
## @return FunctionTask
func execute(function: String, method: int, params: Dictionary = {}, body: Dictionary = {}) -> FunctionTask:
- var function_task : FunctionTask = FunctionTask.new()
- function_task.connect("task_error", self, "_on_task_error")
- function_task.connect("task_finished", self, "_on_task_finished")
- function_task.connect("function_executed", self, "_on_function_executed")
+ set_process(true)
+ var function_task : FunctionTask = FunctionTask.new()
+ function_task.task_error.connect(_on_task_error)
+ function_task.task_finished.connect(_on_task_finished)
+ function_task.function_executed.connect(_on_function_executed)
- function_task._method = method
+ function_task._method = method
- var url : String = _base_url + ("/" if not _base_url.ends_with("/") else "") + function
+ var url : String = _base_url + ("/" if not _base_url.ends_with("/") else "") + function
+ function_task._url = url
- if not params.empty():
- url += "?"
- for key in params.keys():
- url += key + "=" + params[key] + "&"
-
- function_task._url = url
+ if not params.is_empty():
+ url += "?"
+ for key in params.keys():
+ url += key + "=" + params[key] + "&"
- if not body.empty():
- function_task._headers = PoolStringArray(["Content-Type: application/json"])
- function_task._fields = to_json(body)
+ if not body.is_empty():
+ function_task._fields = JSON.stringify(body)
- _pooled_request(function_task)
- return function_task
+ _pooled_request(function_task)
+ return function_task
func set_networking(value: bool) -> void:
- if value:
- enable_networking()
- else:
- disable_networking()
+ if value:
+ enable_networking()
+ else:
+ disable_networking()
func enable_networking() -> void:
- if networking:
- return
- networking = true
- _base_url = _base_url.replace("storeoffline", "functions")
+ if networking:
+ return
+ networking = true
+ _base_url = _base_url.replace("storeoffline", "functions")
func disable_networking() -> void:
- if not networking:
- return
- networking = false
- # Pointing to an invalid url should do the trick.
- _base_url = _base_url.replace("functions", "storeoffline")
+ if not networking:
+ return
+ networking = false
+ # Pointing to an invalid url should do the trick.
+ _base_url = _base_url.replace("functions", "storeoffline")
func _set_offline(value: bool) -> void:
- if value == _offline:
- return
+ if value == _offline:
+ return
- _offline = value
- if not persistence_enabled:
- return
+ _offline = value
+ if not persistence_enabled:
+ return
- return
+ return
func _set_config(config_json : Dictionary) -> void:
- _config = config_json
- _cache_loc = _config["cacheLocation"]
+ _config = config_json
+ _cache_loc = _config["cacheLocation"]
- if _encrypt_key == "": _encrypt_key = _config.apiKey
- _check_emulating()
+ if _encrypt_key == "": _encrypt_key = _config.apiKey
+ _check_emulating()
func _check_emulating() -> void :
- ## Check emulating
- if not Firebase.emulating:
- _base_url = "https://{zone}-{projectId}.cloudfunctions.net/".format({ zone = _config.functionsGeoZone, projectId = _config.projectId })
- else:
- var port : String = _config.emulators.ports.functions
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Cloud Functions has not been configured.")
- else:
- _base_url = "http://localhost:{port}/{projectId}/{zone}/".format({ port = port, zone = _config.functionsGeoZone, projectId = _config.projectId })
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = "https://{zone}-{projectId}.cloudfunctions.net/".format({ zone = _config.functionsGeoZone, projectId = _config.projectId })
+ else:
+ var port : String = _config.emulators.ports.functions
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Cloud Functions has not been configured.")
+ else:
+ _base_url = "http://localhost:{port}/{projectId}/{zone}/".format({ port = port, zone = _config.functionsGeoZone, projectId = _config.projectId })
func _pooled_request(task : FunctionTask) -> void:
- if _offline:
- task._on_request_completed(HTTPRequest.RESULT_CANT_CONNECT, 404, PoolStringArray(), PoolByteArray())
- return
+ if _offline:
+ task._on_request_completed(HTTPRequest.RESULT_CANT_CONNECT, 404, PackedStringArray(), PackedByteArray())
+ return
- if not auth:
- Firebase._print("Unauthenticated request issued...")
- Firebase.Auth.login_anonymous()
- var result : Array = yield(Firebase.Auth, "auth_request")
- if result[0] != 1:
- _check_auth_error(result[0], result[1])
- Firebase._print("Client connected as Anonymous")
+ if auth == null or auth.is_empty():
+ Firebase._print("Unauthenticated request issued...")
+ Firebase.Auth.login_anonymous()
+ var result : Array = await Firebase.Auth.auth_request
+ if result[0] != 1:
+ _check_auth_error(result[0], result[1])
+ Firebase._print("Client connected as Anonymous")
- task._headers = Array(task._headers) + [_AUTHORIZATION_HEADER + auth.idtoken]
+ task._headers = ["Content-Type: application/json", _AUTHORIZATION_HEADER + auth.idtoken]
- var http_request : HTTPRequest
- for request in _http_request_pool:
- if not request.get_meta("requesting"):
- http_request = request
- break
+ var http_request : HTTPRequest
+ for request in _http_request_pool:
+ if not request.get_meta("requesting"):
+ http_request = request
+ break
- if not http_request:
- http_request = HTTPRequest.new()
- _http_request_pool.append(http_request)
- add_child(http_request)
- http_request.connect("request_completed", self, "_on_pooled_request_completed", [http_request])
+ if not http_request:
+ http_request = HTTPRequest.new()
+ Utilities.fix_http_request(http_request)
+ http_request.accept_gzip = false
+ _http_request_pool.append(http_request)
+ add_child(http_request)
+ http_request.request_completed.connect(_on_pooled_request_completed.bind(http_request))
- http_request.set_meta("requesting", true)
- http_request.set_meta("lifetime", 0.0)
- http_request.set_meta("task", task)
- http_request.request(task._url, task._headers, true, task._method, task._fields)
+ http_request.set_meta("requesting", true)
+ http_request.set_meta("lifetime", 0.0)
+ http_request.set_meta("task", task)
+ http_request.request(task._url, task._headers, task._method, task._fields)
# -------------
func _on_task_finished(data : Dictionary) :
- pass
+ pass
func _on_function_executed(result : int, data : Dictionary) :
- pass
+ pass
func _on_task_error(code : int, status : int, message : String):
- emit_signal("task_error", code, status, message)
- Firebase._printerr(message)
+ task_error.emit(code, status, message)
+ Firebase._printerr(message)
func _on_FirebaseAuth_login_succeeded(auth_result : Dictionary) -> void:
- auth = auth_result
+ auth = auth_result
func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
- auth = auth_result
+ auth = auth_result
-func _on_pooled_request_completed(result : int, response_code : int, headers : PoolStringArray, body : PoolByteArray, request : HTTPRequest) -> void:
- request.get_meta("task")._on_request_completed(result, response_code, headers, body)
- request.set_meta("requesting", false)
+func _on_pooled_request_completed(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray, request : HTTPRequest) -> void:
+ request.get_meta("task")._on_request_completed(result, response_code, headers, body)
+ request.set_meta("requesting", false)
func _on_connect_check_request_completed(result : int, _response_code, _headers, _body) -> void:
- _set_offline(result != HTTPRequest.RESULT_SUCCESS)
- #_connect_check_node.request(_base_url)
+ _set_offline(result != HTTPRequest.RESULT_SUCCESS)
func _on_FirebaseAuth_logout() -> void:
- auth = {}
+ auth = {}
func _check_auth_error(code : int, message : String) -> void:
- var err : String
- match code:
- 400: err = "Please, enable Anonymous Sign-in method or Authenticate the Client before issuing a request (best option)"
- Firebase._printerr(err)
+ var err : String
+ match code:
+ 400: err = "Please, enable Anonymous Sign-in method or Authenticate the Client before issuing a request (best option)"
+ Firebase._printerr(err)
diff --git a/addons/godot-firebase/icon.svg.import b/addons/godot-firebase/icon.svg.import
index 19a1c3b..943b056 100644
--- a/addons/godot-firebase/icon.svg.import
+++ b/addons/godot-firebase/icon.svg.import
@@ -1,8 +1,9 @@
[remap]
importer="texture"
-type="StreamTexture"
-path="res://.import/icon.svg-5c4f39d37c9275a3768de73a392fd315.stex"
+type="CompressedTexture2D"
+uid="uid://2selq12fp4q0"
+path="res://.godot/imported/icon.svg-5c4f39d37c9275a3768de73a392fd315.ctex"
metadata={
"vram_texture": false
}
@@ -10,26 +11,27 @@ metadata={
[deps]
source_file="res://addons/godot-firebase/icon.svg"
-dest_files=[ "res://.import/icon.svg-5c4f39d37c9275a3768de73a392fd315.stex" ]
+dest_files=["res://.godot/imported/icon.svg-5c4f39d37c9275a3768de73a392fd315.ctex"]
[params]
compress/mode=0
+compress/high_quality=false
compress/lossy_quality=0.7
-compress/hdr_mode=0
-compress/bptc_ldr=0
+compress/hdr_compression=1
compress/normal_map=0
-flags/repeat=0
-flags/filter=true
-flags/mipmaps=false
-flags/anisotropic=false
-flags/srgb=2
+compress/channel_pack=0
+mipmaps/generate=false
+mipmaps/limit=-1
+roughness/mode=0
+roughness/src_normal=""
process/fix_alpha_border=true
process/premult_alpha=false
-process/HDR_as_SRGB=false
-process/invert_color=false
process/normal_map_invert_y=false
-stream=false
-size_limit=0
-detect_3d=true
+process/hdr_as_srgb=false
+process/hdr_clamp_exposure=false
+process/size_limit=0
+detect_3d/compress_to=1
svg/scale=1.0
+editor/scale_with_editor_scale=false
+editor/convert_colors_with_editor_theme=false
diff --git a/addons/godot-firebase/plugin.cfg b/addons/godot-firebase/plugin.cfg
index 9249db8..9740be9 100644
--- a/addons/godot-firebase/plugin.cfg
+++ b/addons/godot-firebase/plugin.cfg
@@ -1,7 +1,7 @@
[plugin]
name="GodotFirebase"
-description="Google Firebase SDK written in GDScript for use in Godot Engine projects."
-author="Kyle Szklenski"
-version="4.8"
+description="Google Firebase SDK written in GDScript for use in Godot Engine 4.0 projects."
+author="GodotNutsOrg"
+version="2.0"
script="plugin.gd"
diff --git a/addons/godot-firebase/plugin.gd b/addons/godot-firebase/plugin.gd
index e0f7678..f68d5ae 100644
--- a/addons/godot-firebase/plugin.gd
+++ b/addons/godot-firebase/plugin.gd
@@ -1,10 +1,8 @@
-tool
+@tool
extends EditorPlugin
-
func _enter_tree() -> void:
add_autoload_singleton("Firebase", "res://addons/godot-firebase/firebase/firebase.tscn")
-
func _exit_tree() -> void:
remove_autoload_singleton("Firebase")
diff --git a/addons/godot-firebase/queues/queueable_http_request.gd b/addons/godot-firebase/queues/queueable_http_request.gd
new file mode 100644
index 0000000..0143a78
--- /dev/null
+++ b/addons/godot-firebase/queues/queueable_http_request.gd
@@ -0,0 +1,30 @@
+class_name QueueableHTTPRequest
+extends HTTPRequest
+
+signal queue_request_completed(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray)
+
+var _queue := []
+
+# Determine if we need to set Use Threads to true; it can cause collisions with get_http_client_status() due to a thread returning the data _after_ having checked the connection status and result in double-requests.
+
+func _ready() -> void:
+ request_completed.connect(
+ func(result : int, response_code : int, headers : PackedStringArray, body : PackedByteArray):
+ queue_request_completed.emit(result, response_code, headers, body)
+
+ if not _queue.is_empty():
+ var req = _queue.pop_front()
+ self.request(req.url, req.headers, req.method, req.data)
+ )
+
+func request(url : String, headers : PackedStringArray = PackedStringArray(), method := HTTPClient.METHOD_GET, data : String = "") -> Error:
+ var status = get_http_client_status()
+ var result = OK
+
+ if status != HTTPClient.STATUS_DISCONNECTED:
+ _queue.push_back({url=url, headers=headers, method=method, data=data})
+ return result
+
+ result = super.request(url, headers, method, data)
+
+ return result
diff --git a/addons/godot-firebase/queues/queueable_http_request.tscn b/addons/godot-firebase/queues/queueable_http_request.tscn
new file mode 100644
index 0000000..d166941
--- /dev/null
+++ b/addons/godot-firebase/queues/queueable_http_request.tscn
@@ -0,0 +1,6 @@
+[gd_scene load_steps=2 format=3 uid="uid://ctb4l7plg8kqg"]
+
+[ext_resource type="Script" path="res://addons/godot-firebase/queues/queueable_http_request.gd" id="1_2rucc"]
+
+[node name="QueueableHTTPRequest" type="HTTPRequest"]
+script = ExtResource("1_2rucc")
diff --git a/addons/godot-firebase/remote_config/firebase_remote_config.gd b/addons/godot-firebase/remote_config/firebase_remote_config.gd
new file mode 100644
index 0000000..ee3653e
--- /dev/null
+++ b/addons/godot-firebase/remote_config/firebase_remote_config.gd
@@ -0,0 +1,36 @@
+@tool
+class_name FirebaseRemoteConfig
+extends Node
+
+const RemoteConfigFunctionId = "getRemoteConfig"
+
+signal remote_config_received(config)
+signal remote_config_error(error)
+
+var _project_config = {}
+var _headers : PackedStringArray = [
+]
+var _auth : Dictionary
+
+func _set_config(config_json : Dictionary) -> void:
+ _project_config = config_json # This may get confusing, hoping the variable name makes it easier to understand
+
+func _on_FirebaseAuth_login_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
+
+func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
+
+func _on_FirebaseAuth_logout() -> void:
+ _auth = {}
+
+func get_remote_config() -> void:
+ var function_task = Firebase.Functions.execute("getRemoteConfig", HTTPClient.METHOD_GET, {}, {}) as FunctionTask
+ var result = await function_task.task_finished
+ Firebase._print("Config request result: " + str(result))
+ if result.has("error"):
+ remote_config_error.emit(result)
+ return
+
+ var config = RemoteConfig.new(result)
+ remote_config_received.emit(config)
diff --git a/addons/godot-firebase/remote_config/firebase_remote_config.tscn b/addons/godot-firebase/remote_config/firebase_remote_config.tscn
new file mode 100644
index 0000000..5c42d3f
--- /dev/null
+++ b/addons/godot-firebase/remote_config/firebase_remote_config.tscn
@@ -0,0 +1,7 @@
+[gd_scene load_steps=2 format=3 uid="uid://5xa6ulbllkjk"]
+
+[ext_resource type="Script" path="res://addons/godot-firebase/remote_config/firebase_remote_config.gd" id="1_wx4ds"]
+
+[node name="FirebaseRemoteConfig" type="HTTPRequest"]
+use_threads = true
+script = ExtResource("1_wx4ds")
diff --git a/addons/godot-firebase/remote_config/remote_config.gd b/addons/godot-firebase/remote_config/remote_config.gd
new file mode 100644
index 0000000..2b72cc6
--- /dev/null
+++ b/addons/godot-firebase/remote_config/remote_config.gd
@@ -0,0 +1,14 @@
+class_name RemoteConfig
+extends RefCounted
+
+var default_config = {}
+
+func _init(values : Dictionary) -> void:
+ default_config = values
+
+func get_value(key : String) -> Variant:
+ if default_config.has(key):
+ return default_config[key]
+
+ Firebase._printerr("Remote config does not contain key: " + key)
+ return null
diff --git a/addons/godot-firebase/storage/storage.gd b/addons/godot-firebase/storage/storage.gd
index af7c22a..baabd75 100644
--- a/addons/godot-firebase/storage/storage.gd
+++ b/addons/godot-firebase/storage/storage.gd
@@ -4,364 +4,359 @@
## This object handles all firebase storage tasks, variables and references. To use this API, you must first create a [StorageReference] with [method ref]. With the reference, you can then query and manipulate the file or folder in the cloud storage.
##
## [i]Note: In HTML builds, you must configure [url=https://firebase.google.com/docs/storage/web/download-files#cors_configuration]CORS[/url] in your storage bucket.[i]
-tool
+@tool
class_name FirebaseStorage
extends Node
+const _API_VERSION : String = "v0"
-const _API_VERSION: String = "v0"
-
-## @arg-types int, int, PoolStringArray
-## @arg-enums HTTPRequest.Result, HTTPClient.ResponseCode
-## Emitted when a [StorageTask] has finished successful.
-signal task_successful(result, response_code, data)
-
-## @arg-types int, int, PoolStringArray
+## @arg-types int, int, PackedStringArray
## @arg-enums HTTPRequest.Result, HTTPClient.ResponseCode
## Emitted when a [StorageTask] has finished with an error.
signal task_failed(result, response_code, data)
## The current storage bucket the Storage API is referencing.
-var bucket: String
+var bucket : String
## @default false
## Whether a task is currently being processed.
-var requesting: bool = false
-
-var _auth: Dictionary
-var _config: Dictionary
-
-var _references: Dictionary = {}
-
-var _base_url: String = ""
-var _extended_url: String = "/[API_VERSION]/b/[APP_ID]/o/[FILE_PATH]"
-var _root_ref: StorageReference
-
-var _http_client: HTTPClient = HTTPClient.new()
-var _pending_tasks: Array = []
-
-var _current_task: StorageTask
-var _response_code: int
-var _response_headers: PoolStringArray
-var _response_data: PoolByteArray
-var _content_length: int
-var _reading_body: bool
-
-
-func _notification(what: int) -> void:
- if what == NOTIFICATION_INTERNAL_PROCESS:
- _internal_process(get_process_delta_time())
-
-
-func _internal_process(_delta: float) -> void:
- if not requesting:
- set_process_internal(false)
- return
-
- var task = _current_task
-
- match _http_client.get_status():
- HTTPClient.STATUS_DISCONNECTED:
- _http_client.connect_to_host(_base_url, 443, true)
-
- HTTPClient.STATUS_RESOLVING, \
- HTTPClient.STATUS_REQUESTING, \
- HTTPClient.STATUS_CONNECTING:
- _http_client.poll()
-
- HTTPClient.STATUS_CONNECTED:
- var err := _http_client.request_raw(task._method, task._url, task._headers, task.data)
- if err:
- _finish_request(HTTPRequest.RESULT_CONNECTION_ERROR)
-
- HTTPClient.STATUS_BODY:
- if _http_client.has_response() or _reading_body:
- _reading_body = true
-
- # If there is a response...
- if _response_headers.empty():
- _response_headers = _http_client.get_response_headers() # Get response headers.
- _response_code = _http_client.get_response_code()
-
- for header in _response_headers:
- if "Content-Length" in header:
- _content_length = header.trim_prefix("Content-Length: ").to_int()
-
- _http_client.poll()
- var chunk = _http_client.read_response_body_chunk() # Get a chunk.
- if chunk.size() == 0:
- # Got nothing, wait for buffers to fill a bit.
- pass
- else:
- _response_data += chunk # Append to read buffer.
- if _content_length != 0:
- task.progress = float(_response_data.size()) / _content_length
-
- if _http_client.get_status() != HTTPClient.STATUS_BODY:
- task.progress = 1.0
- _finish_request(HTTPRequest.RESULT_SUCCESS)
- else:
- task.progress = 1.0
- _finish_request(HTTPRequest.RESULT_SUCCESS)
-
- HTTPClient.STATUS_CANT_CONNECT:
- _finish_request(HTTPRequest.RESULT_CANT_CONNECT)
- HTTPClient.STATUS_CANT_RESOLVE:
- _finish_request(HTTPRequest.RESULT_CANT_RESOLVE)
- HTTPClient.STATUS_CONNECTION_ERROR:
- _finish_request(HTTPRequest.RESULT_CONNECTION_ERROR)
- HTTPClient.STATUS_SSL_HANDSHAKE_ERROR:
- _finish_request(HTTPRequest.RESULT_SSL_HANDSHAKE_ERROR)
-
+var requesting : bool = false
+
+var _auth : Dictionary
+var _config : Dictionary
+
+var _references : Dictionary = {}
+
+var _base_url : String = ""
+var _extended_url : String = "/[API_VERSION]/b/[APP_ID]/o/[FILE_PATH]"
+var _root_ref : StorageReference
+
+var _http_client : HTTPClient = HTTPClient.new()
+var _pending_tasks : Array = []
+
+var _current_task : StorageTask
+var _response_code : int
+var _response_headers : PackedStringArray
+var _response_data : PackedByteArray
+var _content_length : int
+var _reading_body : bool
+
+func _notification(what : int) -> void:
+ if what == NOTIFICATION_INTERNAL_PROCESS:
+ _internal_process(get_process_delta_time())
+
+func _internal_process(_delta : float) -> void:
+ if not requesting:
+ set_process_internal(false)
+ return
+
+ var task = _current_task
+
+ match _http_client.get_status():
+ HTTPClient.STATUS_DISCONNECTED:
+ _http_client.connect_to_host(_base_url, 443, TLSOptions.client()) # Uhh, check if this is going to work. I assume not.
+
+ HTTPClient.STATUS_RESOLVING, \
+ HTTPClient.STATUS_REQUESTING, \
+ HTTPClient.STATUS_CONNECTING:
+ _http_client.poll()
+
+ HTTPClient.STATUS_CONNECTED:
+ var err := _http_client.request_raw(task._method, task._url, task._headers, task.data)
+ if err:
+ _finish_request(HTTPRequest.RESULT_CONNECTION_ERROR)
+
+ HTTPClient.STATUS_BODY:
+ if _http_client.has_response() or _reading_body:
+ _reading_body = true
+
+ # If there is a response...
+ if _response_headers.is_empty():
+ _response_headers = _http_client.get_response_headers() # Get response headers.
+ _response_code = _http_client.get_response_code()
+
+ for header in _response_headers:
+ if "Content-Length" in header:
+ _content_length = header.trim_prefix("Content-Length: ").to_int()
+ break
+
+ _http_client.poll()
+ var chunk = _http_client.read_response_body_chunk() # Get a chunk.
+ if chunk.size() == 0:
+ # Got nothing, wait for buffers to fill a bit.
+ pass
+ else:
+ _response_data += chunk # Append to read buffer.
+ if _content_length != 0:
+ task.progress = float(_response_data.size()) / _content_length
+
+ if _http_client.get_status() != HTTPClient.STATUS_BODY:
+ task.progress = 1.0
+ _finish_request(HTTPRequest.RESULT_SUCCESS)
+ else:
+ task.progress = 1.0
+ _finish_request(HTTPRequest.RESULT_SUCCESS)
+
+ HTTPClient.STATUS_CANT_CONNECT:
+ _finish_request(HTTPRequest.RESULT_CANT_CONNECT)
+ HTTPClient.STATUS_CANT_RESOLVE:
+ _finish_request(HTTPRequest.RESULT_CANT_RESOLVE)
+ HTTPClient.STATUS_CONNECTION_ERROR:
+ _finish_request(HTTPRequest.RESULT_CONNECTION_ERROR)
+ HTTPClient.STATUS_TLS_HANDSHAKE_ERROR:
+ _finish_request(HTTPRequest.RESULT_TLS_HANDSHAKE_ERROR)
## @args path
## @arg-defaults ""
## @return StorageReference
-## Returns a reference to a file or folder in the storage bucket. It's this reference that should be used to control the file/folder on the server end.
+## Returns a reference to a file or folder in the storage bucket. It's this reference that should be used to control the file/folder checked the server end.
func ref(path := "") -> StorageReference:
- if not _config:
- return null
-
- # Create a root storage reference if there's none
- # and we're not making one.
- if path != "" and not _root_ref:
- _root_ref = ref()
-
- path = _simplify_path(path)
- if not _references.has(path):
- var ref := StorageReference.new()
- _references[path] = ref
- ref.valid = true
- ref.bucket = bucket
- ref.full_path = path
- ref.name = path.get_file()
- ref.parent = ref(path.plus_file(".."))
- ref.root = _root_ref
- ref.storage = self
- return ref
- else:
- return _references[path]
-
-
-func _set_config(config_json: Dictionary) -> void:
- _config = config_json
- if bucket != _config.storageBucket:
- bucket = _config.storageBucket
- _http_client.close()
- _check_emulating()
-
-
-func _check_emulating() -> void:
- ## Check emulating
- if not Firebase.emulating:
- _base_url = "https://firebasestorage.googleapis.com"
- else:
- var port: String = _config.emulators.ports.storage
- if port == "":
- Firebase._printerr("You are in 'emulated' mode, but the port for Storage has not been configured.")
- else:
- _base_url = "http://localhost:{port}/{version}/".format({version = _API_VERSION, port = port})
-
-
-func _upload(data: PoolByteArray, headers: PoolStringArray, ref: StorageReference, meta_only: bool) -> StorageTask:
- if not (_config and _auth):
- return null
-
- var task := StorageTask.new()
- task.ref = ref
- task._url = _get_file_url(ref)
- task.action = StorageTask.Task.TASK_UPLOAD_META if meta_only else StorageTask.Task.TASK_UPLOAD
- task._headers = headers
- task.data = data
- _process_request(task)
- return task
-
-
-func _download(ref: StorageReference, meta_only: bool, url_only: bool) -> StorageTask:
- if not (_config and _auth):
- return null
-
- var info_task := StorageTask.new()
- info_task.ref = ref
- info_task._url = _get_file_url(ref)
- info_task.action = StorageTask.Task.TASK_DOWNLOAD_URL if url_only else StorageTask.Task.TASK_DOWNLOAD_META
- _process_request(info_task)
-
- if url_only or meta_only:
- return info_task
-
- var task := StorageTask.new()
- task.ref = ref
- task._url = _get_file_url(ref) + "?alt=media&token="
- task.action = StorageTask.Task.TASK_DOWNLOAD
- _pending_tasks.append(task)
-
- yield(info_task, "task_finished")
- if info_task.data and not info_task.data.has("error"):
- task._url += info_task.data.downloadTokens
- else:
- task.data = info_task.data
- task.response_headers = info_task.response_headers
- task.response_code = info_task.response_code
- task.result = info_task.result
- task.finished = true
- task.emit_signal("task_finished")
- emit_signal("task_failed", task.result, task.response_code, task.data)
- _pending_tasks.erase(task)
-
- return task
-
-
-func _list(ref: StorageReference, list_all: bool) -> StorageTask:
- if not (_config and _auth):
- return null
-
- var task := StorageTask.new()
- task.ref = ref
- task._url = _get_file_url(_root_ref).trim_suffix("/")
- task.action = StorageTask.Task.TASK_LIST_ALL if list_all else StorageTask.Task.TASK_LIST
- _process_request(task)
- return task
-
-
-func _delete(ref: StorageReference) -> StorageTask:
- if not (_config and _auth):
- return null
-
- var task := StorageTask.new()
- task.ref = ref
- task._url = _get_file_url(ref)
- task.action = StorageTask.Task.TASK_DELETE
- _process_request(task)
- return task
-
-
-func _process_request(task: StorageTask) -> void:
- if requesting:
- _pending_tasks.append(task)
- return
- requesting = true
-
- var headers = Array(task._headers)
- headers.append("Authorization: Bearer " + _auth.idtoken)
- task._headers = PoolStringArray(headers)
-
- _current_task = task
- _response_code = 0
- _response_headers = PoolStringArray()
- _response_data = PoolByteArray()
- _content_length = 0
- _reading_body = false
-
- if not _http_client.get_status() in [HTTPClient.STATUS_CONNECTED, HTTPClient.STATUS_DISCONNECTED]:
- _http_client.close()
- set_process_internal(true)
-
-
-func _finish_request(result: int) -> void:
- var task := _current_task
- requesting = false
-
- task.result = result
- task.response_code = _response_code
- task.response_headers = _response_headers
-
- match task.action:
- StorageTask.Task.TASK_DOWNLOAD:
- task.data = _response_data
-
- StorageTask.Task.TASK_DELETE:
- _references.erase(task.ref.full_path)
- task.ref.valid = false
- if typeof(task.data) == TYPE_RAW_ARRAY:
- task.data = null
-
- StorageTask.Task.TASK_DOWNLOAD_URL:
- var json: Dictionary = JSON.parse(_response_data.get_string_from_utf8()).result
- if json and json.has("downloadTokens"):
- task.data = _base_url + _get_file_url(task.ref) + "?alt=media&token=" + json.downloadTokens
- else:
- task.data = ""
-
- StorageTask.Task.TASK_LIST, StorageTask.Task.TASK_LIST_ALL:
- var json: Dictionary = JSON.parse(_response_data.get_string_from_utf8()).result
- var items := []
- if json and json.has("items"):
- for item in json.items:
- var item_name: String = item.name
- if item.bucket != bucket:
- continue
- if not item_name.begins_with(task.ref.full_path):
- continue
- if task.action == StorageTask.Task.TASK_LIST:
- var dir_path: Array = item_name.split("/")
- var slash_count: int = task.ref.full_path.count("/")
- item_name = ""
- for i in slash_count + 1:
- item_name += dir_path[i]
- if i != slash_count and slash_count != 0:
- item_name += "/"
- if item_name in items:
- continue
-
- items.append(item_name)
- task.data = items
-
- _:
- task.data = JSON.parse(_response_data.get_string_from_utf8()).result
-
- var next_task: StorageTask
- if not _pending_tasks.empty():
- next_task = _pending_tasks.pop_front()
-
- task.finished = true
- task.emit_signal("task_finished")
- if typeof(task.data) == TYPE_DICTIONARY and task.data.has("error"):
- emit_signal("task_failed", task.result, task.response_code, task.data)
- else:
- emit_signal("task_successful", task.result, task.response_code, task.data)
-
- while true:
- if next_task and not next_task.finished:
- _process_request(next_task)
- break
- elif not _pending_tasks.empty():
- next_task = _pending_tasks.pop_front()
- else:
- break
-
-
-func _get_file_url(ref: StorageReference) -> String:
- var url := _extended_url.replace("[APP_ID]", ref.bucket)
- url = url.replace("[API_VERSION]", _API_VERSION)
- return url.replace("[FILE_PATH]", ref.full_path.replace("/", "%2F"))
-
+ if _config == null or _config.is_empty():
+ return null
+
+ # Create a root storage reference if there's none
+ # and we're not making one.
+ if path != "" and not _root_ref:
+ _root_ref = ref()
+
+ path = _simplify_path(path)
+ if not _references.has(path):
+ var ref := StorageReference.new()
+ _references[path] = ref
+ ref.bucket = bucket
+ ref.full_path = path
+ ref.file_name = path.get_file()
+ ref.parent = ref(path.path_join(".."))
+ ref.root = _root_ref
+ ref.storage = self
+ add_child(ref)
+ return ref
+ else:
+ return _references[path]
+
+func _set_config(config_json : Dictionary) -> void:
+ _config = config_json
+ if bucket != _config.storageBucket:
+ bucket = _config.storageBucket
+ _http_client.close()
+ _check_emulating()
+
+
+func _check_emulating() -> void :
+ ## Check emulating
+ if not Firebase.emulating:
+ _base_url = "https://firebasestorage.googleapis.com"
+ else:
+ var port : String = _config.emulators.ports.storage
+ if port == "":
+ Firebase._printerr("You are in 'emulated' mode, but the port for Storage has not been configured.")
+ else:
+ _base_url = "http://localhost:{port}/{version}/".format({ version = _API_VERSION, port = port })
+
+
+func _upload(data : PackedByteArray, headers : PackedStringArray, ref : StorageReference, meta_only : bool) -> Variant:
+ if _is_invalid_authentication():
+ Firebase._printerr("Error uploading to storage: Invalid authentication")
+ return 0
+
+ var task := StorageTask.new()
+ task.ref = ref
+ task._url = _get_file_url(ref)
+ task.action = StorageTask.Task.TASK_UPLOAD_META if meta_only else StorageTask.Task.TASK_UPLOAD
+ task._headers = headers
+ task.data = data
+ _process_request(task)
+ return await task.task_finished
+
+func _download(ref : StorageReference, meta_only : bool, url_only : bool) -> Variant:
+ if _is_invalid_authentication():
+ Firebase._printerr("Error downloading from storage: Invalid authentication")
+ return 0
+
+ var info_task := StorageTask.new()
+ info_task.ref = ref
+ info_task._url = _get_file_url(ref)
+ info_task.action = StorageTask.Task.TASK_DOWNLOAD_URL if url_only else StorageTask.Task.TASK_DOWNLOAD_META
+ _process_request(info_task)
+
+ if url_only or meta_only:
+ return await info_task.task_finished
+
+ var task := StorageTask.new()
+ task.ref = ref
+ task._url = _get_file_url(ref) + "?alt=media&token="
+ task.action = StorageTask.Task.TASK_DOWNLOAD
+ _pending_tasks.append(task)
+
+ var data = await info_task.task_finished
+ if info_task.result == OK:
+ task._url += info_task.data.downloadTokens
+ else:
+ task.data = info_task.data
+ task.response_headers = info_task.response_headers
+ task.response_code = info_task.response_code
+ task.result = info_task.result
+ task.finished = true
+ task.task_finished.emit(null)
+ task_failed.emit(task.result, task.response_code, task.data)
+ _pending_tasks.erase(task)
+ return null
+
+ return await task.task_finished
+
+func _list(ref : StorageReference, list_all : bool) -> Array:
+ if _is_invalid_authentication():
+ Firebase._printerr("Error getting object list from storage: Invalid authentication")
+ return []
+
+ var task := StorageTask.new()
+ task.ref = ref
+ task._url = _get_file_url(_root_ref).trim_suffix("/")
+ task.action = StorageTask.Task.TASK_LIST_ALL if list_all else StorageTask.Task.TASK_LIST
+ _process_request(task)
+ return await task.task_finished
+
+func _delete(ref : StorageReference) -> bool:
+ if _is_invalid_authentication():
+ Firebase._printerr("Error deleting object from storage: Invalid authentication")
+ return false
+
+ var task := StorageTask.new()
+ task.ref = ref
+ task._url = _get_file_url(ref)
+ task.action = StorageTask.Task.TASK_DELETE
+ _process_request(task)
+ var data = await task.task_finished
+
+ return data == null
+
+func _process_request(task : StorageTask) -> void:
+ if requesting:
+ _pending_tasks.append(task)
+ return
+ requesting = true
+
+ var headers = Array(task._headers)
+ headers.append("Authorization: Bearer " + _auth.idtoken)
+ task._headers = PackedStringArray(headers)
+
+ _current_task = task
+ _response_code = 0
+ _response_headers = PackedStringArray()
+ _response_data = PackedByteArray()
+ _content_length = 0
+ _reading_body = false
+
+ if not _http_client.get_status() in [HTTPClient.STATUS_CONNECTED, HTTPClient.STATUS_DISCONNECTED]:
+ _http_client.close()
+ set_process_internal(true)
+
+func _finish_request(result : int) -> void:
+ var task := _current_task
+ requesting = false
+
+ task.result = result
+ task.response_code = _response_code
+ task.response_headers = _response_headers
+
+ match task.action:
+ StorageTask.Task.TASK_DOWNLOAD:
+ task.data = _response_data
+
+ StorageTask.Task.TASK_DELETE:
+ _references.erase(task.ref.full_path)
+ for child in get_children():
+ if child.full_path == task.ref.full_path:
+ child.queue_free()
+ break
+ if typeof(task.data) == TYPE_PACKED_BYTE_ARRAY:
+ task.data = null
+
+ StorageTask.Task.TASK_DOWNLOAD_URL:
+ var json = Utilities.get_json_data(_response_data)
+ if json != null and json.has("error"):
+ Firebase._printerr("Error getting object download url: "+json["error"].message)
+ if json != null and json.has("downloadTokens"):
+ task.data = _base_url + _get_file_url(task.ref) + "?alt=media&token=" + json.downloadTokens
+ else:
+ task.data = ""
+
+ StorageTask.Task.TASK_LIST, StorageTask.Task.TASK_LIST_ALL:
+ var json = Utilities.get_json_data(_response_data)
+ var items := []
+ if json != null and json.has("error"):
+ Firebase._printerr("Error getting data from storage: "+json["error"].message)
+ if json != null and json.has("items"):
+ for item in json.items:
+ var item_name : String = item.name
+ if item.bucket != bucket:
+ continue
+ if not item_name.begins_with(task.ref.full_path):
+ continue
+ if task.action == StorageTask.Task.TASK_LIST:
+ var dir_path : Array = item_name.split("/")
+ var slash_count : int = task.ref.full_path.count("/")
+ item_name = ""
+ for i in slash_count + 1:
+ item_name += dir_path[i]
+ if i != slash_count and slash_count != 0:
+ item_name += "/"
+ if item_name in items:
+ continue
+
+ items.append(item_name)
+ task.data = items
+
+ _:
+ var json = Utilities.get_json_data(_response_data)
+ task.data = json
+
+ var next_task = _get_next_pending_task()
+
+ task.finished = true
+ task.task_finished.emit(task.data) # I believe this parameter has been missing all along, but not sure. Caused weird results at times with a yield/await returning null, but the task containing data.
+ if typeof(task.data) == TYPE_DICTIONARY and task.data.has("error"):
+ task_failed.emit(task.result, task.response_code, task.data)
+
+ if next_task and not next_task.finished:
+ _process_request(next_task)
+
+func _get_next_pending_task() -> StorageTask:
+ if _pending_tasks.is_empty():
+ return null
+
+ return _pending_tasks.pop_front()
+
+func _get_file_url(ref : StorageReference) -> String:
+ var url := _extended_url.replace("[APP_ID]", ref.bucket)
+ url = url.replace("[API_VERSION]", _API_VERSION)
+ return url.replace("[FILE_PATH]", ref.full_path.uri_encode())
# Removes any "../" or "./" in the file path.
-func _simplify_path(path: String) -> String:
- var dirs := path.split("/")
- var new_dirs := []
- for dir in dirs:
- if dir == "..":
- new_dirs.pop_back()
- elif dir == ".":
- pass
- else:
- new_dirs.push_back(dir)
-
- var new_path := PoolStringArray(new_dirs).join("/")
- new_path = new_path.replace("//", "/")
- new_path = new_path.replace("\\", "/")
- return new_path
-
-
-func _on_FirebaseAuth_login_succeeded(auth_token: Dictionary) -> void:
- _auth = auth_token
-
-
-func _on_FirebaseAuth_token_refresh_succeeded(auth_result: Dictionary) -> void:
- _auth = auth_result
-
+func _simplify_path(path : String) -> String:
+ var dirs := path.split("/")
+ var new_dirs := []
+ for dir in dirs:
+ if dir == "..":
+ new_dirs.pop_back()
+ elif dir == ".":
+ pass
+ else:
+ new_dirs.push_back(dir)
+
+ var new_path := "/".join(PackedStringArray(new_dirs))
+ new_path = new_path.replace("//", "/")
+ new_path = new_path.replace("\\", "/")
+ return new_path
+
+func _on_FirebaseAuth_login_succeeded(auth_token : Dictionary) -> void:
+ _auth = auth_token
+
+func _on_FirebaseAuth_token_refresh_succeeded(auth_result : Dictionary) -> void:
+ _auth = auth_result
func _on_FirebaseAuth_logout() -> void:
- _auth = {}
+ _auth = {}
+
+func _is_invalid_authentication() -> bool:
+ return (_config == null or _config.is_empty()) or (_auth == null or _auth.is_empty())
diff --git a/addons/godot-firebase/storage/storage_reference.gd b/addons/godot-firebase/storage/storage_reference.gd
index f47b786..2989d12 100644
--- a/addons/godot-firebase/storage/storage_reference.gd
+++ b/addons/godot-firebase/storage/storage_reference.gd
@@ -2,199 +2,158 @@
## @meta-version 2.2
## A reference to a file or folder in the Firebase cloud storage.
## This object is used to interact with the cloud storage. You may get data from the server, as well as upload your own back to it.
-tool
+@tool
class_name StorageReference
-extends Reference
-
+extends Node
## The default MIME type to use when uploading a file.
-## Data sent with this type are interpreted as plain binary data. Note that firebase will generate an MIME type based on the file extenstion if none is provided.
+## Data sent with this type are interpreted as plain binary data. Note that firebase will generate an MIME type based checked the file extenstion if none is provided.
const DEFAULT_MIME_TYPE = "application/octet-stream"
-## A dictionary of common MIME types based on a file extension.
+## A dictionary of common MIME types based checked a file extension.
## Example: [code]MIME_TYPES.png[/code] will return [code]image/png[/code].
const MIME_TYPES = {
- "bmp": "image/bmp",
- "css": "text/css",
- "csv": "text/csv",
- "gd": "text/plain",
- "htm": "text/html",
- "html": "text/html",
- "jpeg": "image/jpeg",
- "jpg": "image/jpeg",
- "json": "application/json",
- "mp3": "audio/mpeg",
- "mpeg": "video/mpeg",
- "ogg": "audio/ogg",
- "ogv": "video/ogg",
- "png": "image/png",
- "shader": "text/plain",
- "svg": "image/svg+xml",
- "tif": "image/tiff",
- "tiff": "image/tiff",
- "tres": "text/plain",
- "tscn": "text/plain",
- "txt": "text/plain",
- "wav": "audio/wav",
- "webm": "video/webm",
- "webp": "video/webm",
- "xml": "text/xml",
+ "bmp": "image/bmp",
+ "css": "text/css",
+ "csv": "text/csv",
+ "gd": "text/plain",
+ "htm": "text/html",
+ "html": "text/html",
+ "jpeg": "image/jpeg",
+ "jpg": "image/jpeg",
+ "json": "application/json",
+ "mp3": "audio/mpeg",
+ "mpeg": "video/mpeg",
+ "ogg": "audio/ogg",
+ "ogv": "video/ogg",
+ "png": "image/png",
+ "shader": "text/plain",
+ "svg": "image/svg+xml",
+ "tif": "image/tiff",
+ "tiff": "image/tiff",
+ "tres": "text/plain",
+ "tscn": "text/plain",
+ "txt": "text/plain",
+ "wav": "audio/wav",
+ "webm": "video/webm",
+ "webp": "image/webp",
+ "xml": "text/xml",
}
## @default ""
## The stroage bucket this referenced file/folder is located in.
-var bucket: String = ""
+var bucket : String = ""
## @default ""
## The path to the file/folder relative to [member bucket].
-var full_path: String = ""
+var full_path : String = ""
## @default ""
## The name of the file/folder, including any file extension.
## Example: If the [member full_path] is [code]images/user/image.png[/code], then the [member name] would be [code]image.png[/code].
-var name: String = ""
+var file_name : String = ""
## The parent [StorageReference] one level up the file hierarchy.
## If the current [StorageReference] is the root (i.e. the [member full_path] is [code]""[/code]) then the [member parent] will be [code]null[/code].
-var parent: StorageReference
+var parent : StorageReference
## The root [StorageReference].
-var root: StorageReference
+var root : StorageReference
## @type FirebaseStorage
## The Storage API that created this [StorageReference] to begin with.
var storage # FirebaseStorage (Can't static type due to cyclic reference)
-## @default false
-## Whether this [StorageReference] is valid. None of the functions will work when in an invalid state.
-## It is set to false when [method delete] is called.
-var valid: bool = false
-
-
## @args path
## @return StorageReference
## Returns a reference to another [StorageReference] relative to this one.
-func child(path: String) -> StorageReference:
- if not valid:
- return null
- return storage.ref(full_path.plus_file(path))
-
+func child(path : String) -> StorageReference:
+ return storage.ref(full_path.path_join(path))
## @args data, metadata
-## @return StorageTask
-## Makes an attempt to upload data to the referenced file location. Status on this task is found in the returned [StorageTask].
-func put_data(data: PoolByteArray, metadata := {}) -> StorageTask:
- if not valid:
- return null
- if not "Content-Length" in metadata and OS.get_name() != "HTML5":
- metadata["Content-Length"] = data.size()
-
- var headers := []
- for key in metadata:
- headers.append("%s: %s" % [key, metadata[key]])
+## @return int
+## Makes an attempt to upload data to the referenced file location. Returns Variant
+func put_data(data : PackedByteArray, metadata := {}) -> Variant:
+ if not "Content-Length" in metadata and not Utilities.is_web():
+ metadata["Content-Length"] = data.size()
- return storage._upload(data, headers, self, false)
+ var headers := []
+ for key in metadata:
+ headers.append("%s: %s" % [key, metadata[key]])
+ return await storage._upload(data, headers, self, false)
+
## @args data, metadata
-## @return StorageTask
+## @return int
## Like [method put_data], but [code]data[/code] is a [String].
-func put_string(data: String, metadata := {}) -> StorageTask:
- return put_data(data.to_utf8(), metadata)
-
+func put_string(data : String, metadata := {}) -> Variant:
+ return await put_data(data.to_utf8_buffer(), metadata)
## @args file_path, metadata
-## @return StorageTask
+## @return int
## Like [method put_data], but the data comes from a file at [code]file_path[/code].
-func put_file(file_path: String, metadata := {}) -> StorageTask:
- var file := File.new()
- file.open(file_path, File.READ)
- var data := file.get_buffer(file.get_len())
- file.close()
+func put_file(file_path : String, metadata := {}) -> Variant:
+ var file := FileAccess.open(file_path, FileAccess.READ)
+ var data := file.get_buffer(file.get_length())
- if "Content-Type" in metadata:
- metadata["Content-Type"] = MIME_TYPES.get(file_path.get_extension(), DEFAULT_MIME_TYPE)
+ if "Content-Type" in metadata:
+ metadata["Content-Type"] = MIME_TYPES.get(file_path.get_extension(), DEFAULT_MIME_TYPE)
- return put_data(data, metadata)
-
-
-## @return StorageTask
-## Makes an attempt to download the files from the referenced file location. Status on this task is found in the returned [StorageTask].
-func get_data() -> StorageTask:
- if not valid:
- return null
- storage._download(self, false, false)
- return storage._pending_tasks[-1]
+ return await put_data(data, metadata)
+## @return Variant
+## Makes an attempt to download the files from the referenced file location. Status checked this task is found in the returned [StorageTask].
+func get_data() -> Variant:
+ var result = await storage._download(self, false, false)
+ return result
## @return StorageTask
## Like [method get_data], but the data in the returned [StorageTask] comes in the form of a [String].
-func get_string() -> StorageTask:
- var task := get_data()
- task.connect("task_finished", self, "_on_task_finished", [task, "stringify"])
- return task
-
+func get_string() -> String:
+ var task := await get_data()
+ _on_task_finished(task, "stringify")
+ return task.data
## @return StorageTask
-## Attempts to get the download url that points to the referenced file's data. Using the url directly may require an authentication header. Status on this task is found in the returned [StorageTask].
-func get_download_url() -> StorageTask:
- if not valid:
- return null
- return storage._download(self, false, true)
-
+## Attempts to get the download url that points to the referenced file's data. Using the url directly may require an authentication header. Status checked this task is found in the returned [StorageTask].
+func get_download_url() -> Variant:
+ return await storage._download(self, false, true)
## @return StorageTask
-## Attempts to get the metadata of the referenced file. Status on this task is found in the returned [StorageTask].
-func get_metadata() -> StorageTask:
- if not valid:
- return null
- return storage._download(self, true, false)
-
+## Attempts to get the metadata of the referenced file. Status checked this task is found in the returned [StorageTask].
+func get_metadata() -> Variant:
+ return await storage._download(self, true, false)
## @args metadata
## @return StorageTask
-## Attempts to update the metadata of the referenced file. Any field with a value of [code]null[/code] will be deleted on the server end. Status on this task is found in the returned [StorageTask].
-func update_metadata(metadata: Dictionary) -> StorageTask:
- if not valid:
- return null
- var data := JSON.print(metadata).to_utf8()
- var headers := PoolStringArray(["Accept: application/json"])
- return storage._upload(data, headers, self, true)
-
+## Attempts to update the metadata of the referenced file. Any field with a value of [code]null[/code] will be deleted checked the server end. Status checked this task is found in the returned [StorageTask].
+func update_metadata(metadata : Dictionary) -> Variant:
+ var data := JSON.stringify(metadata).to_utf8_buffer()
+ var headers := PackedStringArray(["Accept: application/json"])
+ return await storage._upload(data, headers, self, true)
## @return StorageTask
-## Attempts to get the list of files and/or folders under the referenced folder This function is not nested unlike [method list_all]. Status on this task is found in the returned [StorageTask].
-func list() -> StorageTask:
- if not valid:
- return null
- return storage._list(self, false)
-
+## Attempts to get the list of files and/or folders under the referenced folder This function is not nested unlike [method list_all]. Status checked this task is found in the returned [StorageTask].
+func list() -> Array:
+ return await storage._list(self, false)
## @return StorageTask
-## Attempts to get the list of files and/or folders under the referenced folder This function is nested unlike [method list]. Status on this task is found in the returned [StorageTask].
-func list_all() -> StorageTask:
- if not valid:
- return null
- return storage._list(self, true)
-
+## Attempts to get the list of files and/or folders under the referenced folder This function is nested unlike [method list]. Status checked this task is found in the returned [StorageTask].
+func list_all() -> Array:
+ return await storage._list(self, true)
## @return StorageTask
-## Attempts to delete the referenced file/folder. If successful, the reference will become invalid And can no longer be used. If you need to reference this location again, make a new reference with [method StorageTask.ref]. Status on this task is found in the returned [StorageTask].
-func delete() -> StorageTask:
- if not valid:
- return null
- return storage._delete(self)
-
+## Attempts to delete the referenced file/folder. If successful, the reference will become invalid And can no longer be used. If you need to reference this location again, make a new reference with [method StorageTask.ref]. Status checked this task is found in the returned [StorageTask].
+func delete() -> bool:
+ return await storage._delete(self)
func _to_string() -> String:
- var string := "gs://%s/%s" % [bucket, full_path]
- if not valid:
- string += " [Invalid Reference]"
- return string
-
-
-func _on_task_finished(task: StorageTask, action: String) -> void:
- match action:
- "stringify":
- if typeof(task.data) == TYPE_RAW_ARRAY:
- task.data = task.data.get_string_from_utf8()
+ var string := "gs://%s/%s" % [bucket, full_path]
+ return string
+
+func _on_task_finished(task : StorageTask, action : String) -> void:
+ match action:
+ "stringify":
+ if typeof(task.data) == TYPE_PACKED_BYTE_ARRAY:
+ task.data = task.data.get_string_from_utf8()
diff --git a/addons/godot-firebase/storage/storage_task.gd b/addons/godot-firebase/storage/storage_task.gd
index 3efc353..fa5cefd 100644
--- a/addons/godot-firebase/storage/storage_task.gd
+++ b/addons/godot-firebase/storage/storage_task.gd
@@ -1,75 +1,74 @@
-## @meta-authors SIsilicon
+## @meta-authors SIsilicon, Kyle 'backat50ft' Szklenski
## @meta-version 2.2
## An object that keeps track of an operation performed by [StorageReference].
-tool
+@tool
class_name StorageTask
-extends Reference
-
+extends RefCounted
enum Task {
- TASK_UPLOAD,
- TASK_UPLOAD_META,
- TASK_DOWNLOAD,
- TASK_DOWNLOAD_META,
- TASK_DOWNLOAD_URL,
- TASK_LIST,
- TASK_LIST_ALL,
- TASK_DELETE,
- TASK_MAX ## The number of [enum Task] constants.
+ TASK_UPLOAD,
+ TASK_UPLOAD_META,
+ TASK_DOWNLOAD,
+ TASK_DOWNLOAD_META,
+ TASK_DOWNLOAD_URL,
+ TASK_LIST,
+ TASK_LIST_ALL,
+ TASK_DELETE,
+ TASK_MAX ## The number of [enum Task] constants.
}
-## Emitted when the task is finished. Returns data depending on the success and action of the task.
+## Emitted when the task is finished. Returns data depending checked the success and action of the task.
signal task_finished(data)
-## @type StorageReference
-## The [StorageReference] that created this [StorageTask].
-var ref # Storage Reference (Can't static type due to cyclic reference)
+## Boolean to determine if this request involves metadata only
+var is_meta : bool
## @enum Task
## @default -1
## @setter set_action
## The kind of operation this [StorageTask] is keeping track of.
-var action: int = -1 setget set_action
+var action : int = -1 : set = set_action
+
+var ref # Should not be needed, damnit
-## @default PoolByteArray()
+## @default PackedByteArray()
## Data that the tracked task will/has returned.
-var data = PoolByteArray() # data can be of any type.
+var data = PackedByteArray() # data can be of any type.
## @default 0.0
## The percentage of data that has been received.
-var progress: float = 0.0
+var progress : float = 0.0
## @default -1
## @enum HTTPRequest.Result
## The resulting status of the task. Anyting other than [constant HTTPRequest.RESULT_SUCCESS] means an error has occured.
-var result: int = -1
+var result : int = -1
## @default false
## Whether the task is finished processing.
-var finished: bool = false
+var finished : bool = false
-## @default PoolStringArray()
+## @default PackedStringArray()
## The returned HTTP response headers.
-var response_headers := PoolStringArray()
+var response_headers := PackedStringArray()
## @default 0
## @enum HTTPClient.ResponseCode
## The returned HTTP response code.
-var response_code: int = 0
-
-var _method: int = -1
-var _url: String = ""
-var _headers: PoolStringArray = PoolStringArray()
+var response_code : int = 0
+var _method : int = -1
+var _url : String = ""
+var _headers : PackedStringArray = PackedStringArray()
-func set_action(value: int) -> void:
- action = value
- match action:
- Task.TASK_UPLOAD:
- _method = HTTPClient.METHOD_POST
- Task.TASK_UPLOAD_META:
- _method = HTTPClient.METHOD_PATCH
- Task.TASK_DELETE:
- _method = HTTPClient.METHOD_DELETE
- _:
- _method = HTTPClient.METHOD_GET
+func set_action(value : int) -> void:
+ action = value
+ match action:
+ Task.TASK_UPLOAD:
+ _method = HTTPClient.METHOD_POST
+ Task.TASK_UPLOAD_META:
+ _method = HTTPClient.METHOD_PATCH
+ Task.TASK_DELETE:
+ _method = HTTPClient.METHOD_DELETE
+ _:
+ _method = HTTPClient.METHOD_GET
diff --git a/addons/gut/GutScene.gd b/addons/gut/GutScene.gd
deleted file mode 100644
index 9894c9c..0000000
--- a/addons/gut/GutScene.gd
+++ /dev/null
@@ -1,432 +0,0 @@
-extends Panel
-
-onready var _script_list = $ScriptsList
-onready var _nav = {
- prev = $Navigation/Previous,
- next = $Navigation/Next,
- run = $Navigation/Run,
- current_script = $Navigation/CurrentScript,
- run_single = $Navigation/RunSingleScript
-}
-onready var _progress = {
- script = $ScriptProgress,
- script_xy = $ScriptProgress/xy,
- test = $TestProgress,
- test_xy = $TestProgress/xy
-}
-onready var _summary = {
- failing = $Summary/Failing,
- passing = $Summary/Passing,
- fail_count = 0,
- pass_count = 0
-}
-
-onready var _extras = $ExtraOptions
-onready var _ignore_pauses = $ExtraOptions/IgnorePause
-onready var _continue_button = $Continue/Continue
-onready var _text_box = $TextDisplay/RichTextLabel
-
-onready var _titlebar = {
- bar = $TitleBar,
- time = $TitleBar/Time,
- label = $TitleBar/Title
-}
-
-onready var _user_files = $UserFileViewer
-
-var _mouse = {
- down = false,
- in_title = false,
- down_pos = null,
- in_handle = false
-}
-var _is_running = false
-var _start_time = 0.0
-var _time = 0.0
-
-const DEFAULT_TITLE = 'Gut: The Godot Unit Testing tool.'
-var _pre_maximize_rect = null
-var _font_size = 20
-
-signal end_pause
-signal ignore_pause
-signal log_level_changed
-signal run_script
-signal run_single_script
-
-func _ready():
-
- if(Engine.editor_hint):
- return
-
- _pre_maximize_rect = get_rect()
- _hide_scripts()
- _update_controls()
- _nav.current_script.set_text("No scripts available")
- set_title()
- clear_summary()
- _titlebar.time.set_text("Time 0.0")
-
- _extras.visible = false
- update()
-
- set_font_size(_font_size)
- set_font('CourierPrime')
-
- _user_files.set_position(Vector2(10, 30))
-
-func elapsed_time_as_str():
- return str("%.1f" % (_time / 1000.0), 's')
-
-func _process(_delta):
- if(_is_running):
- _time = OS.get_ticks_msec() - _start_time
- _titlebar.time.set_text(str('Time: ', elapsed_time_as_str()))
-
-func _draw(): # needs get_size()
- # Draw the lines in the corner to show where you can
- # drag to resize the dialog
- var grab_margin = 3
- var line_space = 3
- var grab_line_color = Color(.4, .4, .4)
- for i in range(1, 10):
- var x = rect_size - Vector2(i * line_space, grab_margin)
- var y = rect_size - Vector2(grab_margin, i * line_space)
- draw_line(x, y, grab_line_color, 1, true)
-
-func _on_Maximize_draw():
- # draw the maximize square thing.
- var btn = $TitleBar/Maximize
- btn.set_text('')
- var w = btn.get_size().x
- var h = btn.get_size().y
- btn.draw_rect(Rect2(0, 0, w, h), Color(0, 0, 0, 1))
- btn.draw_rect(Rect2(2, 4, w - 4, h - 6), Color(1,1,1,1))
-
-func _on_ShowExtras_draw():
- var btn = $Continue/ShowExtras
- btn.set_text('')
- var start_x = 20
- var start_y = 15
- var pad = 5
- var color = Color(.1, .1, .1, 1)
- var width = 2
- for i in range(3):
- var y = start_y + pad * i
- btn.draw_line(Vector2(start_x, y), Vector2(btn.get_size().x - start_x, y), color, width, true)
-
-# ####################
-# GUI Events
-# ####################
-func _on_Run_pressed():
- _run_mode()
- emit_signal('run_script', get_selected_index())
-
-func _on_CurrentScript_pressed():
- _toggle_scripts()
-
-func _on_Previous_pressed():
- _select_script(get_selected_index() - 1)
-
-func _on_Next_pressed():
- _select_script(get_selected_index() + 1)
-
-func _on_LogLevelSlider_value_changed(_value):
- emit_signal('log_level_changed', $LogLevelSlider.value)
-
-func _on_Continue_pressed():
- _continue_button.disabled = true
- emit_signal('end_pause')
-
-func _on_IgnorePause_pressed():
- var checked = _ignore_pauses.is_pressed()
- emit_signal('ignore_pause', checked)
- if(checked):
- emit_signal('end_pause')
- _continue_button.disabled = true
-
-func _on_RunSingleScript_pressed():
- _run_mode()
- emit_signal('run_single_script', get_selected_index())
-
-func _on_ScriptsList_item_selected(index):
- var tmr = $ScriptsList/DoubleClickTimer
- if(!tmr.is_stopped()):
- _run_mode()
- emit_signal('run_single_script', get_selected_index())
- tmr.stop()
- else:
- tmr.start()
-
- _select_script(index)
-
-func _on_TitleBar_mouse_entered():
- _mouse.in_title = true
-
-func _on_TitleBar_mouse_exited():
- _mouse.in_title = false
-
-func _input(event):
- if(event is InputEventMouseButton):
- if(event.button_index == 1):
- _mouse.down = event.pressed
- if(_mouse.down):
- _mouse.down_pos = event.position
-
- if(_mouse.in_title):
- if(event is InputEventMouseMotion and _mouse.down):
- set_position(get_position() + (event.position - _mouse.down_pos))
- _mouse.down_pos = event.position
- _pre_maximize_rect = get_rect()
-
- if(_mouse.in_handle):
- if(event is InputEventMouseMotion and _mouse.down):
- var new_size = rect_size + event.position - _mouse.down_pos
- var new_mouse_down_pos = event.position
- rect_size = new_size
- _mouse.down_pos = new_mouse_down_pos
- _pre_maximize_rect = get_rect()
-
-func _on_ResizeHandle_mouse_entered():
- _mouse.in_handle = true
-
-func _on_ResizeHandle_mouse_exited():
- _mouse.in_handle = false
-
-func _on_RichTextLabel_gui_input(ev):
- pass
- # leaving this b/c it is wired up and might have to send
- # more signals through
-
-func _on_Copy_pressed():
- OS.clipboard = _text_box.text
-
-func _on_ShowExtras_toggled(button_pressed):
- _extras.visible = button_pressed
-
-func _on_Maximize_pressed():
- if(get_rect() == _pre_maximize_rect):
- maximize()
- else:
- rect_size = _pre_maximize_rect.size
- rect_position = _pre_maximize_rect.position
-# ####################
-# Private
-# ####################
-func _run_mode(is_running=true):
- if(is_running):
- _start_time = OS.get_ticks_msec()
- _time = 0.0
- clear_summary()
- _is_running = is_running
-
- _hide_scripts()
- var ctrls = $Navigation.get_children()
- for i in range(ctrls.size()):
- ctrls[i].disabled = is_running
-
-func _select_script(index):
- var text = _script_list.get_item_text(index)
- var max_len = 50
- if(text.length() > max_len):
- text = '...' + text.right(text.length() - (max_len - 5))
- $Navigation/CurrentScript.set_text(text)
- _script_list.select(index)
- _update_controls()
-
-func _toggle_scripts():
- if(_script_list.visible):
- _hide_scripts()
- else:
- _show_scripts()
-
-func _show_scripts():
- _script_list.show()
-
-func _hide_scripts():
- _script_list.hide()
-
-func _update_controls():
- var is_empty = _script_list.get_selected_items().size() == 0
- if(is_empty):
- _nav.next.disabled = true
- _nav.prev.disabled = true
- else:
- var index = get_selected_index()
- _nav.prev.disabled = index <= 0
- _nav.next.disabled = index >= _script_list.get_item_count() - 1
-
- _nav.run.disabled = is_empty
- _nav.current_script.disabled = is_empty
- _nav.run_single.disabled = is_empty
-
-func _update_summary():
- if(!_summary):
- return
-
- var total = _summary.fail_count + _summary.pass_count
- $Summary.visible = !total == 0
- $Summary/AssertCount.text = str('Failures ', _summary.fail_count, '/', total)
-# ####################
-# Public
-# ####################
-func run_mode(is_running=true):
- _run_mode(is_running)
-
-func set_scripts(scripts):
- _script_list.clear()
- for i in range(scripts.size()):
- _script_list.add_item(scripts[i])
- _select_script(0)
- _update_controls()
-
-func select_script(index):
- _select_script(index)
-
-func get_selected_index():
- return _script_list.get_selected_items()[0]
-
-func get_log_level():
- return $LogLevelSlider.value
-
-func set_log_level(value):
- var new_value = value
- if(new_value == null):
- new_value = 0
- $LogLevelSlider.value = new_value
-
-func set_ignore_pause(should):
- _ignore_pauses.pressed = should
-
-func get_ignore_pause():
- return _ignore_pauses.pressed
-
-func get_text_box():
- # due to some timing issue, this cannot return _text_box but can return
- # this.
- return $TextDisplay/RichTextLabel
-
-func end_run():
- _run_mode(false)
- _update_controls()
-
-func set_progress_script_max(value):
- var max_val = max(value, 1)
- _progress.script.set_max(max_val)
- _progress.script_xy.set_text(str('0/', max_val))
-
-func set_progress_script_value(value):
- _progress.script.set_value(value)
- var txt = str(value, '/', _progress.test.get_max())
- _progress.script_xy.set_text(txt)
-
-func set_progress_test_max(value):
- var max_val = max(value, 1)
- _progress.test.set_max(max_val)
- _progress.test_xy.set_text(str('0/', max_val))
-
-func set_progress_test_value(value):
- _progress.test.set_value(value)
- var txt = str(value, '/', _progress.test.get_max())
- _progress.test_xy.set_text(txt)
-
-func clear_progress():
- _progress.test.set_value(0)
- _progress.script.set_value(0)
-
-func pause():
- _continue_button.disabled = false
-
-func set_title(title=null):
- if(title == null):
- $TitleBar/Title.set_text(DEFAULT_TITLE)
- else:
- $TitleBar/Title.set_text(title)
-
-func add_passing(amount=1):
- if(!_summary):
- return
- _summary.pass_count += amount
- _update_summary()
-
-func add_failing(amount=1):
- if(!_summary):
- return
- _summary.fail_count += amount
- _update_summary()
-
-func clear_summary():
- _summary.fail_count = 0
- _summary.pass_count = 0
- _update_summary()
-
-func maximize():
- if(is_inside_tree()):
- var vp_size_offset = get_viewport().size
- rect_size = vp_size_offset / get_scale()
- set_position(Vector2(0, 0))
-
-func clear_text():
- _text_box.bbcode_text = ''
-
-func scroll_to_bottom():
- pass
- #_text_box.cursor_set_line(_gui.get_text_box().get_line_count())
-
-func _set_font_size_for_rtl(rtl, new_size):
- if(rtl.get('custom_fonts/normal_font') != null):
- rtl.get('custom_fonts/bold_italics_font').size = new_size
- rtl.get('custom_fonts/bold_font').size = new_size
- rtl.get('custom_fonts/italics_font').size = new_size
- rtl.get('custom_fonts/normal_font').size = new_size
-
-
-func _set_fonts_for_rtl(rtl, base_font_name):
- pass
-
-
-func set_font_size(new_size):
- _font_size = new_size
- _set_font_size_for_rtl(_text_box, new_size)
- _set_font_size_for_rtl(_user_files.get_rich_text_label(), new_size)
-
-
-func _set_font(rtl, font_name, custom_name):
- if(font_name == null):
- rtl.set('custom_fonts/' + custom_name, null)
- else:
- var dyn_font = DynamicFont.new()
- var font_data = DynamicFontData.new()
- font_data.font_path = 'res://addons/gut/fonts/' + font_name + '.ttf'
- font_data.antialiased = true
- dyn_font.font_data = font_data
- rtl.set('custom_fonts/' + custom_name, dyn_font)
-
-func _set_all_fonts_in_ftl(ftl, base_name):
- if(base_name == 'Default'):
- _set_font(ftl, null, 'normal_font')
- _set_font(ftl, null, 'bold_font')
- _set_font(ftl, null, 'italics_font')
- _set_font(ftl, null, 'bold_italics_font')
- else:
- _set_font(ftl, base_name + '-Regular', 'normal_font')
- _set_font(ftl, base_name + '-Bold', 'bold_font')
- _set_font(ftl, base_name + '-Italic', 'italics_font')
- _set_font(ftl, base_name + '-BoldItalic', 'bold_italics_font')
- set_font_size(_font_size)
-
-func set_font(base_name):
- _set_all_fonts_in_ftl(_text_box, base_name)
- _set_all_fonts_in_ftl(_user_files.get_rich_text_label(), base_name)
-
-func set_default_font_color(color):
- _text_box.set('custom_colors/default_color', color)
-
-func set_background_color(color):
- $TextDisplay.color = color
-
-func _on_UserFiles_pressed():
- _user_files.show_open()
-
-func get_waiting_label():
- return $TextDisplay/WaitingLabel
diff --git a/addons/gut/GutScene.tscn b/addons/gut/GutScene.tscn
deleted file mode 100644
index 3819a6e..0000000
--- a/addons/gut/GutScene.tscn
+++ /dev/null
@@ -1,471 +0,0 @@
-[gd_scene load_steps=15 format=2]
-
-[ext_resource path="res://addons/gut/GutScene.gd" type="Script" id=1]
-[ext_resource path="res://addons/gut/fonts/AnonymousPro-Italic.ttf" type="DynamicFontData" id=2]
-[ext_resource path="res://addons/gut/fonts/AnonymousPro-Regular.ttf" type="DynamicFontData" id=3]
-[ext_resource path="res://addons/gut/fonts/AnonymousPro-BoldItalic.ttf" type="DynamicFontData" id=4]
-[ext_resource path="res://addons/gut/fonts/AnonymousPro-Bold.ttf" type="DynamicFontData" id=5]
-[ext_resource path="res://addons/gut/UserFileViewer.tscn" type="PackedScene" id=6]
-
-[sub_resource type="StyleBoxFlat" id=1]
-bg_color = Color( 0.192157, 0.192157, 0.227451, 1 )
-corner_radius_top_left = 10
-corner_radius_top_right = 10
-
-[sub_resource type="StyleBoxFlat" id=2]
-bg_color = Color( 1, 1, 1, 1 )
-border_color = Color( 0, 0, 0, 1 )
-corner_radius_top_left = 5
-corner_radius_top_right = 5
-
-[sub_resource type="Theme" id=3]
-resource_local_to_scene = true
-Panel/styles/panel = SubResource( 2 )
-Panel/styles/panelf = null
-Panel/styles/panelnc = null
-
-[sub_resource type="DynamicFont" id=4]
-font_data = ExtResource( 4 )
-
-[sub_resource type="DynamicFont" id=5]
-font_data = ExtResource( 2 )
-
-[sub_resource type="DynamicFont" id=6]
-font_data = ExtResource( 5 )
-
-[sub_resource type="DynamicFont" id=7]
-font_data = ExtResource( 3 )
-
-[sub_resource type="StyleBoxFlat" id=8]
-bg_color = Color( 0.192157, 0.192157, 0.227451, 1 )
-corner_radius_top_left = 20
-corner_radius_top_right = 20
-
-[node name="Gut" type="Panel"]
-margin_right = 880.0
-margin_bottom = 360.0
-rect_min_size = Vector2( 740, 250 )
-custom_styles/panel = SubResource( 1 )
-script = ExtResource( 1 )
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="UserFileViewer" parent="." instance=ExtResource( 6 )]
-margin_top = 388.0
-margin_bottom = 818.0
-
-[node name="TitleBar" type="Panel" parent="."]
-anchor_top = -0.000491047
-anchor_right = 1.0
-anchor_bottom = -0.000491047
-margin_left = 1.0
-margin_top = 1.17678
-margin_right = -1.0
-margin_bottom = 40.1768
-theme = SubResource( 3 )
-__meta__ = {
-"_edit_group_": true,
-"_edit_use_anchors_": false
-}
-
-[node name="Title" type="Label" parent="TitleBar"]
-anchor_right = 1.0
-margin_bottom = 40.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "Gut"
-align = 1
-valign = 1
-
-[node name="Time" type="Label" parent="TitleBar"]
-anchor_left = 1.0
-anchor_right = 1.0
-margin_left = -105.0
-margin_right = -53.0
-margin_bottom = 40.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "9999.99"
-valign = 1
-
-[node name="Maximize" type="Button" parent="TitleBar"]
-anchor_left = 1.0
-anchor_right = 1.0
-margin_left = -30.0
-margin_top = 10.0
-margin_right = -6.0
-margin_bottom = 30.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "M"
-flat = true
-
-[node name="ScriptProgress" type="ProgressBar" parent="."]
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 75.0
-margin_top = -70.0
-margin_right = 185.0
-margin_bottom = -40.0
-hint_tooltip = "Overall progress of executing tests."
-step = 1.0
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Label" type="Label" parent="ScriptProgress"]
-margin_left = -70.0
-margin_right = -5.0
-margin_bottom = 30.0
-text = "Scripts"
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="xy" type="Label" parent="ScriptProgress"]
-visible = false
-margin_right = 110.0
-margin_bottom = 30.0
-text = "0/0"
-align = 1
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="TestProgress" type="ProgressBar" parent="."]
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 75.0
-margin_top = -105.0
-margin_right = 185.0
-margin_bottom = -75.0
-hint_tooltip = "Test progress for the current script."
-step = 1.0
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Label" type="Label" parent="TestProgress"]
-margin_left = -70.0
-margin_right = -5.0
-margin_bottom = 30.0
-text = "Tests"
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="xy" type="Label" parent="TestProgress"]
-visible = false
-margin_right = 110.0
-margin_bottom = 30.0
-text = "0/0"
-align = 1
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="TextDisplay" type="ColorRect" parent="."]
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_top = 40.0
-margin_bottom = -110.0
-color = Color( 0, 0, 0, 1 )
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="RichTextLabel" type="RichTextLabel" parent="TextDisplay"]
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = 10.0
-focus_mode = 2
-custom_fonts/bold_italics_font = SubResource( 4 )
-custom_fonts/italics_font = SubResource( 5 )
-custom_fonts/bold_font = SubResource( 6 )
-custom_fonts/normal_font = SubResource( 7 )
-bbcode_enabled = true
-scroll_following = true
-selection_enabled = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="WaitingLabel" type="RichTextLabel" parent="TextDisplay"]
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_top = -25.0
-bbcode_enabled = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Navigation" type="Panel" parent="."]
-self_modulate = Color( 1, 1, 1, 0 )
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 220.0
-margin_top = -99.0
-margin_right = 580.0
-margin_bottom = 1.0
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Previous" type="Button" parent="Navigation"]
-margin_left = -20.0
-margin_top = 44.0
-margin_right = 65.0
-margin_bottom = 84.0
-hint_tooltip = "Previous script in the list."
-text = "|<"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Next" type="Button" parent="Navigation"]
-margin_left = 250.0
-margin_top = 44.0
-margin_right = 335.0
-margin_bottom = 84.0
-hint_tooltip = "Next script in the list.
-"
-text = ">|"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Run" type="Button" parent="Navigation"]
-margin_left = 70.0
-margin_top = 44.0
-margin_right = 155.0
-margin_bottom = 84.0
-hint_tooltip = "Run the currently selected item and all after it."
-text = ">"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="CurrentScript" type="Button" parent="Navigation"]
-anchor_top = -0.01
-anchor_bottom = -0.01
-margin_left = -20.0
-margin_top = -5.0
-margin_right = 335.0
-margin_bottom = 35.0
-hint_tooltip = "Select a script to run. You can run just this script, or this script and all scripts after using the run buttons."
-text = "res://test/unit/test_gut.gd"
-clip_text = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="RunSingleScript" type="Button" parent="Navigation"]
-margin_left = 160.0
-margin_top = 44.0
-margin_right = 245.0
-margin_bottom = 84.0
-hint_tooltip = "Run the currently selected item.
-
-If the selected item has Inner Test Classes
-then they will all be run. If the selected item
-is an Inner Test Class then only it will be run."
-text = "> (1)"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="LogLevelSlider" type="HSlider" parent="."]
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 80.0
-margin_top = -40.0
-margin_right = 130.0
-margin_bottom = -20.0
-rect_scale = Vector2( 2, 2 )
-max_value = 2.0
-tick_count = 3
-ticks_on_borders = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Label" type="Label" parent="LogLevelSlider"]
-margin_left = -37.0
-margin_right = 28.0
-margin_bottom = 40.0
-rect_scale = Vector2( 0.5, 0.5 )
-text = "Log Level"
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="ScriptsList" type="ItemList" parent="."]
-anchor_bottom = 1.0
-margin_left = 179.0
-margin_top = 40.0
-margin_right = 619.0
-margin_bottom = -110.0
-allow_reselect = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="DoubleClickTimer" type="Timer" parent="ScriptsList"]
-wait_time = 0.3
-one_shot = true
-
-[node name="ExtraOptions" type="Panel" parent="."]
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -212.0
-margin_top = -260.0
-margin_right = -2.0
-margin_bottom = -106.0
-custom_styles/panel = SubResource( 8 )
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="IgnorePause" type="CheckBox" parent="ExtraOptions"]
-margin_left = 18.0
-margin_right = 136.0
-margin_bottom = 24.0
-rect_scale = Vector2( 1.5, 1.5 )
-hint_tooltip = "Ignore all calls to pause_before_teardown."
-text = "Ignore Pauses"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Copy" type="Button" parent="ExtraOptions"]
-margin_left = 15.0
-margin_top = 40.0
-margin_right = 195.0
-margin_bottom = 80.0
-hint_tooltip = "Copy all output to the clipboard."
-text = "Copy to Clipboard"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="UserFiles" type="Button" parent="ExtraOptions"]
-margin_left = 15.0
-margin_top = 90.0
-margin_right = 195.0
-margin_bottom = 130.0
-hint_tooltip = "Copy all output to the clipboard."
-text = "View User Files"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="ResizeHandle" type="Control" parent="."]
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -40.0
-margin_top = -40.0
-
-[node name="Continue" type="Panel" parent="."]
-self_modulate = Color( 1, 1, 1, 0 )
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -150.0
-margin_top = -100.0
-margin_right = -30.0
-margin_bottom = -10.0
-
-[node name="Continue" type="Button" parent="Continue"]
-margin_left = -2.0
-margin_top = 45.0
-margin_right = 117.0
-margin_bottom = 85.0
-hint_tooltip = "When a pause_before_teardown is encountered this button will be enabled and must be pressed to continue running tests."
-disabled = true
-text = "Continue"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="ShowExtras" type="Button" parent="Continue"]
-anchor_left = -0.0166667
-anchor_right = -0.0166667
-margin_left = 50.0
-margin_top = -5.0
-margin_right = 120.0
-margin_bottom = 35.0
-rect_pivot_offset = Vector2( 35, 20 )
-hint_tooltip = "Show/hide additional options."
-toggle_mode = true
-text = "_"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Summary" type="Node2D" parent="."]
-position = Vector2( 0, 3 )
-
-[node name="Passing" type="Label" parent="Summary"]
-visible = false
-margin_left = 5.0
-margin_top = 7.0
-margin_right = 45.0
-margin_bottom = 21.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "0"
-align = 1
-valign = 1
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Failing" type="Label" parent="Summary"]
-visible = false
-margin_left = 100.0
-margin_top = 7.0
-margin_right = 140.0
-margin_bottom = 21.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "0"
-align = 1
-valign = 1
-
-[node name="AssertCount" type="Label" parent="Summary"]
-margin_left = 5.0
-margin_top = 7.0
-margin_right = 165.0
-margin_bottom = 21.0
-custom_colors/font_color = Color( 0, 0, 0, 1 )
-text = "Assert count"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-[connection signal="mouse_entered" from="TitleBar" to="." method="_on_TitleBar_mouse_entered"]
-[connection signal="mouse_exited" from="TitleBar" to="." method="_on_TitleBar_mouse_exited"]
-[connection signal="draw" from="TitleBar/Maximize" to="." method="_on_Maximize_draw"]
-[connection signal="pressed" from="TitleBar/Maximize" to="." method="_on_Maximize_pressed"]
-[connection signal="gui_input" from="TextDisplay/RichTextLabel" to="." method="_on_RichTextLabel_gui_input"]
-[connection signal="pressed" from="Navigation/Previous" to="." method="_on_Previous_pressed"]
-[connection signal="pressed" from="Navigation/Next" to="." method="_on_Next_pressed"]
-[connection signal="pressed" from="Navigation/Run" to="." method="_on_Run_pressed"]
-[connection signal="pressed" from="Navigation/CurrentScript" to="." method="_on_CurrentScript_pressed"]
-[connection signal="pressed" from="Navigation/RunSingleScript" to="." method="_on_RunSingleScript_pressed"]
-[connection signal="value_changed" from="LogLevelSlider" to="." method="_on_LogLevelSlider_value_changed"]
-[connection signal="item_selected" from="ScriptsList" to="." method="_on_ScriptsList_item_selected"]
-[connection signal="pressed" from="ExtraOptions/IgnorePause" to="." method="_on_IgnorePause_pressed"]
-[connection signal="pressed" from="ExtraOptions/Copy" to="." method="_on_Copy_pressed"]
-[connection signal="pressed" from="ExtraOptions/UserFiles" to="." method="_on_UserFiles_pressed"]
-[connection signal="mouse_entered" from="ResizeHandle" to="." method="_on_ResizeHandle_mouse_entered"]
-[connection signal="mouse_exited" from="ResizeHandle" to="." method="_on_ResizeHandle_mouse_exited"]
-[connection signal="pressed" from="Continue/Continue" to="." method="_on_Continue_pressed"]
-[connection signal="draw" from="Continue/ShowExtras" to="." method="_on_ShowExtras_draw"]
-[connection signal="toggled" from="Continue/ShowExtras" to="." method="_on_ShowExtras_toggled"]
diff --git a/addons/gut/LICENSE.md b/addons/gut/LICENSE.md
deleted file mode 100644
index a38ac23..0000000
--- a/addons/gut/LICENSE.md
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License (MIT)
-=====================
-
-Copyright (c) 2018 Tom "Butch" Wesley
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
diff --git a/addons/gut/UserFileViewer.gd b/addons/gut/UserFileViewer.gd
deleted file mode 100644
index 9713a94..0000000
--- a/addons/gut/UserFileViewer.gd
+++ /dev/null
@@ -1,55 +0,0 @@
-extends WindowDialog
-
-onready var rtl = $TextDisplay/RichTextLabel
-var _has_opened_file = false
-
-func _get_file_as_text(path):
- var to_return = null
- var f = File.new()
- var result = f.open(path, f.READ)
- if(result == OK):
- to_return = f.get_as_text()
- f.close()
- else:
- to_return = str('ERROR: Could not open file. Error code ', result)
- return to_return
-
-func _ready():
- rtl.clear()
-
-func _on_OpenFile_pressed():
- $FileDialog.popup_centered()
-
-func _on_FileDialog_file_selected(path):
- show_file(path)
-
-func _on_Close_pressed():
- self.hide()
-
-func show_file(path):
- var text = _get_file_as_text(path)
- if(text == ''):
- text = ''
- rtl.set_text(text)
- self.window_title = path
-
-func show_open():
- self.popup_centered()
- $FileDialog.popup_centered()
-
-func _on_FileDialog_popup_hide():
- if(rtl.text.length() == 0):
- self.hide()
-
-func get_rich_text_label():
- return $TextDisplay/RichTextLabel
-
-func _on_Home_pressed():
- rtl.scroll_to_line(0)
-
-func _on_End_pressed():
- rtl.scroll_to_line(rtl.get_line_count() -1)
-
-
-func _on_Copy_pressed():
- OS.clipboard = rtl.text
diff --git a/addons/gut/UserFileViewer.tscn b/addons/gut/UserFileViewer.tscn
deleted file mode 100644
index 1236ebb..0000000
--- a/addons/gut/UserFileViewer.tscn
+++ /dev/null
@@ -1,127 +0,0 @@
-[gd_scene load_steps=2 format=2]
-
-[ext_resource path="res://addons/gut/UserFileViewer.gd" type="Script" id=1]
-
-[node name="UserFileViewer" type="WindowDialog"]
-margin_top = 20.0
-margin_right = 800.0
-margin_bottom = 450.0
-rect_min_size = Vector2( 800, 180 )
-popup_exclusive = true
-window_title = "View File"
-resizable = true
-script = ExtResource( 1 )
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="FileDialog" type="FileDialog" parent="."]
-margin_right = 416.0
-margin_bottom = 184.0
-rect_min_size = Vector2( 400, 140 )
-rect_scale = Vector2( 2, 2 )
-popup_exclusive = true
-window_title = "Open a File"
-resizable = true
-mode = 0
-access = 1
-show_hidden_files = true
-current_dir = "user://"
-current_path = "user://"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="TextDisplay" type="ColorRect" parent="."]
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = 8.0
-margin_right = -10.0
-margin_bottom = -65.0
-color = Color( 0.2, 0.188235, 0.188235, 1 )
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="RichTextLabel" type="RichTextLabel" parent="TextDisplay"]
-anchor_right = 1.0
-anchor_bottom = 1.0
-focus_mode = 2
-text = "In publishing and graphic design, Lorem ipsum is a placeholder text commonly used to demonstrate the visual form of a document or a typeface without relying on meaningful content. Lorem ipsum may be used before final copy is available, but it may also be used to temporarily replace copy in a process called greeking, which allows designers to consider form without the meaning of the text influencing the design.
-
-Lorem ipsum is typically a corrupted version of De finibus bonorum et malorum, a first-century BCE text by the Roman statesman and philosopher Cicero, with words altered, added, and removed to make it nonsensical, improper Latin.
-
-Versions of the Lorem ipsum text have been used in typesetting at least since the 1960s, when it was popularized by advertisements for Letraset transfer sheets. Lorem ipsum was introduced to the digital world in the mid-1980s when Aldus employed it in graphic and word-processing templates for its desktop publishing program PageMaker. Other popular word processors including Pages and Microsoft Word have since adopted Lorem ipsum as well."
-selection_enabled = true
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="OpenFile" type="Button" parent="."]
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -158.0
-margin_top = -50.0
-margin_right = -84.0
-margin_bottom = -30.0
-rect_scale = Vector2( 2, 2 )
-text = "Open File"
-
-[node name="Home" type="Button" parent="."]
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -478.0
-margin_top = -50.0
-margin_right = -404.0
-margin_bottom = -30.0
-rect_scale = Vector2( 2, 2 )
-text = "Home"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="Copy" type="Button" parent="."]
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 160.0
-margin_top = -50.0
-margin_right = 234.0
-margin_bottom = -30.0
-rect_scale = Vector2( 2, 2 )
-text = "Copy"
-__meta__ = {
-"_edit_use_anchors_": false
-}
-
-[node name="End" type="Button" parent="."]
-anchor_left = 1.0
-anchor_top = 1.0
-anchor_right = 1.0
-anchor_bottom = 1.0
-margin_left = -318.0
-margin_top = -50.0
-margin_right = -244.0
-margin_bottom = -30.0
-rect_scale = Vector2( 2, 2 )
-text = "End"
-
-[node name="Close" type="Button" parent="."]
-anchor_top = 1.0
-anchor_bottom = 1.0
-margin_left = 10.0
-margin_top = -50.0
-margin_right = 80.0
-margin_bottom = -30.0
-rect_scale = Vector2( 2, 2 )
-text = "Close"
-[connection signal="file_selected" from="FileDialog" to="." method="_on_FileDialog_file_selected"]
-[connection signal="popup_hide" from="FileDialog" to="." method="_on_FileDialog_popup_hide"]
-[connection signal="pressed" from="OpenFile" to="." method="_on_OpenFile_pressed"]
-[connection signal="pressed" from="Home" to="." method="_on_Home_pressed"]
-[connection signal="pressed" from="Copy" to="." method="_on_Copy_pressed"]
-[connection signal="pressed" from="End" to="." method="_on_End_pressed"]
-[connection signal="pressed" from="Close" to="." method="_on_Close_pressed"]
diff --git a/addons/gut/autofree.gd b/addons/gut/autofree.gd
deleted file mode 100644
index 80b4e89..0000000
--- a/addons/gut/autofree.gd
+++ /dev/null
@@ -1,59 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# Class used to keep track of objects to be freed and utilities to free them.
-# ##############################################################################
-var _to_free = []
-var _to_queue_free = []
-
-func add_free(thing):
- if(typeof(thing) == TYPE_OBJECT):
- if(!thing is Reference):
- _to_free.append(thing)
-
-func add_queue_free(thing):
- _to_queue_free.append(thing)
-
-func get_queue_free_count():
- return _to_queue_free.size()
-
-func get_free_count():
- return _to_free.size()
-
-func free_all():
- for i in range(_to_free.size()):
- if(is_instance_valid(_to_free[i])):
- _to_free[i].free()
- _to_free.clear()
-
- for i in range(_to_queue_free.size()):
- if(is_instance_valid(_to_queue_free[i])):
- _to_queue_free[i].queue_free()
- _to_queue_free.clear()
-
-
diff --git a/addons/gut/comparator.gd b/addons/gut/comparator.gd
deleted file mode 100644
index ff03af8..0000000
--- a/addons/gut/comparator.gd
+++ /dev/null
@@ -1,130 +0,0 @@
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _strutils = _utils.Strutils.new()
-var _max_length = 100
-var _should_compare_int_to_float = true
-
-const MISSING = '|__missing__gut__compare__value__|'
-const DICTIONARY_DISCLAIMER = 'Dictionaries are compared-by-ref. See assert_eq in wiki.'
-
-func _cannot_comapre_text(v1, v2):
- return str('Cannot compare ', _strutils.types[typeof(v1)], ' with ',
- _strutils.types[typeof(v2)], '.')
-
-func _make_missing_string(text):
- return ''
-
-func _create_missing_result(v1, v2, text):
- var to_return = null
- var v1_str = format_value(v1)
- var v2_str = format_value(v2)
-
- if(typeof(v1) == TYPE_STRING and v1 == MISSING):
- v1_str = _make_missing_string(text)
- to_return = _utils.CompareResult.new()
- elif(typeof(v2) == TYPE_STRING and v2 == MISSING):
- v2_str = _make_missing_string(text)
- to_return = _utils.CompareResult.new()
-
- if(to_return != null):
- to_return.summary = str(v1_str, ' != ', v2_str)
- to_return.are_equal = false
-
- return to_return
-
-
-func simple(v1, v2, missing_string=''):
- var missing_result = _create_missing_result(v1, v2, missing_string)
- if(missing_result != null):
- return missing_result
-
- var result = _utils.CompareResult.new()
- var cmp_str = null
- var extra = ''
-
- if(_should_compare_int_to_float and [2, 3].has(typeof(v1)) and [2, 3].has(typeof(v2))):
- result.are_equal = v1 == v2
-
- elif(_utils.are_datatypes_same(v1, v2)):
- result.are_equal = v1 == v2
- if(typeof(v1) == TYPE_DICTIONARY):
- if(result.are_equal):
- extra = '. Same dictionary ref. '
- else:
- extra = '. Different dictionary refs. '
- extra += DICTIONARY_DISCLAIMER
-
- if(typeof(v1) == TYPE_ARRAY):
- var array_result = _utils.DiffTool.new(v1, v2, _utils.DIFF.SHALLOW)
- result.summary = array_result.get_short_summary()
- if(!array_result.are_equal()):
- extra = ".\n" + array_result.get_short_summary()
-
- else:
- cmp_str = '!='
- result.are_equal = false
- extra = str('. ', _cannot_comapre_text(v1, v2))
-
- cmp_str = get_compare_symbol(result.are_equal)
- if(typeof(v1) != TYPE_ARRAY):
- result.summary = str(format_value(v1), ' ', cmp_str, ' ', format_value(v2), extra)
-
- return result
-
-
-func shallow(v1, v2):
- var result = null
-
- if(_utils.are_datatypes_same(v1, v2)):
- if(typeof(v1) in [TYPE_ARRAY, TYPE_DICTIONARY]):
- result = _utils.DiffTool.new(v1, v2, _utils.DIFF.SHALLOW)
- else:
- result = simple(v1, v2)
- else:
- result = simple(v1, v2)
-
- return result
-
-
-func deep(v1, v2):
- var result = null
-
- if(_utils.are_datatypes_same(v1, v2)):
- if(typeof(v1) in [TYPE_ARRAY, TYPE_DICTIONARY]):
- result = _utils.DiffTool.new(v1, v2, _utils.DIFF.DEEP)
- else:
- result = simple(v1, v2)
- else:
- result = simple(v1, v2)
-
- return result
-
-
-func format_value(val, max_val_length=_max_length):
- return _strutils.truncate_string(_strutils.type2str(val), max_val_length)
-
-
-func compare(v1, v2, diff_type=_utils.DIFF.SIMPLE):
- var result = null
- if(diff_type == _utils.DIFF.SIMPLE):
- result = simple(v1, v2)
- elif(diff_type == _utils.DIFF.SHALLOW):
- result = shallow(v1, v2)
- elif(diff_type == _utils.DIFF.DEEP):
- result = deep(v1, v2)
-
- return result
-
-
-func get_should_compare_int_to_float():
- return _should_compare_int_to_float
-
-
-func set_should_compare_int_to_float(should_compare_int_float):
- _should_compare_int_to_float = should_compare_int_float
-
-
-func get_compare_symbol(is_equal):
- if(is_equal):
- return '=='
- else:
- return '!='
diff --git a/addons/gut/compare_result.gd b/addons/gut/compare_result.gd
deleted file mode 100644
index be6aebd..0000000
--- a/addons/gut/compare_result.gd
+++ /dev/null
@@ -1,47 +0,0 @@
-var are_equal = null setget set_are_equal, get_are_equal
-var summary = null setget set_summary, get_summary
-var max_differences = 30 setget set_max_differences, get_max_differences
-var differences = {} setget set_differences, get_differences
-
-func _block_set(which, val):
- push_error(str('cannot set ', which, ', value [', val, '] ignored.'))
-
-func _to_string():
- return str(get_summary()) # could be null, gotta str it.
-
-func get_are_equal():
- return are_equal
-
-func set_are_equal(r_eq):
- are_equal = r_eq
-
-func get_summary():
- return summary
-
-func set_summary(smry):
- summary = smry
-
-func get_total_count():
- pass
-
-func get_different_count():
- pass
-
-func get_short_summary():
- return summary
-
-func get_max_differences():
- return max_differences
-
-func set_max_differences(max_diff):
- max_differences = max_diff
-
-func get_differences():
- return differences
-
-func set_differences(diffs):
- _block_set('differences', diffs)
-
-func get_brackets():
- return null
-
diff --git a/addons/gut/diff_formatter.gd b/addons/gut/diff_formatter.gd
deleted file mode 100644
index fd954af..0000000
--- a/addons/gut/diff_formatter.gd
+++ /dev/null
@@ -1,64 +0,0 @@
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _strutils = _utils.Strutils.new()
-const INDENT = ' '
-var _max_to_display = 30
-const ABSOLUTE_MAX_DISPLAYED = 10000
-const UNLIMITED = -1
-
-
-func _single_diff(diff, depth=0):
- var to_return = ""
- var brackets = diff.get_brackets()
-
- if(brackets != null and !diff.are_equal):
- to_return = ''
- to_return += str(brackets.open, "\n",
- _strutils.indent_text(differences_to_s(diff.differences, depth), depth+1, INDENT), "\n",
- brackets.close)
- else:
- to_return = str(diff)
-
- return to_return
-
-
-func make_it(diff):
- var to_return = ''
- if(diff.are_equal):
- to_return = diff.summary
- else:
- if(_max_to_display == ABSOLUTE_MAX_DISPLAYED):
- to_return = str(diff.get_value_1(), ' != ', diff.get_value_2())
- else:
- to_return = diff.get_short_summary()
- to_return += str("\n", _strutils.indent_text(_single_diff(diff, 0), 1, ' '))
- return to_return
-
-
-func differences_to_s(differences, depth=0):
- var to_return = ''
- var keys = differences.keys()
- keys.sort()
- var limit = min(_max_to_display, differences.size())
-
- for i in range(limit):
- var key = keys[i]
- to_return += str(key, ": ", _single_diff(differences[key], depth))
-
- if(i != limit -1):
- to_return += "\n"
-
- if(differences.size() > _max_to_display):
- to_return += str("\n\n... ", differences.size() - _max_to_display, " more.")
-
- return to_return
-
-
-func get_max_to_display():
- return _max_to_display
-
-
-func set_max_to_display(max_to_display):
- _max_to_display = max_to_display
- if(_max_to_display == UNLIMITED):
- _max_to_display = ABSOLUTE_MAX_DISPLAYED
-
diff --git a/addons/gut/diff_tool.gd b/addons/gut/diff_tool.gd
deleted file mode 100644
index 9dbbd1c..0000000
--- a/addons/gut/diff_tool.gd
+++ /dev/null
@@ -1,162 +0,0 @@
-extends 'res://addons/gut/compare_result.gd'
-const INDENT = ' '
-enum {
- DEEP,
- SHALLOW,
- SIMPLE
-}
-
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _strutils = _utils.Strutils.new()
-var _compare = _utils.Comparator.new()
-var DiffTool = load('res://addons/gut/diff_tool.gd')
-
-var _value_1 = null
-var _value_2 = null
-var _total_count = 0
-var _diff_type = null
-var _brackets = null
-var _valid = true
-var _desc_things = 'somethings'
-
-# -------- comapre_result.gd "interface" ---------------------
-func set_are_equal(val):
- _block_set('are_equal', val)
-
-func get_are_equal():
- return are_equal()
-
-func set_summary(val):
- _block_set('summary', val)
-
-func get_summary():
- return summarize()
-
-func get_different_count():
- return differences.size()
-
-func get_total_count():
- return _total_count
-
-func get_short_summary():
- var text = str(_strutils.truncate_string(str(_value_1), 50),
- ' ', _compare.get_compare_symbol(are_equal()), ' ',
- _strutils.truncate_string(str(_value_2), 50))
- if(!are_equal()):
- text += str(' ', get_different_count(), ' of ', get_total_count(),
- ' ', _desc_things, ' do not match.')
- return text
-
-func get_brackets():
- return _brackets
-# -------- comapre_result.gd "interface" ---------------------
-
-
-func _invalidate():
- _valid = false
- differences = null
-
-
-func _init(v1, v2, diff_type=DEEP):
- _value_1 = v1
- _value_2 = v2
- _diff_type = diff_type
- _compare.set_should_compare_int_to_float(false)
- _find_differences(_value_1, _value_2)
-
-
-func _find_differences(v1, v2):
- if(_utils.are_datatypes_same(v1, v2)):
- if(typeof(v1) == TYPE_ARRAY):
- _brackets = {'open':'[', 'close':']'}
- _desc_things = 'indexes'
- _diff_array(v1, v2)
- elif(typeof(v2) == TYPE_DICTIONARY):
- _brackets = {'open':'{', 'close':'}'}
- _desc_things = 'keys'
- _diff_dictionary(v1, v2)
- else:
- _invalidate()
- _utils.get_logger().error('Only Arrays and Dictionaries are supported.')
- else:
- _invalidate()
- _utils.get_logger().error('Only Arrays and Dictionaries are supported.')
-
-
-func _diff_array(a1, a2):
- _total_count = max(a1.size(), a2.size())
- for i in range(a1.size()):
- var result = null
- if(i < a2.size()):
- if(_diff_type == DEEP):
- result = _compare.deep(a1[i], a2[i])
- else:
- result = _compare.simple(a1[i], a2[i])
- else:
- result = _compare.simple(a1[i], _compare.MISSING, 'index')
-
- if(!result.are_equal):
- differences[i] = result
-
- if(a1.size() < a2.size()):
- for i in range(a1.size(), a2.size()):
- differences[i] = _compare.simple(_compare.MISSING, a2[i], 'index')
-
-
-func _diff_dictionary(d1, d2):
- var d1_keys = d1.keys()
- var d2_keys = d2.keys()
-
- # Process all the keys in d1
- _total_count += d1_keys.size()
- for key in d1_keys:
- if(!d2.has(key)):
- differences[key] = _compare.simple(d1[key], _compare.MISSING, 'key')
- else:
- d2_keys.remove(d2_keys.find(key))
-
- var result = null
- if(_diff_type == DEEP):
- result = _compare.deep(d1[key], d2[key])
- else:
- result = _compare.simple(d1[key], d2[key])
-
- if(!result.are_equal):
- differences[key] = result
-
- # Process all the keys in d2 that didn't exist in d1
- _total_count += d2_keys.size()
- for i in range(d2_keys.size()):
- differences[d2_keys[i]] = _compare.simple(_compare.MISSING, d2[d2_keys[i]], 'key')
-
-
-func summarize():
- var summary = ''
-
- if(are_equal()):
- summary = get_short_summary()
- else:
- var formatter = load('res://addons/gut/diff_formatter.gd').new()
- formatter.set_max_to_display(max_differences)
- summary = formatter.make_it(self)
-
- return summary
-
-
-func are_equal():
- if(!_valid):
- return null
- else:
- return differences.size() == 0
-
-
-func get_diff_type():
- return _diff_type
-
-
-func get_value_1():
- return _value_1
-
-
-func get_value_2():
- return _value_2
diff --git a/addons/gut/double_templates/function_template.txt b/addons/gut/double_templates/function_template.txt
deleted file mode 100644
index 666952e..0000000
--- a/addons/gut/double_templates/function_template.txt
+++ /dev/null
@@ -1,6 +0,0 @@
-{func_decleration}
- __gut_spy('{method_name}', {param_array})
- if(__gut_should_call_super('{method_name}', {param_array})):
- return {super_call}
- else:
- return __gut_get_stubbed_return('{method_name}', {param_array})
diff --git a/addons/gut/double_templates/script_template.txt b/addons/gut/double_templates/script_template.txt
deleted file mode 100644
index 6fc7165..0000000
--- a/addons/gut/double_templates/script_template.txt
+++ /dev/null
@@ -1,41 +0,0 @@
-{extends}
-
-var __gut_metadata_ = {
- path = '{path}',
- subpath = '{subpath}',
- stubber = __gut_instance_from_id({stubber_id}),
- spy = __gut_instance_from_id({spy_id}),
- gut = __gut_instance_from_id({gut_id}),
-}
-
-func __gut_instance_from_id(inst_id):
- if(inst_id == -1):
- return null
- else:
- return instance_from_id(inst_id)
-
-func __gut_should_call_super(method_name, called_with):
- if(__gut_metadata_.stubber != null):
- return __gut_metadata_.stubber.should_call_super(self, method_name, called_with)
- else:
- return false
-
-var __gut_utils_ = load('res://addons/gut/utils.gd').get_instance()
-
-func __gut_spy(method_name, called_with):
- if(__gut_metadata_.spy != null):
- __gut_metadata_.spy.add_call(self, method_name, called_with)
-
-func __gut_get_stubbed_return(method_name, called_with):
- if(__gut_metadata_.stubber != null):
- return __gut_metadata_.stubber.get_return(self, method_name, called_with)
- else:
- return null
-
-func _init():
- if(__gut_metadata_.gut != null):
- __gut_metadata_.gut.get_autofree().add_free(self)
-
-# ------------------------------------------------------------------------------
-# Methods start here
-# ------------------------------------------------------------------------------
diff --git a/addons/gut/doubler.gd b/addons/gut/doubler.gd
deleted file mode 100644
index c5e9e0e..0000000
--- a/addons/gut/doubler.gd
+++ /dev/null
@@ -1,556 +0,0 @@
-# ------------------------------------------------------------------------------
-# Utility class to hold the local and built in methods separately. Add all local
-# methods FIRST, then add built ins.
-# ------------------------------------------------------------------------------
-class ScriptMethods:
- # List of methods that should not be overloaded when they are not defined
- # in the class being doubled. These either break things if they are
- # overloaded or do not have a "super" equivalent so we can't just pass
- # through.
- var _blacklist = [
- 'has_method',
- 'get_script',
- 'get',
- '_notification',
- 'get_path',
- '_enter_tree',
- '_exit_tree',
- '_process',
- '_draw',
- '_physics_process',
- '_input',
- '_unhandled_input',
- '_unhandled_key_input',
- '_set',
- '_get', # probably
- 'emit_signal', # can't handle extra parameters to be sent with signal.
- 'draw_mesh', # issue with one parameter, value is `Null((..), (..), (..))``
- '_to_string', # nonexistant function ._to_string
- '_get_minimum_size', # Nonexistent function _get_minimum_size
- ]
-
- # These methods should not be included in the double.
- var _skip = [
- # There is an init in the template. There is also no real reason
- # to include this method since it will always be called, it has no
- # return value, and you cannot prevent super from being called.
- '_init'
- ]
-
- var built_ins = []
- var local_methods = []
- var _method_names = []
-
- func is_blacklisted(method_meta):
- return _blacklist.find(method_meta.name) != -1
-
- func _add_name_if_does_not_have(method_name):
- if(_skip.has(method_name)):
- return false
- var should_add = _method_names.find(method_name) == -1
- if(should_add):
- _method_names.append(method_name)
- return should_add
-
- func add_built_in_method(method_meta):
- var did_add = _add_name_if_does_not_have(method_meta.name)
- if(did_add and !is_blacklisted(method_meta)):
- built_ins.append(method_meta)
-
- func add_local_method(method_meta):
- var did_add = _add_name_if_does_not_have(method_meta.name)
- if(did_add):
- local_methods.append(method_meta)
-
- func to_s():
- var text = "Locals\n"
- for i in range(local_methods.size()):
- text += str(" ", local_methods[i].name, "\n")
- text += "Built-Ins\n"
- for i in range(built_ins.size()):
- text += str(" ", built_ins[i].name, "\n")
- return text
-
-# ------------------------------------------------------------------------------
-# Helper class to deal with objects and inner classes.
-# ------------------------------------------------------------------------------
-class ObjectInfo:
- var _path = null
- var _subpaths = []
- var _utils = load('res://addons/gut/utils.gd').get_instance()
- var _method_strategy = null
- var make_partial_double = false
- var scene_path = null
- var _native_class = null
- var _native_class_name = null
-
- func _init(path, subpath=null):
- _path = path
- if(subpath != null):
- _subpaths = _utils.split_string(subpath, '/')
-
- # Returns an instance of the class/inner class
- func instantiate():
- var to_return = null
- if(is_native()):
- to_return = _native_class.new()
- else:
- to_return = get_loaded_class().new()
- return to_return
-
- # Can't call it get_class because that is reserved so it gets this ugly name.
- # Loads up the class and then any inner classes to give back a reference to
- # the desired Inner class (if there is any)
- func get_loaded_class():
- var LoadedClass = load(_path)
- for i in range(_subpaths.size()):
- LoadedClass = LoadedClass.get(_subpaths[i])
- return LoadedClass
-
- func to_s():
- return str(_path, '[', get_subpath(), ']')
-
- func get_path():
- return _path
-
- func get_subpath():
- return _utils.join_array(_subpaths, '/')
-
- func has_subpath():
- return _subpaths.size() != 0
-
- func get_extends_text():
- var extend = null
- if(is_native()):
- var native = get_native_class_name()
- if(native.begins_with('_')):
- native = native.substr(1)
- extend = str("extends ", native)
- else:
- extend = str("extends '", get_path(), "'")
-
- if(has_subpath()):
- extend += str('.', get_subpath().replace('/', '.'))
-
- return extend
-
- func get_method_strategy():
- return _method_strategy
-
- func set_method_strategy(method_strategy):
- _method_strategy = method_strategy
-
- func is_native():
- return _native_class != null
-
- func set_native_class(native_class):
- _native_class = native_class
- var inst = native_class.new()
- _native_class_name = inst.get_class()
- _path = _native_class_name
- if(!inst is Reference):
- inst.free()
-
- func get_native_class_name():
- return _native_class_name
-
-# ------------------------------------------------------------------------------
-# Allows for interacting with a file but only creating a string. This was done
-# to ease the transition from files being created for doubles to loading
-# doubles from a string. This allows the files to be created for debugging
-# purposes since reading a file is easier than reading a dumped out string.
-# ------------------------------------------------------------------------------
-class FileOrString:
- extends File
-
- var _do_file = false
- var _contents = ''
- var _path = null
-
- func open(path, mode):
- _path = path
- if(_do_file):
- return .open(path, mode)
- else:
- return OK
-
- func close():
- if(_do_file):
- return .close()
-
- func store_string(s):
- if(_do_file):
- .store_string(s)
- _contents += s
-
- func get_contents():
- return _contents
-
- func get_path():
- return _path
-
- func load_it():
- if(_contents != ''):
- var script = GDScript.new()
- script.set_source_code(get_contents())
- script.reload()
- return script
- else:
- return load(_path)
-
-# ------------------------------------------------------------------------------
-# A stroke of genius if I do say so. This allows for doubling a scene without
-# having to write any files. By overloading instance we can make whatever
-# we want.
-# ------------------------------------------------------------------------------
-class PackedSceneDouble:
- extends PackedScene
- var _script = null
- var _scene = null
-
- func set_script_obj(obj):
- _script = obj
-
- func instance(edit_state=0):
- var inst = _scene.instance(edit_state)
- if(_script != null):
- inst.set_script(_script)
- return inst
-
- func load_scene(path):
- _scene = load(path)
-
-
-
-
-# ------------------------------------------------------------------------------
-# START Doubler
-# ------------------------------------------------------------------------------
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-
-var _ignored_methods = _utils.OneToMany.new()
-var _stubber = _utils.Stubber.new()
-var _lgr = _utils.get_logger()
-var _method_maker = _utils.MethodMaker.new()
-
-var _output_dir = 'user://gut_temp_directory'
-var _double_count = 0 # used in making files names unique
-var _spy = null
-var _gut = null
-var _strategy = null
-var _base_script_text = _utils.get_file_as_text('res://addons/gut/double_templates/script_template.txt')
-var _make_files = false
-
-# These methods all call super implicitly. Stubbing them to call super causes
-# super to be called twice.
-var _non_super_methods = [
- "_init",
- "_ready",
- "_notification",
- "_enter_world",
- "_exit_world",
- "_process",
- "_physics_process",
- "_exit_tree",
- "_gui_input ",
-]
-
-func _init(strategy=_utils.DOUBLE_STRATEGY.PARTIAL):
- set_logger(_utils.get_logger())
- _strategy = strategy
-
-# ###############
-# Private
-# ###############
-func _get_indented_line(indents, text):
- var to_return = ''
- for _i in range(indents):
- to_return += "\t"
- return str(to_return, text, "\n")
-
-
-func _stub_to_call_super(obj_info, method_name):
- if(_non_super_methods.has(method_name)):
- return
- var path = obj_info.get_path()
- if(obj_info.scene_path != null):
- path = obj_info.scene_path
- var params = _utils.StubParams.new(path, method_name, obj_info.get_subpath())
- params.to_call_super()
- _stubber.add_stub(params)
-
-func _get_base_script_text(obj_info, override_path):
- var path = obj_info.get_path()
- if(override_path != null):
- path = override_path
-
- var stubber_id = -1
- if(_stubber != null):
- stubber_id = _stubber.get_instance_id()
-
- var spy_id = -1
- if(_spy != null):
- spy_id = _spy.get_instance_id()
-
- var gut_id = -1
- if(_gut != null):
- gut_id = _gut.get_instance_id()
-
- var values = {
- "path":path,
- "subpath":obj_info.get_subpath(),
- "stubber_id":stubber_id,
- "spy_id":spy_id,
- "extends":obj_info.get_extends_text(),
- "gut_id":gut_id
- }
-
- return _base_script_text.format(values)
-
-func _write_file(obj_info, dest_path, override_path=null):
- var base_script = _get_base_script_text(obj_info, override_path)
- var script_methods = _get_methods(obj_info)
-
- var f = FileOrString.new()
- f._do_file = _make_files
- var f_result = f.open(dest_path, f.WRITE)
-
- if(f_result != OK):
- _lgr.error(str('Error creating file ', dest_path))
- _lgr.error(str('Could not create double for :', obj_info.to_s()))
- return
-
- f.store_string(base_script)
-
- for i in range(script_methods.local_methods.size()):
- if(obj_info.make_partial_double):
- _stub_to_call_super(obj_info, script_methods.local_methods[i].name)
- f.store_string(_get_func_text(script_methods.local_methods[i]))
-
- for i in range(script_methods.built_ins.size()):
- _stub_to_call_super(obj_info, script_methods.built_ins[i].name)
- f.store_string(_get_func_text(script_methods.built_ins[i]))
-
- f.close()
- return f
-
-func _double_scene_and_script(scene_info):
- var to_return = PackedSceneDouble.new()
- to_return.load_scene(scene_info.get_path())
-
- var inst = load(scene_info.get_path()).instance()
- var script_path = null
- if(inst.get_script()):
- script_path = inst.get_script().get_path()
- inst.free()
-
- if(script_path):
- var oi = ObjectInfo.new(script_path)
- oi.set_method_strategy(scene_info.get_method_strategy())
- oi.make_partial_double = scene_info.make_partial_double
- oi.scene_path = scene_info.get_path()
- to_return.set_script_obj(_double(oi, scene_info.get_path()).load_it())
-
- return to_return
-
-func _get_methods(object_info):
- var obj = object_info.instantiate()
- # any method in the script or super script
- var script_methods = ScriptMethods.new()
- var methods = obj.get_method_list()
- if(!(obj is Reference)):
- obj.free()
-
- # first pass is for local methods only
- for i in range(methods.size()):
- # 65 is a magic number for methods in script, though documentation
- # says 64. This picks up local overloads of base class methods too.
- if(methods[i].flags == 65 and !_ignored_methods.has(object_info.get_path(), methods[i]['name'])):
- script_methods.add_local_method(methods[i])
-
-
- if(object_info.get_method_strategy() == _utils.DOUBLE_STRATEGY.FULL):
- # second pass is for anything not local
- for i in range(methods.size()):
- # 65 is a magic number for methods in script, though documentation
- # says 64. This picks up local overloads of base class methods too.
- if(methods[i].flags != 65 and !_ignored_methods.has(object_info.get_path(), methods[i]['name'])):
- script_methods.add_built_in_method(methods[i])
-
- return script_methods
-
-func _get_inst_id_ref_str(inst):
- var ref_str = 'null'
- if(inst):
- ref_str = str('instance_from_id(', inst.get_instance_id(),')')
- return ref_str
-
-func _get_func_text(method_hash):
- return _method_maker.get_function_text(method_hash) + "\n"
-
-# returns the path to write the double file to
-func _get_temp_path(object_info):
- var file_name = null
- var extension = null
- if(object_info.is_native()):
- file_name = object_info.get_native_class_name()
- extension = 'gd'
- else:
- file_name = object_info.get_path().get_file().get_basename()
- extension = object_info.get_path().get_extension()
-
- if(object_info.has_subpath()):
- file_name += '__' + object_info.get_subpath().replace('/', '__')
-
- file_name += str('__dbl', _double_count, '__.', extension)
-
- var to_return = _output_dir.plus_file(file_name)
- return to_return
-
-func _load_double(fileOrString):
- return fileOrString.load_it()
-
-func _double(obj_info, override_path=null):
- var temp_path = _get_temp_path(obj_info)
- var result = _write_file(obj_info, temp_path, override_path)
- _double_count += 1
- return result
-
-func _double_script(path, make_partial, strategy):
- var oi = ObjectInfo.new(path)
- oi.make_partial_double = make_partial
- oi.set_method_strategy(strategy)
- return _double(oi).load_it()
-
-func _double_inner(path, subpath, make_partial, strategy):
- var oi = ObjectInfo.new(path, subpath)
- oi.set_method_strategy(strategy)
- oi.make_partial_double = make_partial
- return _double(oi).load_it()
-
-func _double_scene(path, make_partial, strategy):
- var oi = ObjectInfo.new(path)
- oi.set_method_strategy(strategy)
- oi.make_partial_double = make_partial
- return _double_scene_and_script(oi)
-
-func _double_gdnative(native_class, make_partial, strategy):
- var oi = ObjectInfo.new(null)
- oi.set_native_class(native_class)
- oi.set_method_strategy(strategy)
- oi.make_partial_double = make_partial
- return _double(oi).load_it()
-
-# ###############
-# Public
-# ###############
-func get_output_dir():
- return _output_dir
-
-func set_output_dir(output_dir):
- if(output_dir != null):
- _output_dir = output_dir
- if(_make_files):
- var d = Directory.new()
- d.make_dir_recursive(output_dir)
-
-func get_spy():
- return _spy
-
-func set_spy(spy):
- _spy = spy
-
-func get_stubber():
- return _stubber
-
-func set_stubber(stubber):
- _stubber = stubber
-
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
- _method_maker.set_logger(logger)
-
-func get_strategy():
- return _strategy
-
-func set_strategy(strategy):
- _strategy = strategy
-
-func get_gut():
- return _gut
-
-func set_gut(gut):
- _gut = gut
-
-func partial_double_scene(path, strategy=_strategy):
- return _double_scene(path, true, strategy)
-
-# double a scene
-func double_scene(path, strategy=_strategy):
- return _double_scene(path, false, strategy)
-
-# double a script/object
-func double(path, strategy=_strategy):
- return _double_script(path, false, strategy)
-
-func partial_double(path, strategy=_strategy):
- return _double_script(path, true, strategy)
-
-func partial_double_inner(path, subpath, strategy=_strategy):
- return _double_inner(path, subpath, true, strategy)
-
-# double an inner class in a script
-func double_inner(path, subpath, strategy=_strategy):
- return _double_inner(path, subpath, false, strategy)
-
-# must always use FULL strategy since this is a native class and you won't get
-# any methods if you don't use FULL
-func double_gdnative(native_class):
- return _double_gdnative(native_class, false, _utils.DOUBLE_STRATEGY.FULL)
-
-# must always use FULL strategy since this is a native class and you won't get
-# any methods if you don't use FULL
-func partial_double_gdnative(native_class):
- return _double_gdnative(native_class, true, _utils.DOUBLE_STRATEGY.FULL)
-
-func clear_output_directory():
- if(!_make_files):
- return false
-
- var did = false
- if(_output_dir.find('user://') == 0):
- var d = Directory.new()
- var result = d.open(_output_dir)
- # BIG GOTCHA HERE. If it cannot open the dir w/ erro 31, then the
- # directory becomes res:// and things go on normally and gut clears out
- # out res:// which is SUPER BAD.
- if(result == OK):
- d.list_dir_begin(true)
- var f = d.get_next()
- while(f != ''):
- d.remove(f)
- f = d.get_next()
- did = true
- return did
-
-func delete_output_directory():
- var did = clear_output_directory()
- if(did):
- var d = Directory.new()
- d.remove(_output_dir)
-
-func add_ignored_method(path, method_name):
- _ignored_methods.add(path, method_name)
-
-func get_ignored_methods():
- return _ignored_methods
-
-func get_make_files():
- return _make_files
-
-func set_make_files(make_files):
- _make_files = make_files
- set_output_dir(_output_dir)
diff --git a/addons/gut/fonts/AnonymousPro-Bold.ttf b/addons/gut/fonts/AnonymousPro-Bold.ttf
deleted file mode 100644
index 1d4bf2b..0000000
Binary files a/addons/gut/fonts/AnonymousPro-Bold.ttf and /dev/null differ
diff --git a/addons/gut/fonts/AnonymousPro-BoldItalic.ttf b/addons/gut/fonts/AnonymousPro-BoldItalic.ttf
deleted file mode 100644
index 12863ca..0000000
Binary files a/addons/gut/fonts/AnonymousPro-BoldItalic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/AnonymousPro-Italic.ttf b/addons/gut/fonts/AnonymousPro-Italic.ttf
deleted file mode 100644
index f6870b7..0000000
Binary files a/addons/gut/fonts/AnonymousPro-Italic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/AnonymousPro-Regular.ttf b/addons/gut/fonts/AnonymousPro-Regular.ttf
deleted file mode 100644
index 57aa893..0000000
Binary files a/addons/gut/fonts/AnonymousPro-Regular.ttf and /dev/null differ
diff --git a/addons/gut/fonts/CourierPrime-Bold.ttf b/addons/gut/fonts/CourierPrime-Bold.ttf
deleted file mode 100644
index 91d6de4..0000000
Binary files a/addons/gut/fonts/CourierPrime-Bold.ttf and /dev/null differ
diff --git a/addons/gut/fonts/CourierPrime-BoldItalic.ttf b/addons/gut/fonts/CourierPrime-BoldItalic.ttf
deleted file mode 100644
index 0afaa98..0000000
Binary files a/addons/gut/fonts/CourierPrime-BoldItalic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/CourierPrime-Italic.ttf b/addons/gut/fonts/CourierPrime-Italic.ttf
deleted file mode 100644
index f8a20bd..0000000
Binary files a/addons/gut/fonts/CourierPrime-Italic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/CourierPrime-Regular.ttf b/addons/gut/fonts/CourierPrime-Regular.ttf
deleted file mode 100644
index 4f638f6..0000000
Binary files a/addons/gut/fonts/CourierPrime-Regular.ttf and /dev/null differ
diff --git a/addons/gut/fonts/LobsterTwo-Bold.ttf b/addons/gut/fonts/LobsterTwo-Bold.ttf
deleted file mode 100644
index 2e979fb..0000000
Binary files a/addons/gut/fonts/LobsterTwo-Bold.ttf and /dev/null differ
diff --git a/addons/gut/fonts/LobsterTwo-BoldItalic.ttf b/addons/gut/fonts/LobsterTwo-BoldItalic.ttf
deleted file mode 100644
index 8bbf8d8..0000000
Binary files a/addons/gut/fonts/LobsterTwo-BoldItalic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/LobsterTwo-Italic.ttf b/addons/gut/fonts/LobsterTwo-Italic.ttf
deleted file mode 100644
index b88ec17..0000000
Binary files a/addons/gut/fonts/LobsterTwo-Italic.ttf and /dev/null differ
diff --git a/addons/gut/fonts/LobsterTwo-Regular.ttf b/addons/gut/fonts/LobsterTwo-Regular.ttf
deleted file mode 100644
index 556c45e..0000000
Binary files a/addons/gut/fonts/LobsterTwo-Regular.ttf and /dev/null differ
diff --git a/addons/gut/fonts/OFL.txt b/addons/gut/fonts/OFL.txt
deleted file mode 100644
index 3ed0152..0000000
--- a/addons/gut/fonts/OFL.txt
+++ /dev/null
@@ -1,94 +0,0 @@
-Copyright (c) 2009, Mark Simonson (http://www.ms-studio.com, mark@marksimonson.com),
-with Reserved Font Name Anonymous Pro.
-
-This Font Software is licensed under the SIL Open Font License, Version 1.1.
-This license is copied below, and is also available with a FAQ at:
-http://scripts.sil.org/OFL
-
-
------------------------------------------------------------
-SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
------------------------------------------------------------
-
-PREAMBLE
-The goals of the Open Font License (OFL) are to stimulate worldwide
-development of collaborative font projects, to support the font creation
-efforts of academic and linguistic communities, and to provide a free and
-open framework in which fonts may be shared and improved in partnership
-with others.
-
-The OFL allows the licensed fonts to be used, studied, modified and
-redistributed freely as long as they are not sold by themselves. The
-fonts, including any derivative works, can be bundled, embedded,
-redistributed and/or sold with any software provided that any reserved
-names are not used by derivative works. The fonts and derivatives,
-however, cannot be released under any other type of license. The
-requirement for fonts to remain under this license does not apply
-to any document created using the fonts or their derivatives.
-
-DEFINITIONS
-"Font Software" refers to the set of files released by the Copyright
-Holder(s) under this license and clearly marked as such. This may
-include source files, build scripts and documentation.
-
-"Reserved Font Name" refers to any names specified as such after the
-copyright statement(s).
-
-"Original Version" refers to the collection of Font Software components as
-distributed by the Copyright Holder(s).
-
-"Modified Version" refers to any derivative made by adding to, deleting,
-or substituting -- in part or in whole -- any of the components of the
-Original Version, by changing formats or by porting the Font Software to a
-new environment.
-
-"Author" refers to any designer, engineer, programmer, technical
-writer or other person who contributed to the Font Software.
-
-PERMISSION & CONDITIONS
-Permission is hereby granted, free of charge, to any person obtaining
-a copy of the Font Software, to use, study, copy, merge, embed, modify,
-redistribute, and sell modified and unmodified copies of the Font
-Software, subject to the following conditions:
-
-1) Neither the Font Software nor any of its individual components,
-in Original or Modified Versions, may be sold by itself.
-
-2) Original or Modified Versions of the Font Software may be bundled,
-redistributed and/or sold with any software, provided that each copy
-contains the above copyright notice and this license. These can be
-included either as stand-alone text files, human-readable headers or
-in the appropriate machine-readable metadata fields within text or
-binary files as long as those fields can be easily viewed by the user.
-
-3) No Modified Version of the Font Software may use the Reserved Font
-Name(s) unless explicit written permission is granted by the corresponding
-Copyright Holder. This restriction only applies to the primary font name as
-presented to the users.
-
-4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
-Software shall not be used to promote, endorse or advertise any
-Modified Version, except to acknowledge the contribution(s) of the
-Copyright Holder(s) and the Author(s) or with their explicit written
-permission.
-
-5) The Font Software, modified or unmodified, in part or in whole,
-must be distributed entirely under this license, and must not be
-distributed under any other license. The requirement for fonts to
-remain under this license does not apply to any document created
-using the Font Software.
-
-TERMINATION
-This license becomes null and void if any of the above conditions are
-not met.
-
-DISCLAIMER
-THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
-MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
-OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
-COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
-INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
-DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
-OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/addons/gut/gut.gd b/addons/gut/gut.gd
deleted file mode 100644
index fc56ce9..0000000
--- a/addons/gut/gut.gd
+++ /dev/null
@@ -1,1566 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# View readme for usage details.
-# ##############################################################################
-extends Control
-
-# -- Settings --
-var _select_script = ''
-var _tests_like = ''
-var _inner_class_name = ''
-var _should_maximize = false setget set_should_maximize, get_should_maximize
-var _log_level = 1 setget set_log_level, get_log_level
-var _disable_strict_datatype_checks = false setget disable_strict_datatype_checks, is_strict_datatype_checks_disabled
-var _test_prefix = 'test_'
-var _file_prefix = 'test_'
-var _file_extension = '.gd'
-var _inner_class_prefix = 'Test'
-var _temp_directory = 'user://gut_temp_directory'
-var _export_path = '' setget set_export_path, get_export_path
-var _include_subdirectories = false setget set_include_subdirectories, get_include_subdirectories
-var _double_strategy = 1 setget set_double_strategy, get_double_strategy
-var _pre_run_script = '' setget set_pre_run_script, get_pre_run_script
-var _post_run_script = '' setget set_post_run_script, get_post_run_script
-var _color_output = false setget set_color_output, get_color_output
-# -- End Settings --
-
-
-# ###########################
-# Other Vars
-# ###########################
-const LOG_LEVEL_FAIL_ONLY = 0
-const LOG_LEVEL_TEST_AND_FAILURES = 1
-const LOG_LEVEL_ALL_ASSERTS = 2
-const WAITING_MESSAGE = '/# waiting #/'
-const PAUSE_MESSAGE = '/# Pausing. Press continue button...#/'
-const COMPLETED = 'completed'
-
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _lgr = _utils.get_logger()
-var _strutils = _utils.Strutils.new()
-# Used to prevent multiple messages for deprecated setup/teardown messages
-var _deprecated_tracker = _utils.ThingCounter.new()
-
-# The instance that is created from _pre_run_script. Accessible from
-# get_pre_run_script_instance.
-var _pre_run_script_instance = null
-var _post_run_script_instance = null # This is not used except in tests.
-
-
-var _script_name = null
-var _test_collector = _utils.TestCollector.new()
-
-# The instanced scripts. This is populated as the scripts are run.
-var _test_script_objects = []
-
-var _waiting = false
-var _done = false
-var _is_running = false
-
-var _current_test = null
-var _log_text = ""
-
-var _pause_before_teardown = false
-# when true _pause_before_teardown will be ignored. useful
-# when batch processing and you don't want to watch.
-var _ignore_pause_before_teardown = false
-var _wait_timer = Timer.new()
-
-var _yield_between = {
- should = false,
- timer = Timer.new(),
- after_x_tests = 5,
- tests_since_last_yield = 0
-}
-
-var _was_yield_method_called = false
-# used when yielding to gut instead of some other
-# signal. Start with set_yield_time()
-var _yield_timer = Timer.new()
-
-var _unit_test_name = ''
-var _new_summary = null
-
-var _yielding_to = {
- obj = null,
- signal_name = ''
-}
-
-var _stubber = _utils.Stubber.new()
-var _doubler = _utils.Doubler.new()
-var _spy = _utils.Spy.new()
-var _gui = null
-var _orphan_counter = _utils.OrphanCounter.new()
-var _autofree = _utils.AutoFree.new()
-
-# This is populated by test.gd each time a paramterized test is encountered
-# for the first time.
-var _parameter_handler = null
-
-# Used to cancel importing scripts if an error has occurred in the setup. This
-# prevents tests from being run if they were exported and ensures that the
-# error displayed is seen since importing generates a lot of text.
-var _cancel_import = false
-
-# Used for proper assert tracking and printing during before_all
-var _before_all_test_obj = load('res://addons/gut/test_collector.gd').Test.new()
-# Used for proper assert tracking and printing during after_all
-var _after_all_test_obj = load('res://addons/gut/test_collector.gd').Test.new()
-
-const SIGNAL_TESTS_FINISHED = 'tests_finished'
-const SIGNAL_STOP_YIELD_BEFORE_TEARDOWN = 'stop_yield_before_teardown'
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-var _should_print_versions = true # used to cut down on output in tests.
-func _init():
- _before_all_test_obj.name = 'before_all'
- _after_all_test_obj.name = 'after_all'
- # When running tests for GUT itself, _utils has been setup to always return
- # a new logger so this does not set the gut instance on the base logger
- # when creating test instances of GUT.
- _lgr.set_gut(self)
-
- add_user_signal(SIGNAL_TESTS_FINISHED)
- add_user_signal('test_finished')
- add_user_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
- add_user_signal('timeout')
-
- _doubler.set_output_dir(_temp_directory)
- _doubler.set_stubber(_stubber)
- _doubler.set_spy(_spy)
- _doubler.set_gut(self)
-
- # TODO remove these, universal logger should fix this.
- _doubler.set_logger(_lgr)
- _spy.set_logger(_lgr)
- _stubber.set_logger(_lgr)
- _test_collector.set_logger(_lgr)
-
- _gui = load('res://addons/gut/GutScene.tscn').instance()
-
-# ------------------------------------------------------------------------------
-# Initialize controls
-# ------------------------------------------------------------------------------
-func _ready():
- if(!_utils.is_version_ok()):
- _print_versions()
- push_error(_utils.get_bad_version_text())
- print('Error: ', _utils.get_bad_version_text())
- get_tree().quit()
- return
-
- if(_should_print_versions):
- _lgr.info(str('using [', OS.get_user_data_dir(), '] for temporary output.'))
-
- set_process_input(true)
-
- add_child(_wait_timer)
- _wait_timer.set_wait_time(1)
- _wait_timer.set_one_shot(true)
-
- add_child(_yield_between.timer)
- _wait_timer.set_one_shot(true)
-
- add_child(_yield_timer)
- _yield_timer.set_one_shot(true)
- _yield_timer.connect('timeout', self, '_yielding_callback')
-
- _setup_gui()
-
- if(_select_script != null):
- select_script(_select_script)
-
- if(_tests_like != null):
- set_unit_test_name(_tests_like)
-
- if(_should_maximize):
- # GUI checks for is_in_tree will not pass yet.
- call_deferred('maximize')
-
- # hide the panel that IS gut so that only the GUI is seen
- self.self_modulate = Color(1,1,1,0)
- show()
- _print_versions()
-
-# ------------------------------------------------------------------------------
-# Runs right before free is called. Can't override `free`.
-# ------------------------------------------------------------------------------
-func _notification(what):
- if(what == NOTIFICATION_PREDELETE):
- for test_script in _test_script_objects:
- if(is_instance_valid(test_script)):
- test_script.free()
-
- _test_script_objects = []
-
- if(is_instance_valid(_gui)):
- _gui.free()
-
-func _print_versions(send_all = true):
- if(!_should_print_versions):
- return
-
- var info = _utils.get_version_text()
-
- if(send_all):
- p(info)
- else:
- var printer = _lgr.get_printer('gui')
- printer.send(info + "\n")
-
-
-# ##############################################################################
-#
-# GUI Events and setup
-#
-# ##############################################################################
-func _setup_gui():
- # This is how we get the size of the control to translate to the gui when
- # the scene is run. This is also another reason why the min_rect_size
- # must match between both gut and the gui.
- _gui.rect_size = self.rect_size
- add_child(_gui)
- _gui.set_anchor(MARGIN_RIGHT, ANCHOR_END)
- _gui.set_anchor(MARGIN_BOTTOM, ANCHOR_END)
- _gui.connect('run_single_script', self, '_on_run_one')
- _gui.connect('run_script', self, '_on_new_gui_run_script')
- _gui.connect('end_pause', self, '_on_new_gui_end_pause')
- _gui.connect('ignore_pause', self, '_on_new_gui_ignore_pause')
- _gui.connect('log_level_changed', self, '_on_log_level_changed')
- var _foo = connect('tests_finished', _gui, 'end_run')
-
-func _add_scripts_to_gui():
- var scripts = []
- for i in range(_test_collector.scripts.size()):
- var s = _test_collector.scripts[i]
- var txt = ''
- if(s.has_inner_class()):
- txt = str(' - ', s.inner_class_name, ' (', s.tests.size(), ')')
- else:
- txt = str(s.get_full_name(), ' (', s.tests.size(), ')')
- scripts.append(txt)
- _gui.set_scripts(scripts)
-
-func _on_run_one(index):
- clear_text()
- var indexes = [index]
- if(!_test_collector.scripts[index].has_inner_class()):
- indexes = _get_indexes_matching_path(_test_collector.scripts[index].path)
- _test_the_scripts(indexes)
-
-func _on_new_gui_run_script(index):
- var indexes = []
- clear_text()
- for i in range(index, _test_collector.scripts.size()):
- indexes.append(i)
- _test_the_scripts(indexes)
-
-func _on_new_gui_end_pause():
- _pause_before_teardown = false
- emit_signal(SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
-
-func _on_new_gui_ignore_pause(should):
- _ignore_pause_before_teardown = should
-
-func _on_log_level_changed(value):
- set_log_level(value)
-
-#####################
-#
-# Events
-#
-#####################
-
-# ------------------------------------------------------------------------------
-# Timeout for the built in timer. emits the timeout signal. Start timer
-# with set_yield_time()
-# ------------------------------------------------------------------------------
-func _yielding_callback(from_obj=false):
- _lgr.end_yield()
- if(_yielding_to.obj):
- _yielding_to.obj.call_deferred(
- "disconnect",
- _yielding_to.signal_name, self,
- '_yielding_callback')
- _yielding_to.obj = null
- _yielding_to.signal_name = ''
-
- if(from_obj):
- # we must yiled for a little longer after the signal is emitted so that
- # the signal can propagate to other objects. This was discovered trying
- # to assert that obj/signal_name was emitted. Without this extra delay
- # the yield returns and processing finishes before the rest of the
- # objects can get the signal. This works b/c the timer will timeout
- # and come back into this method but from_obj will be false.
- _yield_timer.set_wait_time(.1)
- _yield_timer.start()
- else:
- emit_signal('timeout')
-
-# ------------------------------------------------------------------------------
-# completed signal for GDScriptFucntionState returned from a test script that
-# has yielded
-# ------------------------------------------------------------------------------
-func _on_test_script_yield_completed():
- _waiting = false
-
-#####################
-#
-# Private
-#
-#####################
-func _log_test_children_warning(test_script):
- if(!_lgr.is_type_enabled(_lgr.types.orphan)):
- return
-
- var kids = test_script.get_children()
- if(kids.size() > 0):
- var msg = ''
- if(_log_level == 2):
- msg = "Test script still has children when all tests finisehd.\n"
- for i in range(kids.size()):
- msg += str(" ", _strutils.type2str(kids[i]), "\n")
- msg += "You can use autofree, autoqfree, add_child_autofree, or add_child_autoqfree to automatically free objects."
- else:
- msg = str("Test script has ", kids.size(), " unfreed children. Increase log level for more details.")
-
-
- _lgr.warn(msg)
-
-# ------------------------------------------------------------------------------
-# Convert the _summary dictionary into text
-# ------------------------------------------------------------------------------
-func _print_summary():
- _lgr.log("\n\n*** Run Summary ***", _lgr.fmts.yellow)
-
- _new_summary.log_summary_text(_lgr)
-
- var logger_text = ''
- if(_lgr.get_errors().size() > 0):
- logger_text += str("\n* ", _lgr.get_errors().size(), ' Errors.')
- if(_lgr.get_warnings().size() > 0):
- logger_text += str("\n* ", _lgr.get_warnings().size(), ' Warnings.')
- if(_lgr.get_deprecated().size() > 0):
- logger_text += str("\n* ", _lgr.get_deprecated().size(), ' Deprecated calls.')
- if(logger_text != ''):
- logger_text = "\nWarnings/Errors:" + logger_text + "\n\n"
- _lgr.log(logger_text)
-
- if(_new_summary.get_totals().tests > 0):
- var fmt = _lgr.fmts.green
- var msg = str(_new_summary.get_totals().passing) + ' passed ' + str(_new_summary.get_totals().failing) + ' failed. ' + \
- str("Tests finished in ", _gui.elapsed_time_as_str())
- if(_new_summary.get_totals().failing > 0):
- fmt = _lgr.fmts.red
- elif(_new_summary.get_totals().pending > 0):
- fmt = _lgr.fmts.yellow
-
- _lgr.log(msg, fmt)
- else:
- _lgr.log('No tests ran', _lgr.fmts.red)
-
-
-func _validate_hook_script(path):
- var result = {
- valid = true,
- instance = null
- }
-
- # empty path is valid but will have a null instance
- if(path == ''):
- return result
-
- var f = File.new()
- if(f.file_exists(path)):
- var inst = load(path).new()
- if(inst and inst is _utils.HookScript):
- result.instance = inst
- result.valid = true
- else:
- result.valid = false
- _lgr.error('The hook script [' + path + '] does not extend res://addons/gut/hook_script.gd')
- else:
- result.valid = false
- _lgr.error('The hook script [' + path + '] does not exist.')
-
- return result
-
-
-# ------------------------------------------------------------------------------
-# Runs a hook script. Script must exist, and must extend
-# res://addons/gut/hook_script.gd
-# ------------------------------------------------------------------------------
-func _run_hook_script(inst):
- if(inst != null):
- inst.gut = self
- inst.run()
- return inst
-
-# ------------------------------------------------------------------------------
-# Initialize variables for each run of a single test script.
-# ------------------------------------------------------------------------------
-func _init_run():
- var valid = true
- _test_collector.set_test_class_prefix(_inner_class_prefix)
- _test_script_objects = []
- _new_summary = _utils.Summary.new()
-
- _log_text = ""
-
- _current_test = null
-
- _is_running = true
-
- _yield_between.tests_since_last_yield = 0
-
- var pre_hook_result = _validate_hook_script(_pre_run_script)
- _pre_run_script_instance = pre_hook_result.instance
- var post_hook_result = _validate_hook_script(_post_run_script)
- _post_run_script_instance = post_hook_result.instance
-
- valid = pre_hook_result.valid and post_hook_result.valid
-
- return valid
-
-
-# ------------------------------------------------------------------------------
-# Print out run information and close out the run.
-# ------------------------------------------------------------------------------
-func _end_run():
- _gui.end_run()
- _print_summary()
- p("\n")
-
- # Do not count any of the _test_script_objects since these will be released
- # when GUT is released.
- _orphan_counter._counters.total += _test_script_objects.size()
- if(_orphan_counter.get_counter('total') > 0 and _lgr.is_type_enabled('orphan')):
- _orphan_counter.print_orphans('total', _lgr)
- p("Note: This count does not include GUT objects that will be freed upon exit.")
- p(" It also does not include any orphans created by global scripts")
- p(" loaded before tests were ran.")
- p(str("Total orphans = ", _orphan_counter.orphan_count()))
-
- if(!_utils.is_null_or_empty(_select_script)):
- p('Ran Scripts matching "' + _select_script + '"')
- if(!_utils.is_null_or_empty(_unit_test_name)):
- p('Ran Tests matching "' + _unit_test_name + '"')
- if(!_utils.is_null_or_empty(_inner_class_name)):
- p('Ran Inner Classes matching "' + _inner_class_name + '"')
-
- # For some reason the text edit control isn't scrolling to the bottom after
- # the summary is printed. As a workaround, yield for a short time and
- # then move the cursor. I found this workaround through trial and error.
- _yield_between.timer.set_wait_time(0.1)
- _yield_between.timer.start()
- yield(_yield_between.timer, 'timeout')
- _gui.scroll_to_bottom()
-
- _is_running = false
- update()
- _run_hook_script(_post_run_script_instance)
- emit_signal(SIGNAL_TESTS_FINISHED)
-
- _gui.set_title("Finished.")
-
-
-# ------------------------------------------------------------------------------
-# Checks the passed in thing to see if it is a "function state" object that gets
-# returned when a function yields.
-# ------------------------------------------------------------------------------
-func _is_function_state(script_result):
- return script_result != null and \
- typeof(script_result) == TYPE_OBJECT and \
- script_result is GDScriptFunctionState and \
- script_result.is_valid()
-
-# ------------------------------------------------------------------------------
-# Print out the heading for a new script
-# ------------------------------------------------------------------------------
-func _print_script_heading(script):
- if(_does_class_name_match(_inner_class_name, script.inner_class_name)):
- var fmt = _lgr.fmts.underline
- var divider = '-----------------------------------------'
-
- var text = ''
- if(script.inner_class_name == null):
- text = script.path
- else:
- text = script.path + '.' + script.inner_class_name
- _lgr.log("\n\n" + text, fmt)
-
- if(!_utils.is_null_or_empty(_inner_class_name) and _does_class_name_match(_inner_class_name, script.inner_class_name)):
- _lgr.log(str(' [',script.inner_class_name, '] matches [', _inner_class_name, ']'), fmt)
-
- if(!_utils.is_null_or_empty(_unit_test_name)):
- _lgr.log(' Only running tests like: "' + _unit_test_name + '"', fmt)
-
-
-# ------------------------------------------------------------------------------
-# Just gets more logic out of _test_the_scripts. Decides if we should yield after
-# this test based on flags and counters.
-# ------------------------------------------------------------------------------
-func _should_yield_now():
- var should = _yield_between.should and \
- _yield_between.tests_since_last_yield == _yield_between.after_x_tests
- if(should):
- _yield_between.tests_since_last_yield = 0
- else:
- _yield_between.tests_since_last_yield += 1
- return should
-
-# ------------------------------------------------------------------------------
-# Yes if the class name is null or the script's class name includes class_name
-# ------------------------------------------------------------------------------
-func _does_class_name_match(the_class_name, script_class_name):
- return (the_class_name == null or the_class_name == '') or (script_class_name != null and script_class_name.findn(the_class_name) != -1)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _setup_script(test_script):
- test_script.gut = self
- test_script.set_logger(_lgr)
- add_child(test_script)
- _test_script_objects.append(test_script)
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _do_yield_between(time):
- _yield_between.timer.set_wait_time(time)
- _yield_between.timer.start()
- return _yield_between.timer
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _wait_for_done(result):
- var iter_counter = 0
- var print_after = 3
-
- # callback method sets waiting to false.
- result.connect(COMPLETED, self, '_on_test_script_yield_completed')
- if(!_was_yield_method_called):
- _lgr.log('-- Yield detected, waiting --', _lgr.fmts.yellow)
-
- _was_yield_method_called = false
- _waiting = true
- _wait_timer.set_wait_time(0.4)
-
- var dots = ''
- while(_waiting):
- iter_counter += 1
- _lgr.yield_text('waiting' + dots)
- _wait_timer.start()
- yield(_wait_timer, 'timeout')
- dots += '.'
- if(dots.length() > 5):
- dots = ''
-
- _lgr.end_yield()
-
-# ------------------------------------------------------------------------------
-# returns self so it can be integrated into the yield call.
-# ------------------------------------------------------------------------------
-func _wait_for_continue_button():
- p(PAUSE_MESSAGE, 0)
- _waiting = true
- return self
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _call_deprecated_script_method(script, method, alt):
- if(script.has_method(method)):
- var txt = str(script, '-', method)
- if(!_deprecated_tracker.has(txt)):
- # Removing the deprecated line. I think it's still too early to
- # start bothering people with this. Left everything here though
- # because I don't want to remember how I did this last time.
- _lgr.deprecated(str('The method ', method, ' has been deprecated, use ', alt, ' instead.'))
- _deprecated_tracker.add(txt)
- script.call(method)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _get_indexes_matching_script_name(name):
- var indexes = [] # empty runs all
- for i in range(_test_collector.scripts.size()):
- if(_test_collector.scripts[i].get_filename().find(name) != -1):
- indexes.append(i)
- return indexes
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _get_indexes_matching_path(path):
- var indexes = []
- for i in range(_test_collector.scripts.size()):
- if(_test_collector.scripts[i].path == path):
- indexes.append(i)
- return indexes
-
-# ------------------------------------------------------------------------------
-# Execute all calls of a parameterized test.
-# ------------------------------------------------------------------------------
-func _run_parameterized_test(test_script, test_name):
- var script_result = _run_test(test_script, test_name)
- if(_is_function_state(script_result)):
- # _run_tests does _wait_for_done so just wait on it to complete
- yield(script_result, COMPLETED)
-
- if(_parameter_handler == null):
- _lgr.error(str('Parameterized test ', _current_test.name, ' did not call use_parameters for the default value of the parameter.'))
- _fail(str('Parameterized test ', _current_test.name, ' did not call use_parameters for the default value of the parameter.'))
- else:
- while(!_parameter_handler.is_done()):
- script_result = _run_test(test_script, test_name)
- if(_is_function_state(script_result)):
- # _run_tests does _wait_for_done so just wait on it to complete
- yield(script_result, COMPLETED)
-
- _parameter_handler = null
-
-
-# ------------------------------------------------------------------------------
-# Runs a single test given a test.gd instance and the name of the test to run.
-# ------------------------------------------------------------------------------
-func _run_test(script_inst, test_name):
- _lgr.log_test_name()
- _lgr.set_indent_level(1)
- _orphan_counter.add_counter('test')
- var script_result = null
-
- _call_deprecated_script_method(script_inst, 'setup', 'before_each')
- var before_each_result = script_inst.before_each()
- if(_is_function_state(before_each_result)):
- yield(_wait_for_done(before_each_result), COMPLETED)
-
- # When the script yields it will return a GDScriptFunctionState object
- script_result = script_inst.call(test_name)
- _new_summary.add_test(test_name)
-
- # Cannot detect future yields since we never tell the method to resume. If
- # there was some way to tell the method to resume we could use what comes
- # back from that to detect additional yields. I don't think this is
- # possible since we only know what the yield was for except when yield_for
- # and yield_to are used.
- if(_is_function_state(script_result)):
- yield(_wait_for_done(script_result), COMPLETED)
-
- # if the test called pause_before_teardown then yield until
- # the continue button is pressed.
- if(_pause_before_teardown and !_ignore_pause_before_teardown):
- _gui.pause()
- yield(_wait_for_continue_button(), SIGNAL_STOP_YIELD_BEFORE_TEARDOWN)
-
- script_inst.clear_signal_watcher()
-
- # call each post-each-test method until teardown is removed.
- _call_deprecated_script_method(script_inst, 'teardown', 'after_each')
- var after_each_result = script_inst.after_each()
- if(_is_function_state(after_each_result)):
- yield(_wait_for_done(after_each_result), COMPLETED)
-
- # Free up everything in the _autofree. Yield for a bit if we
- # have anything with a queue_free so that they have time to
- # free and are not found by the orphan counter.
- var aqf_count = _autofree.get_queue_free_count()
- _autofree.free_all()
- if(aqf_count > 0):
- yield(_do_yield_between(0.1), 'timeout')
-
- if(_log_level > 0):
- _orphan_counter.print_orphans('test', _lgr)
-
- _doubler.get_ignored_methods().clear()
-
-# ------------------------------------------------------------------------------
-# Calls after_all on the passed in test script and takes care of settings so all
-# logger output appears indented and with a proper heading
-#
-# Calls both pre-all-tests methods until prerun_setup is removed
-# ------------------------------------------------------------------------------
-func _call_before_all(test_script):
- _current_test = _before_all_test_obj
- _current_test.has_printed_name = false
- _lgr.inc_indent()
-
- # Next 3 lines can be removed when prerun_setup removed.
- _current_test.name = 'prerun_setup'
- _call_deprecated_script_method(test_script, 'prerun_setup', 'before_all')
- _current_test.name = 'before_all'
-
- var result = test_script.before_all()
- if(_is_function_state(result)):
- yield(_wait_for_done(result), COMPLETED)
-
- _lgr.dec_indent()
- _current_test = null
-
-# ------------------------------------------------------------------------------
-# Calls after_all on the passed in test script and takes care of settings so all
-# logger output appears indented and with a proper heading
-#
-# Calls both post-all-tests methods until postrun_teardown is removed.
-# ------------------------------------------------------------------------------
-func _call_after_all(test_script):
- _current_test = _after_all_test_obj
- _current_test.has_printed_name = false
- _lgr.inc_indent()
-
- # Next 3 lines can be removed when postrun_teardown removed.
- _current_test.name = 'postrun_teardown'
- _call_deprecated_script_method(test_script, 'postrun_teardown', 'after_all')
- _current_test.name = 'after_all'
-
- var result = test_script.after_all()
- if(_is_function_state(result)):
- yield(_wait_for_done(result), COMPLETED)
-
-
- _lgr.dec_indent()
- _current_test = null
-
-# ------------------------------------------------------------------------------
-# Run all tests in a script. This is the core logic for running tests.
-# ------------------------------------------------------------------------------
-func _test_the_scripts(indexes=[]):
- _orphan_counter.add_counter('total')
-
- _print_versions(false)
- var is_valid = _init_run()
- if(!is_valid):
- _lgr.error('Something went wrong and the run was aborted.')
- return
-
- _run_hook_script(_pre_run_script_instance)
- if(_pre_run_script_instance!= null and _pre_run_script_instance.should_abort()):
- _lgr.error('pre-run abort')
- emit_signal(SIGNAL_TESTS_FINISHED)
- return
-
- _gui.run_mode()
-
- var indexes_to_run = []
- if(indexes.size()==0):
- for i in range(_test_collector.scripts.size()):
- indexes_to_run.append(i)
- else:
- indexes_to_run = indexes
-
- _gui.set_progress_script_max(indexes_to_run.size()) # New way
- _gui.set_progress_script_value(0)
-
- if(_doubler.get_strategy() == _utils.DOUBLE_STRATEGY.FULL):
- _lgr.info("Using Double Strategy FULL as default strategy. Keep an eye out for weirdness, this is still experimental.")
-
- # loop through scripts
- for test_indexes in range(indexes_to_run.size()):
- var the_script = _test_collector.scripts[indexes_to_run[test_indexes]]
- _orphan_counter.add_counter('script')
-
- if(the_script.tests.size() > 0):
- _gui.set_title(the_script.get_full_name())
- _lgr.set_indent_level(0)
- _print_script_heading(the_script)
- _new_summary.add_script(the_script.get_full_name())
-
- var test_script = the_script.get_new()
- var script_result = null
- _setup_script(test_script)
- _doubler.set_strategy(_double_strategy)
-
- # yield between test scripts so things paint
- if(_yield_between.should):
- yield(_do_yield_between(0.01), 'timeout')
-
- # !!!
- # Hack so there isn't another indent to this monster of a method. if
- # inner class is set and we do not have a match then empty the tests
- # for the current test.
- # !!!
- if(!_does_class_name_match(_inner_class_name, the_script.inner_class_name)):
- the_script.tests = []
- else:
- var before_all_result = _call_before_all(test_script)
- if(_is_function_state(before_all_result)):
- # _call_before_all calls _wait for done, just wait for that to finish
- yield(before_all_result, COMPLETED)
-
-
- _gui.set_progress_test_max(the_script.tests.size()) # New way
-
- # Each test in the script
- for i in range(the_script.tests.size()):
- _stubber.clear()
- _spy.clear()
- _doubler.clear_output_directory()
- _current_test = the_script.tests[i]
- script_result = null
-
- if((_unit_test_name != '' and _current_test.name.find(_unit_test_name) > -1) or
- (_unit_test_name == '')):
-
- # yield so things paint
- if(_should_yield_now()):
- yield(_do_yield_between(0.001), 'timeout')
-
- if(_current_test.arg_count > 1):
- _lgr.error(str('Parameterized test ', _current_test.name,
- ' has too many parameters: ', _current_test.arg_count, '.'))
- elif(_current_test.arg_count == 1):
- script_result = _run_parameterized_test(test_script, _current_test.name)
- else:
- script_result = _run_test(test_script, _current_test.name)
-
- if(_is_function_state(script_result)):
- # _run_test calls _wait for done, just wait for that to finish
- yield(script_result, COMPLETED)
-
- if(_current_test.assert_count == 0 and !_current_test.pending):
- _lgr.warn('Test did not assert')
- _current_test.has_printed_name = false
- _gui.set_progress_test_value(i + 1)
- emit_signal('test_finished')
-
-
- _current_test = null
- _lgr.dec_indent()
- _orphan_counter.print_orphans('script', _lgr)
-
- if(_does_class_name_match(_inner_class_name, the_script.inner_class_name)):
- var after_all_result = _call_after_all(test_script)
- if(_is_function_state(after_all_result)):
- # _call_after_all calls _wait for done, just wait for that to finish
- yield(after_all_result, COMPLETED)
-
-
- _log_test_children_warning(test_script)
- # This might end up being very resource intensive if the scripts
- # don't clean up after themselves. Might have to consolidate output
- # into some other structure and kill the script objects with
- # test_script.free() instead of remove child.
- remove_child(test_script)
-
- _lgr.set_indent_level(0)
- if(test_script.get_assert_count() > 0):
- var script_sum = str(test_script.get_pass_count(), '/', test_script.get_assert_count(), ' passed.')
- _lgr.log(script_sum, _lgr.fmts.bold)
-
- _gui.set_progress_script_value(test_indexes + 1) # new way
- # END TEST SCRIPT LOOP
-
- _lgr.set_indent_level(0)
- _end_run()
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _pass(text=''):
- _gui.add_passing() # increments counters
- if(_current_test):
- _current_test.assert_count += 1
- _new_summary.add_pass(_current_test.name, text)
- else:
- if(_new_summary != null): # b/c of tests.
- _new_summary.add_pass('script level', text)
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _fail(text=''):
- _gui.add_failing() # increments counters
- if(_current_test != null):
- var line_text = ' at line ' + str(_extract_line_number(_current_test))
- p(line_text, LOG_LEVEL_FAIL_ONLY)
- # format for summary
- line_text = "\n " + line_text
- var call_count_text = ''
- if(_parameter_handler != null):
- call_count_text = str('(call #', _parameter_handler.get_call_count(), ') ')
- _new_summary.add_fail(_current_test.name, call_count_text + text + line_text)
- _current_test.passed = false
- _current_test.assert_count += 1
- else:
- if(_new_summary != null): # b/c of tests.
- _new_summary.add_fail('script level', text)
-
-
-# ------------------------------------------------------------------------------
-# Extracts the line number from curren stacktrace by matching the test case name
-# ------------------------------------------------------------------------------
-func _extract_line_number(current_test):
- var line_number = -1
- # if stack trace available than extraxt the test case line number
- var stackTrace = get_stack()
- if(stackTrace!=null):
- for index in stackTrace.size():
- var line = stackTrace[index]
- var function = line.get("function")
- if function == current_test.name:
- line_number = line.get("line")
- return line_number
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _pending(text=''):
- if(_current_test):
- _current_test.pending = true
- _new_summary.add_pending(_current_test.name, text)
-
-
-# ------------------------------------------------------------------------------
-# Gets all the files in a directory and all subdirectories if get_include_subdirectories
-# is true. The files returned are all sorted by name.
-# ------------------------------------------------------------------------------
-func _get_files(path, prefix, suffix):
- var files = []
- var directories = []
-
- var d = Directory.new()
- d.open(path)
- # true parameter tells list_dir_begin not to include "." and ".." directories.
- d.list_dir_begin(true)
-
- # Traversing a directory is kinda odd. You have to start the process of listing
- # the contents of a directory with list_dir_begin then use get_next until it
- # returns an empty string. Then I guess you should end it.
- var fs_item = d.get_next()
- var full_path = ''
- while(fs_item != ''):
- full_path = path.plus_file(fs_item)
-
- #file_exists returns fasle for directories
- if(d.file_exists(full_path)):
- if(fs_item.begins_with(prefix) and fs_item.ends_with(suffix)):
- files.append(full_path)
- elif(get_include_subdirectories() and d.dir_exists(full_path)):
- directories.append(full_path)
-
- fs_item = d.get_next()
- d.list_dir_end()
-
- for dir in range(directories.size()):
- var dir_files = _get_files(directories[dir], prefix, suffix)
- for i in range(dir_files.size()):
- files.append(dir_files[i])
-
- files.sort()
- return files
-
-
-#########################
-#
-# public
-#
-#########################
-
-# ------------------------------------------------------------------------------
-# Conditionally prints the text to the console/results variable based on the
-# current log level and what level is passed in. Whenever currently in a test,
-# the text will be indented under the test. It can be further indented if
-# desired.
-#
-# The first time output is generated when in a test, the test name will be
-# printed.
-#
-# NOT_USED_ANYMORE was indent level. This was deprecated in 7.0.0.
-# ------------------------------------------------------------------------------
-func p(text, level=0, NOT_USED_ANYMORE=-123):
- if(NOT_USED_ANYMORE != -123):
- _lgr.deprecated('gut.p no longer supports the optional 3rd parameter for indent_level parameter.')
- var str_text = str(text)
-
- if(level <= _utils.nvl(_log_level, 0)):
- _lgr.log(str_text)
-
-################
-#
-# RUN TESTS/ADD SCRIPTS
-#
-################
-func get_minimum_size():
- return Vector2(810, 380)
-
-
-# ------------------------------------------------------------------------------
-# Runs all the scripts that were added using add_script
-# ------------------------------------------------------------------------------
-func test_scripts(run_rest=false):
- clear_text()
-
- if(_script_name != null and _script_name != ''):
- var indexes = _get_indexes_matching_script_name(_script_name)
- if(indexes == []):
- _lgr.error('Could not find script matching ' + _script_name)
- else:
- _test_the_scripts(indexes)
- else:
- _test_the_scripts([])
-
-# alias
-func run_tests(run_rest=false):
- test_scripts(run_rest)
-
-
-# ------------------------------------------------------------------------------
-# Runs a single script passed in.
-# ------------------------------------------------------------------------------
-func test_script(script):
- _test_collector.set_test_class_prefix(_inner_class_prefix)
- _test_collector.clear()
- _test_collector.add_script(script)
- _test_the_scripts()
-
-
-# ------------------------------------------------------------------------------
-# Adds a script to be run when test_scripts called.
-# ------------------------------------------------------------------------------
-func add_script(script):
- if(!Engine.is_editor_hint()):
- _test_collector.set_test_class_prefix(_inner_class_prefix)
- _test_collector.add_script(script)
- _add_scripts_to_gui()
-
-
-# ------------------------------------------------------------------------------
-# Add all scripts in the specified directory that start with the prefix and end
-# with the suffix. Does not look in sub directories. Can be called multiple
-# times.
-# ------------------------------------------------------------------------------
-func add_directory(path, prefix=_file_prefix, suffix=_file_extension):
- # check for '' b/c the calls to addin the exported directories 1-6 will pass
- # '' if the field has not been populated. This will cause res:// to be
- # processed which will include all files if include_subdirectories is true.
- if(path == '' or path == null):
- return
-
- var d = Directory.new()
- if(!d.dir_exists(path)):
- _lgr.error(str('The path [', path, '] does not exist.'))
- OS.exit_code = 1
- else:
- var files = _get_files(path, prefix, suffix)
- for i in range(files.size()):
- add_script(files[i])
-
-
-# ------------------------------------------------------------------------------
-# This will try to find a script in the list of scripts to test that contains
-# the specified script name. It does not have to be a full match. It will
-# select the first matching occurrence so that this script will run when run_tests
-# is called. Works the same as the select_this_one option of add_script.
-#
-# returns whether it found a match or not
-# ------------------------------------------------------------------------------
-func select_script(script_name):
- _script_name = script_name
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func export_tests(path=_export_path):
- if(path == null):
- _lgr.error('You must pass a path or set the export_path before calling export_tests')
- else:
- var result = _test_collector.export_tests(path)
- if(result):
- p(_test_collector.to_s())
- p("Exported to " + path)
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func import_tests(path=_export_path):
- if(!_utils.file_exists(path)):
- _lgr.error(str('Cannot import tests: the path [', path, '] does not exist.'))
- else:
- _test_collector.clear()
- var result = _test_collector.import_tests(path)
- if(result):
- p(_test_collector.to_s())
- p("Imported from " + path)
- _add_scripts_to_gui()
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func import_tests_if_none_found():
- if(!_cancel_import and _test_collector.scripts.size() == 0):
- import_tests()
-
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func export_if_tests_found():
- if(_test_collector.scripts.size() > 0):
- export_tests()
-
-################
-#
-# MISC
-#
-################
-
-
-# ------------------------------------------------------------------------------
-# Maximize test runner window to fit the viewport.
-# ------------------------------------------------------------------------------
-func set_should_maximize(should):
- _should_maximize = should
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_should_maximize():
- return _should_maximize
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func maximize():
- _gui.maximize()
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func disable_strict_datatype_checks(should):
- _disable_strict_datatype_checks = should
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func is_strict_datatype_checks_disabled():
- return _disable_strict_datatype_checks
-
-# ------------------------------------------------------------------------------
-# Pauses the test and waits for you to press a confirmation button. Useful when
-# you want to watch a test play out onscreen or inspect results.
-# ------------------------------------------------------------------------------
-func end_yielded_test():
- _lgr.deprecated('end_yielded_test is no longer necessary, you can remove it.')
-
-# ------------------------------------------------------------------------------
-# Clears the text of the text box. This resets all counters.
-# ------------------------------------------------------------------------------
-func clear_text():
- _gui.clear_text()
- update()
-
-# ------------------------------------------------------------------------------
-# Get the number of tests that were ran
-# ------------------------------------------------------------------------------
-func get_test_count():
- return _new_summary.get_totals().tests
-
-# ------------------------------------------------------------------------------
-# Get the number of assertions that were made
-# ------------------------------------------------------------------------------
-func get_assert_count():
- var t = _new_summary.get_totals()
- return t.passing + t.failing
-
-# ------------------------------------------------------------------------------
-# Get the number of assertions that passed
-# ------------------------------------------------------------------------------
-func get_pass_count():
- return _new_summary.get_totals().passing
-
-# ------------------------------------------------------------------------------
-# Get the number of assertions that failed
-# ------------------------------------------------------------------------------
-func get_fail_count():
- return _new_summary.get_totals().failing
-
-# ------------------------------------------------------------------------------
-# Get the number of tests flagged as pending
-# ------------------------------------------------------------------------------
-func get_pending_count():
- return _new_summary.get_totals().pending
-
-# ------------------------------------------------------------------------------
-# Get the results of all tests ran as text. This string is the same as is
-# displayed in the text box, and similar to what is printed to the console.
-# ------------------------------------------------------------------------------
-func get_result_text():
- return _log_text
-
-# ------------------------------------------------------------------------------
-# Set the log level. Use one of the various LOG_LEVEL_* constants.
-# ------------------------------------------------------------------------------
-func set_log_level(level):
- _log_level = max(level, 0)
-
- # Level 0 settings
- _lgr.set_less_test_names(level == 0)
- # Explicitly always enabled
- _lgr.set_type_enabled(_lgr.types.normal, true)
- _lgr.set_type_enabled(_lgr.types.error, true)
- _lgr.set_type_enabled(_lgr.types.pending, true)
-
- # Level 1 types
- _lgr.set_type_enabled(_lgr.types.warn, level > 0)
- _lgr.set_type_enabled(_lgr.types.deprecated, level > 0)
-
- # Level 2 types
- _lgr.set_type_enabled(_lgr.types.passed, level > 1)
- _lgr.set_type_enabled(_lgr.types.info, level > 1)
- _lgr.set_type_enabled(_lgr.types.debug, level > 1)
-
- if(!Engine.is_editor_hint()):
- _gui.set_log_level(level)
-
-# ------------------------------------------------------------------------------
-# Get the current log level.
-# ------------------------------------------------------------------------------
-func get_log_level():
- return _log_level
-
-# ------------------------------------------------------------------------------
-# Call this method to make the test pause before teardown so that you can inspect
-# anything that you have rendered to the screen.
-# ------------------------------------------------------------------------------
-func pause_before_teardown():
- _pause_before_teardown = true;
-
-# ------------------------------------------------------------------------------
-# For batch processing purposes, you may want to ignore any calls to
-# pause_before_teardown that you forgot to remove.
-# ------------------------------------------------------------------------------
-func set_ignore_pause_before_teardown(should_ignore):
- _ignore_pause_before_teardown = should_ignore
- _gui.set_ignore_pause(should_ignore)
-
-func get_ignore_pause_before_teardown():
- return _ignore_pause_before_teardown
-
-# ------------------------------------------------------------------------------
-# Set to true so that painting of the screen will occur between tests. Allows you
-# to see the output as tests occur. Especially useful with long running tests that
-# make it appear as though it has humg.
-#
-# NOTE: not compatible with 1.0 so this is disabled by default. This will
-# change in future releases.
-# ------------------------------------------------------------------------------
-func set_yield_between_tests(should):
- _yield_between.should = should
-
-func get_yield_between_tests():
- return _yield_between.should
-
-# ------------------------------------------------------------------------------
-# Call _process or _fixed_process, if they exist, on obj and all it's children
-# and their children and so and so forth. Delta will be passed through to all
-# the _process or _fixed_process methods.
-# ------------------------------------------------------------------------------
-func simulate(obj, times, delta):
- for _i in range(times):
- if(obj.has_method("_process")):
- obj._process(delta)
- if(obj.has_method("_physics_process")):
- obj._physics_process(delta)
-
- for kid in obj.get_children():
- simulate(kid, 1, delta)
-
-# ------------------------------------------------------------------------------
-# Starts an internal timer with a timeout of the passed in time. A 'timeout'
-# signal will be sent when the timer ends. Returns itself so that it can be
-# used in a call to yield...cutting down on lines of code.
-#
-# Example, yield to the Gut object for 10 seconds:
-# yield(gut.set_yield_time(10), 'timeout')
-# ------------------------------------------------------------------------------
-func set_yield_time(time, text=''):
- _yield_timer.set_wait_time(time)
- _yield_timer.start()
- var msg = '-- Yielding (' + str(time) + 's)'
- if(text == ''):
- msg += ' --'
- else:
- msg += ': ' + text + ' --'
- _lgr.log(msg, _lgr.fmts.yellow)
- _was_yield_method_called = true
- return self
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_yield_signal_or_time(obj, signal_name, max_wait, text=''):
- obj.connect(signal_name, self, '_yielding_callback', [true])
- _yielding_to.obj = obj
- _yielding_to.signal_name = signal_name
-
- _yield_timer.set_wait_time(max_wait)
- _yield_timer.start()
- _was_yield_method_called = true
- _lgr.log(str('-- Yielding to signal "', signal_name, '" or for ', max_wait, ' seconds -- ', text), _lgr.fmts.yellow)
- return self
-
-# ------------------------------------------------------------------------------
-# get the specific unit test that should be run
-# ------------------------------------------------------------------------------
-func get_unit_test_name():
- return _unit_test_name
-
-# ------------------------------------------------------------------------------
-# set the specific unit test that should be run.
-# ------------------------------------------------------------------------------
-func set_unit_test_name(test_name):
- _unit_test_name = test_name
-
-# ------------------------------------------------------------------------------
-# Creates an empty file at the specified path
-# ------------------------------------------------------------------------------
-func file_touch(path):
- var f = File.new()
- f.open(path, f.WRITE)
- f.close()
-
-# ------------------------------------------------------------------------------
-# deletes the file at the specified path
-# ------------------------------------------------------------------------------
-func file_delete(path):
- var d = Directory.new()
- var result = d.open(path.get_base_dir())
- if(result == OK):
- d.remove(path)
-
-# ------------------------------------------------------------------------------
-# Checks to see if the passed in file has any data in it.
-# ------------------------------------------------------------------------------
-func is_file_empty(path):
- var f = File.new()
- f.open(path, f.READ)
- var empty = f.get_len() == 0
- f.close()
- return empty
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_file_as_text(path):
- return _utils.get_file_as_text(path)
-
-# ------------------------------------------------------------------------------
-# deletes all files in a given directory
-# ------------------------------------------------------------------------------
-func directory_delete_files(path):
- var d = Directory.new()
- var result = d.open(path)
-
- # SHORTCIRCUIT
- if(result != OK):
- return
-
- # Traversing a directory is kinda odd. You have to start the process of listing
- # the contents of a directory with list_dir_begin then use get_next until it
- # returns an empty string. Then I guess you should end it.
- d.list_dir_begin()
- var thing = d.get_next() # could be a dir or a file or something else maybe?
- var full_path = ''
- while(thing != ''):
- full_path = path + "/" + thing
- #file_exists returns fasle for directories
- if(d.file_exists(full_path)):
- d.remove(full_path)
- thing = d.get_next()
- d.list_dir_end()
-
-# ------------------------------------------------------------------------------
-# Returns the instantiated script object that is currently being run.
-# ------------------------------------------------------------------------------
-func get_current_script_object():
- var to_return = null
- if(_test_script_objects.size() > 0):
- to_return = _test_script_objects[-1]
- return to_return
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_current_test_object():
- return _current_test
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_stubber():
- return _stubber
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_doubler():
- return _doubler
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_spy():
- return _spy
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_temp_directory():
- return _temp_directory
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_temp_directory(temp_directory):
- _temp_directory = temp_directory
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_inner_class_name():
- return _inner_class_name
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_inner_class_name(inner_class_name):
- _inner_class_name = inner_class_name
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_summary():
- return _new_summary
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_double_strategy():
- return _double_strategy
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_double_strategy(double_strategy):
- _double_strategy = double_strategy
- _doubler.set_strategy(double_strategy)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_include_subdirectories():
- return _include_subdirectories
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_logger():
- return _lgr
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_logger(logger):
- _lgr = logger
- _lgr.set_gut(self)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_include_subdirectories(include_subdirectories):
- _include_subdirectories = include_subdirectories
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_test_collector():
- return _test_collector
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_export_path():
- return _export_path
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_export_path(export_path):
- _export_path = export_path
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_version():
- return _utils.version
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_pre_run_script():
- return _pre_run_script
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_pre_run_script(pre_run_script):
- _pre_run_script = pre_run_script
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_post_run_script():
- return _post_run_script
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_post_run_script(post_run_script):
- _post_run_script = post_run_script
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_pre_run_script_instance():
- return _pre_run_script_instance
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_post_run_script_instance():
- return _post_run_script_instance
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_color_output():
- return _color_output
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_color_output(color_output):
- _color_output = color_output
- _lgr.disable_formatting(!color_output)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_parameter_handler():
- return _parameter_handler
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func set_parameter_handler(parameter_handler):
- _parameter_handler = parameter_handler
- _parameter_handler.set_logger(_lgr)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_gui():
- return _gui
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_orphan_counter():
- return _orphan_counter
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func show_orphans(should):
- _lgr.set_type_enabled(_lgr.types.orphan, should)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func get_autofree():
- return _autofree
diff --git a/addons/gut/gut_cmdln.gd b/addons/gut/gut_cmdln.gd
deleted file mode 100644
index b1df4d3..0000000
--- a/addons/gut/gut_cmdln.gd
+++ /dev/null
@@ -1,402 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# Description
-# -----------
-# Command line interface for the GUT unit testing tool. Allows you to run tests
-# from the command line instead of running a scene. Place this script along with
-# gut.gd into your scripts directory at the root of your project. Once there you
-# can run this script (from the root of your project) using the following command:
-# godot -s -d test/gut/gut_cmdln.gd
-#
-# See the readme for a list of options and examples. You can also use the -gh
-# option to get more information about how to use the command line interface.
-# ##############################################################################
-extends SceneTree
-
-var Optparse = load('res://addons/gut/optparse.gd')
-var Gut = load('res://addons/gut/gut.gd')
-
-# ------------------------------------------------------------------------------
-# Helper class to resolve the various different places where an option can
-# be set. Using the get_value method will enforce the order of precedence of:
-# 1. command line value
-# 2. config file value
-# 3. default value
-#
-# The idea is that you set the base_opts. That will get you a copies of the
-# hash with null values for the other types of values. Lower precedented hashes
-# will punch through null values of higher precedented hashes.
-# ------------------------------------------------------------------------------
-class OptionResolver:
- var base_opts = null
- var cmd_opts = null
- var config_opts = null
-
-
- func get_value(key):
- return _nvl(cmd_opts[key], _nvl(config_opts[key], base_opts[key]))
-
- func set_base_opts(opts):
- base_opts = opts
- cmd_opts = _null_copy(opts)
- config_opts = _null_copy(opts)
-
- # creates a copy of a hash with all values null.
- func _null_copy(h):
- var new_hash = {}
- for key in h:
- new_hash[key] = null
- return new_hash
-
- func _nvl(a, b):
- if(a == null):
- return b
- else:
- return a
- func _string_it(h):
- var to_return = ''
- for key in h:
- to_return += str('(',key, ':', _nvl(h[key], 'NULL'), ')')
- return to_return
-
- func to_s():
- return str("base:\n", _string_it(base_opts), "\n", \
- "config:\n", _string_it(config_opts), "\n", \
- "cmd:\n", _string_it(cmd_opts), "\n", \
- "resolved:\n", _string_it(get_resolved_values()))
-
- func get_resolved_values():
- var to_return = {}
- for key in base_opts:
- to_return[key] = get_value(key)
- return to_return
-
- func to_s_verbose():
- var to_return = ''
- var resolved = get_resolved_values()
- for key in base_opts:
- to_return += str(key, "\n")
- to_return += str(' default: ', _nvl(base_opts[key], 'NULL'), "\n")
- to_return += str(' config: ', _nvl(config_opts[key], ' --'), "\n")
- to_return += str(' cmd: ', _nvl(cmd_opts[key], ' --'), "\n")
- to_return += str(' final: ', _nvl(resolved[key], 'NULL'), "\n")
-
- return to_return
-
-# ------------------------------------------------------------------------------
-# Here starts the actual script that uses the Options class to kick off Gut
-# and run your tests.
-# ------------------------------------------------------------------------------
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-# instance of gut
-var _tester = null
-# array of command line options specified
-var _final_opts = []
-# Hash for easier access to the options in the code. Options will be
-# extracted into this hash and then the hash will be used afterwards so
-# that I don't make any dumb typos and get the neat code-sense when I
-# type a dot.
-var options = {
- background_color = Color(.15, .15, .15, 1).to_html(),
- config_file = 'res://.gutconfig.json',
- dirs = [],
- disable_colors = false,
- double_strategy = 'partial',
- font_color = Color(.8, .8, .8, 1).to_html(),
- font_name = 'CourierPrime',
- font_size = 16,
- hide_orphans = false,
- ignore_pause = false,
- include_subdirs = false,
- inner_class = '',
- log_level = 1,
- opacity = 100,
- post_run_script = '',
- pre_run_script = '',
- prefix = 'test_',
- selected = '',
- should_exit = false,
- should_exit_on_success = false,
- should_maximize = false,
- show_help = false,
- suffix = '.gd',
- tests = [],
- unit_test_name = '',
-}
-var valid_fonts = ['AnonymousPro', 'CourierPro', 'LobsterTwo', 'Default']
-
-# flag to indicate if only a single script should be run.
-var _run_single = false
-
-
-func setup_options():
- var opts = Optparse.new()
- opts.set_banner(('This is the command line interface for the unit testing tool Gut. With this ' +
- 'interface you can run one or more test scripts from the command line. In order ' +
- 'for the Gut options to not clash with any other godot options, each option starts ' +
- 'with a "g". Also, any option that requires a value will take the form of ' +
- '"-g=". There cannot be any spaces between the option, the "=", or ' +
- 'inside a specified value or godot will think you are trying to run a scene.'))
- opts.add('-gtest', [], 'Comma delimited list of full paths to test scripts to run.')
- opts.add('-gdir', options.dirs, 'Comma delimited list of directories to add tests from.')
- opts.add('-gprefix', options.prefix, 'Prefix used to find tests when specifying -gdir. Default "[default]".')
- opts.add('-gsuffix', options.suffix, 'Suffix used to find tests when specifying -gdir. Default "[default]".')
- opts.add('-ghide_orphans', false, 'Display orphan counts for tests and scripts. Default "[default]".')
- opts.add('-gmaximize', false, 'Maximizes test runner window to fit the viewport.')
- opts.add('-gexit', false, 'Exit after running tests. If not specified you have to manually close the window.')
- opts.add('-gexit_on_success', false, 'Only exit if all tests pass.')
- opts.add('-glog', options.log_level, 'Log level. Default [default]')
- opts.add('-gignore_pause', false, 'Ignores any calls to gut.pause_before_teardown.')
- opts.add('-gselect', '', ('Select a script to run initially. The first script that ' +
- 'was loaded using -gtest or -gdir that contains the specified ' +
- 'string will be executed. You may run others by interacting ' +
- 'with the GUI.'))
- opts.add('-gunit_test_name', '', ('Name of a test to run. Any test that contains the specified ' +
- 'text will be run, all others will be skipped.'))
- opts.add('-gh', false, 'Print this help, then quit')
- opts.add('-gconfig', 'res://.gutconfig.json', 'A config file that contains configuration information. Default is res://.gutconfig.json')
- opts.add('-ginner_class', '', 'Only run inner classes that contain this string')
- opts.add('-gopacity', options.opacity, 'Set opacity of test runner window. Use range 0 - 100. 0 = transparent, 100 = opaque.')
- opts.add('-gpo', false, 'Print option values from all sources and the value used, then quit.')
- opts.add('-ginclude_subdirs', false, 'Include subdirectories of -gdir.')
- opts.add('-gdouble_strategy', 'partial', 'Default strategy to use when doubling. Valid values are [partial, full]. Default "[default]"')
- opts.add('-gdisable_colors', false, 'Disable command line colors.')
- opts.add('-gpre_run_script', '', 'pre-run hook script path')
- opts.add('-gpost_run_script', '', 'post-run hook script path')
- opts.add('-gprint_gutconfig_sample', false, 'Print out json that can be used to make a gutconfig file then quit.')
-
- opts.add('-gfont_name', options.font_name, str('Valid values are: ', valid_fonts, '. Default "[default]"'))
- opts.add('-gfont_size', options.font_size, 'Font size, default "[default]"')
- opts.add('-gbackground_color', options.background_color, 'Background color as an html color, default "[default]"')
- opts.add('-gfont_color',options.font_color, 'Font color as an html color, default "[default]"')
- return opts
-
-
-# Parses options, applying them to the _tester or setting values
-# in the options struct.
-func extract_command_line_options(from, to):
- to.config_file = from.get_value('-gconfig')
- to.dirs = from.get_value('-gdir')
- to.disable_colors = from.get_value('-gdisable_colors')
- to.double_strategy = from.get_value('-gdouble_strategy')
- to.ignore_pause = from.get_value('-gignore_pause')
- to.include_subdirs = from.get_value('-ginclude_subdirs')
- to.inner_class = from.get_value('-ginner_class')
- to.log_level = from.get_value('-glog')
- to.opacity = from.get_value('-gopacity')
- to.post_run_script = from.get_value('-gpost_run_script')
- to.pre_run_script = from.get_value('-gpre_run_script')
- to.prefix = from.get_value('-gprefix')
- to.selected = from.get_value('-gselect')
- to.should_exit = from.get_value('-gexit')
- to.should_exit_on_success = from.get_value('-gexit_on_success')
- to.should_maximize = from.get_value('-gmaximize')
- to.hide_orphans = from.get_value('-ghide_orphans')
- to.suffix = from.get_value('-gsuffix')
- to.tests = from.get_value('-gtest')
- to.unit_test_name = from.get_value('-gunit_test_name')
-
- to.font_size = from.get_value('-gfont_size')
- to.font_name = from.get_value('-gfont_name')
- to.background_color = from.get_value('-gbackground_color')
- to.font_color = from.get_value('-gfont_color')
-
-
-func load_options_from_config_file(file_path, into):
- # SHORTCIRCUIT
- var f = File.new()
- if(!f.file_exists(file_path)):
- if(file_path != 'res://.gutconfig.json'):
- print('ERROR: Config File "', file_path, '" does not exist.')
- return -1
- else:
- return 1
-
- f.open(file_path, f.READ)
- var json = f.get_as_text()
- f.close()
-
- var results = JSON.parse(json)
- # SHORTCIRCUIT
- if(results.error != OK):
- print("\n\n",'!! ERROR parsing file: ', file_path)
- print(' at line ', results.error_line, ':')
- print(' ', results.error_string)
- return -1
-
- # Get all the options out of the config file using the option name. The
- # options hash is now the default source of truth for the name of an option.
- for key in into:
- if(results.result.has(key)):
- into[key] = results.result[key]
-
- return 1
-
-
-# Apply all the options specified to _tester. This is where the rubber meets
-# the road.
-func apply_options(opts):
- _tester = Gut.new()
- get_root().add_child(_tester)
- _tester.connect('tests_finished', self, '_on_tests_finished', [opts.should_exit, opts.should_exit_on_success])
- _tester.set_yield_between_tests(true)
- _tester.set_modulate(Color(1.0, 1.0, 1.0, min(1.0, float(opts.opacity) / 100)))
- _tester.show()
-
- _tester.set_include_subdirectories(opts.include_subdirs)
-
- if(opts.should_maximize):
- _tester.maximize()
-
- if(opts.inner_class != ''):
- _tester.set_inner_class_name(opts.inner_class)
- _tester.set_log_level(opts.log_level)
- _tester.set_ignore_pause_before_teardown(opts.ignore_pause)
-
- for i in range(opts.dirs.size()):
- _tester.add_directory(opts.dirs[i], opts.prefix, opts.suffix)
-
- for i in range(opts.tests.size()):
- _tester.add_script(opts.tests[i])
-
- if(opts.selected != ''):
- _tester.select_script(opts.selected)
- _run_single = true
-
- if(opts.double_strategy == 'full'):
- _tester.set_double_strategy(_utils.DOUBLE_STRATEGY.FULL)
- elif(opts.double_strategy == 'partial'):
- _tester.set_double_strategy(_utils.DOUBLE_STRATEGY.PARTIAL)
-
- _tester.set_unit_test_name(opts.unit_test_name)
- _tester.set_pre_run_script(opts.pre_run_script)
- _tester.set_post_run_script(opts.post_run_script)
- _tester.set_color_output(!opts.disable_colors)
- _tester.show_orphans(!opts.hide_orphans)
-
- _tester.get_gui().set_font_size(opts.font_size)
- _tester.get_gui().set_font(opts.font_name)
- if(opts.font_color != null and opts.font_color.is_valid_html_color()):
- _tester.get_gui().set_default_font_color(Color(opts.font_color))
- if(opts.background_color != null and opts.background_color.is_valid_html_color()):
- _tester.get_gui().set_background_color(Color(opts.background_color))
-
-
-func _print_gutconfigs(values):
- var header = """Here is a sample of a full .gutconfig.json file.
-You do not need to specify all values in your own file. The values supplied in
-this sample are what would be used if you ran gut w/o the -gprint_gutconfig_sample
-option (the resolved values where default < .gutconfig < command line)."""
- print("\n", header.replace("\n", ' '), "\n\n")
- var resolved = values
-
- # remove some options that don't make sense to be in config
- resolved.erase("config_file")
- resolved.erase("show_help")
-
- print("Here's a config with all the properties set based off of your current command and config.")
- var text = JSON.print(resolved)
- print(text.replace(',', ",\n"))
-
- for key in resolved:
- resolved[key] = null
-
- print("\n\nAnd here's an empty config for you fill in what you want.")
- text = JSON.print(resolved)
- print(text.replace(',', ",\n"))
-
-
-# parse options and run Gut
-func _run_gut():
- var opt_resolver = OptionResolver.new()
- opt_resolver.set_base_opts(options)
-
- print("\n\n", ' --- Gut ---')
- var o = setup_options()
-
- var all_options_valid = o.parse()
- extract_command_line_options(o, opt_resolver.cmd_opts)
- var load_result = \
- load_options_from_config_file(opt_resolver.get_value('config_file'), opt_resolver.config_opts)
-
- if(load_result == -1): # -1 indicates json parse error
- quit(1)
- else:
- if(!all_options_valid):
- quit(1)
- elif(o.get_value('-gh')):
- print(_utils.get_version_text())
- o.print_help()
- quit()
- elif(o.get_value('-gpo')):
- print('All command line options and where they are specified. ' +
- 'The "final" value shows which value will actually be used ' +
- 'based on order of precedence (default < .gutconfig < cmd line).' + "\n")
- print(opt_resolver.to_s_verbose())
- quit()
- elif(o.get_value('-gprint_gutconfig_sample')):
- _print_gutconfigs(opt_resolver.get_resolved_values())
- quit()
- else:
- _final_opts = opt_resolver.get_resolved_values();
- apply_options(_final_opts)
- _tester.test_scripts(!_run_single)
-
-
-# exit if option is set.
-func _on_tests_finished(should_exit, should_exit_on_success):
- if(_final_opts.dirs.size() == 0):
- if(_tester.get_summary().get_totals().scripts == 0):
- var lgr = _tester.get_logger()
- lgr.error('No directories configured. Add directories with options or a .gutconfig.json file. Use the -gh option for more information.')
-
- if(_tester.get_fail_count()):
- OS.exit_code = 1
-
- # Overwrite the exit code with the post_script
- var post_inst = _tester.get_post_run_script_instance()
- if(post_inst != null and post_inst.get_exit_code() != null):
- OS.exit_code = post_inst.get_exit_code()
-
- if(should_exit or (should_exit_on_success and _tester.get_fail_count() == 0)):
- quit()
- else:
- print("Tests finished, exit manually")
-
-# ------------------------------------------------------------------------------
-# MAIN
-# ------------------------------------------------------------------------------
-func _init():
- if(!_utils.is_version_ok()):
- print("\n\n", _utils.get_version_text())
- push_error(_utils.get_bad_version_text())
- OS.exit_code = 1
- quit()
- else:
- _run_gut()
diff --git a/addons/gut/gut_plugin.gd b/addons/gut/gut_plugin.gd
deleted file mode 100644
index 8981f28..0000000
--- a/addons/gut/gut_plugin.gd
+++ /dev/null
@@ -1,12 +0,0 @@
-tool
-extends EditorPlugin
-
-func _enter_tree():
- # Initialization of the plugin goes here
- # Add the new type with a name, a parent type, a script and an icon
- add_custom_type("Gut", "Control", preload("plugin_control.gd"), preload("icon.png"))
-
-func _exit_tree():
- # Clean-up of the plugin goes here
- # Always remember to remove it from the engine when deactivated
- remove_custom_type("Gut")
diff --git a/addons/gut/hook_script.gd b/addons/gut/hook_script.gd
deleted file mode 100644
index 10a5e12..0000000
--- a/addons/gut/hook_script.gd
+++ /dev/null
@@ -1,35 +0,0 @@
-# ------------------------------------------------------------------------------
-# This script is the base for custom scripts to be used in pre and post
-# run hooks.
-# ------------------------------------------------------------------------------
-
-# This is the instance of GUT that is running the tests. You can get
-# information about the run from this object. This is set by GUT when the
-# script is instantiated.
-var gut = null
-
-# the exit code to be used by gut_cmdln. See set method.
-var _exit_code = null
-
-var _should_abort = false
-# Virtual method that will be called by GUT after instantiating
-# this script.
-func run():
- pass
-
-# Set the exit code when running from the command line. If not set then the
-# default exit code will be returned (0 when no tests fail, 1 when any tests
-# fail).
-func set_exit_code(code):
- _exit_code = code
-
-func get_exit_code():
- return _exit_code
-
-# Usable by pre-run script to cause the run to end AFTER the run() method
-# finishes. post-run script will not be ran.
-func abort():
- _should_abort = true
-
-func should_abort():
- return _should_abort
diff --git a/addons/gut/icon.png b/addons/gut/icon.png
deleted file mode 100644
index 9ad6a1d..0000000
Binary files a/addons/gut/icon.png and /dev/null differ
diff --git a/addons/gut/logger.gd b/addons/gut/logger.gd
deleted file mode 100644
index 900b928..0000000
--- a/addons/gut/logger.gd
+++ /dev/null
@@ -1,348 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# This class wraps around the various printers and supplies formatting for the
-# various message types (error, warning, etc).
-# ##############################################################################
-var types = {
- debug = 'debug',
- deprecated = 'deprecated',
- error = 'error',
- failed = 'failed',
- info = 'info',
- normal = 'normal',
- orphan = 'orphan',
- passed = 'passed',
- pending = 'pending',
- warn ='warn',
-}
-
-var fmts = {
- red = 'red',
- yellow = 'yellow',
- green = 'green',
-
- bold = 'bold',
- underline = 'underline',
-
- none = null
-}
-
-var _type_data = {
- types.debug: {disp='DEBUG', enabled=true, fmt=fmts.none},
- types.deprecated: {disp='DEPRECATED', enabled=true, fmt=fmts.none},
- types.error: {disp='ERROR', enabled=true, fmt=fmts.red},
- types.failed: {disp='Failed', enabled=true, fmt=fmts.red},
- types.info: {disp='INFO', enabled=true, fmt=fmts.bold},
- types.normal: {disp='NORMAL', enabled=true, fmt=fmts.none},
- types.orphan: {disp='Orphans', enabled=true, fmt=fmts.yellow},
- types.passed: {disp='Passed', enabled=true, fmt=fmts.green},
- types.pending: {disp='Pending', enabled=true, fmt=fmts.yellow},
- types.warn: {disp='WARNING', enabled=true, fmt=fmts.yellow},
-}
-
-var _logs = {
- types.warn: [],
- types.error: [],
- types.info: [],
- types.debug: [],
- types.deprecated: [],
-}
-
-var _printers = {
- terminal = null,
- gui = null,
- console = null
-}
-
-var _gut = null
-var _utils = null
-var _indent_level = 0
-var _indent_string = ' '
-var _skip_test_name_for_testing = false
-var _less_test_names = false
-var _yield_calls = 0
-var _last_yield_text = ''
-
-
-func _init():
- _utils = load('res://addons/gut/utils.gd').get_instance()
- _printers.terminal = _utils.Printers.TerminalPrinter.new()
- _printers.console = _utils.Printers.ConsolePrinter.new()
- # There were some problems in the timing of disabling this at the right
- # time in gut_cmdln so it is disabled by default. This is enabled
- # by plugin_control.gd based on settings.
- _printers.console.set_disabled(true)
-
-func get_indent_text():
- var pad = ''
- for i in range(_indent_level):
- pad += _indent_string
-
- return pad
-
-func _indent_text(text):
- var to_return = text
- var ending_newline = ''
-
- if(text.ends_with("\n")):
- ending_newline = "\n"
- to_return = to_return.left(to_return.length() -1)
-
- var pad = get_indent_text()
- to_return = to_return.replace("\n", "\n" + pad)
- to_return += ending_newline
-
- return pad + to_return
-
-func _should_print_to_printer(key_name):
- return _printers[key_name] != null and !_printers[key_name].get_disabled()
-
-func _print_test_name():
- if(_gut == null):
- return
- var cur_test = _gut.get_current_test_object()
- if(cur_test == null):
- return false
-
- if(!cur_test.has_printed_name):
- _output('* ' + cur_test.name + "\n")
- cur_test.has_printed_name = true
-
-func _output(text, fmt=null):
- for key in _printers:
- if(_should_print_to_printer(key)):
- var info = ''#str(self, ':', key, ':', _printers[key], '| ')
- _printers[key].send(info + text, fmt)
-
-func _log(text, fmt=fmts.none):
- _print_test_name()
- var indented = _indent_text(text)
- _output(indented, fmt)
-
-# ---------------
-# Get Methods
-# ---------------
-func get_warnings():
- return get_log_entries(types.warn)
-
-func get_errors():
- return get_log_entries(types.error)
-
-func get_infos():
- return get_log_entries(types.info)
-
-func get_debugs():
- return get_log_entries(types.debug)
-
-func get_deprecated():
- return get_log_entries(types.deprecated)
-
-func get_count(log_type=null):
- var count = 0
- if(log_type == null):
- for key in _logs:
- count += _logs[key].size()
- else:
- count = _logs[log_type].size()
- return count
-
-func get_log_entries(log_type):
- return _logs[log_type]
-
-# ---------------
-# Log methods
-# ---------------
-func _output_type(type, text):
- var td = _type_data[type]
- if(!td.enabled):
- return
-
- _print_test_name()
- if(type != types.normal):
- if(_logs.has(type)):
- _logs[type].append(text)
-
- var start = str('[', td.disp, ']')
- if(text != null and text != ''):
- start += ': '
- else:
- start += ' '
- var indented_start = _indent_text(start)
- var indented_end = _indent_text(text)
- indented_end = indented_end.lstrip(_indent_string)
- _output(indented_start, td.fmt)
- _output(indented_end + "\n")
-
-func debug(text):
- _output_type(types.debug, text)
-
-# supply some text or the name of the deprecated method and the replacement.
-func deprecated(text, alt_method=null):
- var msg = text
- if(alt_method):
- msg = str('The method ', text, ' is deprecated, use ', alt_method , ' instead.')
- return _output_type(types.deprecated, msg)
-
-func error(text):
- _output_type(types.error, text)
-
-func failed(text):
- _output_type(types.failed, text)
-
-func info(text):
- _output_type(types.info, text)
-
-func orphan(text):
- _output_type(types.orphan, text)
-
-func passed(text):
- _output_type(types.passed, text)
-
-func pending(text):
- _output_type(types.pending, text)
-
-func warn(text):
- _output_type(types.warn, text)
-
-func log(text='', fmt=fmts.none):
- end_yield()
- if(text == ''):
- _output("\n")
- else:
- _log(text + "\n", fmt)
- return null
-
-func lograw(text, fmt=fmts.none):
- return _output(text, fmt)
-
-# Print the test name if we aren't skipping names of tests that pass (basically
-# what _less_test_names means))
-func log_test_name():
- # suppress output if we haven't printed the test name yet and
- # what to print is the test name.
- if(!_less_test_names):
- _print_test_name()
-
-# ---------------
-# Misc
-# ---------------
-func get_gut():
- return _gut
-
-func set_gut(gut):
- _gut = gut
- if(_gut == null):
- _printers.gui = null
- else:
- if(_printers.gui == null):
- _printers.gui = _utils.Printers.GutGuiPrinter.new()
- _printers.gui.set_gut(gut)
-
-func get_indent_level():
- return _indent_level
-
-func set_indent_level(indent_level):
- _indent_level = indent_level
-
-func get_indent_string():
- return _indent_string
-
-func set_indent_string(indent_string):
- _indent_string = indent_string
-
-func clear():
- for key in _logs:
- _logs[key].clear()
-
-func inc_indent():
- _indent_level += 1
-
-func dec_indent():
- _indent_level = max(0, _indent_level -1)
-
-func is_type_enabled(type):
- return _type_data[type].enabled
-
-func set_type_enabled(type, is_enabled):
- _type_data[type].enabled = is_enabled
-
-func get_less_test_names():
- return _less_test_names
-
-func set_less_test_names(less_test_names):
- _less_test_names = less_test_names
-
-func disable_printer(name, is_disabled):
- _printers[name].set_disabled(is_disabled)
-
-func is_printer_disabled(name):
- return _printers[name].get_disabled()
-
-func disable_formatting(is_disabled):
- for key in _printers:
- _printers[key].set_format_enabled(!is_disabled)
-
-func get_printer(printer_key):
- return _printers[printer_key]
-
-func _yield_text_terminal(text):
- var printer = _printers['terminal']
- if(_yield_calls != 0):
- printer.clear_line()
- printer.back(_last_yield_text.length())
- printer.send(text, fmts.yellow)
-
-func _end_yield_terminal():
- var printer = _printers['terminal']
- printer.clear_line()
- printer.back(_last_yield_text.length())
-
-func _yield_text_gui(text):
- var lbl = _gut.get_gui().get_waiting_label()
- lbl.visible = true
- lbl.set_bbcode('[color=yellow]' + text + '[/color]')
-
-func _end_yield_gui():
- var lbl = _gut.get_gui().get_waiting_label()
- lbl.visible = false
- lbl.set_text('')
-
-func yield_text(text):
- _yield_text_terminal(text)
- _yield_text_gui(text)
- _last_yield_text = text
- _yield_calls += 1
-
-func end_yield():
- if(_yield_calls == 0):
- return
- _end_yield_terminal()
- _end_yield_gui()
- _yield_calls = 0
- _last_yield_text = ''
diff --git a/addons/gut/method_maker.gd b/addons/gut/method_maker.gd
deleted file mode 100644
index 0415b88..0000000
--- a/addons/gut/method_maker.gd
+++ /dev/null
@@ -1,213 +0,0 @@
-# This class will generate method declaration lines based on method meta
-# data. It will create defaults that match the method data.
-#
-# --------------------
-# function meta data
-# --------------------
-# name:
-# flags:
-# args: [{
-# (class_name:),
-# (hint:0),
-# (hint_string:),
-# (name:),
-# (type:4),
-# (usage:7)
-# }]
-# default_args []
-
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _lgr = _utils.get_logger()
-const PARAM_PREFIX = 'p_'
-
-# ------------------------------------------------------
-# _supported_defaults
-#
-# This array contains all the data types that are supported for default values.
-# If a value is supported it will contain either an empty string or a prefix
-# that should be used when setting the parameter default value.
-# For example int, real, bool do not need anything func(p1=1, p2=2.2, p3=false)
-# but things like Vectors and Colors do since only the parameters to create a
-# new Vector or Color are included in the metadata.
-# ------------------------------------------------------
- # TYPE_NIL = 0 — Variable is of type nil (only applied for null).
- # TYPE_BOOL = 1 — Variable is of type bool.
- # TYPE_INT = 2 — Variable is of type int.
- # TYPE_REAL = 3 — Variable is of type float/real.
- # TYPE_STRING = 4 — Variable is of type String.
- # TYPE_VECTOR2 = 5 — Variable is of type Vector2.
- # TYPE_RECT2 = 6 — Variable is of type Rect2.
- # TYPE_VECTOR3 = 7 — Variable is of type Vector3.
- # TYPE_COLOR = 14 — Variable is of type Color.
- # TYPE_OBJECT = 17 — Variable is of type Object.
- # TYPE_DICTIONARY = 18 — Variable is of type Dictionary.
- # TYPE_ARRAY = 19 — Variable is of type Array.
- # TYPE_VECTOR2_ARRAY = 24 — Variable is of type PoolVector2Array.
-
-
-
-# TYPE_TRANSFORM2D = 8 — Variable is of type Transform2D.
-# TYPE_PLANE = 9 — Variable is of type Plane.
-# TYPE_QUAT = 10 — Variable is of type Quat.
-# TYPE_AABB = 11 — Variable is of type AABB.
-# TYPE_BASIS = 12 — Variable is of type Basis.
-# TYPE_TRANSFORM = 13 — Variable is of type Transform.
-# TYPE_NODE_PATH = 15 — Variable is of type NodePath.
-# TYPE_RID = 16 — Variable is of type RID.
-# TYPE_RAW_ARRAY = 20 — Variable is of type PoolByteArray.
-# TYPE_INT_ARRAY = 21 — Variable is of type PoolIntArray.
-# TYPE_REAL_ARRAY = 22 — Variable is of type PoolRealArray.
-# TYPE_STRING_ARRAY = 23 — Variable is of type PoolStringArray.
-# TYPE_VECTOR3_ARRAY = 25 — Variable is of type PoolVector3Array.
-# TYPE_COLOR_ARRAY = 26 — Variable is of type PoolColorArray.
-# TYPE_MAX = 27 — Marker for end of type constants.
-# ------------------------------------------------------
-var _supported_defaults = []
-
-func _init():
- for _i in range(TYPE_MAX):
- _supported_defaults.append(null)
-
- # These types do not require a prefix for defaults
- _supported_defaults[TYPE_NIL] = ''
- _supported_defaults[TYPE_BOOL] = ''
- _supported_defaults[TYPE_INT] = ''
- _supported_defaults[TYPE_REAL] = ''
- _supported_defaults[TYPE_OBJECT] = ''
- _supported_defaults[TYPE_ARRAY] = ''
- _supported_defaults[TYPE_STRING] = ''
- _supported_defaults[TYPE_DICTIONARY] = ''
- _supported_defaults[TYPE_VECTOR2_ARRAY] = ''
-
- # These require a prefix for whatever default is provided
- _supported_defaults[TYPE_VECTOR2] = 'Vector2'
- _supported_defaults[TYPE_RECT2] = 'Rect2'
- _supported_defaults[TYPE_VECTOR3] = 'Vector3'
- _supported_defaults[TYPE_COLOR] = 'Color'
-
-# ###############
-# Private
-# ###############
-var _func_text = _utils.get_file_as_text('res://addons/gut/double_templates/function_template.txt')
-
-func _is_supported_default(type_flag):
- return type_flag >= 0 and type_flag < _supported_defaults.size() and [type_flag] != null
-
-# Creates a list of parameters with defaults of null unless a default value is
-# found in the metadata. If a default is found in the meta then it is used if
-# it is one we know how support.
-#
-# If a default is found that we don't know how to handle then this method will
-# return null.
-func _get_arg_text(method_meta):
- var text = ''
- var args = method_meta.args
- var defaults = []
- var has_unsupported_defaults = false
-
- # fill up the defaults with null defaults for everything that doesn't have
- # a default in the meta data. default_args is an array of default values
- # for the last n parameters where n is the size of default_args so we only
- # add nulls for everything up to the first parameter with a default.
- for _i in range(args.size() - method_meta.default_args.size()):
- defaults.append('null')
-
- # Add meta-data defaults.
- for i in range(method_meta.default_args.size()):
- var t = args[defaults.size()]['type']
- var value = ''
- if(_is_supported_default(t)):
- # strings are special, they need quotes around the value
- if(t == TYPE_STRING):
- value = str("'", str(method_meta.default_args[i]), "'")
- # Colors need the parens but things like Vector2 and Rect2 don't
- elif(t == TYPE_COLOR):
- value = str(_supported_defaults[t], '(', str(method_meta.default_args[i]), ')')
- elif(t == TYPE_OBJECT):
- if(str(method_meta.default_args[i]) == "[Object:null]"):
- value = str(_supported_defaults[t], 'null')
- else:
- value = str(_supported_defaults[t], str(method_meta.default_args[i]).to_lower())
-
- # Everything else puts the prefix (if one is there) form _supported_defaults
- # in front. The to_lower is used b/c for some reason the defaults for
- # null, true, false are all "Null", "True", "False".
- else:
- value = str(_supported_defaults[t], str(method_meta.default_args[i]).to_lower())
- else:
- _lgr.warn(str(
- 'Unsupported default param type: ',method_meta.name, '-', args[defaults.size()].name, ' ', t, ' = ', method_meta.default_args[i]))
- value = str('unsupported=',t)
- has_unsupported_defaults = true
-
- defaults.append(value)
-
- # construct the string of parameters
- for i in range(args.size()):
- text += str(PARAM_PREFIX, args[i].name, '=', defaults[i])
- if(i != args.size() -1):
- text += ', '
-
- # if we don't know how to make a default then we have to return null b/c
- # it will cause a runtime error and it's one thing we could return to let
- # callers know it didn't work.
- if(has_unsupported_defaults):
- text = null
-
- return text
-
-# ###############
-# Public
-# ###############
-
-# Creates a delceration for a function based off of function metadata. All
-# types whose defaults are supported will have their values. If a datatype
-# is not supported and the parameter has a default, a warning message will be
-# printed and the declaration will return null.
-func get_function_text(meta):
- var method_params = _get_arg_text(meta)
- var text = null
-
- var param_array = get_spy_call_parameters_text(meta)
- if(param_array == 'null'):
- param_array = '[]'
-
- if(method_params != null):
- var decleration = str('func ', meta.name, '(', method_params, '):')
- text = _func_text.format({
- "func_decleration":decleration,
- "method_name":meta.name,
- "param_array":param_array,
- "super_call":get_super_call_text(meta)
- })
- return text
-
-# creates a call to the function in meta in the super's class.
-func get_super_call_text(meta):
- var params = ''
-
- for i in range(meta.args.size()):
- params += PARAM_PREFIX + meta.args[i].name
- if(meta.args.size() > 1 and i != meta.args.size() -1):
- params += ', '
- if(meta.name == '_init'):
- return 'null'
- else:
- return str('.', meta.name, '(', params, ')')
-
-func get_spy_call_parameters_text(meta):
- var called_with = 'null'
- if(meta.args.size() > 0):
- called_with = '['
- for i in range(meta.args.size()):
- called_with += str(PARAM_PREFIX, meta.args[i].name)
- if(i < meta.args.size() - 1):
- called_with += ', '
- called_with += ']'
- return called_with
-
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
diff --git a/addons/gut/one_to_many.gd b/addons/gut/one_to_many.gd
deleted file mode 100644
index 6a0f818..0000000
--- a/addons/gut/one_to_many.gd
+++ /dev/null
@@ -1,38 +0,0 @@
-# ------------------------------------------------------------------------------
-# This datastructure represents a simple one-to-many relationship. It manages
-# a dictionary of value/array pairs. It ignores duplicates of both the "one"
-# and the "many".
-# ------------------------------------------------------------------------------
-var _items = {}
-
-# return the size of _items or the size of an element in _items if "one" was
-# specified.
-func size(one=null):
- var to_return = 0
- if(one == null):
- to_return = _items.size()
- elif(_items.has(one)):
- to_return = _items[one].size()
- return to_return
-
-# Add an element to "one" if it does not already exist
-func add(one, many_item):
- if(_items.has(one) and !_items[one].has(many_item)):
- _items[one].append(many_item)
- else:
- _items[one] = [many_item]
-
-func clear():
- _items.clear()
-
-func has(one, many_item):
- var to_return = false
- if(_items.has(one)):
- to_return = _items[one].has(many_item)
- return to_return
-
-func to_s():
- var to_return = ''
- for key in _items:
- to_return += str(key, ": ", _items[key], "\n")
- return to_return
diff --git a/addons/gut/optparse.gd b/addons/gut/optparse.gd
deleted file mode 100644
index 290ed9d..0000000
--- a/addons/gut/optparse.gd
+++ /dev/null
@@ -1,248 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# Description
-# -----------
-# Command line interface for the GUT unit testing tool. Allows you to run tests
-# from the command line instead of running a scene. Place this script along with
-# gut.gd into your scripts directory at the root of your project. Once there you
-# can run this script (from the root of your project) using the following command:
-# godot -s -d test/gut/gut_cmdln.gd
-#
-# See the readme for a list of options and examples. You can also use the -gh
-# option to get more information about how to use the command line interface.
-# ##############################################################################
-
-#-------------------------------------------------------------------------------
-# Parses the command line arguments supplied into an array that can then be
-# examined and parsed based on how the gut options work.
-#-------------------------------------------------------------------------------
-class CmdLineParser:
- var _used_options = []
- # an array of arrays. Each element in this array will contain an option
- # name and if that option contains a value then it will have a sedond
- # element. For example:
- # [[-gselect, test.gd], [-gexit]]
- var _opts = []
-
- func _init():
- for i in range(OS.get_cmdline_args().size()):
- var opt_val = OS.get_cmdline_args()[i].split('=')
- _opts.append(opt_val)
-
- # Parse out multiple comma delimited values from a command line
- # option. Values are separated from option name with "=" and
- # additional values are comma separated.
- func _parse_array_value(full_option):
- var value = _parse_option_value(full_option)
- var split = value.split(',')
- return split
-
- # Parse out the value of an option. Values are separated from
- # the option name with "="
- func _parse_option_value(full_option):
- if(full_option.size() > 1):
- return full_option[1]
- else:
- return null
-
- # Search _opts for an element that starts with the option name
- # specified.
- func find_option(name):
- var found = false
- var idx = 0
-
- while(idx < _opts.size() and !found):
- if(_opts[idx][0] == name):
- found = true
- else:
- idx += 1
-
- if(found):
- return idx
- else:
- return -1
-
- func get_array_value(option):
- _used_options.append(option)
- var to_return = []
- var opt_loc = find_option(option)
- if(opt_loc != -1):
- to_return = _parse_array_value(_opts[opt_loc])
- _opts.remove(opt_loc)
-
- return to_return
-
- # returns the value of an option if it was specified, null otherwise. This
- # used to return the default but that became problemnatic when trying to
- # punch through the different places where values could be specified.
- func get_value(option):
- _used_options.append(option)
- var to_return = null
- var opt_loc = find_option(option)
- if(opt_loc != -1):
- to_return = _parse_option_value(_opts[opt_loc])
- _opts.remove(opt_loc)
-
- return to_return
-
- # returns true if it finds the option, false if not.
- func was_specified(option):
- _used_options.append(option)
- return find_option(option) != -1
-
- # Returns any unused command line options. I found that only the -s and
- # script name come through from godot, all other options that godot uses
- # are not sent through OS.get_cmdline_args().
- #
- # This is a onetime thing b/c i kill all items in _used_options
- func get_unused_options():
- var to_return = []
- for i in range(_opts.size()):
- to_return.append(_opts[i][0])
-
- var script_option = to_return.find('-s')
- if script_option != -1:
- to_return.remove(script_option + 1)
- to_return.remove(script_option)
-
- while(_used_options.size() > 0):
- var index = to_return.find(_used_options[0].split("=")[0])
- if(index != -1):
- to_return.remove(index)
- _used_options.remove(0)
-
- return to_return
-
-#-------------------------------------------------------------------------------
-# Simple class to hold a command line option
-#-------------------------------------------------------------------------------
-class Option:
- var value = null
- var option_name = ''
- var default = null
- var description = ''
-
- func _init(name, default_value, desc=''):
- option_name = name
- default = default_value
- description = desc
- value = null#default_value
-
- func pad(to_pad, size, pad_with=' '):
- var to_return = to_pad
- for _i in range(to_pad.length(), size):
- to_return += pad_with
-
- return to_return
-
- func to_s(min_space=0):
- var subbed_desc = description
- if(subbed_desc.find('[default]') != -1):
- subbed_desc = subbed_desc.replace('[default]', str(default))
- return pad(option_name, min_space) + subbed_desc
-
-#-------------------------------------------------------------------------------
-# The high level interface between this script and the command line options
-# supplied. Uses Option class and CmdLineParser to extract information from
-# the command line and make it easily accessible.
-#-------------------------------------------------------------------------------
-var options = []
-var _opts = []
-var _banner = ''
-
-func add(name, default, desc):
- options.append(Option.new(name, default, desc))
-
-func get_value(name):
- var found = false
- var idx = 0
-
- while(idx < options.size() and !found):
- if(options[idx].option_name == name):
- found = true
- else:
- idx += 1
-
- if(found):
- return options[idx].value
- else:
- print("COULD NOT FIND OPTION " + name)
- return null
-
-func set_banner(banner):
- _banner = banner
-
-func print_help():
- var longest = 0
- for i in range(options.size()):
- if(options[i].option_name.length() > longest):
- longest = options[i].option_name.length()
-
- print('---------------------------------------------------------')
- print(_banner)
-
- print("\nOptions\n-------")
- for i in range(options.size()):
- print(' ' + options[i].to_s(longest + 2))
- print('---------------------------------------------------------')
-
-func print_options():
- for i in range(options.size()):
- print(options[i].option_name + '=' + str(options[i].value))
-
-func parse():
- var parser = CmdLineParser.new()
-
- for i in range(options.size()):
- var t = typeof(options[i].default)
- # only set values that were specified at the command line so that
- # we can punch through default and config values correctly later.
- # Without this check, you can't tell the difference between the
- # defaults and what was specified, so you can't punch through
- # higher level options.
- if(parser.was_specified(options[i].option_name)):
- if(t == TYPE_INT):
- options[i].value = int(parser.get_value(options[i].option_name))
- elif(t == TYPE_STRING):
- options[i].value = parser.get_value(options[i].option_name)
- elif(t == TYPE_ARRAY):
- options[i].value = parser.get_array_value(options[i].option_name)
- elif(t == TYPE_BOOL):
- options[i].value = parser.was_specified(options[i].option_name)
- elif(t == TYPE_NIL):
- print(options[i].option_name + ' cannot be processed, it has a nil datatype')
- else:
- print(options[i].option_name + ' cannot be processed, it has unknown datatype:' + str(t))
-
- var unused = parser.get_unused_options()
- if(unused.size() > 0):
- print("Unrecognized options: ", unused)
- return false
-
- return true
diff --git a/addons/gut/orphan_counter.gd b/addons/gut/orphan_counter.gd
deleted file mode 100644
index cbfbea4..0000000
--- a/addons/gut/orphan_counter.gd
+++ /dev/null
@@ -1,55 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# This is a utility for tracking changes in the orphan count. Each time
-# add_counter is called it adds/resets the value in the dictionary to the
-# current number of orphans. Each call to get_counter will return the change
-# in orphans since add_counter was last called.
-# ##############################################################################
-var _counters = {}
-
-func orphan_count():
- return Performance.get_monitor(Performance.OBJECT_ORPHAN_NODE_COUNT)
-
-func add_counter(name):
- _counters[name] = orphan_count()
-
-# Returns the number of orphans created since add_counter was last called for
-# the name. Returns -1 to avoid blowing up with an invalid name but still
-# be somewhat visible that we've done something wrong.
-func get_counter(name):
- return orphan_count() - _counters[name] if _counters.has(name) else -1
-
-func print_orphans(name, lgr):
- var count = get_counter(name)
-
- if(count > 0):
- var o = 'orphan'
- if(count > 1):
- o = 'orphans'
- lgr.orphan(str(count, ' new ', o, '(', name, ').'))
diff --git a/addons/gut/parameter_factory.gd b/addons/gut/parameter_factory.gd
deleted file mode 100644
index 6bffe4c..0000000
--- a/addons/gut/parameter_factory.gd
+++ /dev/null
@@ -1,75 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# This is the home for all parameter creation helpers. These functions should
-# all return an array of values to be used as parameters for parameterized
-# tests.
-# ##############################################################################
-
-# ------------------------------------------------------------------------------
-# Creates an array of dictionaries. It pairs up the names array with each set
-# of values in values. If more names than values are specified then the missing
-# values will be filled with nulls. If more values than names are specified
-# those values will be ignored.
-#
-# Example:
-# create_named_parameters(['a', 'b'], [[1, 2], ['one', 'two']]) returns
-# [{a:1, b:2}, {a:'one', b:'two'}]
-#
-# This allows you to increase readability of your parameterized tests:
-# var params = create_named_parameters(['a', 'b'], [[1, 2], ['one', 'two']])
-# func test_foo(p = use_parameters(params)):
-# assert_eq(p.a, p.b)
-#
-# Parameters:
-# names: an array of names to be used as keys in the dictionaries
-# values: an array of arrays of values.
-# ------------------------------------------------------------------------------
-static func named_parameters(names, values):
- var named = []
- for i in range(values.size()):
- var entry = {}
-
- var parray = values[i]
- if(typeof(parray) != TYPE_ARRAY):
- parray = [values[i]]
-
- for j in range(names.size()):
- if(j >= parray.size()):
- entry[names[j]] = null
- else:
- entry[names[j]] = parray[j]
- named.append(entry)
-
- return named
-
-# Additional Helper Ideas
-# * File. IDK what it would look like. csv maybe.
-# * Random values within a range?
-# * All int values in a range or add an optioanal step.
-# *
diff --git a/addons/gut/parameter_handler.gd b/addons/gut/parameter_handler.gd
deleted file mode 100644
index 6b37e82..0000000
--- a/addons/gut/parameter_handler.gd
+++ /dev/null
@@ -1,37 +0,0 @@
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _params = null
-var _call_count = 0
-var _logger = null
-
-func _init(params=null):
- _params = params
- _logger = _utils.get_logger()
- if(typeof(_params) != TYPE_ARRAY):
- _logger.error('You must pass an array to parameter_handler constructor.')
- _params = null
-
-
-func next_parameters():
- _call_count += 1
- return _params[_call_count -1]
-
-func get_current_parameters():
- return _params[_call_count]
-
-func is_done():
- var done = true
- if(_params != null):
- done = _call_count == _params.size()
- return done
-
-func get_logger():
- return _logger
-
-func set_logger(logger):
- _logger = logger
-
-func get_call_count():
- return _call_count
-
-func get_parameter_count():
- return _params.size()
diff --git a/addons/gut/plugin.cfg b/addons/gut/plugin.cfg
deleted file mode 100644
index 128ccd0..0000000
--- a/addons/gut/plugin.cfg
+++ /dev/null
@@ -1,7 +0,0 @@
-[plugin]
-
-name="Gut"
-description="Unit Testing tool for Godot."
-author="Butch Wesley"
-version="7.1.0"
-script="gut_plugin.gd"
diff --git a/addons/gut/plugin_control.gd b/addons/gut/plugin_control.gd
deleted file mode 100644
index 959ce17..0000000
--- a/addons/gut/plugin_control.gd
+++ /dev/null
@@ -1,247 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# This is the control that is added via the editor. It exposes GUT settings
-# through the editor and delays the creation of the GUT instance until
-# Engine.get_main_loop() works as expected.
-# ##############################################################################
-tool
-extends Control
-
-# ------------------------------------------------------------------------------
-# GUT Settings
-# ------------------------------------------------------------------------------
-export(String, 'AnonymousPro', 'CourierPrime', 'LobsterTwo', 'Default') var _font_name = 'AnonymousPro'
-export(int) var _font_size = 20
-export(Color) var _font_color = Color(.8, .8, .8, 1)
-export(Color) var _background_color = Color(.15, .15, .15, 1)
-# Enable/Disable coloring of output.
-export(bool) var _color_output = true
-# The full/partial name of a script to select upon startup
-export(String) var _select_script = ''
-# The full/partial name of a test. All tests that contain the string will be
-# run
-export(String) var _tests_like = ''
-# The full/partial name of an Inner Class to be run. All Inner Classes that
-# contain the string will be run.
-export(String) var _inner_class_name = ''
-# Start running tests when the scene finishes loading
-export var _run_on_load = false
-# Maximize the GUT control on startup
-export var _should_maximize = false
-# Print output to the consol as well
-export var _should_print_to_console = true
-# Display orphan counts at the end of tests/scripts.
-export var _show_orphans = true
-# The log level.
-export(int, 'Fail/Errors', 'Errors/Warnings/Test Names', 'Everything') var _log_level = 1
-# When enabled GUT will yield between tests to give the GUI time to paint.
-# Disabling this can make the program appear to hang and can have some
-# unwanted consequences with the timing of freeing objects
-export var _yield_between_tests = true
-# When GUT compares values it first checks the types to prevent runtime errors.
-# This behavior can be disabled if desired. This flag was added early in
-# development to prevent any breaking changes and will likely be removed in
-# the future.
-export var _disable_strict_datatype_checks = false
-# The prefix used to find test methods.
-export var _test_prefix = 'test_'
-# The prefix used to find test scripts.
-export var _file_prefix = 'test_'
-# The file extension for test scripts (I don't think you can change this and
-# everythign work).
-export var _file_extension = '.gd'
-# The prefix used to find Inner Test Classes.
-export var _inner_class_prefix = 'Test'
-# The directory GUT will use to write any temporary files. This isn't used
-# much anymore since there was a change to the double creation implementation.
-# This will be removed in a later release.
-export(String) var _temp_directory = 'user://gut_temp_directory'
-# The path and filename for exported test information.
-export(String) var _export_path = ''
-# When enabled, any directory added will also include its subdirectories when
-# GUT looks for test scripts.
-export var _include_subdirectories = false
-# Allow user to add test directories via editor. This is done with strings
-# instead of an array because the interface for editing arrays is really
-# cumbersome and complicates testing because arrays set through the editor
-# apply to ALL instances. This also allows the user to use the built in
-# dialog to pick a directory.
-export(String, DIR) var _directory1 = ''
-export(String, DIR) var _directory2 = ''
-export(String, DIR) var _directory3 = ''
-export(String, DIR) var _directory4 = ''
-export(String, DIR) var _directory5 = ''
-export(String, DIR) var _directory6 = ''
-# Must match the types in _utils for double strategy
-export(int, 'FULL', 'PARTIAL') var _double_strategy = 1
-# Path and filename to the script to run before all tests are run.
-export(String, FILE) var _pre_run_script = ''
-# Path and filename to the script to run after all tests are run.
-export(String, FILE) var _post_run_script = ''
-# ------------------------------------------------------------------------------
-
-
-# ------------------------------------------------------------------------------
-# Signals
-# ------------------------------------------------------------------------------
-# Emitted when all the tests have finished running.
-signal tests_finished
-# Emitted when GUT is ready to be interacted with, and before any tests are run.
-signal gut_ready
-
-
-# ------------------------------------------------------------------------------
-# Private stuff.
-# ------------------------------------------------------------------------------
-var _gut = null
-var _lgr = null
-var _cancel_import = false
-var _placeholder = null
-
-func _init():
- # This min size has to be what the min size of the GutScene's min size is
- # but it has to be set here and not inferred i think.
- rect_min_size = Vector2(740, 250)
-
-func _ready():
- # Must call this deferred so that there is enough time for
- # Engine.get_main_loop() is populated and the psuedo singleton utils.gd
- # can be setup correctly.
- if(Engine.editor_hint):
- _placeholder = load('res://addons/gut/GutScene.tscn').instance()
- call_deferred('add_child', _placeholder)
- _placeholder.rect_size = rect_size
- else:
- call_deferred('_setup_gut')
-
- connect('resized', self, '_on_resized')
-
-func _on_resized():
- if(_placeholder != null):
- _placeholder.rect_size = rect_size
-
-
-# Templates can be missing if tests are exported and the export config for the
-# project does not include '*.txt' files. This check and related flags make
-# sure GUT does not blow up and that the error is not lost in all the import
-# output that is generated as well as ensuring that no tests are run.
-#
-# Assumption: This is only a concern when running from the scene since you
-# cannot run GUT from the command line in an exported game.
-func _check_for_templates():
- var f = File.new()
- if(!f.file_exists('res://addons/gut/double_templates/function_template.txt')):
- _lgr.error('Templates are missing. Make sure you are exporting "*.txt" or "addons/gut/double_templates/*.txt".')
- _run_on_load = false
- _cancel_import = true
- return false
- return true
-
-func _setup_gut():
- var _utils = load('res://addons/gut/utils.gd').get_instance()
-
- _lgr = _utils.get_logger()
- _gut = load('res://addons/gut/gut.gd').new()
- _gut.connect('tests_finished', self, '_on_tests_finished')
-
- if(!_check_for_templates()):
- return
-
- _gut._select_script = _select_script
- _gut._tests_like = _tests_like
- _gut._inner_class_name = _inner_class_name
-
- _gut._test_prefix = _test_prefix
- _gut._file_prefix = _file_prefix
- _gut._file_extension = _file_extension
- _gut._inner_class_prefix = _inner_class_prefix
- _gut._temp_directory = _temp_directory
-
- _gut.set_should_maximize(_should_maximize)
- _gut.set_yield_between_tests(_yield_between_tests)
- _gut.disable_strict_datatype_checks(_disable_strict_datatype_checks)
- _gut.set_export_path(_export_path)
- _gut.set_include_subdirectories(_include_subdirectories)
- _gut.set_double_strategy(_double_strategy)
- _gut.set_pre_run_script(_pre_run_script)
- _gut.set_post_run_script(_post_run_script)
- _gut.set_color_output(_color_output)
- _gut.show_orphans(_show_orphans)
-
- get_parent().add_child(_gut)
-
- if(!_utils.is_version_ok()):
- return
-
- _gut.set_log_level(_log_level)
-
- _gut.add_directory(_directory1)
- _gut.add_directory(_directory2)
- _gut.add_directory(_directory3)
- _gut.add_directory(_directory4)
- _gut.add_directory(_directory5)
- _gut.add_directory(_directory6)
-
- _gut.get_logger().disable_printer('console', !_should_print_to_console)
- # When file logging enabled then the log will contain terminal escape
- # strings. So when running the scene this is disabled. Also if enabled
- # this may cause duplicate entries into the logs.
- _gut.get_logger().disable_printer('terminal', true)
-
- _gut.get_gui().set_font_size(_font_size)
- _gut.get_gui().set_font(_font_name)
- _gut.get_gui().set_default_font_color(_font_color)
- _gut.get_gui().set_background_color(_background_color)
- _gut.get_gui().rect_size = rect_size
- emit_signal('gut_ready')
-
- if(_run_on_load):
- # Run the test scripts. If one has been selected then only run that one
- # otherwise all tests will be run.
- var run_rest_of_scripts = _select_script == null
- _gut.test_scripts(run_rest_of_scripts)
-
-func _is_ready_to_go(action):
- if(_gut == null):
- push_error(str('GUT is not ready for ', action, ' yet. Perform actions on GUT in/after the gut_ready signal.'))
- return _gut != null
-
-func _on_tests_finished():
- emit_signal('tests_finished')
-
-func get_gut():
- return _gut
-
-func export_if_tests_found():
- if(_is_ready_to_go('export_if_tests_found')):
- _gut.export_if_tests_found()
-
-func import_tests_if_none_found():
- if(_is_ready_to_go('import_tests_if_none_found') and !_cancel_import):
- _gut.import_tests_if_none_found()
diff --git a/addons/gut/printers.gd b/addons/gut/printers.gd
deleted file mode 100644
index c543603..0000000
--- a/addons/gut/printers.gd
+++ /dev/null
@@ -1,157 +0,0 @@
-# ------------------------------------------------------------------------------
-# Interface and some basic functionality for all printers.
-# ------------------------------------------------------------------------------
-class Printer:
- var _format_enabled = true
- var _disabled = false
- var _printer_name = 'NOT SET'
- var _show_name = false # used for debugging, set manually
-
- func get_format_enabled():
- return _format_enabled
-
- func set_format_enabled(format_enabled):
- _format_enabled = format_enabled
-
- func send(text, fmt=null):
- if(_disabled):
- return
-
- var formatted = text
- if(fmt != null and _format_enabled):
- formatted = format_text(text, fmt)
-
- if(_show_name):
- formatted = str('(', _printer_name, ')') + formatted
-
- _output(formatted)
-
- func get_disabled():
- return _disabled
-
- func set_disabled(disabled):
- _disabled = disabled
-
- # --------------------
- # Virtual Methods (some have some default behavior)
- # --------------------
- func _output(text):
- pass
-
- func format_text(text, fmt):
- return text
-
-# ------------------------------------------------------------------------------
-# Responsible for sending text to a GUT gui.
-# ------------------------------------------------------------------------------
-class GutGuiPrinter:
- extends Printer
- var _gut = null
-
- var _colors = {
- red = Color.red,
- yellow = Color.yellow,
- green = Color.green
- }
-
- func _init():
- _printer_name = 'gui'
-
- func _wrap_with_tag(text, tag):
- return str('[', tag, ']', text, '[/', tag, ']')
-
- func _color_text(text, c_word):
- return '[color=' + c_word + ']' + text + '[/color]'
-
- func format_text(text, fmt):
- var box = _gut.get_gui().get_text_box()
-
- if(fmt == 'bold'):
- box.push_bold()
- elif(fmt == 'underline'):
- box.push_underline()
- elif(_colors.has(fmt)):
- box.push_color(_colors[fmt])
- else:
- # just pushing something to pop.
- box.push_normal()
-
- box.add_text(text)
- box.pop()
-
- return ''
-
- func _output(text):
- _gut.get_gui().get_text_box().add_text(text)
-
- func get_gut():
- return _gut
-
- func set_gut(gut):
- _gut = gut
-
- # This can be very very slow when the box has a lot of text.
- func clear_line():
- var box = _gut.get_gui().get_text_box()
- box.remove_line(box.get_line_count() - 1)
- box.update()
-
-# ------------------------------------------------------------------------------
-# This AND TerminalPrinter should not be enabled at the same time since it will
-# result in duplicate output. printraw does not print to the console so i had
-# to make another one.
-# ------------------------------------------------------------------------------
-class ConsolePrinter:
- extends Printer
- var _buffer = ''
-
- func _init():
- _printer_name = 'console'
-
- # suppresses output until it encounters a newline to keep things
- # inline as much as possible.
- func _output(text):
- if(text.ends_with("\n")):
- print(_buffer + text.left(text.length() -1))
- _buffer = ''
- else:
- _buffer += text
-
-# ------------------------------------------------------------------------------
-# Prints text to terminal, formats some words.
-# ------------------------------------------------------------------------------
-class TerminalPrinter:
- extends Printer
-
- var escape = PoolByteArray([0x1b]).get_string_from_ascii()
- var cmd_colors = {
- red = escape + '[31m',
- yellow = escape + '[33m',
- green = escape + '[32m',
-
- underline = escape + '[4m',
- bold = escape + '[1m',
-
- default = escape + '[0m',
-
- clear_line = escape + '[2K'
- }
-
- func _init():
- _printer_name = 'terminal'
-
- func _output(text):
- # Note, printraw does not print to the console.
- printraw(text)
-
- func format_text(text, fmt):
- return cmd_colors[fmt] + text + cmd_colors.default
-
- func clear_line():
- send(cmd_colors.clear_line)
-
- func back(n):
- send(escape + str('[', n, 'D'))
-
- func forward(n):
- send(escape + str('[', n, 'C'))
diff --git a/addons/gut/signal_watcher.gd b/addons/gut/signal_watcher.gd
deleted file mode 100644
index e127421..0000000
--- a/addons/gut/signal_watcher.gd
+++ /dev/null
@@ -1,166 +0,0 @@
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-
-# Some arbitrary string that should never show up by accident. If it does, then
-# shame on you.
-const ARG_NOT_SET = '_*_argument_*_is_*_not_set_*_'
-
-# This hash holds the objects that are being watched, the signals that are being
-# watched, and an array of arrays that contains arguments that were passed
-# each time the signal was emitted.
-#
-# For example:
-# _watched_signals => {
-# ref1 => {
-# 'signal1' => [[], [], []],
-# 'signal2' => [[p1, p2]],
-# 'signal3' => [[p1]]
-# },
-# ref2 => {
-# 'some_signal' => [],
-# 'other_signal' => [[p1, p2, p3], [p1, p2, p3], [p1, p2, p3]]
-# }
-# }
-#
-# In this sample:
-# - signal1 on the ref1 object was emitted 3 times and each time, zero
-# parameters were passed.
-# - signal3 on ref1 was emitted once and passed a single parameter
-# - some_signal on ref2 was never emitted.
-# - other_signal on ref2 was emitted 3 times, each time with 3 parameters.
-var _watched_signals = {}
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-
-func _add_watched_signal(obj, name):
- # SHORTCIRCUIT - ignore dupes
- if(_watched_signals.has(obj) and _watched_signals[obj].has(name)):
- return
-
- if(!_watched_signals.has(obj)):
- _watched_signals[obj] = {name:[]}
- else:
- _watched_signals[obj][name] = []
- obj.connect(name, self, '_on_watched_signal', [obj, name])
-
-# This handles all the signals that are watched. It supports up to 9 parameters
-# which could be emitted by the signal and the two parameters used when it is
-# connected via watch_signal. I chose 9 since you can only specify up to 9
-# parameters when dynamically calling a method via call (per the Godot
-# documentation, i.e. some_object.call('some_method', 1, 2, 3...)).
-#
-# Based on the documentation of emit_signal, it appears you can only pass up
-# to 4 parameters when firing a signal. I haven't verified this, but this should
-# future proof this some if the value ever grows.
-func _on_watched_signal(arg1=ARG_NOT_SET, arg2=ARG_NOT_SET, arg3=ARG_NOT_SET, \
- arg4=ARG_NOT_SET, arg5=ARG_NOT_SET, arg6=ARG_NOT_SET, \
- arg7=ARG_NOT_SET, arg8=ARG_NOT_SET, arg9=ARG_NOT_SET, \
- arg10=ARG_NOT_SET, arg11=ARG_NOT_SET):
- var args = [arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11]
-
- # strip off any unused vars.
- var idx = args.size() -1
- while(str(args[idx]) == ARG_NOT_SET):
- args.remove(idx)
- idx -= 1
-
- # retrieve object and signal name from the array and remove them. These
- # will always be at the end since they are added when the connect happens.
- var signal_name = args[args.size() -1]
- args.pop_back()
- var object = args[args.size() -1]
- args.pop_back()
-
- _watched_signals[object][signal_name].append(args)
-
-func does_object_have_signal(object, signal_name):
- var signals = object.get_signal_list()
- for i in range(signals.size()):
- if(signals[i]['name'] == signal_name):
- return true
- return false
-
-func watch_signals(object):
- var signals = object.get_signal_list()
- for i in range(signals.size()):
- _add_watched_signal(object, signals[i]['name'])
-
-func watch_signal(object, signal_name):
- var did = false
- if(does_object_have_signal(object, signal_name)):
- _add_watched_signal(object, signal_name)
- did = true
- return did
-
-func get_emit_count(object, signal_name):
- var to_return = -1
- if(is_watching(object, signal_name)):
- to_return = _watched_signals[object][signal_name].size()
- return to_return
-
-func did_emit(object, signal_name):
- var did = false
- if(is_watching(object, signal_name)):
- did = get_emit_count(object, signal_name) != 0
- return did
-
-func print_object_signals(object):
- var list = object.get_signal_list()
- for i in range(list.size()):
- print(list[i].name, "\n ", list[i])
-
-func get_signal_parameters(object, signal_name, index=-1):
- var params = null
- if(is_watching(object, signal_name)):
- var all_params = _watched_signals[object][signal_name]
- if(all_params.size() > 0):
- if(index == -1):
- index = all_params.size() -1
- params = all_params[index]
- return params
-
-func is_watching_object(object):
- return _watched_signals.has(object)
-
-func is_watching(object, signal_name):
- return _watched_signals.has(object) and _watched_signals[object].has(signal_name)
-
-func clear():
- for obj in _watched_signals:
- if(_utils.is_not_freed(obj)):
- for signal_name in _watched_signals[obj]:
- obj.disconnect(signal_name, self, '_on_watched_signal')
- _watched_signals.clear()
-
-# Returns a list of all the signal names that were emitted by the object.
-# If the object is not being watched then an empty list is returned.
-func get_signals_emitted(obj):
- var emitted = []
- if(is_watching_object(obj)):
- for signal_name in _watched_signals[obj]:
- if(_watched_signals[obj][signal_name].size() > 0):
- emitted.append(signal_name)
-
- return emitted
diff --git a/addons/gut/source_code_pro.fnt b/addons/gut/source_code_pro.fnt
deleted file mode 100644
index 3367650..0000000
Binary files a/addons/gut/source_code_pro.fnt and /dev/null differ
diff --git a/addons/gut/spy.gd b/addons/gut/spy.gd
deleted file mode 100644
index 2aef4ad..0000000
--- a/addons/gut/spy.gd
+++ /dev/null
@@ -1,108 +0,0 @@
-# {
-# instance_id_or_path1:{
-# method1:[ [p1, p2], [p1, p2] ],
-# method2:[ [p1, p2], [p1, p2] ]
-# },
-# instance_id_or_path1:{
-# method1:[ [p1, p2], [p1, p2] ],
-# method2:[ [p1, p2], [p1, p2] ]
-# },
-# }
-var _calls = {}
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _lgr = _utils.get_logger()
-var _compare = _utils.Comparator.new()
-
-func _find_parameters(call_params, params_to_find):
- var found = false
- var idx = 0
- while(idx < call_params.size() and !found):
- var result = _compare.deep(call_params[idx], params_to_find)
- if(result.are_equal):
- found = true
- else:
- idx += 1
- return found
-
-func _get_params_as_string(params):
- var to_return = ''
- if(params == null):
- return ''
-
- for i in range(params.size()):
- if(params[i] == null):
- to_return += 'null'
- else:
- if(typeof(params[i]) == TYPE_STRING):
- to_return += str('"', params[i], '"')
- else:
- to_return += str(params[i])
- if(i != params.size() -1):
- to_return += ', '
- return to_return
-
-func add_call(variant, method_name, parameters=null):
- if(!_calls.has(variant)):
- _calls[variant] = {}
-
- if(!_calls[variant].has(method_name)):
- _calls[variant][method_name] = []
-
- _calls[variant][method_name].append(parameters)
-
-func was_called(variant, method_name, parameters=null):
- var to_return = false
- if(_calls.has(variant) and _calls[variant].has(method_name)):
- if(parameters):
- to_return = _find_parameters(_calls[variant][method_name], parameters)
- else:
- to_return = true
- return to_return
-
-func get_call_parameters(variant, method_name, index=-1):
- var to_return = null
- var get_index = -1
-
- if(_calls.has(variant) and _calls[variant].has(method_name)):
- var call_size = _calls[variant][method_name].size()
- if(index == -1):
- # get the most recent call by default
- get_index = call_size -1
- else:
- get_index = index
-
- if(get_index < call_size):
- to_return = _calls[variant][method_name][get_index]
- else:
- _lgr.error(str('Specified index ', index, ' is outside range of the number of registered calls: ', call_size))
-
- return to_return
-
-func call_count(instance, method_name, parameters=null):
- var to_return = 0
-
- if(was_called(instance, method_name)):
- if(parameters):
- for i in range(_calls[instance][method_name].size()):
- if(_calls[instance][method_name][i] == parameters):
- to_return += 1
- else:
- to_return = _calls[instance][method_name].size()
- return to_return
-
-func clear():
- _calls = {}
-
-func get_call_list_as_string(instance):
- var to_return = ''
- if(_calls.has(instance)):
- for method in _calls[instance]:
- for i in range(_calls[instance][method].size()):
- to_return += str(method, '(', _get_params_as_string(_calls[instance][method][i]), ")\n")
- return to_return
-
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
diff --git a/addons/gut/strutils.gd b/addons/gut/strutils.gd
deleted file mode 100644
index c175d90..0000000
--- a/addons/gut/strutils.gd
+++ /dev/null
@@ -1,166 +0,0 @@
-
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-# Hash containing all the built in types in Godot. This provides an English
-# name for the types that corosponds with the type constants defined in the
-# engine.
-var types = {}
-
-func _init_types_dictionary():
- types[TYPE_NIL] = 'TYPE_NIL'
- types[TYPE_BOOL] = 'Bool'
- types[TYPE_INT] = 'Int'
- types[TYPE_REAL] = 'Float/Real'
- types[TYPE_STRING] = 'String'
- types[TYPE_VECTOR2] = 'Vector2'
- types[TYPE_RECT2] = 'Rect2'
- types[TYPE_VECTOR3] = 'Vector3'
- #types[8] = 'Matrix32'
- types[TYPE_PLANE] = 'Plane'
- types[TYPE_QUAT] = 'QUAT'
- types[TYPE_AABB] = 'AABB'
- #types[12] = 'Matrix3'
- types[TYPE_TRANSFORM] = 'Transform'
- types[TYPE_COLOR] = 'Color'
- #types[15] = 'Image'
- types[TYPE_NODE_PATH] = 'Node Path'
- types[TYPE_RID] = 'RID'
- types[TYPE_OBJECT] = 'TYPE_OBJECT'
- #types[19] = 'TYPE_INPUT_EVENT'
- types[TYPE_DICTIONARY] = 'Dictionary'
- types[TYPE_ARRAY] = 'Array'
- types[TYPE_RAW_ARRAY] = 'TYPE_RAW_ARRAY'
- types[TYPE_INT_ARRAY] = 'TYPE_INT_ARRAY'
- types[TYPE_REAL_ARRAY] = 'TYPE_REAL_ARRAY'
- types[TYPE_STRING_ARRAY] = 'TYPE_STRING_ARRAY'
- types[TYPE_VECTOR2_ARRAY] = 'TYPE_VECTOR2_ARRAY'
- types[TYPE_VECTOR3_ARRAY] = 'TYPE_VECTOR3_ARRAY'
- types[TYPE_COLOR_ARRAY] = 'TYPE_COLOR_ARRAY'
- types[TYPE_MAX] = 'TYPE_MAX'
-
-# Types to not be formatted when using _str
-var _str_ignore_types = [
- TYPE_INT, TYPE_REAL, TYPE_STRING,
- TYPE_NIL, TYPE_BOOL
-]
-
-func _init():
- _init_types_dictionary()
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _get_filename(path):
- return path.split('/')[-1]
-
-# ------------------------------------------------------------------------------
-# Gets the filename of an object passed in. This does not return the
-# full path to the object, just the filename.
-# ------------------------------------------------------------------------------
-func _get_obj_filename(thing):
- var filename = null
-
- if(thing == null or
- !is_instance_valid(thing) or
- str(thing) == '[Object:null]' or
- typeof(thing) != TYPE_OBJECT or
- thing.has_method('__gut_instance_from_id')):
- return
-
- if(thing.get_script() == null):
- if(thing is PackedScene):
- filename = _get_filename(thing.resource_path)
- else:
- # If it isn't a packed scene and it doesn't have a script then
- # we do nothing. This just read better.
- pass
- elif(thing.get_script() is NativeScript):
- # Work with GDNative scripts:
- # inst2dict fails with "Not a script with an instance" on GDNative script instances
- filename = _get_filename(thing.get_script().resource_path)
- elif(!_utils.is_native_class(thing)):
- var dict = inst2dict(thing)
- filename = _get_filename(dict['@path'])
- if(dict['@subpath'] != ''):
- filename += str('/', dict['@subpath'])
-
- return filename
-
-# ------------------------------------------------------------------------------
-# Better object/thing to string conversion. Includes extra details about
-# whatever is passed in when it can/should.
-# ------------------------------------------------------------------------------
-func type2str(thing):
- var oc = _utils.OrphanCounter.new()
- var filename = _get_obj_filename(thing)
- var str_thing = str(thing)
-
- if(thing == null):
- # According to str there is a difference between null and an Object
- # that is somehow null. To avoid getting '[Object:null]' as output
- # always set it to str(null) instead of str(thing). A null object
- # will pass typeof(thing) == TYPE_OBJECT check so this has to be
- # before that.
- str_thing = str(null)
- elif(typeof(thing) == TYPE_REAL):
- if(!'.' in str_thing):
- str_thing += '.0'
- elif(typeof(thing) == TYPE_STRING):
- str_thing = str('"', thing, '"')
- elif(typeof(thing) in _str_ignore_types):
- # do nothing b/c we already have str(thing) in
- # to_return. I think this just reads a little
- # better this way.
- pass
- elif(typeof(thing) == TYPE_OBJECT):
- if(_utils.is_native_class(thing)):
- str_thing = _utils.get_native_class_name(thing)
- elif(_utils.is_double(thing)):
- var double_path = _get_filename(thing.__gut_metadata_.path)
- if(thing.__gut_metadata_.subpath != ''):
- double_path += str('/', thing.__gut_metadata_.subpath)
-
- str_thing += '(double of ' + double_path + ')'
- filename = null
- elif(types.has(typeof(thing))):
- if(!str_thing.begins_with('(')):
- str_thing = '(' + str_thing + ')'
- str_thing = str(types[typeof(thing)], str_thing)
-
- if(filename != null):
- str_thing += str('(', filename, ')')
- return str_thing
-
-# ------------------------------------------------------------------------------
-# Returns the string truncated with an '...' in it. Shows the start and last
-# 10 chars. If the string is smaller than max_size the entire string is
-# returned. If max_size is -1 then truncation is skipped.
-# ------------------------------------------------------------------------------
-func truncate_string(src, max_size):
- var to_return = src
- if(src.length() > max_size - 10 and max_size != -1):
- to_return = str(src.substr(0, max_size - 10), '...', src.substr(src.length() - 10, src.length()))
- return to_return
-
-
-func _get_indent_text(times, pad):
- var to_return = ''
- for i in range(times):
- to_return += pad
-
- return to_return
-
-func indent_text(text, times, pad):
- if(times == 0):
- return text
-
- var to_return = text
- var ending_newline = ''
-
- if(text.ends_with("\n")):
- ending_newline = "\n"
- to_return = to_return.left(to_return.length() -1)
-
- var padding = _get_indent_text(times, pad)
- to_return = to_return.replace("\n", "\n" + padding)
- to_return += ending_newline
-
- return padding + to_return
diff --git a/addons/gut/stub_params.gd b/addons/gut/stub_params.gd
deleted file mode 100644
index 8a749f4..0000000
--- a/addons/gut/stub_params.gd
+++ /dev/null
@@ -1,43 +0,0 @@
-var return_val = null
-var stub_target = null
-var target_subpath = null
-var parameters = null
-var stub_method = null
-var call_super = false
-
-const NOT_SET = '|_1_this_is_not_set_1_|'
-
-func _init(target=null, method=null, subpath=null):
- stub_target = target
- stub_method = method
- target_subpath = subpath
-
-func to_return(val):
- return_val = val
- call_super = false
- return self
-
-func to_do_nothing():
- return to_return(null)
-
-func to_call_super():
- call_super = true
- return self
-
-func when_passed(p1=NOT_SET,p2=NOT_SET,p3=NOT_SET,p4=NOT_SET,p5=NOT_SET,p6=NOT_SET,p7=NOT_SET,p8=NOT_SET,p9=NOT_SET,p10=NOT_SET):
- parameters = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10]
- var idx = 0
- while(idx < parameters.size()):
- if(str(parameters[idx]) == NOT_SET):
- parameters.remove(idx)
- else:
- idx += 1
- return self
-
-func to_s():
- var base_string = str(stub_target, '[', target_subpath, '].', stub_method)
- if(call_super):
- base_string += " to call SUPER"
- else:
- base_string += str(' with (', parameters, ') = ', return_val)
- return base_string
diff --git a/addons/gut/stubber.gd b/addons/gut/stubber.gd
deleted file mode 100644
index 590f17d..0000000
--- a/addons/gut/stubber.gd
+++ /dev/null
@@ -1,163 +0,0 @@
-# {
-# inst_id_or_path1:{
-# method_name1: [StubParams, StubParams],
-# method_name2: [StubParams, StubParams]
-# },
-# inst_id_or_path2:{
-# method_name1: [StubParams, StubParams],
-# method_name2: [StubParams, StubParams]
-# }
-# }
-var returns = {}
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _lgr = _utils.get_logger()
-var _strutils = _utils.Strutils.new()
-
-func _make_key_from_metadata(doubled):
- var to_return = doubled.__gut_metadata_.path
- if(doubled.__gut_metadata_.subpath != ''):
- to_return += str('-', doubled.__gut_metadata_.subpath)
- return to_return
-
-# Creates they key for the returns hash based on the type of object passed in
-# obj could be a string of a path to a script with an optional subpath or
-# it could be an instance of a doubled object.
-func _make_key_from_variant(obj, subpath=null):
- var to_return = null
-
- match typeof(obj):
- TYPE_STRING:
- # this has to match what is done in _make_key_from_metadata
- to_return = obj
- if(subpath != null and subpath != ''):
- to_return += str('-', subpath)
- TYPE_OBJECT:
- if(_utils.is_instance(obj)):
- to_return = _make_key_from_metadata(obj)
- elif(_utils.is_native_class(obj)):
- to_return = _utils.get_native_class_name(obj)
- else:
- to_return = obj.resource_path
- return to_return
-
-func _add_obj_method(obj, method, subpath=null):
- var key = _make_key_from_variant(obj, subpath)
- if(_utils.is_instance(obj)):
- key = obj
-
- if(!returns.has(key)):
- returns[key] = {}
- if(!returns[key].has(method)):
- returns[key][method] = []
-
- return key
-
-# ##############
-# Public
-# ##############
-
-# TODO: This method is only used in tests and should be refactored out. It
-# does not support inner classes and isn't helpful.
-func set_return(obj, method, value, parameters=null):
- var key = _add_obj_method(obj, method)
- var sp = _utils.StubParams.new(key, method)
- sp.parameters = parameters
- sp.return_val = value
- returns[key][method].append(sp)
-
-func add_stub(stub_params):
- if(stub_params.stub_method == '_init'):
- _lgr.error("You cannot stub _init. Super's _init is ALWAYS called.")
- else:
- var key = _add_obj_method(stub_params.stub_target, stub_params.stub_method, stub_params.target_subpath)
- returns[key][stub_params.stub_method].append(stub_params)
-
-# Searches returns for an entry that matches the instance or the class that
-# passed in obj is.
-#
-# obj can be an instance, class, or a path.
-func _find_stub(obj, method, parameters=null):
- var key = _make_key_from_variant(obj)
- var to_return = null
-
- if(_utils.is_instance(obj)):
- if(returns.has(obj) and returns[obj].has(method)):
- key = obj
- elif(obj.get('__gut_metadata_')):
- key = _make_key_from_metadata(obj)
-
- if(returns.has(key) and returns[key].has(method)):
- var param_idx = -1
- var null_idx = -1
-
- for i in range(returns[key][method].size()):
- if(returns[key][method][i].parameters == parameters):
- param_idx = i
- if(returns[key][method][i].parameters == null):
- null_idx = i
-
- # We have matching parameter values so return the stub value for that
- if(param_idx != -1):
- to_return = returns[key][method][param_idx]
- # We found a case where the parameters were not specified so return
- # parameters for that
- elif(null_idx != -1):
- to_return = returns[key][method][null_idx]
- else:
- _lgr.warn(str('Call to [', method, '] was not stubbed for the supplied parameters ', parameters, '. Null was returned.'))
-
- return to_return
-
-# Gets a stubbed return value for the object and method passed in. If the
-# instance was stubbed it will use that, otherwise it will use the path and
-# subpath of the object to try to find a value.
-#
-# It will also use the optional list of parameter values to find a value. If
-# the object was stubbed with no parameters than any parameters will match.
-# If it was stubbed with specific parameter values then it will try to match.
-# If the parameters do not match BUT there was also an empty parameter list stub
-# then it will return those.
-# If it cannot find anything that matches then null is returned.for
-#
-# Parameters
-# obj: this should be an instance of a doubled object.
-# method: the method called
-# parameters: optional array of parameter vales to find a return value for.
-func get_return(obj, method, parameters=null):
- var stub_info = _find_stub(obj, method, parameters)
-
- if(stub_info != null):
- return stub_info.return_val
- else:
- return null
-
-func should_call_super(obj, method, parameters=null):
- var stub_info = _find_stub(obj, method, parameters)
- if(stub_info != null):
- return stub_info.call_super
- else:
- # this log message is here because of how the generated doubled scripts
- # are structured. With this log msg here, you will only see one
- # "unstubbed" info instead of multiple.
- _lgr.info('Unstubbed call to ' + method + '::' + _strutils.type2str(obj))
- return false
-
-
-func clear():
- returns.clear()
-
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
-
-func to_s():
- var text = ''
- for thing in returns:
- text += str(thing) + "\n"
- for method in returns[thing]:
- text += str("\t", method, "\n")
- for i in range(returns[thing][method].size()):
- text += "\t\t" + returns[thing][method][i].to_s() + "\n"
- return text
diff --git a/addons/gut/summary.gd b/addons/gut/summary.gd
deleted file mode 100644
index 288a584..0000000
--- a/addons/gut/summary.gd
+++ /dev/null
@@ -1,171 +0,0 @@
-# ------------------------------------------------------------------------------
-# Contains all the results of a single test. Allows for multiple asserts results
-# and pending calls.
-# ------------------------------------------------------------------------------
-class Test:
- var pass_texts = []
- var fail_texts = []
- var pending_texts = []
-
- # NOTE: The "failed" and "pending" text must match what is outputted by
- # the logger in order for text highlighting to occur in summary.
- func to_s():
- var pad = ' '
- var to_return = ''
- for i in range(fail_texts.size()):
- to_return += str(pad, '[Failed]: ', fail_texts[i], "\n")
- for i in range(pending_texts.size()):
- to_return += str(pad, '[Pending]: ', pending_texts[i], "\n")
- return to_return
-
-# ------------------------------------------------------------------------------
-# Contains all the results for a single test-script/inner class. Persists the
-# names of the tests and results and the order in which the tests were run.
-# ------------------------------------------------------------------------------
-class TestScript:
- var name = 'NOT_SET'
- var _tests = {}
- var _test_order = []
-
- func _init(script_name):
- name = script_name
-
- func get_pass_count():
- var count = 0
- for key in _tests:
- count += _tests[key].pass_texts.size()
- return count
-
- func get_fail_count():
- var count = 0
- for key in _tests:
- count += _tests[key].fail_texts.size()
- return count
-
- func get_pending_count():
- var count = 0
- for key in _tests:
- count += _tests[key].pending_texts.size()
- return count
-
- func get_test_obj(obj_name):
- if(!_tests.has(obj_name)):
- _tests[obj_name] = Test.new()
- _test_order.append(obj_name)
- return _tests[obj_name]
-
- func add_pass(test_name, reason):
- var t = get_test_obj(test_name)
- t.pass_texts.append(reason)
-
- func add_fail(test_name, reason):
- var t = get_test_obj(test_name)
- t.fail_texts.append(reason)
-
- func add_pending(test_name, reason):
- var t = get_test_obj(test_name)
- t.pending_texts.append(reason)
-
-# ------------------------------------------------------------------------------
-# Summary Class
-#
-# This class holds the results of all the test scripts and Inner Classes that
-# were run.
-# -------------------------------------------d-----------------------------------
-var _scripts = []
-
-func add_script(name):
- _scripts.append(TestScript.new(name))
-
-func get_scripts():
- return _scripts
-
-func get_current_script():
- return _scripts[_scripts.size() - 1]
-
-func add_test(test_name):
- get_current_script().get_test_obj(test_name)
-
-func add_pass(test_name, reason = ''):
- get_current_script().add_pass(test_name, reason)
-
-func add_fail(test_name, reason = ''):
- get_current_script().add_fail(test_name, reason)
-
-func add_pending(test_name, reason = ''):
- get_current_script().add_pending(test_name, reason)
-
-func get_test_text(test_name):
- return test_name + "\n" + get_current_script().get_test_obj(test_name).to_s()
-
-# Gets the count of unique script names minus the . at the
-# end. Used for displaying the number of scripts without including all the
-# Inner Classes.
-func get_non_inner_class_script_count():
- var unique_scripts = {}
- for i in range(_scripts.size()):
- var ext_loc = _scripts[i].name.find_last('.gd.')
- if(ext_loc == -1):
- unique_scripts[_scripts[i].name] = 1
- else:
- unique_scripts[_scripts[i].name.substr(0, ext_loc + 3)] = 1
- return unique_scripts.keys().size()
-
-func get_totals():
- var totals = {
- passing = 0,
- pending = 0,
- failing = 0,
- tests = 0,
- scripts = 0
- }
-
- for s in range(_scripts.size()):
- totals.passing += _scripts[s].get_pass_count()
- totals.pending += _scripts[s].get_pending_count()
- totals.failing += _scripts[s].get_fail_count()
- totals.tests += _scripts[s]._test_order.size()
-
- totals.scripts = get_non_inner_class_script_count()
-
- return totals
-
-func log_summary_text(lgr):
- var orig_indent = lgr.get_indent_level()
- var found_failing_or_pending = false
-
- for s in range(_scripts.size()):
- lgr.set_indent_level(0)
- if(_scripts[s].get_fail_count() > 0 or _scripts[s].get_pending_count() > 0):
- lgr.log(_scripts[s].name, lgr.fmts.underline)
-
-
- for t in range(_scripts[s]._test_order.size()):
- var tname = _scripts[s]._test_order[t]
- var test = _scripts[s].get_test_obj(tname)
- if(test.fail_texts.size() > 0 or test.pending_texts.size() > 0):
- found_failing_or_pending = true
- lgr.log(str('- ', tname))
- lgr.inc_indent()
-
- for i in range(test.fail_texts.size()):
- lgr.failed(test.fail_texts[i])
- for i in range(test.pending_texts.size()):
- lgr.pending(test.pending_texts[i])
- lgr.dec_indent()
-
- lgr.set_indent_level(0)
- if(!found_failing_or_pending):
- lgr.log('All tests passed', lgr.fmts.green)
-
- lgr.log()
- var _totals = get_totals()
- lgr.log("Totals", lgr.fmts.yellow)
- lgr.log(str('Scripts: ', get_non_inner_class_script_count()))
- lgr.log(str('Tests: ', _totals.tests))
- lgr.log(str('Passing asserts: ', _totals.passing))
- lgr.log(str('Failing asserts: ',_totals.failing))
- lgr.log(str('Pending: ', _totals.pending))
-
- lgr.set_indent_level(orig_indent)
-
diff --git a/addons/gut/test.gd b/addons/gut/test.gd
deleted file mode 100644
index ca665f7..0000000
--- a/addons/gut/test.gd
+++ /dev/null
@@ -1,1566 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# View readme for usage details.
-#
-# Version - see gut.gd
-# ##############################################################################
-# Class that all test scripts must extend.
-#
-# This provides all the asserts and other testing features. Test scripts are
-# run by the Gut class in gut.gd
-# ##############################################################################
-extends Node
-
-# ------------------------------------------------------------------------------
-# Helper class to hold info for objects to double. This extracts info and has
-# some convenience methods. This is key in being able to make the "smart double"
-# method which makes doubling much easier for the user.
-# ------------------------------------------------------------------------------
-class DoubleInfo:
- var path
- var subpath
- var strategy
- var make_partial
- var extension
- var _utils = load('res://addons/gut/utils.gd').get_instance()
- var _is_native = false
- var is_valid = false
-
- # Flexible init method. p2 can be subpath or stategy unless p3 is
- # specified, then p2 must be subpath and p3 is strategy.
- #
- # Examples:
- # (object_to_double)
- # (object_to_double, subpath)
- # (object_to_double, strategy)
- # (object_to_double, subpath, strategy)
- func _init(thing, p2=null, p3=null):
- strategy = p2
-
- # short-circuit and ensure that is_valid
- # is not set to true.
- if(_utils.is_instance(thing)):
- return
-
- if(typeof(p2) == TYPE_STRING):
- strategy = p3
- subpath = p2
-
- if(typeof(thing) == TYPE_OBJECT):
- if(_utils.is_native_class(thing)):
- path = thing
- _is_native = true
- extension = 'native_class_not_used'
- else:
- path = thing.resource_path
- else:
- path = thing
-
- if(!_is_native):
- extension = path.get_extension()
-
- is_valid = true
-
- func is_scene():
- return extension == 'tscn'
-
- func is_script():
- return extension == 'gd'
-
- func is_native():
- return _is_native
-
-# ------------------------------------------------------------------------------
-# Begin test.gd
-# ------------------------------------------------------------------------------
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _compare = _utils.Comparator.new()
-
-# constant for signal when calling yield_for
-const YIELD = 'timeout'
-
-# Need a reference to the instance that is running the tests. This
-# is set by the gut class when it runs the tests. This gets you
-# access to the asserts in the tests you write.
-var gut = null
-
-var _disable_strict_datatype_checks = false
-# Holds all the text for a test's fail/pass. This is used for testing purposes
-# to see the text of a failed sub-test in test_test.gd
-var _fail_pass_text = []
-
-const EDITOR_PROPERTY = PROPERTY_USAGE_SCRIPT_VARIABLE | PROPERTY_USAGE_DEFAULT
-const VARIABLE_PROPERTY = PROPERTY_USAGE_SCRIPT_VARIABLE
-
-# Used with assert_setget
-enum {
- DEFAULT_SETTER_GETTER,
- SETTER_ONLY,
- GETTER_ONLY
-}
-
-# Summary counts for the test.
-var _summary = {
- asserts = 0,
- passed = 0,
- failed = 0,
- tests = 0,
- pending = 0
-}
-
-# This is used to watch signals so we can make assertions about them.
-var _signal_watcher = load('res://addons/gut/signal_watcher.gd').new()
-
-# Convenience copy of _utils.DOUBLE_STRATEGY
-var DOUBLE_STRATEGY = null
-var _lgr = _utils.get_logger()
-var _strutils = _utils.Strutils.new()
-
-# syntax sugar
-var ParameterFactory = _utils.ParameterFactory
-var CompareResult = _utils.CompareResult
-
-func _init():
- DOUBLE_STRATEGY = _utils.DOUBLE_STRATEGY # yes, this is right
-
-func _str(thing):
- return _strutils.type2str(thing)
-
-# ------------------------------------------------------------------------------
-# Fail an assertion. Causes test and script to fail as well.
-# ------------------------------------------------------------------------------
-func _fail(text):
- _summary.asserts += 1
- _summary.failed += 1
- _fail_pass_text.append('failed: ' + text)
- if(gut):
- _lgr.failed(text)
- gut._fail(text)
-
-# ------------------------------------------------------------------------------
-# Pass an assertion.
-# ------------------------------------------------------------------------------
-func _pass(text):
- _summary.asserts += 1
- _summary.passed += 1
- _fail_pass_text.append('passed: ' + text)
- if(gut):
- _lgr.passed(text)
- gut._pass(text)
-
-# ------------------------------------------------------------------------------
-# Checks if the datatypes passed in match. If they do not then this will cause
-# a fail to occur. If they match then TRUE is returned, FALSE if not. This is
-# used in all the assertions that compare values.
-# ------------------------------------------------------------------------------
-func _do_datatypes_match__fail_if_not(got, expected, text):
- var did_pass = true
-
- if(!_disable_strict_datatype_checks):
- var got_type = typeof(got)
- var expect_type = typeof(expected)
- if(got_type != expect_type and got != null and expected != null):
- # If we have a mismatch between float and int (types 2 and 3) then
- # print out a warning but do not fail.
- if([2, 3].has(got_type) and [2, 3].has(expect_type)):
- _lgr.warn(str('Warn: Float/Int comparison. Got ', _strutils.types[got_type],
- ' but expected ', _strutils.types[expect_type]))
- else:
- _fail('Cannot compare ' + _strutils.types[got_type] + '[' + _str(got) + '] to ' + \
- _strutils.types[expect_type] + '[' + _str(expected) + ']. ' + text)
- did_pass = false
-
- return did_pass
-
-# ------------------------------------------------------------------------------
-# Create a string that lists all the methods that were called on an spied
-# instance.
-# ------------------------------------------------------------------------------
-func _get_desc_of_calls_to_instance(inst):
- var BULLET = ' * '
- var calls = gut.get_spy().get_call_list_as_string(inst)
- # indent all the calls
- calls = BULLET + calls.replace("\n", "\n" + BULLET)
- # remove trailing newline and bullet
- calls = calls.substr(0, calls.length() - BULLET.length() - 1)
- return "Calls made on " + str(inst) + "\n" + calls
-
-# ------------------------------------------------------------------------------
-# Signal assertion helper. Do not call directly, use _can_make_signal_assertions
-# ------------------------------------------------------------------------------
-func _fail_if_does_not_have_signal(object, signal_name):
- var did_fail = false
- if(!_signal_watcher.does_object_have_signal(object, signal_name)):
- _fail(str('Object ', object, ' does not have the signal [', signal_name, ']'))
- did_fail = true
- return did_fail
-
-# ------------------------------------------------------------------------------
-# Signal assertion helper. Do not call directly, use _can_make_signal_assertions
-# ------------------------------------------------------------------------------
-func _fail_if_not_watching(object):
- var did_fail = false
- if(!_signal_watcher.is_watching_object(object)):
- _fail(str('Cannot make signal assertions because the object ', object, \
- ' is not being watched. Call watch_signals(some_object) to be able to make assertions about signals.'))
- did_fail = true
- return did_fail
-
-# ------------------------------------------------------------------------------
-# Returns text that contains original text and a list of all the signals that
-# were emitted for the passed in object.
-# ------------------------------------------------------------------------------
-func _get_fail_msg_including_emitted_signals(text, object):
- return str(text," (Signals emitted: ", _signal_watcher.get_signals_emitted(object), ")")
-
-# ------------------------------------------------------------------------------
-# This validates that parameters is an array and generates a specific error
-# and a failure with a specific message
-# ------------------------------------------------------------------------------
-func _fail_if_parameters_not_array(parameters):
- var invalid = parameters != null and typeof(parameters) != TYPE_ARRAY
- if(invalid):
- _lgr.error('The "parameters" parameter must be an array of expected parameter values.')
- _fail('Cannot compare paramter values because an array was not passed.')
- return invalid
-
-
-func _create_obj_from_type(type):
- var obj = null
- if type.is_class("PackedScene"):
- obj = type.instance()
- add_child(obj)
- else:
- obj = type.new()
- return obj
-
-
-func _get_type_from_obj(obj):
- var type = null
- if obj.has_method(get_filename()):
- type = load(obj.get_filename())
- else:
- type = obj.get_script()
- return type
-
-# #######################
-# Virtual Methods
-# #######################
-
-# alias for prerun_setup
-func before_all():
- pass
-
-# alias for setup
-func before_each():
- pass
-
-# alias for postrun_teardown
-func after_all():
- pass
-
-# alias for teardown
-func after_each():
- pass
-
-# #######################
-# Public
-# #######################
-
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
-
-
-# #######################
-# Asserts
-# #######################
-
-# ------------------------------------------------------------------------------
-# Asserts that the expected value equals the value got.
-# ------------------------------------------------------------------------------
-func assert_eq(got, expected, text=""):
-
- if(_do_datatypes_match__fail_if_not(got, expected, text)):
- var disp = "[" + _str(got) + "] expected to equal [" + _str(expected) + "]: " + text
- var result = null
-
- if(typeof(got) == TYPE_ARRAY):
- result = _compare.shallow(got, expected)
- else:
- result = _compare.simple(got, expected)
-
- if(typeof(got) in [TYPE_ARRAY, TYPE_DICTIONARY]):
- disp = str(result.summary, ' ', text)
-
- if(result.are_equal):
- _pass(disp)
- else:
- _fail(disp)
-
-
-# ------------------------------------------------------------------------------
-# Asserts that the value got does not equal the "not expected" value.
-# ------------------------------------------------------------------------------
-func assert_ne(got, not_expected, text=""):
- if(_do_datatypes_match__fail_if_not(got, not_expected, text)):
- var disp = "[" + _str(got) + "] expected to not equal [" + _str(not_expected) + "]: " + text
- var result = null
-
- if(typeof(got) == TYPE_ARRAY):
- result = _compare.shallow(got, not_expected)
- else:
- result = _compare.simple(got, not_expected)
-
- if(typeof(got) in [TYPE_ARRAY, TYPE_DICTIONARY]):
- disp = str(result.summary, ' ', text)
-
- if(result.are_equal):
- _fail(disp)
- else:
- _pass(disp)
-
-
-# ------------------------------------------------------------------------------
-# Asserts that the expected value almost equals the value got.
-# ------------------------------------------------------------------------------
-func assert_almost_eq(got, expected, error_interval, text=''):
- var disp = "[" + _str(got) + "] expected to equal [" + _str(expected) + "] +/- [" + str(error_interval) + "]: " + text
- if(_do_datatypes_match__fail_if_not(got, expected, text) and _do_datatypes_match__fail_if_not(got, error_interval, text)):
- if(got < (expected - error_interval) or got > (expected + error_interval)):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that the expected value does not almost equal the value got.
-# ------------------------------------------------------------------------------
-func assert_almost_ne(got, not_expected, error_interval, text=''):
- var disp = "[" + _str(got) + "] expected to not equal [" + _str(not_expected) + "] +/- [" + str(error_interval) + "]: " + text
- if(_do_datatypes_match__fail_if_not(got, not_expected, text) and _do_datatypes_match__fail_if_not(got, error_interval, text)):
- if(got < (not_expected - error_interval) or got > (not_expected + error_interval)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts got is greater than expected
-# ------------------------------------------------------------------------------
-func assert_gt(got, expected, text=""):
- var disp = "[" + _str(got) + "] expected to be > than [" + _str(expected) + "]: " + text
- if(_do_datatypes_match__fail_if_not(got, expected, text)):
- if(got > expected):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts got is less than expected
-# ------------------------------------------------------------------------------
-func assert_lt(got, expected, text=""):
- var disp = "[" + _str(got) + "] expected to be < than [" + _str(expected) + "]: " + text
- if(_do_datatypes_match__fail_if_not(got, expected, text)):
- if(got < expected):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# asserts that got is true
-# ------------------------------------------------------------------------------
-func assert_true(got, text=""):
- if(typeof(got) == TYPE_BOOL):
- if(got):
- _pass(text)
- else:
- _fail(text)
- else:
- var msg = str("Cannot convert ", _strutils.type2str(got), " to boolean")
- _fail(msg)
-
-# ------------------------------------------------------------------------------
-# Asserts that got is false
-# ------------------------------------------------------------------------------
-func assert_false(got, text=""):
- if(typeof(got) == TYPE_BOOL):
- if(got):
- _fail(text)
- else:
- _pass(text)
- else:
- var msg = str("Cannot convert ", _strutils.type2str(got), " to boolean")
- _fail(msg)
-
-# ------------------------------------------------------------------------------
-# Asserts value is between (inclusive) the two expected values.
-# ------------------------------------------------------------------------------
-func assert_between(got, expect_low, expect_high, text=""):
- var disp = "[" + _str(got) + "] expected to be between [" + _str(expect_low) + "] and [" + str(expect_high) + "]: " + text
-
- if(_do_datatypes_match__fail_if_not(got, expect_low, text) and _do_datatypes_match__fail_if_not(got, expect_high, text)):
- if(expect_low > expect_high):
- disp = "INVALID range. [" + str(expect_low) + "] is not less than [" + str(expect_high) + "]"
- _fail(disp)
- else:
- if(got < expect_low or got > expect_high):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts value is not between (exclusive) the two expected values.
-# ------------------------------------------------------------------------------
-func assert_not_between(got, expect_low, expect_high, text=""):
- var disp = "[" + _str(got) + "] expected not to be between [" + _str(expect_low) + "] and [" + str(expect_high) + "]: " + text
-
- if(_do_datatypes_match__fail_if_not(got, expect_low, text) and _do_datatypes_match__fail_if_not(got, expect_high, text)):
- if(expect_low > expect_high):
- disp = "INVALID range. [" + str(expect_low) + "] is not less than [" + str(expect_high) + "]"
- _fail(disp)
- else:
- if(got > expect_low and got < expect_high):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Uses the 'has' method of the object passed in to determine if it contains
-# the passed in element.
-# ------------------------------------------------------------------------------
-func assert_has(obj, element, text=""):
- var disp = str('Expected [', _str(obj), '] to contain value: [', _str(element), ']: ', text)
- if(obj.has(element)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func assert_does_not_have(obj, element, text=""):
- var disp = str('Expected [', _str(obj), '] to NOT contain value: [', _str(element), ']: ', text)
- if(obj.has(element)):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that a file exists
-# ------------------------------------------------------------------------------
-func assert_file_exists(file_path):
- var disp = 'expected [' + file_path + '] to exist.'
- var f = File.new()
- if(f.file_exists(file_path)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that a file should not exist
-# ------------------------------------------------------------------------------
-func assert_file_does_not_exist(file_path):
- var disp = 'expected [' + file_path + '] to NOT exist'
- var f = File.new()
- if(!f.file_exists(file_path)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts the specified file is empty
-# ------------------------------------------------------------------------------
-func assert_file_empty(file_path):
- var disp = 'expected [' + file_path + '] to be empty'
- var f = File.new()
- if(f.file_exists(file_path) and gut.is_file_empty(file_path)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts the specified file is not empty
-# ------------------------------------------------------------------------------
-func assert_file_not_empty(file_path):
- var disp = 'expected [' + file_path + '] to contain data'
- if(!gut.is_file_empty(file_path)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts the object has the specified method
-# ------------------------------------------------------------------------------
-func assert_has_method(obj, method):
- assert_true(obj.has_method(method), _str(obj) + ' should have method: ' + method)
-
-# Old deprecated method name
-func assert_get_set_methods(obj, property, default, set_to):
- _lgr.deprecated('assert_get_set_methods', 'assert_accessors')
- assert_accessors(obj, property, default, set_to)
-
-# ------------------------------------------------------------------------------
-# Verifies the object has get and set methods for the property passed in. The
-# property isn't tied to anything, just a name to be appended to the end of
-# get_ and set_. Asserts the get_ and set_ methods exist, if not, it stops there.
-# If they exist then it asserts get_ returns the expected default then calls
-# set_ and asserts get_ has the value it was set to.
-# ------------------------------------------------------------------------------
-func assert_accessors(obj, property, default, set_to):
- var fail_count = _summary.failed
- var get = 'get_' + property
- var set = 'set_' + property
- assert_has_method(obj, get)
- assert_has_method(obj, set)
- # SHORT CIRCUIT
- if(_summary.failed > fail_count):
- return
- assert_eq(obj.call(get), default, 'It should have the expected default value.')
- obj.call(set, set_to)
- assert_eq(obj.call(get), set_to, 'The set value should have been returned.')
-
-
-# ---------------------------------------------------------------------------
-# Property search helper. Used to retrieve Dictionary of specified property
-# from passed object. Returns null if not found.
-# If provided, property_usage constrains the type of property returned by
-# passing either:
-# EDITOR_PROPERTY for properties defined as: export(int) var some_value
-# VARIABLE_PROPERTY for properties defined as: var another_value
-# ---------------------------------------------------------------------------
-func _find_object_property(obj, property_name, property_usage=null):
- var result = null
- var found = false
- var properties = obj.get_property_list()
-
- while !found and !properties.empty():
- var property = properties.pop_back()
- if property['name'] == property_name:
- if property_usage == null or property['usage'] == property_usage:
- result = property
- found = true
- return result
-
-# ------------------------------------------------------------------------------
-# Asserts a class exports a variable.
-# ------------------------------------------------------------------------------
-func assert_exports(obj, property_name, type):
- var disp = 'expected %s to have editor property [%s]' % [_str(obj), property_name]
- var property = _find_object_property(obj, property_name, EDITOR_PROPERTY)
- if property != null:
- disp += ' of type [%s]. Got type [%s].' % [_strutils.types[type], _strutils.types[property['type']]]
- if property['type'] == type:
- _pass(disp)
- else:
- _fail(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Signal assertion helper.
-#
-# Verifies that the object and signal are valid for making signal assertions.
-# This will fail with specific messages that indicate why they are not valid.
-# This returns true/false to indicate if the object and signal are valid.
-# ------------------------------------------------------------------------------
-func _can_make_signal_assertions(object, signal_name):
- return !(_fail_if_not_watching(object) or _fail_if_does_not_have_signal(object, signal_name))
-
-# ------------------------------------------------------------------------------
-# Check if an object is connected to a signal on another object. Returns True
-# if it is and false otherwise
-# ------------------------------------------------------------------------------
-func _is_connected(signaler_obj, connect_to_obj, signal_name, method_name=""):
- if(method_name != ""):
- return signaler_obj.is_connected(signal_name, connect_to_obj, method_name)
- else:
- var connections = signaler_obj.get_signal_connection_list(signal_name)
- for conn in connections:
- if((conn.source == signaler_obj) and (conn.target == connect_to_obj)):
- return true
- return false
-# ------------------------------------------------------------------------------
-# Watch the signals for an object. This must be called before you can make
-# any assertions about the signals themselves.
-# ------------------------------------------------------------------------------
-func watch_signals(object):
- _signal_watcher.watch_signals(object)
-
-# ------------------------------------------------------------------------------
-# Asserts that an object is connected to a signal on another object
-#
-# This will fail with specific messages if the target object is not connected
-# to the specified signal on the source object.
-# ------------------------------------------------------------------------------
-func assert_connected(signaler_obj, connect_to_obj, signal_name, method_name=""):
- pass
- var method_disp = ''
- if (method_name != ""):
- method_disp = str(' using method: [', method_name, '] ')
- var disp = str('Expected object ', _str(signaler_obj),\
- ' to be connected to signal: [', signal_name, '] on ',\
- _str(connect_to_obj), method_disp)
- if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that an object is not connected to a signal on another object
-#
-# This will fail with specific messages if the target object is connected
-# to the specified signal on the source object.
-# ------------------------------------------------------------------------------
-func assert_not_connected(signaler_obj, connect_to_obj, signal_name, method_name=""):
- var method_disp = ''
- if (method_name != ""):
- method_disp = str(' using method: [', method_name, '] ')
- var disp = str('Expected object ', _str(signaler_obj),\
- ' to not be connected to signal: [', signal_name, '] on ',\
- _str(connect_to_obj), method_disp)
- if(_is_connected(signaler_obj, connect_to_obj, signal_name, method_name)):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that a signal has been emitted at least once.
-#
-# This will fail with specific messages if the object is not being watched or
-# the object does not have the specified signal
-# ------------------------------------------------------------------------------
-func assert_signal_emitted(object, signal_name, text=""):
- var disp = str('Expected object ', _str(object), ' to have emitted signal [', signal_name, ']: ', text)
- if(_can_make_signal_assertions(object, signal_name)):
- if(_signal_watcher.did_emit(object, signal_name)):
- _pass(disp)
- else:
- _fail(_get_fail_msg_including_emitted_signals(disp, object))
-
-# ------------------------------------------------------------------------------
-# Asserts that a signal has not been emitted.
-#
-# This will fail with specific messages if the object is not being watched or
-# the object does not have the specified signal
-# ------------------------------------------------------------------------------
-func assert_signal_not_emitted(object, signal_name, text=""):
- var disp = str('Expected object ', _str(object), ' to NOT emit signal [', signal_name, ']: ', text)
- if(_can_make_signal_assertions(object, signal_name)):
- if(_signal_watcher.did_emit(object, signal_name)):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that a signal was fired with the specified parameters. The expected
-# parameters should be passed in as an array. An optional index can be passed
-# when a signal has fired more than once. The default is to retrieve the most
-# recent emission of the signal.
-#
-# This will fail with specific messages if the object is not being watched or
-# the object does not have the specified signal
-# ------------------------------------------------------------------------------
-func assert_signal_emitted_with_parameters(object, signal_name, parameters, index=-1):
- var disp = str('Expected object ', _str(object), ' to emit signal [', signal_name, '] with parameters ', parameters, ', got ')
- if(_can_make_signal_assertions(object, signal_name)):
- if(_signal_watcher.did_emit(object, signal_name)):
- var parms_got = _signal_watcher.get_signal_parameters(object, signal_name, index)
- var diff_result = _compare.deep(parameters, parms_got)
- if(diff_result.are_equal()):
- _pass(str(disp, parms_got))
- else:
- _fail(str('Expected object ', _str(object), ' to emit signal [', signal_name, '] with parameters ', diff_result.summarize()))
- else:
- var text = str('Object ', object, ' did not emit signal [', signal_name, ']')
- _fail(_get_fail_msg_including_emitted_signals(text, object))
-
-# ------------------------------------------------------------------------------
-# Assert that a signal has been emitted a specific number of times.
-#
-# This will fail with specific messages if the object is not being watched or
-# the object does not have the specified signal
-# ------------------------------------------------------------------------------
-func assert_signal_emit_count(object, signal_name, times, text=""):
-
- if(_can_make_signal_assertions(object, signal_name)):
- var count = _signal_watcher.get_emit_count(object, signal_name)
- var disp = str('Expected the signal [', signal_name, '] emit count of [', count, '] to equal [', times, ']: ', text)
- if(count== times):
- _pass(disp)
- else:
- _fail(_get_fail_msg_including_emitted_signals(disp, object))
-
-# ------------------------------------------------------------------------------
-# Assert that the passed in object has the specified signal
-# ------------------------------------------------------------------------------
-func assert_has_signal(object, signal_name, text=""):
- var disp = str('Expected object ', _str(object), ' to have signal [', signal_name, ']: ', text)
- if(_signal_watcher.does_object_have_signal(object, signal_name)):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Returns the number of times a signal was emitted. -1 returned if the object
-# is not being watched.
-# ------------------------------------------------------------------------------
-func get_signal_emit_count(object, signal_name):
- return _signal_watcher.get_emit_count(object, signal_name)
-
-# ------------------------------------------------------------------------------
-# Get the parmaters of a fired signal. If the signal was not fired null is
-# returned. You can specify an optional index (use get_signal_emit_count to
-# determine the number of times it was emitted). The default index is the
-# latest time the signal was fired (size() -1 insetead of 0). The parameters
-# returned are in an array.
-# ------------------------------------------------------------------------------
-func get_signal_parameters(object, signal_name, index=-1):
- return _signal_watcher.get_signal_parameters(object, signal_name, index)
-
-# ------------------------------------------------------------------------------
-# Get the parameters for a method call to a doubled object. By default it will
-# return the most recent call. You can optionally specify an index.
-#
-# Returns:
-# * an array of parameter values if a call the method was found
-# * null when a call to the method was not found or the index specified was
-# invalid.
-# ------------------------------------------------------------------------------
-func get_call_parameters(object, method_name, index=-1):
- var to_return = null
- if(_utils.is_double(object)):
- to_return = gut.get_spy().get_call_parameters(object, method_name, index)
- else:
- _lgr.error('You must pass a doulbed object to get_call_parameters.')
-
- return to_return
-
-# ------------------------------------------------------------------------------
-# Assert that object is an instance of a_class
-# ------------------------------------------------------------------------------
-func assert_extends(object, a_class, text=''):
- _lgr.deprecated('assert_extends', 'assert_is')
- assert_is(object, a_class, text)
-
-# Alias for assert_extends
-func assert_is(object, a_class, text=''):
- var disp = ''#var disp = str('Expected [', _str(object), '] to be type of [', a_class, ']: ', text)
- var NATIVE_CLASS = 'GDScriptNativeClass'
- var GDSCRIPT_CLASS = 'GDScript'
- var bad_param_2 = 'Parameter 2 must be a Class (like Node2D or Label). You passed '
-
- if(typeof(object) != TYPE_OBJECT):
- _fail(str('Parameter 1 must be an instance of an object. You passed: ', _str(object)))
- elif(typeof(a_class) != TYPE_OBJECT):
- _fail(str(bad_param_2, _str(a_class)))
- else:
- var a = _str(a_class)
- disp = str('Expected [', _str(object), '] to extend [', _str(a_class), ']: ', text)
- if(a_class.get_class() != NATIVE_CLASS and a_class.get_class() != GDSCRIPT_CLASS):
- _fail(str(bad_param_2, _str(a_class)))
- else:
- if(object is a_class):
- _pass(disp)
- else:
- _fail(disp)
-
-func _get_typeof_string(the_type):
- var to_return = ""
- if(_strutils.types.has(the_type)):
- to_return += str(the_type, '(', _strutils.types[the_type], ')')
- else:
- to_return += str(the_type)
- return to_return
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func assert_typeof(object, type, text=''):
- var disp = str('Expected [typeof(', object, ') = ')
- disp += _get_typeof_string(typeof(object))
- disp += '] to equal ['
- disp += _get_typeof_string(type) + ']'
- disp += '. ' + text
- if(typeof(object) == type):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func assert_not_typeof(object, type, text=''):
- var disp = str('Expected [typeof(', object, ') = ')
- disp += _get_typeof_string(typeof(object))
- disp += '] to not equal ['
- disp += _get_typeof_string(type) + ']'
- disp += '. ' + text
- if(typeof(object) != type):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Assert that text contains given search string.
-# The match_case flag determines case sensitivity.
-# ------------------------------------------------------------------------------
-func assert_string_contains(text, search, match_case=true):
- var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.'
- var disp = 'Expected \'%s\' to contain \'%s\', match_case=%s' % [text, search, match_case]
- if(text == '' or search == ''):
- _fail(empty_search % [text, search])
- elif(match_case):
- if(text.find(search) == -1):
- _fail(disp)
- else:
- _pass(disp)
- else:
- if(text.to_lower().find(search.to_lower()) == -1):
- _fail(disp)
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Assert that text starts with given search string.
-# match_case flag determines case sensitivity.
-# ------------------------------------------------------------------------------
-func assert_string_starts_with(text, search, match_case=true):
- var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.'
- var disp = 'Expected \'%s\' to start with \'%s\', match_case=%s' % [text, search, match_case]
- if(text == '' or search == ''):
- _fail(empty_search % [text, search])
- elif(match_case):
- if(text.find(search) == 0):
- _pass(disp)
- else:
- _fail(disp)
- else:
- if(text.to_lower().find(search.to_lower()) == 0):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Assert that text ends with given search string.
-# match_case flag determines case sensitivity.
-# ------------------------------------------------------------------------------
-func assert_string_ends_with(text, search, match_case=true):
- var empty_search = 'Expected text and search strings to be non-empty. You passed \'%s\' and \'%s\'.'
- var disp = 'Expected \'%s\' to end with \'%s\', match_case=%s' % [text, search, match_case]
- var required_index = len(text) - len(search)
- if(text == '' or search == ''):
- _fail(empty_search % [text, search])
- elif(match_case):
- if(text.find(search) == required_index):
- _pass(disp)
- else:
- _fail(disp)
- else:
- if(text.to_lower().find(search.to_lower()) == required_index):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Assert that a method was called on an instance of a doubled class. If
-# parameters are supplied then the params passed in when called must match.
-# TODO make 3rd parameter "param_or_text" and add fourth parameter of "text" and
-# then work some magic so this can have a "text" parameter without being
-# annoying.
-# ------------------------------------------------------------------------------
-func assert_called(inst, method_name, parameters=null):
- var disp = str('Expected [',method_name,'] to have been called on ',_str(inst))
-
- if(_fail_if_parameters_not_array(parameters)):
- return
-
- if(!_utils.is_double(inst)):
- _fail('You must pass a doubled instance to assert_called. Check the wiki for info on using double.')
- else:
- if(gut.get_spy().was_called(inst, method_name, parameters)):
- _pass(disp)
- else:
- if(parameters != null):
- disp += str(' with parameters ', parameters)
- _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst)))
-
-# ------------------------------------------------------------------------------
-# Assert that a method was not called on an instance of a doubled class. If
-# parameters are specified then this will only fail if it finds a call that was
-# sent matching parameters.
-# ------------------------------------------------------------------------------
-func assert_not_called(inst, method_name, parameters=null):
- var disp = str('Expected [', method_name, '] to NOT have been called on ', _str(inst))
-
- if(_fail_if_parameters_not_array(parameters)):
- return
-
- if(!_utils.is_double(inst)):
- _fail('You must pass a doubled instance to assert_not_called. Check the wiki for info on using double.')
- else:
- if(gut.get_spy().was_called(inst, method_name, parameters)):
- if(parameters != null):
- disp += str(' with parameters ', parameters)
- _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst)))
- else:
- _pass(disp)
-
-# ------------------------------------------------------------------------------
-# Assert that a method on an instance of a doubled class was called a number
-# of times. If parameters are specified then only calls with matching
-# parameter values will be counted.
-# ------------------------------------------------------------------------------
-func assert_call_count(inst, method_name, expected_count, parameters=null):
- var count = gut.get_spy().call_count(inst, method_name, parameters)
-
- if(_fail_if_parameters_not_array(parameters)):
- return
-
- var param_text = ''
- if(parameters):
- param_text = ' with parameters ' + str(parameters)
- var disp = 'Expected [%s] on %s to be called [%s] times%s. It was called [%s] times.'
- disp = disp % [method_name, _str(inst), expected_count, param_text, count]
-
- if(!_utils.is_double(inst)):
- _fail('You must pass a doubled instance to assert_call_count. Check the wiki for info on using double.')
- else:
- if(count == expected_count):
- _pass(disp)
- else:
- _fail(str(disp, "\n", _get_desc_of_calls_to_instance(inst)))
-
-# ------------------------------------------------------------------------------
-# Asserts the passed in value is null
-# ------------------------------------------------------------------------------
-func assert_null(got, text=''):
- var disp = str('Expected [', _str(got), '] to be NULL: ', text)
- if(got == null):
- _pass(disp)
- else:
- _fail(disp)
-
-# ------------------------------------------------------------------------------
-# Asserts the passed in value is null
-# ------------------------------------------------------------------------------
-func assert_not_null(got, text=''):
- var disp = str('Expected [', _str(got), '] to be anything but NULL: ', text)
- if(got == null):
- _fail(disp)
- else:
- _pass(disp)
-
-# -----------------------------------------------------------------------------
-# Asserts object has been freed from memory
-# We pass in a title (since if it is freed, we lost all identity data)
-# -----------------------------------------------------------------------------
-func assert_freed(obj, title):
- var disp = title
- if(is_instance_valid(obj)):
- disp = _strutils.type2str(obj) + title
- assert_true(not is_instance_valid(obj), "Expected [%s] to be freed" % disp)
-
-# ------------------------------------------------------------------------------
-# Asserts Object has not been freed from memory
-# -----------------------------------------------------------------------------
-func assert_not_freed(obj, title):
- var disp = title
- if(is_instance_valid(obj)):
- disp = _strutils.type2str(obj) + title
- assert_true(is_instance_valid(obj), "Expected [%s] to not be freed" % disp)
-
-# ------------------------------------------------------------------------------
-# Asserts that the current test has not introduced any new orphans. This only
-# applies to the test code that preceedes a call to this method so it should be
-# the last thing your test does.
-# ------------------------------------------------------------------------------
-func assert_no_new_orphans(text=''):
- var count = gut.get_orphan_counter().get_counter('test')
- var msg = ''
- if(text != ''):
- msg = ': ' + text
- # Note that get_counter will return -1 if the counter does not exist. This
- # can happen with a misplaced assert_no_new_orphans. Checking for > 0
- # ensures this will not cause some weird failure.
- if(count > 0):
- _fail(str('Expected no orphans, but found ', count, msg))
- else:
- _pass('No new orphans found.' + msg)
-
-# ------------------------------------------------------------------------------
-# Returns a dictionary that contains
-# - an is_valid flag whether validation was successful or not and
-# - a message that gives some information about the validation errors.
-# ------------------------------------------------------------------------------
-func _validate_assert_setget_called_input(type, name_property
- , name_setter, name_getter):
- var obj = null
- var result = {"is_valid": true, "msg": ""}
-
- if null == type or typeof(type) != TYPE_OBJECT or not type.is_class("Resource"):
- result.is_valid = false
- result.msg = str("The type parameter should be a ressource, input is ", _str(type))
- return result
-
- if null == double(type):
- result.is_valid = false
- result.msg = str("Attempt to double the type parameter failed. The type parameter should be a ressource that can be doubled.")
- return result
-
- obj = _create_obj_from_type(type)
- var property = _find_object_property(obj, str(name_property))
-
- if null == property:
- result.is_valid = false
- result.msg += str("The property %s does not exist." % _str(name_property))
- if name_setter == "" and name_getter == "":
- result.is_valid = false
- result.msg += str("Either setter or getter method must be specified.")
- if name_setter != "" and not obj.has_method(str(name_setter)):
- result.is_valid = false
- result.msg += str("Setter method %s does not exist. " % _str(name_setter))
- if name_getter != "" and not obj.has_method(str(name_getter)):
- result.is_valid = false
- result.msg += str("Getter method %s does not exist. " %_str(name_getter))
-
- obj.free()
- return result
-
-# ------------------------------------------------------------------------------
-# Asserts the given setter and getter methods are called when the given property
-# is accessed.
-# ------------------------------------------------------------------------------
-func _assert_setget_called(type, name_property, setter = "", getter = ""):
- var name_setter = _utils.nvl(setter, "")
- var name_getter = _utils.nvl(getter, "")
-
- var validation = _validate_assert_setget_called_input(type, name_property, str(name_setter), str(name_getter))
- if not validation.is_valid:
- _fail(validation.msg)
- return
-
- var message = ""
- var amount_calls_setter = 0
- var amount_calls_getter = 0
- var expected_calls_setter = 0
- var expected_calls_getter = 0
- var obj = _create_obj_from_type(double(type))
-
- if name_setter != '':
- expected_calls_setter = 1
- stub(obj, name_setter).to_do_nothing()
- obj.set(name_property, null)
- amount_calls_setter = gut.get_spy().call_count(obj, str(name_setter))
-
- if name_getter != '':
- expected_calls_getter = 1
- stub(obj, name_getter).to_do_nothing()
- var new_property = obj.get(name_property)
- amount_calls_getter = gut.get_spy().call_count(obj, str(name_getter))
-
- obj.free()
-
- # assert
-
- if amount_calls_setter == expected_calls_setter and amount_calls_getter == expected_calls_getter:
- _pass(str("setget for %s is correctly configured." % _str(name_property)))
- else:
- if amount_calls_setter < expected_calls_setter:
- message += " The setter was not called."
- elif amount_calls_setter > expected_calls_setter:
- message += " The setter was called but should not have been."
- if amount_calls_getter < expected_calls_getter:
- message += " The getter was not called."
- elif amount_calls_getter > expected_calls_getter:
- message += " The getter was called but should not have been."
- _fail(str(message))
-
-# ------------------------------------------------------------------------------
-# Wrapper: invokes assert_setget_called but provides a slightly more convenient
-# signature
-# ------------------------------------------------------------------------------
-func assert_setget(
- instance, name_property,
- const_or_setter = DEFAULT_SETTER_GETTER, getter="__not_set__"):
-
- var getter_name = null
- if(getter != "__not_set__"):
- getter_name = getter
-
- var setter_name = null
- if(typeof(const_or_setter) == TYPE_INT):
- if(const_or_setter in [SETTER_ONLY, DEFAULT_SETTER_GETTER]):
- setter_name = str("set_", name_property)
-
- if(const_or_setter in [GETTER_ONLY, DEFAULT_SETTER_GETTER]):
- getter_name = str("get_", name_property)
- else:
- setter_name = const_or_setter
-
- var resource = null
- if instance.is_class("Resource"):
- resource = instance
- else:
- resource = _get_type_from_obj(instance)
-
- _assert_setget_called(resource, str(name_property), setter_name, getter_name)
-
-
-# ------------------------------------------------------------------------------
-# Wrapper: asserts if the property exists, the accessor methods exist and the
-# setget keyword is set for accessor methods
-# ------------------------------------------------------------------------------
-func assert_property(instance, name_property, default_value, new_value) -> void:
- var free_me = []
- var resource = null
- var obj = null
- if instance.is_class("Resource"):
- resource = instance
- obj = _create_obj_from_type(resource)
- free_me.append(obj)
- else:
- resource = _get_type_from_obj(instance)
- obj = instance
-
- var name_setter = "set_" + str(name_property)
- var name_getter = "get_" + str(name_property)
-
- var pre_fail_count = get_fail_count()
- assert_accessors(obj, str(name_property), default_value, new_value)
- _assert_setget_called(resource, str(name_property), name_setter, name_getter)
-
- for entry in free_me:
- entry.free()
-
- # assert
- if get_fail_count() == pre_fail_count:
- _pass(str("The property is set up as expected."))
- else:
- _fail(str("The property is not set up as expected. Examine subtests to see what failed."))
-
-
-# ------------------------------------------------------------------------------
-# Mark the current test as pending.
-# ------------------------------------------------------------------------------
-func pending(text=""):
- _summary.pending += 1
- if(gut):
- _lgr.pending(text)
- gut._pending(text)
-
-# ------------------------------------------------------------------------------
-# Returns the number of times a signal was emitted. -1 returned if the object
-# is not being watched.
-# ------------------------------------------------------------------------------
-
-# ------------------------------------------------------------------------------
-# Yield for the time sent in. The optional message will be printed when
-# Gut detects the yield. When the time expires the YIELD signal will be
-# emitted.
-# ------------------------------------------------------------------------------
-func yield_for(time, msg=''):
- return gut.set_yield_time(time, msg)
-
-# ------------------------------------------------------------------------------
-# Yield to a signal or a maximum amount of time, whichever comes first. When
-# the conditions are met the YIELD signal will be emitted.
-# ------------------------------------------------------------------------------
-func yield_to(obj, signal_name, max_wait, msg=''):
- watch_signals(obj)
- gut.set_yield_signal_or_time(obj, signal_name, max_wait, msg)
-
- return gut
-
-# ------------------------------------------------------------------------------
-# Ends a test that had a yield in it. You only need to use this if you do
-# not make assertions after a yield.
-# ------------------------------------------------------------------------------
-func end_test():
- _lgr.deprecated('end_test is no longer necessary, you can remove it.')
- #gut.end_yielded_test()
-
-func get_summary():
- return _summary
-
-func get_fail_count():
- return _summary.failed
-
-func get_pass_count():
- return _summary.passed
-
-func get_pending_count():
- return _summary.pending
-
-func get_assert_count():
- return _summary.asserts
-
-func clear_signal_watcher():
- _signal_watcher.clear()
-
-func get_double_strategy():
- return gut.get_doubler().get_strategy()
-
-func set_double_strategy(double_strategy):
- gut.get_doubler().set_strategy(double_strategy)
-
-func pause_before_teardown():
- gut.pause_before_teardown()
-
-# ------------------------------------------------------------------------------
-# Convert the _summary dictionary into text
-# ------------------------------------------------------------------------------
-func get_summary_text():
- var to_return = get_script().get_path() + "\n"
- to_return += str(' ', _summary.passed, ' of ', _summary.asserts, ' passed.')
- if(_summary.pending > 0):
- to_return += str("\n ", _summary.pending, ' pending')
- if(_summary.failed > 0):
- to_return += str("\n ", _summary.failed, ' failed.')
- return to_return
-
-# ------------------------------------------------------------------------------
-# Double a script, inner class, or scene using a path or a loaded script/scene.
-#
-#
-# ------------------------------------------------------------------------------
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func _smart_double(double_info):
- var override_strat = _utils.nvl(double_info.strategy, gut.get_doubler().get_strategy())
- var to_return = null
-
- if(double_info.is_scene()):
- if(double_info.make_partial):
- to_return = gut.get_doubler().partial_double_scene(double_info.path, override_strat)
- else:
- to_return = gut.get_doubler().double_scene(double_info.path, override_strat)
-
- elif(double_info.is_native()):
- if(double_info.make_partial):
- to_return = gut.get_doubler().partial_double_gdnative(double_info.path)
- else:
- to_return = gut.get_doubler().double_gdnative(double_info.path)
-
- elif(double_info.is_script()):
- if(double_info.subpath == null):
- if(double_info.make_partial):
- to_return = gut.get_doubler().partial_double(double_info.path, override_strat)
- else:
- to_return = gut.get_doubler().double(double_info.path, override_strat)
- else:
- if(double_info.make_partial):
- to_return = gut.get_doubler().partial_double_inner(double_info.path, double_info.subpath, override_strat)
- else:
- to_return = gut.get_doubler().double_inner(double_info.path, double_info.subpath, override_strat)
- return to_return
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func double(thing, p2=null, p3=null):
- var double_info = DoubleInfo.new(thing, p2, p3)
- if(!double_info.is_valid):
- _lgr.error('double requires a class or path, you passed an instance: ' + _str(thing))
- return null
-
- double_info.make_partial = false
-
- return _smart_double(double_info)
-
-# ------------------------------------------------------------------------------
-# ------------------------------------------------------------------------------
-func partial_double(thing, p2=null, p3=null):
- var double_info = DoubleInfo.new(thing, p2, p3)
- if(!double_info.is_valid):
- _lgr.error('partial_double requires a class or path, you passed an instance: ' + _str(thing))
- return null
-
- double_info.make_partial = true
-
- return _smart_double(double_info)
-
-
-# ------------------------------------------------------------------------------
-# Specifically double a scene
-# ------------------------------------------------------------------------------
-func double_scene(path, strategy=null):
- var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy())
- return gut.get_doubler().double_scene(path, override_strat)
-
-# ------------------------------------------------------------------------------
-# Specifically double a script
-# ------------------------------------------------------------------------------
-func double_script(path, strategy=null):
- var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy())
- return gut.get_doubler().double(path, override_strat)
-
-# ------------------------------------------------------------------------------
-# Specifically double an Inner class in a a script
-# ------------------------------------------------------------------------------
-func double_inner(path, subpath, strategy=null):
- var override_strat = _utils.nvl(strategy, gut.get_doubler().get_strategy())
- return gut.get_doubler().double_inner(path, subpath, override_strat)
-
-# ------------------------------------------------------------------------------
-# Add a method that the doubler will ignore. You can pass this the path to a
-# script or scene or a loaded script or scene. When running tests, these
-# ignores are cleared after every test.
-# ------------------------------------------------------------------------------
-func ignore_method_when_doubling(thing, method_name):
- var double_info = DoubleInfo.new(thing)
- var path = double_info.path
-
- if(double_info.is_scene()):
- var inst = thing.instance()
- if(inst.get_script()):
- path = inst.get_script().get_path()
-
- gut.get_doubler().add_ignored_method(path, method_name)
-
-# ------------------------------------------------------------------------------
-# Stub something.
-#
-# Parameters
-# 1: the thing to stub, a file path or a instance or a class
-# 2: either an inner class subpath or the method name
-# 3: the method name if an inner class subpath was specified
-# NOTE: right now we cannot stub inner classes at the path level so this should
-# only be called with two parameters. I did the work though so I'm going
-# to leave it but not update the wiki.
-# ------------------------------------------------------------------------------
-func stub(thing, p2, p3=null):
- if(_utils.is_instance(thing) and !_utils.is_double(thing)):
- _lgr.error(str('You cannot use stub on ', _str(thing), ' because it is not a double.'))
- return _utils.StubParams.new()
-
- var method_name = p2
- var subpath = null
- if(p3 != null):
- subpath = p2
- method_name = p3
-
- var sp = _utils.StubParams.new(thing, method_name, subpath)
- gut.get_stubber().add_stub(sp)
- return sp
-
-# ------------------------------------------------------------------------------
-# convenience wrapper.
-# ------------------------------------------------------------------------------
-func simulate(obj, times, delta):
- gut.simulate(obj, times, delta)
-
-# ------------------------------------------------------------------------------
-# Replace the node at base_node.get_node(path) with with_this. All references
-# to the node via $ and get_node(...) will now return with_this. with_this will
-# get all the groups that the node that was replaced had.
-#
-# The node that was replaced is queued to be freed.
-#
-# TODO see replace_by method, this could simplify the logic here.
-# ------------------------------------------------------------------------------
-func replace_node(base_node, path_or_node, with_this):
- var path = path_or_node
-
- if(typeof(path_or_node) != TYPE_STRING):
- # This will cause an engine error if it fails. It always returns a
- # NodePath, even if it fails. Checking the name count is the only way
- # I found to check if it found something or not (after it worked I
- # didn't look any farther).
- path = base_node.get_path_to(path_or_node)
- if(path.get_name_count() == 0):
- _lgr.error('You passed an object that base_node does not have. Cannot replace node.')
- return
-
- if(!base_node.has_node(path)):
- _lgr.error(str('Could not find node at path [', path, ']'))
- return
-
- var to_replace = base_node.get_node(path)
- var parent = to_replace.get_parent()
- var replace_name = to_replace.get_name()
-
- parent.remove_child(to_replace)
- parent.add_child(with_this)
- with_this.set_name(replace_name)
- with_this.set_owner(parent)
-
- var groups = to_replace.get_groups()
- for i in range(groups.size()):
- with_this.add_to_group(groups[i])
-
- to_replace.queue_free()
-
-
-# ------------------------------------------------------------------------------
-# This method does a somewhat complicated dance with Gut. It assumes that Gut
-# will clear its parameter handler after it finishes calling a parameterized test
-# enough times.
-# ------------------------------------------------------------------------------
-func use_parameters(params):
- var ph = gut.get_parameter_handler()
- if(ph == null):
- ph = _utils.ParameterHandler.new(params)
- gut.set_parameter_handler(ph)
-
- var output = str('(call #', ph.get_call_count() + 1, ') with paramters: ', ph.get_current_parameters())
- _lgr.log(output)
- _lgr.inc_indent()
- return ph.next_parameters()
-
-# ------------------------------------------------------------------------------
-# Marks whatever is passed in to be freed after the test finishes. It also
-# returns what is passed in so you can save a line of code.
-# var thing = autofree(Thing.new())
-# ------------------------------------------------------------------------------
-func autofree(thing):
- gut.get_autofree().add_free(thing)
- return thing
-
-# ------------------------------------------------------------------------------
-# Works the same as autofree except queue_free will be called on the object
-# instead. This also imparts a brief pause after the test finishes so that
-# the queued object has time to free.
-# ------------------------------------------------------------------------------
-func autoqfree(thing):
- gut.get_autofree().add_queue_free(thing)
- return thing
-
-# ------------------------------------------------------------------------------
-# The same as autofree but it also adds the object as a child of the test.
-# ------------------------------------------------------------------------------
-func add_child_autofree(node, legible_unique_name = false):
- gut.get_autofree().add_free(node)
- # Explicitly calling super here b/c add_child MIGHT change and I don't want
- # a bug sneaking its way in here.
- .add_child(node, legible_unique_name)
- return node
-
-# ------------------------------------------------------------------------------
-# The same as autoqfree but it also adds the object as a child of the test.
-# ------------------------------------------------------------------------------
-func add_child_autoqfree(node, legible_unique_name=false):
- gut.get_autofree().add_queue_free(node)
- # Explicitly calling super here b/c add_child MIGHT change and I don't want
- # a bug sneaking its way in here.
- .add_child(node, legible_unique_name)
- return node
-
-# ------------------------------------------------------------------------------
-# Returns true if the test is passing as of the time of this call. False if not.
-# ------------------------------------------------------------------------------
-func is_passing():
- if(gut.get_current_test_object() != null and
- !['before_all', 'after_all'].has(gut.get_current_test_object().name)):
- return gut.get_current_test_object().passed and \
- gut.get_current_test_object().assert_count > 0
- else:
- _lgr.error('No current test object found. is_passing must be called inside a test.')
- return null
-
-# ------------------------------------------------------------------------------
-# Returns true if the test is failing as of the time of this call. False if not.
-# ------------------------------------------------------------------------------
-func is_failing():
- if(gut.get_current_test_object() != null and
- !['before_all', 'after_all'].has(gut.get_current_test_object().name)):
- return !gut.get_current_test_object().passed
- else:
- _lgr.error('No current test object found. is_failing must be called inside a test.')
- return null
-
-# ------------------------------------------------------------------------------
-# Marks the test as passing. Does not override any failing asserts or calls to
-# fail_test. Same as a passing assert.
-# ------------------------------------------------------------------------------
-func pass_test(text):
- _pass(text)
-
-# ------------------------------------------------------------------------------
-# Marks the test as failing. Same as a failing assert.
-# ------------------------------------------------------------------------------
-func fail_test(text):
- _fail(text)
-
-# ------------------------------------------------------------------------------
-# Peforms a deep compare on both values, a CompareResult instnace is returned.
-# The optional max_differences paramter sets the max_differences to be displayed.
-# ------------------------------------------------------------------------------
-func compare_deep(v1, v2, max_differences=null):
- var result = _compare.deep(v1, v2)
- if(max_differences != null):
- result.max_differences = max_differences
- return result
-
-# ------------------------------------------------------------------------------
-# Peforms a shallow compare on both values, a CompareResult instnace is returned.
-# The optional max_differences paramter sets the max_differences to be displayed.
-# ------------------------------------------------------------------------------
-func compare_shallow(v1, v2, max_differences=null):
- var result = _compare.shallow(v1, v2)
- if(max_differences != null):
- result.max_differences = max_differences
- return result
-
-# ------------------------------------------------------------------------------
-# Performs a deep compare and asserts the values are equal
-# ------------------------------------------------------------------------------
-func assert_eq_deep(v1, v2):
- var result = compare_deep(v1, v2)
- if(result.are_equal):
- _pass(result.get_short_summary())
- else:
- _fail(result.summary)
-
-# ------------------------------------------------------------------------------
-# Performs a deep compare and asserts the values are not equal
-# ------------------------------------------------------------------------------
-func assert_ne_deep(v1, v2):
- var result = compare_deep(v1, v2)
- if(!result.are_equal):
- _pass(result.get_short_summary())
- else:
- _fail(result.get_short_summary())
-
-# ------------------------------------------------------------------------------
-# Performs a shallow compare and asserts the values are equal
-# ------------------------------------------------------------------------------
-func assert_eq_shallow(v1, v2):
- var result = compare_shallow(v1, v2)
- if(result.are_equal):
- _pass(result.get_short_summary())
- else:
- _fail(result.summary)
-
-# ------------------------------------------------------------------------------
-# Performs a shallow compare and asserts the values are not equal
-# ------------------------------------------------------------------------------
-func assert_ne_shallow(v1, v2):
- var result = compare_shallow(v1, v2)
- if(!result.are_equal):
- _pass(result.get_short_summary())
- else:
- _fail(result.get_short_summary())
diff --git a/addons/gut/test_collector.gd b/addons/gut/test_collector.gd
deleted file mode 100644
index bbed3e0..0000000
--- a/addons/gut/test_collector.gd
+++ /dev/null
@@ -1,286 +0,0 @@
-# ------------------------------------------------------------------------------
-# Used to keep track of info about each test ran.
-# ------------------------------------------------------------------------------
-class Test:
- # indicator if it passed or not. defaults to true since it takes only
- # one failure to make it not pass. _fail in gut will set this.
- var passed = true
- # the name of the function
- var name = ""
- # flag to know if the name has been printed yet.
- var has_printed_name = false
- # the number of arguments the method has
- var arg_count = 0
- # The number of asserts in the test
- var assert_count = 0
- # if the test has been marked pending at anypont during
- # execution.
- var pending = false
-
-
-# ------------------------------------------------------------------------------
-# This holds all the meta information for a test script. It contains the
-# name of the inner class and an array of Test "structs".
-#
-# This class also facilitates all the exporting and importing of tests.
-# ------------------------------------------------------------------------------
-class TestScript:
- var inner_class_name = null
- var tests = []
- var path = null
- var _utils = null
- var _lgr = null
-
- func _init(utils=null, logger=null):
- _utils = utils
- _lgr = logger
-
- func to_s():
- var to_return = path
- if(inner_class_name != null):
- to_return += str('.', inner_class_name)
- to_return += "\n"
- for i in range(tests.size()):
- to_return += str(' ', tests[i].name, "\n")
- return to_return
-
- func get_new():
- return load_script().new()
-
- func load_script():
- #print('loading: ', get_full_name())
- var to_return = load(path)
- if(inner_class_name != null):
- # If we wanted to do inner classes in inner classses
- # then this would have to become some kind of loop or recursive
- # call to go all the way down the chain or this class would
- # have to change to hold onto the loaded class instead of
- # just path information.
- to_return = to_return.get(inner_class_name)
- return to_return
-
- func get_filename_and_inner():
- var to_return = get_filename()
- if(inner_class_name != null):
- to_return += '.' + inner_class_name
- return to_return
-
- func get_full_name():
- var to_return = path
- if(inner_class_name != null):
- to_return += '.' + inner_class_name
- return to_return
-
- func get_filename():
- return path.get_file()
-
- func has_inner_class():
- return inner_class_name != null
-
- # Note: although this no longer needs to export the inner_class names since
- # they are pulled from metadata now, it is easier to leave that in
- # so we don't have to cut the export down to unique script names.
- func export_to(config_file, section):
- config_file.set_value(section, 'path', path)
- config_file.set_value(section, 'inner_class', inner_class_name)
- var names = []
- for i in range(tests.size()):
- names.append(tests[i].name)
- config_file.set_value(section, 'tests', names)
-
- func _remap_path(source_path):
- var to_return = source_path
- if(!_utils.file_exists(source_path)):
- _lgr.debug('Checking for remap for: ' + source_path)
- var remap_path = source_path.get_basename() + '.gd.remap'
- if(_utils.file_exists(remap_path)):
- var cf = ConfigFile.new()
- cf.load(remap_path)
- to_return = cf.get_value('remap', 'path')
- else:
- _lgr.warn('Could not find remap file ' + remap_path)
- return to_return
-
- func import_from(config_file, section):
- path = config_file.get_value(section, 'path')
- path = _remap_path(path)
- # Null is an acceptable value, but you can't pass null as a default to
- # get_value since it thinks you didn't send a default...then it spits
- # out red text. This works around that.
- var inner_name = config_file.get_value(section, 'inner_class', 'Placeholder')
- if(inner_name != 'Placeholder'):
- inner_class_name = inner_name
- else: # just being explicit
- inner_class_name = null
-
- func get_test_named(name):
- return _utils.search_array(tests, 'name', name)
-
-# ------------------------------------------------------------------------------
-# start test_collector, I don't think I like the name.
-# ------------------------------------------------------------------------------
-var scripts = []
-var _test_prefix = 'test_'
-var _test_class_prefix = 'Test'
-
-var _utils = load('res://addons/gut/utils.gd').get_instance()
-var _lgr = _utils.get_logger()
-
-func _does_inherit_from_test(thing):
- var base_script = thing.get_base_script()
- var to_return = false
- if(base_script != null):
- var base_path = base_script.get_path()
- if(base_path == 'res://addons/gut/test.gd'):
- to_return = true
- else:
- to_return = _does_inherit_from_test(base_script)
- return to_return
-
-func _populate_tests(test_script):
- var methods = test_script.load_script().get_script_method_list()
- for i in range(methods.size()):
- var name = methods[i]['name']
- if(name.begins_with(_test_prefix)):
- var t = Test.new()
- t.name = name
- t.arg_count = methods[i]['args'].size()
- test_script.tests.append(t)
-
-func _get_inner_test_class_names(loaded):
- var inner_classes = []
- var const_map = loaded.get_script_constant_map()
- for key in const_map:
- var thing = const_map[key]
- if(typeof(thing) == TYPE_OBJECT):
- if(key.begins_with(_test_class_prefix)):
- if(_does_inherit_from_test(thing)):
- inner_classes.append(key)
- else:
- _lgr.warn(str('Ignoring Inner Class ', key,
- ' because it does not extend res://addons/gut/test.gd'))
-
- # This could go deeper and find inner classes within inner classes
- # but requires more experimentation. Right now I'm keeping it at
- # one level since that is what the previous version did and there
- # has been no demand for deeper nesting.
- # _populate_inner_test_classes(thing)
- return inner_classes
-
-func _parse_script(test_script):
- var inner_classes = []
- var scripts_found = []
-
- var loaded = load(test_script.path)
- if(_does_inherit_from_test(loaded)):
- _populate_tests(test_script)
- scripts_found.append(test_script.path)
- inner_classes = _get_inner_test_class_names(loaded)
-
- for i in range(inner_classes.size()):
- var loaded_inner = loaded.get(inner_classes[i])
- if(_does_inherit_from_test(loaded_inner)):
- var ts = TestScript.new(_utils, _lgr)
- ts.path = test_script.path
- ts.inner_class_name = inner_classes[i]
- _populate_tests(ts)
- scripts.append(ts)
- scripts_found.append(test_script.path + '[' + inner_classes[i] +']')
-
- return scripts_found
-
-# -----------------
-# Public
-# -----------------
-func add_script(path):
- # SHORTCIRCUIT
- if(has_script(path)):
- return []
-
- var f = File.new()
- # SHORTCIRCUIT
- if(!f.file_exists(path)):
- _lgr.error('Could not find script: ' + path)
- return
-
- var ts = TestScript.new(_utils, _lgr)
- ts.path = path
- scripts.append(ts)
- return _parse_script(ts)
-
-func clear():
- scripts.clear()
-
-func has_script(path):
- var found = false
- var idx = 0
- while(idx < scripts.size() and !found):
- if(scripts[idx].get_full_name() == path):
- found = true
- else:
- idx += 1
- return found
-
-func export_tests(path):
- var success = true
- var f = ConfigFile.new()
- for i in range(scripts.size()):
- scripts[i].export_to(f, str('TestScript-', i))
- var result = f.save(path)
- if(result != OK):
- _lgr.error(str('Could not save exported tests to [', path, ']. Error code: ', result))
- success = false
- return success
-
-func import_tests(path):
- var success = false
- var f = ConfigFile.new()
- var result = f.load(path)
- if(result != OK):
- _lgr.error(str('Could not load exported tests from [', path, ']. Error code: ', result))
- else:
- var sections = f.get_sections()
- for key in sections:
- var ts = TestScript.new(_utils, _lgr)
- ts.import_from(f, key)
- _populate_tests(ts)
- scripts.append(ts)
- success = true
- return success
-
-func get_script_named(name):
- return _utils.search_array(scripts, 'get_filename_and_inner', name)
-
-func get_test_named(script_name, test_name):
- var s = get_script_named(script_name)
- if(s != null):
- return s.get_test_named(test_name)
- else:
- return null
-
-func to_s():
- var to_return = ''
- for i in range(scripts.size()):
- to_return += scripts[i].to_s() + "\n"
- return to_return
-
-# ---------------------
-# Accessors
-# ---------------------
-func get_logger():
- return _lgr
-
-func set_logger(logger):
- _lgr = logger
-
-func get_test_prefix():
- return _test_prefix
-
-func set_test_prefix(test_prefix):
- _test_prefix = test_prefix
-
-func get_test_class_prefix():
- return _test_class_prefix
-
-func set_test_class_prefix(test_class_prefix):
- _test_class_prefix = test_class_prefix
diff --git a/addons/gut/thing_counter.gd b/addons/gut/thing_counter.gd
deleted file mode 100644
index a9b0b48..0000000
--- a/addons/gut/thing_counter.gd
+++ /dev/null
@@ -1,43 +0,0 @@
-var things = {}
-
-func get_unique_count():
- return things.size()
-
-func add(thing):
- if(things.has(thing)):
- things[thing] += 1
- else:
- things[thing] = 1
-
-func has(thing):
- return things.has(thing)
-
-func get(thing):
- var to_return = 0
- if(things.has(thing)):
- to_return = things[thing]
- return to_return
-
-func sum():
- var count = 0
- for key in things:
- count += things[key]
- return count
-
-func to_s():
- var to_return = ""
- for key in things:
- to_return += str(key, ": ", things[key], "\n")
- to_return += str("sum: ", sum())
- return to_return
-
-func get_max_count():
- var max_val = null
- for key in things:
- if(max_val == null or things[key] > max_val):
- max_val = things[key]
- return max_val
-
-func add_array_items(array):
- for i in range(array.size()):
- add(array[i])
diff --git a/addons/gut/utils.gd b/addons/gut/utils.gd
deleted file mode 100644
index ce13d98..0000000
--- a/addons/gut/utils.gd
+++ /dev/null
@@ -1,344 +0,0 @@
-# ##############################################################################
-#(G)odot (U)nit (T)est class
-#
-# ##############################################################################
-# The MIT License (MIT)
-# =====================
-#
-# Copyright (c) 2020 Tom "Butch" Wesley
-#
-# Permission is hereby granted, free of charge, to any person obtaining a copy
-# of this software and associated documentation files (the "Software"), to deal
-# in the Software without restriction, including without limitation the rights
-# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-# copies of the Software, and to permit persons to whom the Software is
-# furnished to do so, subject to the following conditions:
-#
-# The above copyright notice and this permission notice shall be included in
-# all copies or substantial portions of the Software.
-#
-# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-# THE SOFTWARE.
-#
-# ##############################################################################
-# Description
-# -----------
-# This class is a PSUEDO SINGLETON. You should not make instances of it but use
-# the get_instance static method.
-# ##############################################################################
-extends Node
-
-# ------------------------------------------------------------------------------
-# The instance name as a function since you can't have static variables.
-# ------------------------------------------------------------------------------
-static func INSTANCE_NAME():
- return '__GutUtilsInstName__'
-
-# ------------------------------------------------------------------------------
-# Gets the root node without having to be in the tree and pushing out an error
-# if we don't have a main loop ready to go yet.
-# ------------------------------------------------------------------------------
-static func get_root_node():
- var to_return = null
- var main_loop = Engine.get_main_loop()
- if(main_loop != null):
- return main_loop.root
- else:
- push_error('No Main Loop Yet')
- return null
-
-# ------------------------------------------------------------------------------
-# Get the ONE instance of utils
-# ------------------------------------------------------------------------------
-static func get_instance():
- var the_root = get_root_node()
- var inst = null
- if(the_root.has_node(INSTANCE_NAME())):
- inst = the_root.get_node(INSTANCE_NAME())
- else:
- inst = load('res://addons/gut/utils.gd').new()
- inst.set_name(INSTANCE_NAME())
- the_root.add_child(inst)
- return inst
-
-var Logger = load('res://addons/gut/logger.gd') # everything should use get_logger
-var _lgr = null
-
-var _test_mode = false
-
-var AutoFree = load('res://addons/gut/autofree.gd')
-var Comparator = load('res://addons/gut/comparator.gd')
-var CompareResult = load('res://addons/gut/compare_result.gd')
-var DiffTool = load('res://addons/gut/diff_tool.gd')
-var Doubler = load('res://addons/gut/doubler.gd')
-var Gut = load('res://addons/gut/gut.gd')
-var HookScript = load('res://addons/gut/hook_script.gd')
-var MethodMaker = load('res://addons/gut/method_maker.gd')
-var OneToMany = load('res://addons/gut/one_to_many.gd')
-var OrphanCounter = load('res://addons/gut/orphan_counter.gd')
-var ParameterFactory = load('res://addons/gut/parameter_factory.gd')
-var ParameterHandler = load('res://addons/gut/parameter_handler.gd')
-var Printers = load('res://addons/gut/printers.gd')
-var Spy = load('res://addons/gut/spy.gd')
-var Strutils = load('res://addons/gut/strutils.gd')
-var Stubber = load('res://addons/gut/stubber.gd')
-var StubParams = load('res://addons/gut/stub_params.gd')
-var Summary = load('res://addons/gut/summary.gd')
-var Test = load('res://addons/gut/test.gd')
-var TestCollector = load('res://addons/gut/test_collector.gd')
-var ThingCounter = load('res://addons/gut/thing_counter.gd')
-
-# Source of truth for the GUT version
-var version = '7.1.0'
-# The required Godot version as an array.
-var req_godot = [3, 2, 0]
-# Used for doing file manipulation stuff so as to not keep making File instances.
-# could be a bit of overkill but who cares.
-var _file_checker = File.new()
-
-const GUT_METADATA = '__gut_metadata_'
-
-enum DOUBLE_STRATEGY{
- FULL,
- PARTIAL
-}
-
-enum DIFF {
- DEEP,
- SHALLOW,
- SIMPLE
-}
-
-# ------------------------------------------------------------------------------
-# Blurb of text with GUT and Godot versions.
-# ------------------------------------------------------------------------------
-func get_version_text():
- var v_info = Engine.get_version_info()
- var gut_version_info = str('GUT version: ', version)
- var godot_version_info = str('Godot version: ', v_info.major, '.', v_info.minor, '.', v_info.patch)
- return godot_version_info + "\n" + gut_version_info
-
-
-# ------------------------------------------------------------------------------
-# Returns a nice string for erroring out when we have a bad Godot version.
-# ------------------------------------------------------------------------------
-func get_bad_version_text():
- var ver = join_array(req_godot, '.')
- var info = Engine.get_version_info()
- var gd_version = str(info.major, '.', info.minor, '.', info.patch)
- return 'GUT ' + version + ' requires Godot ' + ver + ' or greater. Godot version is ' + gd_version
-
-
-# ------------------------------------------------------------------------------
-# Checks the Godot version against req_godot array.
-# ------------------------------------------------------------------------------
-func is_version_ok(engine_info=Engine.get_version_info(),required=req_godot):
- var is_ok = null
- var engine_array = [engine_info.major, engine_info.minor, engine_info.patch]
-
- var idx = 0
- while(is_ok == null and idx < engine_array.size()):
- if(int(engine_array[idx]) > int(required[idx])):
- is_ok = true
- elif(int(engine_array[idx]) < int(required[idx])):
- is_ok = false
-
- idx += 1
-
- # still null means each index was the same.
- return nvl(is_ok, true)
-
-
-# ------------------------------------------------------------------------------
-# Everything should get a logger through this.
-#
-# When running in test mode this will always return a new logger so that errors
-# are not caused by getting bad warn/error/etc counts.
-# ------------------------------------------------------------------------------
-func get_logger():
- if(_test_mode):
- return Logger.new()
- else:
- if(_lgr == null):
- _lgr = Logger.new()
- return _lgr
-
-
-# ------------------------------------------------------------------------------
-# Returns an array created by splitting the string by the delimiter
-# ------------------------------------------------------------------------------
-func split_string(to_split, delim):
- var to_return = []
-
- var loc = to_split.find(delim)
- while(loc != -1):
- to_return.append(to_split.substr(0, loc))
- to_split = to_split.substr(loc + 1, to_split.length() - loc)
- loc = to_split.find(delim)
- to_return.append(to_split)
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# Returns a string containing all the elements in the array separated by delim
-# ------------------------------------------------------------------------------
-func join_array(a, delim):
- var to_return = ''
- for i in range(a.size()):
- to_return += str(a[i])
- if(i != a.size() -1):
- to_return += str(delim)
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# return if_null if value is null otherwise return value
-# ------------------------------------------------------------------------------
-func nvl(value, if_null):
- if(value == null):
- return if_null
- else:
- return value
-
-
-# ------------------------------------------------------------------------------
-# returns true if the object has been freed, false if not
-#
-# From what i've read, the weakref approach should work. It seems to work most
-# of the time but sometimes it does not catch it. The str comparison seems to
-# fill in the gaps. I've not seen any errors after adding that check.
-# ------------------------------------------------------------------------------
-func is_freed(obj):
- var wr = weakref(obj)
- return !(wr.get_ref() and str(obj) != '[Deleted Object]')
-
-
-# ------------------------------------------------------------------------------
-# Pretty self explanitory.
-# ------------------------------------------------------------------------------
-func is_not_freed(obj):
- return !is_freed(obj)
-
-
-# ------------------------------------------------------------------------------
-# Checks if the passed in object is a GUT Double or Partial Double.
-# ------------------------------------------------------------------------------
-func is_double(obj):
- var to_return = false
- if(typeof(obj) == TYPE_OBJECT and is_instance_valid(obj)):
- to_return = obj.has_method('__gut_instance_from_id')
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# Checks if the passed in is an instance of a class
-# ------------------------------------------------------------------------------
-func is_instance(obj):
- return typeof(obj) == TYPE_OBJECT and !obj.has_method('new') and !obj.has_method('instance')
-
-
-# ------------------------------------------------------------------------------
-# Returns an array of values by calling get(property) on each element in source
-# ------------------------------------------------------------------------------
-func extract_property_from_array(source, property):
- var to_return = []
- for i in (source.size()):
- to_return.append(source[i].get(property))
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# true if file exists, false if not.
-# ------------------------------------------------------------------------------
-func file_exists(path):
- return _file_checker.file_exists(path)
-
-
-# ------------------------------------------------------------------------------
-# Write a file.
-# ------------------------------------------------------------------------------
-func write_file(path, content):
- var f = File.new()
- var result = f.open(path, f.WRITE)
- if(result == OK):
- f.store_string(content)
- f.close()
-
-
-# ------------------------------------------------------------------------------
-# true if what is passed in is null or an empty string.
-# ------------------------------------------------------------------------------
-func is_null_or_empty(text):
- return text == null or text == ''
-
-
-# ------------------------------------------------------------------------------
-# Get the name of a native class or null if the object passed in is not a
-# native class.
-# ------------------------------------------------------------------------------
-func get_native_class_name(thing):
- var to_return = null
- if(is_native_class(thing)):
- var newone = thing.new()
- to_return = newone.get_class()
- newone.free()
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# Checks an object to see if it is a GDScriptNativeClass
-# ------------------------------------------------------------------------------
-func is_native_class(thing):
- var it_is = false
- if(typeof(thing) == TYPE_OBJECT):
- it_is = str(thing).begins_with("[GDScriptNativeClass:")
- return it_is
-
-
-# ------------------------------------------------------------------------------
-# Returns the text of a file or an empty string if the file could not be opened.
-# ------------------------------------------------------------------------------
-func get_file_as_text(path):
- var to_return = ''
- var f = File.new()
- var result = f.open(path, f.READ)
- if(result == OK):
- to_return = f.get_as_text()
- f.close()
- return to_return
-
-
-# ------------------------------------------------------------------------------
-# Loops through an array of things and calls a method or checks a property on
-# each element until it finds the returned value. The item in the array is
-# returned or null if it is not found.
-# ------------------------------------------------------------------------------
-func search_array(ar, prop_method, value):
- var found = false
- var idx = 0
-
- while(idx < ar.size() and !found):
- var item = ar[idx]
- if(item.get(prop_method) != null):
- if(item.get(prop_method) == value):
- found = true
- elif(item.has_method(prop_method)):
- if(item.call(prop_method) == value):
- found = true
-
- if(!found):
- idx += 1
-
- if(found):
- return ar[idx]
- else:
- return null
-
-
-func are_datatypes_same(got, expected):
- return !(typeof(got) != typeof(expected) and got != null and expected != null)
diff --git a/addons/http-sse-client/HTTPSSEClient.gd b/addons/http-sse-client/HTTPSSEClient.gd
index ea77a34..2a01706 100644
--- a/addons/http-sse-client/HTTPSSEClient.gd
+++ b/addons/http-sse-client/HTTPSSEClient.gd
@@ -1,7 +1,6 @@
-tool
+@tool
extends Node
-
signal new_sse_event(headers, event, data)
signal connected
signal connection_error(error)
@@ -16,31 +15,30 @@ var is_connected = false
var domain
var url_after_domain
var port
-var use_ssl
-var verify_host
+var trusted_chain
+var common_name_override
var told_to_connect = false
var connection_in_progress = false
var is_requested = false
-var response_body = PoolByteArray()
-
+var response_body = PackedByteArray()
-func connect_to_host(domain: String, url_after_domain: String, port: int = -1, use_ssl: bool = false, verify_host: bool = true):
+func connect_to_host(domain : String, url_after_domain : String, port : int = -1, trusted_chain : X509Certificate = null, common_name_override : String = ""):
+ process_mode = Node.PROCESS_MODE_INHERIT
self.domain = domain
self.url_after_domain = url_after_domain
self.port = port
- self.use_ssl = use_ssl
- self.verify_host = verify_host
+ self.trusted_chain = trusted_chain
+ self.common_name_override = common_name_override
told_to_connect = true
-
func attempt_to_connect():
- var err = httpclient.connect_to_host(domain, port, use_ssl, verify_host)
+ var tls_options = TLSOptions.client(trusted_chain, common_name_override)
+ var err = httpclient.connect_to_host(domain, port, tls_options)
if err == OK:
- emit_signal("connected")
+ connected.emit()
is_connected = true
else:
- emit_signal("connection_error", str(err))
-
+ connection_error.emit(str(err))
func attempt_to_request(httpclient_status):
if httpclient_status == HTTPClient.STATUS_CONNECTING or httpclient_status == HTTPClient.STATUS_RESOLVING:
@@ -51,33 +49,34 @@ func attempt_to_request(httpclient_status):
if err == OK:
is_requested = true
-
func _parse_response_body(headers):
var body = response_body.get_string_from_utf8()
if body:
var event_data = get_event_data(body)
if event_data.event != "keep-alive" and event_data.event != continue_internal:
- var result = JSON.parse(event_data.data).result
- if response_body.size() > 0 and result: # stop here if the value doesn't parse
+ var result = Utilities.get_json_data(event_data.data)
+ if result != null:
+ var parsed_text = result
+ if response_body.size() > 0: # stop here if the value doesn't parse
+ response_body.resize(0)
+ new_sse_event.emit(headers, event_data.event, result)
+ else:
+ if event_data.event != continue_internal:
response_body.resize(0)
- emit_signal("new_sse_event", headers, event_data.event, result)
- elif event_data.event != continue_internal:
- response_body.resize(0)
-
func _process(delta):
- if not told_to_connect:
+ if !told_to_connect:
return
- if not is_connected:
- if not connection_in_progress:
+ if !is_connected:
+ if !connection_in_progress:
attempt_to_connect()
connection_in_progress = true
return
httpclient.poll()
var httpclient_status = httpclient.get_status()
- if not is_requested:
+ if !is_requested:
attempt_to_request(httpclient_status)
return
@@ -87,7 +86,7 @@ func _process(delta):
if httpclient_status == HTTPClient.STATUS_BODY:
httpclient.poll()
var chunk = httpclient.read_response_body_chunk()
- if chunk.size() == 0:
+ if(chunk.size() == 0):
return
else:
response_body = response_body + chunk
@@ -105,8 +104,7 @@ func _process(delta):
if response_body.size() > 0:
_parse_response_body(headers)
-
-func get_event_data(body: String) -> Dictionary:
+func get_event_data(body : String):
var result = {}
var event_idx = body.find(event_tag)
if event_idx == -1:
@@ -116,17 +114,16 @@ func get_event_data(body: String) -> Dictionary:
var data_idx = body.find(data_tag, event_idx + event_tag.length())
assert(data_idx != -1)
var event = body.substr(event_idx, data_idx)
- event = event.replace(event_tag, "").strip_edges()
- assert(event)
- assert(event.length() > 0)
- result["event"] = event
- var data = body.right(data_idx + data_tag.length()).strip_edges()
+ var event_value = event.replace(event_tag, "").strip_edges()
+ assert(event_value)
+ assert(event_value.length() > 0)
+ result["event"] = event_value
+ var data = body.right(body.length() - (data_idx + data_tag.length())).strip_edges()
assert(data)
assert(data.length() > 0)
result["data"] = data
return result
-
func _exit_tree():
if httpclient:
httpclient.close()
diff --git a/addons/http-sse-client/httpsseclient_plugin.gd b/addons/http-sse-client/httpsseclient_plugin.gd
index 26dda6c..87303c8 100644
--- a/addons/http-sse-client/httpsseclient_plugin.gd
+++ b/addons/http-sse-client/httpsseclient_plugin.gd
@@ -1,10 +1,8 @@
-tool
+@tool
extends EditorPlugin
-
func _enter_tree():
add_custom_type("HTTPSSEClient", "Node", preload("HTTPSSEClient.gd"), preload("icon.png"))
-
func _exit_tree():
remove_custom_type("HTTPSSEClient")
diff --git a/addons/silicon.util.custom_docs/class_doc_generator.gd b/addons/silicon.util.custom_docs/class_doc_generator.gd
deleted file mode 100644
index e703056..0000000
--- a/addons/silicon.util.custom_docs/class_doc_generator.gd
+++ /dev/null
@@ -1,342 +0,0 @@
-tool
-extends Reference
-
-
-var _pending_docs := {}
-var _docs_queue := []
-
-const _GD_TYPES = [
- "", "bool", "int", "float",
- "String", "Vector2", "Rect2", "Vector3",
- "Transform2D", "Plane", "Quat", "AABB",
- "Basis", "Transform", "Color", "NodePath",
- "RID", "Object", "Dictionary", "Array",
- "PoolByteArray", "PoolIntArray", "PoolRealArray", "PoolStringArray",
- "PoolVector2Array", "PoolVector3Array", "PoolColorArray"
-]
-
-var plugin: EditorPlugin
-
-
-func _update() -> void:
- var time := OS.get_ticks_msec()
- while not _docs_queue.empty() and OS.get_ticks_msec() - time < 5:
- var name: String = _docs_queue.pop_front()
- var doc: ClassDocItem = _pending_docs[name]
- var should_first_gen := _generate(doc)
-
- if should_first_gen.empty():
- _pending_docs.erase(name)
- else:
- _docs_queue.push_back(name)
- _docs_queue.erase(should_first_gen)
- _docs_queue.push_front(should_first_gen)
-
-
-func generate(name: String, base: String, script_path: String) -> ClassDocItem:
- if name in _pending_docs:
- return _pending_docs[name]
-
- var doc := ClassDocItem.new({
- name = name,
- base = base,
- path = script_path
- })
-
- _pending_docs[name] = doc
- _docs_queue.append(name)
- return doc
-
-
-func _generate(doc: ClassDocItem) -> String:
- var script: GDScript = load(doc.path)
- var code_lines := script.source_code.split("\n")
-
- var inherits := doc.base
- var parent_props := []
- var parent_methods := []
- var parent_constants := []
- while inherits != "" and inherits in plugin.class_docs:
- if inherits in _pending_docs:
- return inherits
-
- for prop in plugin.class_docs[inherits].properties:
- parent_props.append(prop.name)
- for method in plugin.class_docs[inherits].methods:
- parent_methods.append(method.name)
- for constant in plugin.class_docs[inherits].constants:
- parent_constants.append(constant.name)
- inherits = plugin.get_parent_class(inherits)
-
- for method in script.get_script_method_list():
- if method.name.begins_with("_") or method.name in parent_methods:
- continue
- doc.methods.append(_create_method_doc(method.name, script, method))
-
- for property in script.get_script_property_list():
- if property.name.begins_with("_") or property.name in parent_props:
- continue
- doc.properties.append(_create_property_doc(property.name, script, property))
-
- for _signal in script.get_script_signal_list():
- var signal_doc := SignalDocItem.new({
- "name": _signal.name
- })
- doc.signals.append(signal_doc)
-
- for arg in _signal.args:
- signal_doc.args.append(ArgumentDocItem.new({
- "name": arg.name,
- "type": _type_string(
- arg.type,
- arg["class_name"]
- ) if arg.type != TYPE_NIL else "Variant"
- }))
-
- for constant in script.get_script_constant_map():
- if constant.begins_with("_") or constant in parent_constants:
- continue
- var value = script.get_script_constant_map()[constant]
-
- # Check if constant is an enumerator.
- var is_enum := false
- if typeof(value) == TYPE_DICTIONARY:
- is_enum = true
- for i in value.size():
- if typeof(value.keys()[i]) != TYPE_STRING or typeof(value.values()[i]) != TYPE_INT:
- is_enum = false
- break
-
- if is_enum:
- for _enum in value:
- doc.constants.append(ConstantDocItem.new({
- "name": _enum,
- "value": value[_enum],
- "enumeration": constant
- }))
- else:
- doc.constants.append(ConstantDocItem.new({
- "name": constant,
- "value": value
- }))
-
- var comment_block := ""
- var annotations := {}
- var reading_block := false
- var enum_block := false
- for line in code_lines:
- var indented: bool = line.begins_with(" ") or line.begins_with("\t")
- if line.begins_with("##"):
- reading_block = true
- else:
- reading_block = false
- comment_block = comment_block.trim_suffix("\n")
-
- if line.begins_with("enum"):
- enum_block = true
- if line.find("}") != -1 and enum_block:
- enum_block = false
-
- if line.find("##") != -1 and not reading_block:
- var offset := 3 if line.find("## ") != -1 else 2
- comment_block = line.right(line.find("##") + offset)
-
- if reading_block:
- if line.begins_with("## "):
- line = line.trim_prefix("## ")
- else:
- line = line.trim_prefix("##")
- if line.begins_with("@"):
- var annote: Array = line.split(" ", true, 1)
- if annote[0] == "@tutorial" and annote.size() == 2:
- if annotations.has("@tutorial"):
- annotations["@tutorial"].append(annote[1])
- annote[1] = annotations["@tutorial"]
- else:
- annote[1] = [annote[1]]
- annotations[annote[0]] = null if annote.size() == 1 else annote[1]
- else:
- comment_block += line + "\n"
-
- elif not comment_block.empty():
- var doc_item: DocItem
-
- # Class document
- if line.begins_with("extends") or line.begins_with("tool") or line.begins_with("class_name"):
- if annotations.has("@doc-ignore"):
- return ""
- if annotations.has("@contribute"):
- doc.contriute_url = annotations["@contribute"]
- if annotations.has("@tutorial"):
- doc.tutorials = annotations["@tutorial"]
- var doc_split = comment_block.split("\n", true, 1)
- doc.brief = doc_split[0]
- if doc_split.size() == 2:
- doc.description = doc_split[1]
- doc_item = doc
-
- # Method document
- elif line.find("func ") != -1 and not indented:
- var regex := RegEx.new()
- regex.compile("func ([a-zA-Z0-9_]+)")
- var method := regex.search(line).get_string(1)
- var method_doc := doc.get_method_doc(method)
-
- if not method_doc and method:
- method_doc = _create_method_doc(method, script)
- if method_doc:
- doc.methods.append(method_doc)
-
- if method_doc:
- if annotations.has("@args"):
- var params = annotations["@args"].split(",")
- for i in min(params.size(), method_doc.args.size()):
- method_doc.args[i].name = params[i].strip_edges()
- if annotations.has("@arg-defaults"):
- var params = annotations["@arg-defaults"].split(",")
- for i in min(params.size(), method_doc.args.size()):
- method_doc.args[i].default = params[i].strip_edges().replace(";", ",")
- if annotations.has("@arg-types"):
- var params = annotations["@arg-types"].split(",")
- for i in min(params.size(), method_doc.args.size()):
- method_doc.args[i].type = params[i].strip_edges()
- if annotations.has("@arg-enums"):
- var params = annotations["@arg-enums"].split(",")
- for i in min(params.size(), method_doc.args.size()):
- method_doc.args[i].enumeration = params[i].strip_edges()
- if annotations.has("@return"):
- method_doc.return_type = annotations["@return"]
- if annotations.has("@return-enum"):
- method_doc.return_enum = annotations["@return-enum"]
- method_doc.is_virtual = annotations.has("@virtual")
- method_doc.description = comment_block
- doc_item = method_doc
-
- # Property document
- elif line.find("var ") != -1 and not indented:
- var regex := RegEx.new()
- regex.compile("var ([a-zA-Z0-9_]+)")
- var prop := regex.search(line).get_string(1)
- var prop_doc := doc.get_property_doc(prop)
- if not prop_doc and prop:
- prop_doc = _create_property_doc(prop, script)
- if prop_doc:
- doc.properties.append(prop_doc)
-
- if prop_doc:
- if annotations.has("@type"):
- prop_doc.type = annotations["@type"]
- if annotations.has("@default"):
- prop_doc.default = annotations["@default"]
- if annotations.has("@enum"):
- prop_doc.enumeration = annotations["@enum"]
- if annotations.has("@setter"):
- prop_doc.setter = annotations["@setter"]
- if annotations.has("@getter"):
- prop_doc.getter = annotations["@getter"]
- prop_doc.description = comment_block
- doc_item = prop_doc
-
- # Signal document
- elif line.find("signal") != -1 and not indented:
- var regex := RegEx.new()
- regex.compile("signal ([a-zA-Z0-9_]+)")
- var signl := regex.search(line).get_string(1)
- var signal_doc := doc.get_signal_doc(signl)
- if signal_doc:
- if annotations.has("@arg-types"):
- var params = annotations["@arg-types"].split(",")
- for i in min(params.size(), signal_doc.args.size()):
- signal_doc.args[i].type = params[i].strip_edges()
- if annotations.has("@arg-enums"):
- var params = annotations["@arg-enums"].split(",")
- for i in min(params.size(), signal_doc.args.size()):
- signal_doc.args[i].enumeration = params[i].strip_edges()
- signal_doc.description = comment_block
- doc_item = signal_doc
-
- # Constant document
- elif line.find("const") != -1 and not indented:
- var regex := RegEx.new()
- regex.compile("const ([a-zA-Z0-9_]+)")
- var constant := regex.search(line).get_string(1)
- var const_doc := doc.get_constant_doc(constant)
- if const_doc:
- const_doc.description = comment_block
- doc_item = const_doc
-
- # Enumerator document
- elif enum_block: # Handle enumerators
- for enum_doc in doc.constants:
- if line.find(enum_doc.name) != -1:
- enum_doc.description = comment_block
- doc_item = enum_doc
- break
-
- # Meta annotations
- if doc_item:
- for annote in annotations:
- if annote.find("@meta-") == 0:
- var key: String = annote.right("@meta-".length())
- doc_item.meta[key] = annotations[annote].strip_edges()
-
- comment_block = ""
- annotations.clear()
- return ""
-
-
-func _create_method_doc(name: String, script: Script = null, method := {}) -> MethodDocItem:
- if method.empty():
- var methods := script.get_script_method_list()
- for m in methods:
- if m.name == name:
- method = m
- break
-
- if not method.has("name"):
- return null
-
- var method_doc := MethodDocItem.new({
- "name": method.name,
- "return_type": _type_string(
- method["return"]["type"],
- method["return"]["class_name"]
- ) if method["return"]["type"] != TYPE_NIL else "void",
- })
- for arg in method.args:
- method_doc.args.append(ArgumentDocItem.new({
- "name": arg.name,
- "type": _type_string(
- arg.type,
- arg["class_name"]
- ) if arg.type != TYPE_NIL else "Variant"
- }))
- return method_doc
-
-
-func _create_property_doc(name: String, script: Script = null, property := {}) -> PropertyDocItem:
- if property.empty():
- var properties := script.get_script_property_list()
- for p in properties:
- if p.name == name:
- property = p
- break
-
- if not property.has("name"):
- return null
-
- var property_doc := PropertyDocItem.new({
- "name": name,
- "type": _type_string(
- property.type,
- property["class_name"]
- ) if property.type != TYPE_NIL else "Variant"
- })
- return property_doc
-
-
-func _type_string(type: int, _class_name: String) -> String:
- if type == TYPE_OBJECT:
- return _class_name
- else:
- return _GD_TYPES[type]
diff --git a/addons/silicon.util.custom_docs/doc_exporter/doc_exporter.gd b/addons/silicon.util.custom_docs/doc_exporter/doc_exporter.gd
deleted file mode 100644
index 6591e71..0000000
--- a/addons/silicon.util.custom_docs/doc_exporter/doc_exporter.gd
+++ /dev/null
@@ -1,13 +0,0 @@
-## The base class for every document exporter.
-## @contribute https://placeholder_contribute.com
-tool
-class_name DocExporter
-extends Reference
-
-
-## @virtual
-## @args doc
-## @arg-types ClassDocItem
-## This function gets called to generate a document string from a [ClassDocItem].
-func _generate(doc: ClassDocItem) -> String:
- return ""
diff --git a/addons/silicon.util.custom_docs/doc_exporter/editor_help_doc_exporter.gd b/addons/silicon.util.custom_docs/doc_exporter/editor_help_doc_exporter.gd
deleted file mode 100644
index 260f87c..0000000
--- a/addons/silicon.util.custom_docs/doc_exporter/editor_help_doc_exporter.gd
+++ /dev/null
@@ -1,1046 +0,0 @@
-tool
-extends DocExporter
-
-var plugin: EditorPlugin
-
-var label: RichTextLabel
-var class_docs: Dictionary
-
-var editor_settings: EditorSettings
-var theme: Theme
-var class_list := Array(ClassDB.get_class_list()) + [
- "Variant", "bool", "int", "float",
- "String", "Vector2", "Rect2", "Vector3",
- "Transform2D", "Plane", "Quat", "AABB",
- "Basis", "Transform", "Color", "NodePath",
- "RID", "Object", "Dictionary", "Array",
- "PoolByteArray", "PoolIntArray", "PoolRealArray",
- "PoolStringArray", "PoolVector2Array",
- "PoolVector3Array", "PoolColorArray"
-]
-
-var section_lines := []
-var description_line := 0
-var signal_line := {}
-var method_line := {}
-var property_line := {}
-var enum_line := {}
-var constant_line := {}
-
-
-var doc_font: Font
-var doc_bold_font: Font
-var doc_title_font: Font
-var doc_code_font: Font
-
-var title_color: Color
-var text_color: Color
-var headline_color: Color
-var base_type_color: Color
-var comment_color: Color
-var symbol_color: Color
-var value_color: Color
-var qualifier_color: Color
-var type_color: Color
-
-
-func _generate(doc: ClassDocItem) -> String:
- var is_current: bool = label.is_visible_in_tree()
- var link_color_text := title_color.to_html()
- section_lines.clear()
- if is_current:
- signal_line.clear()
- method_line.clear()
- property_line.clear()
- enum_line.clear()
- constant_line.clear()
-
- label.visible = true
- label.clear()
-
- # Class Name
- if is_current:
- section_lines.append(["Top", 0])
- label.push_font(doc_title_font)
- label.push_color(title_color)
- label.add_text("Class: ")
- label.push_color(headline_color)
- add_text(doc.name)
- label.pop()
- label.pop()
- label.pop()
- label.add_text("\n")
-
- # Ascendance
- if doc.base != "":
- label.push_color(title_color)
- label.push_font(doc_font)
- label.add_text("Inherits: ")
- label.pop()
-
- var inherits = doc.base
-
- while inherits != "":
- add_type(inherits, "")
- inherits = plugin.get_parent_class(inherits)
-
- if inherits != "":
- label.add_text(" < ")
-
- label.pop()
- label.add_text("\n")
-
- # Descendents
- var found := false
- var prev := false
- for name in class_docs:
- if class_docs[name].base == doc.name:
- if not found:
- label.push_color(title_color)
- label.push_font(doc_font)
- label.add_text("Inherited by: ")
- label.pop()
- found = true
-
- if prev:
- label.add_text(" , ")
-
- add_type(name, "")
- prev = true
- if found:
- label.pop()
- label.add_text("\n")
-
- label.add_text("\n")
- label.add_text("\n")
-
- # Brief description
- if doc.brief != "":
- label.push_color(text_color)
- label.push_font(doc_bold_font)
- label.push_indent(1)
- add_text(doc.brief)
- label.pop()
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
- label.add_text("\n")
-
- if doc.description != "":
- if is_current:
- section_lines.append(["Description", label.get_line_count() - 2])
- description_line = label.get_line_count() - 2
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Description")
- label.pop()
- label.pop()
-
- label.add_text("\n")
- label.add_text("\n")
- label.push_color(text_color)
- label.push_font(doc_font)
- label.push_indent(1)
- add_text(doc.description)
- label.pop()
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
- label.add_text("\n")
-
- # Online tutorials
- if doc.tutorials.size():
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Online Tutorials")
- label.pop()
- label.pop()
-
- label.push_indent(1)
- label.push_font(doc_code_font)
- label.add_text("\n")
-
- for tutorial in doc.tutorials:
- var link: String = tutorial
- var linktxt: String = tutorial
- var seppos := link.find("//")
- if seppos != -1:
- link = link.right(seppos + 2)
-
- label.push_color(symbol_color)
- label.append_bbcode("[url=" + linktxt + "]" + link + "[/url]")
- label.pop()
- label.add_text("\n")
-
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
-
- # Properties overview
- var skip_methods := []
- var property_descr := false
-
- if doc.properties.size():
- if is_current:
- section_lines.append(["Properties", label.get_line_count() - 2])
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Properties")
- label.pop()
- label.pop()
-
- label.add_text("\n")
- label.push_font(doc_code_font)
- label.push_indent(1)
- label.push_table(2)
- label.set_table_column_expand(1, true, 1)
-
- for property in doc.properties:
- property_line[property.name] = label.get_line_count() - 2 #gets overridden if description
- label.push_cell()
- label.push_align(RichTextLabel.ALIGN_RIGHT)
- label.push_font(doc_code_font)
- add_type(property.type, property.enumeration)
- label.pop()
- label.pop()
- label.pop()
-
- var describe := false
-
- if property.setter != "":
- skip_methods.append(property.setter)
- describe = true
- if property.getter != "":
- skip_methods.append(property.getter)
- describe = true
-
- if property.description != "":
- describe = true
-
- label.push_cell()
- label.push_font(doc_code_font)
- label.push_color(headline_color)
-
- if describe:
- label.push_meta("@member " + property.name)
-
- add_text(property.name)
-
- if describe:
- label.pop()
- property_descr = true
-
- if property.default != "":
- label.push_color(symbol_color)
- label.add_text(" [default: ")
- label.pop()
- label.push_color(value_color)
- add_text(property.default)
- label.pop()
- label.push_color(symbol_color)
- label.add_text("]")
- label.pop()
-
- label.pop()
- label.pop()
- label.pop()
-
- label.pop() #table
- label.pop()
- label.pop() # font
- label.add_text("\n")
- label.add_text("\n")
-
- # Methods overview
- var method_descr := false
- var sort_methods: bool = editor_settings.get("text_editor/help/sort_functions_alphabetically")
- var methods := []
-
- for method in doc.methods:
- if skip_methods.has(method.name):
- if method.args.size() == 0 or (method.args.size() == 1 and method.return_type == "void"):
- continue
- methods.append(method)
-
- if methods.size():
- if sort_methods:
- methods.sort_custom(self, "sort_methods")
- if is_current:
- section_lines.append(["Methods", label.get_line_count() - 2])
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Methods")
- label.pop()
- label.pop()
-
- label.add_text("\n")
- label.push_font(doc_code_font)
- label.push_indent(1)
- label.push_table(2)
- label.set_table_column_expand(1, true, 1)
-
- var any_previous := false
- for _pass in 2:
- var m := []
- for method in methods:
- if (_pass == 0 and method.is_virtual) or (_pass == 1 and not method.is_virtual):
- m.append(method)
-
- if any_previous and not m.empty():
- label.push_cell()
- label.pop() #cell
- label.push_cell()
- label.pop() #cell
-
- var group_prefix := ""
- for i in m.size():
- var new_prefix: String = m[i].name.substr(0, 3)
- var is_new_group := false
-
- if i < m.size() - 1 and new_prefix == m[i + 1].name.substr(0, 3) and new_prefix != group_prefix:
- is_new_group = i > 0
- group_prefix = new_prefix
- elif group_prefix != "" and new_prefix != group_prefix:
- is_new_group = true
- group_prefix = ""
-
- if is_new_group and _pass == 1:
- label.push_cell()
- label.pop() #cell
- label.push_cell()
- label.pop() #cell
-
- if m[i].description != "":
- method_descr = true
-
- add_method(m[i], true)
-
- any_previous = !m.empty()
-
- label.pop() #table
- label.pop()
- label.pop() # font
- label.add_text("\n")
- label.add_text("\n")
-
- # Theme properties
-# if doc.theme_properties.size():
-#
-# section_line.append(Pair(TTR("Theme Properties"), label.get_line_count() - 2))
-# label.push_color(title_color)
-# label.push_font(doc_title_font)
-# label.add_text(TTR("Theme Properties"))
-# label.pop()
-# label.pop()
-#
-# label.push_indent(1)
-# label.push_table(2)
-# label.set_table_column_expand(1, 1)
-#
-# for int i = 0 i < doc.theme_properties.size() i++:
-#
-# theme_property_line[doc.theme_properties[i].name] = label.get_line_count() - 2 #gets overridden if description
-#
-# label.push_cell()
-# label.push_align(RichTextLabel.ALIGN_RIGHT)
-# label.push_font(doc_code_font)
-# //add_type(doc.theme_properties[i].type)
-# label.pop()
-# label.pop()
-# label.pop()
-#
-# label.push_cell()
-# label.push_font(doc_code_font)
-# label.push_color(headline_color)
-# //add_text(doc.theme_properties[i].name)
-# label.pop()
-#
-# if doc.theme_properties[i].default != "":
-# label.push_color(symbol_color)
-# label.add_text(" [" + TTR("default:") + " ")
-# label.pop()
-# label.push_color(value_color)
-# //add_text(_fix_constant(doc.theme_properties[i].default))
-# label.pop()
-# label.push_color(symbol_color)
-# label.add_text("]")
-# label.pop()
-# }
-#
-# label.pop()
-#
-# if doc.theme_properties[i].description != "":
-# label.push_font(doc_font)
-# label.add_text(" ")
-# label.push_color(comment_color)
-# //add_text(doc.theme_properties[i].description)
-# label.pop()
-# label.pop()
-# }
-# label.pop() # cell
-# }
-#
-# label.pop() # table
-# label.pop()
-# label.add_text("\n")
-# label.add_text("\n")
-# }
-#
- # Signals
- var signals := doc.signals.duplicate()
- if signals.size():
- if sort_methods:
- signals.sort()
- if is_current:
- section_lines.append(["Signals", label.get_line_count() - 2])
-
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Signals")
- label.pop()
- label.pop()
-
- label.add_text("\n")
- label.add_text("\n")
-
- label.push_indent(1)
-
- for _signal in signals:
- signal_line[_signal.name] = label.get_line_count() - 2 #gets overridden if description
- label.push_font(doc_code_font) # monofont
- label.push_color(headline_color)
- add_text(_signal.name)
- label.pop()
- label.push_color(symbol_color)
- label.add_text("(")
- label.pop()
- for j in _signal.args.size():
- label.push_color(text_color)
- if j > 0:
- label.add_text(", ")
-
- add_text(_signal.args[j].name)
- label.add_text(": ")
- add_type(_signal.args[j].type, _signal.args[j].enumeration)
- if _signal.args[j].default != "":
- label.push_color(symbol_color)
- label.add_text(" = ")
- label.pop()
- add_text(_signal.args[j].default)
-
- label.pop()
-
- label.push_color(symbol_color)
- label.add_text(")")
- label.pop()
- label.pop() # end monofont
- if _signal.description != "":
- label.push_font(doc_font)
- label.push_color(comment_color)
- label.push_indent(1)
- add_text(_signal.description)
- label.pop() # indent
- label.pop()
- label.pop() # font
- label.add_text("\n")
- label.add_text("\n")
-
- label.pop()
- label.add_text("\n")
-
- # Constants and enums
- if doc.constants.size():
- var enums := {}
- var constants := []
- for i in doc.constants.size():
- if doc.constants[i].enumeration != "":
- if not enums.has(doc.constants[i].enumeration):
- enums[doc.constants[i].enumeration] = []
- enums[doc.constants[i].enumeration].append(doc.constants[i])
- else:
- constants.append(doc.constants[i])
-
- # Enums
- if enums.size():
- section_lines.append(["Enumerations", label.get_line_count() - 2])
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Enumerations")
- label.pop()
- label.pop()
- label.push_indent(1)
-
- label.add_text("\n")
-
- for e in enums:
- enum_line[e] = label.get_line_count() - 2
-
- label.push_color(title_color)
- label.add_text("enum ")
- label.pop()
- label.push_font(doc_code_font)
- if (e.split(".").size() > 1) and (e.split(".")[0] == doc.name):
- e = e.split(".")[1]
-
- label.push_color(headline_color)
- label.add_text(e)
- label.pop()
- label.pop()
- label.push_color(symbol_color)
- label.add_text(":")
- label.pop()
- label.add_text("\n")
-
- label.push_indent(1)
- var enum_list: Array = enums[e]
-
- for _enum in enum_list:
- # Add the enum constant line to the constant_line map so we can locate it as a constant
- constant_line[_enum.name] = label.get_line_count() - 2
-
- label.push_font(doc_code_font)
- label.push_color(headline_color)
- add_text(_enum.name)
- label.pop()
- label.push_color(symbol_color)
- label.add_text(" = ")
- label.pop()
- label.push_color(value_color)
- add_text(_enum.value)
- label.pop()
- label.pop()
- if _enum.description != "":
- label.push_font(doc_font)
- #label.add_text(" ")
- label.push_indent(1)
- label.push_color(comment_color)
- add_text(_enum.description)
- label.pop()
- label.pop()
- label.pop() # indent
- label.add_text("\n")
- label.add_text("\n")
-
- label.pop()
- label.add_text("\n")
-
- label.pop()
- label.add_text("\n")
-
- # Constants
- if constants.size():
- section_lines.append(["Constants", label.get_line_count() - 2])
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Constants")
- label.pop()
- label.pop()
- label.push_indent(1)
-
- label.add_text("\n")
-
- for i in constants.size():
-# constant_line[constants[i].name] = label.get_line_count() - 2
- label.push_font(doc_code_font)
-
- if constants[i].value.begins_with("Color(") and constants[i].value.ends_with(")"):
- var stripped: String = constants[i].value.replace(" ", "").replace("Color(", "").replace(")", "")
- var color := stripped.split_floats(",")
- if color.size() >= 3:
- label.push_color(Color(color[0], color[1], color[2]))
- var prefix := [0x25CF, ' ', 0]
- label.add_text(String(prefix))
- label.pop()
-
- label.push_color(headline_color)
- add_text(constants[i].name)
- label.pop()
- label.push_color(symbol_color)
- label.add_text(" = ")
- label.pop()
- label.push_color(value_color)
- add_text(constants[i].value)
- label.pop()
-
- label.pop()
- if constants[i].description != "":
- label.push_font(doc_font)
- label.push_indent(1)
- label.push_color(comment_color)
- add_text(constants[i].description)
- label.pop()
- label.pop()
- label.pop() # indent
- label.add_text("\n")
-
- label.add_text("\n")
-
- label.pop()
- label.add_text("\n")
-
- # Property descriptions
- if property_descr:
- section_lines.append(["Property Descriptions", label.get_line_count() - 2])
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Property Descriptions")
- label.pop()
- label.pop()
-
- label.add_text("\n")
- label.add_text("\n")
-
- for prop in doc.properties:
-# if doc.properties[i].overridden:
-# continue
-
- property_line[prop.name] = label.get_line_count() - 2
- label.push_table(2)
- label.set_table_column_expand(1, true, 1)
-
- label.push_cell()
- label.push_font(doc_code_font)
- add_type(prop.type, prop.enumeration)
- label.add_text(" ")
- label.pop() # font
- label.pop() # cell
-
- label.push_cell()
- label.push_font(doc_code_font)
- label.push_color(headline_color)
- add_text(prop.name)
- label.pop() # color
-
- if prop.default != "":
- label.push_color(symbol_color)
- label.add_text(" [default: ")
- label.pop() # color
-
- label.push_color(value_color)
- add_text(prop.default)
- label.pop() # color
-
- label.push_color(symbol_color)
- label.add_text("]")
- label.pop() # color
-
- label.pop() # font
- label.pop() # cell
-
- var method_map := {}
- for method in methods:
- method_map[method.name] = method
-
- if prop.setter != "":
- label.push_cell()
- label.pop() # cell
-
- label.push_cell()
- label.push_font(doc_code_font)
- label.push_color(text_color)
- if method_map.has(prop.setter) and method_map[prop.setter].args.size() > 1:
- # Setters with additional args are exposed in the method list, so we link them here for quick access.
- label.push_meta("@method " + prop.setter)
- label.add_text(prop.setter + "(value)")
- label.pop()
- else:
- label.add_text(prop.setter + "(value)")
- label.pop() # color
- label.push_color(comment_color)
- label.add_text(" setter")
- label.pop() # color
- label.pop() # font
- label.pop() # cell
- method_line[prop.setter] = property_line[prop.name]
-
- if prop.getter != "":
- label.push_cell()
- label.pop() # cell
-
- label.push_cell()
- label.push_font(doc_code_font)
- label.push_color(text_color)
- if method_map.has(prop.getter) and method_map[prop.getter].args.size() > 0:
- # Getters with additional args are exposed in the method list, so we link them here for quick access.
- label.push_meta("@method " + prop.getter)
- label.add_text(prop.getter + "()")
- label.pop()
- else:
- label.add_text(prop.getter + "()")
- label.pop() #color
- label.push_color(comment_color)
- label.add_text(" getter")
- label.pop() #color
- label.pop() #font
- label.pop() #cell
- method_line[prop.getter] = property_line[prop.name]
-
- label.pop() # table
-
- label.add_text("\n")
- label.add_text("\n")
-
- label.push_color(text_color)
- label.push_font(doc_font)
- label.push_indent(1)
- if prop.description.strip_edges() != "":
- add_text(prop.description)
- else:
- label.add_image(theme.get_icon("Error", "EditorIcons"))
- label.add_text(" ")
- label.push_color(comment_color)
- label.append_bbcode("There is currently no description for this property. Please help us by [color=$color][url=$url]contributing one[/url][/color]!".replace("$url", doc.contriute_url).replace("$color", link_color_text))
- label.pop()
- label.pop()
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
- label.add_text("\n")
-
- # Method descriptions
- if method_descr:
-# section_line.append(Pair(TTR("Method Descriptions"), label.get_line_count() - 2))
- label.push_color(title_color)
- label.push_font(doc_title_font)
- label.add_text("Method Descriptions")
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
-
- for _pass in 2:
- var methods_filtered := []
- for method in methods:
- if (_pass == 0 and method.is_virtual) or (_pass == 1 and not method.is_virtual):
- methods_filtered.append(method)
-
- for i in methods_filtered.size():
- label.push_font(doc_code_font)
- add_method(methods_filtered[i], false)
- label.pop()
-
- label.add_text("\n")
- label.add_text("\n")
-
- label.push_color(text_color)
- label.push_font(doc_font)
- label.push_indent(1)
- if methods_filtered[i].description.strip_edges() != "":
- add_text(methods_filtered[i].description)
- else:
- label.add_image(theme.get_icon("Error", "EditorIcons"))
- label.add_text(" ")
- label.push_color(comment_color)
- label.append_bbcode("There is currently no description for this method. Please help us by [color=$color][url=$url]contributing one[/url][/color]!".replace("$url", doc.contriute_url).replace("$color", link_color_text))
- label.pop()
-
- label.pop()
- label.pop()
- label.pop()
- label.add_text("\n")
- label.add_text("\n")
- label.add_text("\n")
-
- return str(is_current)
-
-
-func update_theme_vars() -> void:
- doc_font = theme.get_font("doc", "EditorFonts")
- doc_bold_font = theme.get_font("doc_bold", "EditorFonts")
- doc_title_font = theme.get_font("doc_title", "EditorFonts")
- doc_code_font = theme.get_font("doc_source", "EditorFonts")
-
- title_color = theme.get_color("accent_color", "Editor")
- text_color = theme.get_color("default_color", "RichTextLabel")
- headline_color = theme.get_color("headline_color", "EditorHelp")
- base_type_color = title_color.linear_interpolate(text_color, 0.5)
- comment_color = text_color * Color(1, 1, 1, 0.6)
- symbol_color = comment_color
- value_color = text_color * Color(1, 1, 1, 0.6)
- qualifier_color = text_color * Color(1, 1, 1, 0.8)
- type_color = theme.get_color("accent_color", "Editor").linear_interpolate(text_color, 0.5)
-
-
-func add_type(type: String, _enum: String):
- var t := type
- if t.empty():
- t = "void"
- var can_ref := (t != "void") or not _enum.empty()
-
- if not _enum.empty():
- if _enum.split(".").size() > 1:
- t = _enum.split(".")[1]
- else:
- t = _enum.split(".")[0]
-
- var text_color := label.get_color("default_color", "RichTextLabel")
- var type_color := label.get_color("accent_color", "Editor").linear_interpolate(text_color, 0.5)
- label.push_color(type_color)
- if can_ref:
- if _enum.empty():
- label.push_meta("#" + t) #class
- else:
- label.push_meta("$" + _enum) #class
- label.add_text(t)
- if can_ref:
- label.pop()
- label.pop()
-
-
-func add_method(method: MethodDocItem, overview: bool) -> void:
- method_line[method.name] = label.get_line_count() - 2 # gets overridden if description
- if overview:
- label.push_cell()
- label.push_align(RichTextLabel.ALIGN_RIGHT)
-
- add_type(method.return_type, method.return_enum)
-
- if overview:
- label.pop() #align
- label.pop() #cell
- label.push_cell()
- else:
- label.add_text(" ")
-
- if overview and method.description != "":
- label.push_meta("@method " + method.name)
-
- label.push_color(headline_color)
- add_text(method.name)
- label.pop()
-
- if overview and method.description != "":
- label.pop() #meta
-
- label.push_color(symbol_color)
- label.add_text("(")
- label.pop()
-
- for j in method.args.size():
- label.push_color(text_color)
- if j > 0:
- label.add_text(", ")
-
- add_text(method.args[j].name)
- label.add_text(": ")
- add_type(method.args[j].type, method.args[j].enumeration)
- if method.args[j].default != "":
- label.push_color(symbol_color)
- label.add_text(" = ")
- label.pop()
- label.push_color(value_color)
- add_text(method.args[j].default)
- label.pop()
- label.pop()
-
- label.push_color(symbol_color)
- label.add_text(")")
- label.pop()
- if method.is_virtual:
- label.push_color(qualifier_color)
- label.add_text(" ")
- add_text("virtual")
- label.pop()
-
- if overview:
- label.pop() #cell
-
-
-func add_text(bbcode: String) -> void:
- var base_path: String
-
- var doc_font := label.get_font("doc", "EditorFonts")
- var doc_bold_font := label.get_font("doc_bold", "EditorFonts")
- var doc_code_font := label.get_font("doc_source", "EditorFonts")
- var doc_kbd_font := label.get_font("doc_keyboard", "EditorFonts")
-
- var headline_color := label.get_color("headline_color", "EditorHelp")
- var accent_color := label.get_color("accent_color", "Editor")
- var property_color := label.get_color("property_color", "Editor")
- var link_color := accent_color.linear_interpolate(headline_color, 0.8)
- var code_color := accent_color.linear_interpolate(headline_color, 0.6)
- var kbd_color := accent_color.linear_interpolate(property_color, 0.6)
-
- bbcode = bbcode.dedent().replace("\t", "").replace("\r", "").strip_edges()
-
- bbcode = bbcode.replace("[csharp]", "[b]C#:[/b]\n[codeblock]")
- bbcode = bbcode.replace("[gdscript]", "[b]GDScript:[/b]\n[codeblock]")
- bbcode = bbcode.replace("[/csharp]", "[/codeblock]")
- bbcode = bbcode.replace("[/gdscript]", "[/codeblock]")
-
- # Remove codeblocks (they would be printed otherwise)
- bbcode = bbcode.replace("[codeblocks]\n", "")
- bbcode = bbcode.replace("\n[/codeblocks]", "")
- bbcode = bbcode.replace("[codeblocks]", "")
- bbcode = bbcode.replace("[/codeblocks]", "")
-
- # remove extra new lines around code blocks
- bbcode = bbcode.replace("[codeblock]\n", "[codeblock]")
- bbcode = bbcode.replace("\n[/codeblock]", "[/codeblock]")
-
- var tag_stack := []
- var code_tag := false
-
- var pos := 0
- while pos < bbcode.length():
- var brk_pos := bbcode.find("[", pos)
- if brk_pos < 0:
- brk_pos = bbcode.length()
-
- if brk_pos > pos:
- var text := bbcode.substr(pos, brk_pos - pos)
-# if not code_tag:
-# text = text.replace("\n", "\n\n")
- label.add_text(text)
-
- if brk_pos == bbcode.length():
- break #nothing else to add
-
- var brk_end := bbcode.find("]", brk_pos + 1)
-
- if brk_end == -1:
- var text := bbcode.substr(brk_pos, bbcode.length() - brk_pos)
- if not code_tag:
- text = text.replace("\n", "\n\n")
- label.add_text(text)
- break
-
- var tag := bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1)
-
- if tag.begins_with("/"):
- var tag_ok = tag_stack.size() and tag_stack[0] == tag.substr(1, tag.length())
- if not tag_ok:
- label.add_text("[")
- pos = brk_pos + 1
- continue
-
- tag_stack.pop_front()
- pos = brk_end + 1
- if tag != "/img":
- label.pop()
- if code_tag:
- label.pop()
- code_tag = false
-
- elif code_tag:
- label.add_text("[")
- pos = brk_pos + 1
-
- elif tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant "):
- var tag_end := tag.find(" ")
- var link_tag := tag.substr(0, tag_end)
- var link_target := tag.substr(tag_end + 1, tag.length()).lstrip(" ")
-
- label.push_color(link_color)
- label.push_meta("@" + link_tag + " " + link_target)
- label.add_text(link_target + ("()" if tag.begins_with("method ") else ""))
- label.pop()
- label.pop()
- pos = brk_end + 1
-
- elif class_list.has(tag):
- label.push_color(link_color)
- label.push_meta("#" + tag)
- label.add_text(tag)
- label.pop()
- label.pop()
- pos = brk_end + 1
-
- elif tag == "b":
- #use bold font
- label.push_font(doc_bold_font)
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "i":
- #use italics font
- label.push_color(headline_color)
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "code" || tag == "codeblock":
- #use monospace font
- label.push_font(doc_code_font)
- label.push_color(code_color)
- code_tag = true
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "kbd":
- #use keyboard font with custom color
- label.push_font(doc_kbd_font)
- label.push_color(kbd_color)
- code_tag = true # though not strictly a code tag, logic is similar
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "center":
- #align to center
- label.push_paragraph(RichTextLabel.ALIGN_CENTER, Control.TEXT_DIRECTION_AUTO, "")
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "br":
- #force a line break
- label.add_newline()
- pos = brk_end + 1
- elif tag == "u":
- #use underline
- label.push_underline()
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "s":
- #use strikethrough
- label.push_strikethrough()
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag == "url":
- var end := bbcode.find("[", brk_end)
- if end == -1:
- end = bbcode.length()
- var url = bbcode.substr(brk_end + 1, end - brk_end - 1)
- label.push_meta(url)
-
- pos = brk_end + 1
- tag_stack.push_front(tag)
- elif tag.begins_with("url="):
- var url := tag.substr(4, tag.length())
- label.push_meta(url)
- pos = brk_end + 1
- tag_stack.push_front("url")
- elif tag == "img":
- var end := bbcode.find("[", brk_end)
- if end == -1:
- end = bbcode.length()
- var image := bbcode.substr(brk_end + 1, end - brk_end - 1)
- var texture := load(base_path.plus_file(image)) as Texture
- if texture:
- label.add_image(texture)
-
- pos = end
- tag_stack.push_front(tag)
- elif tag.begins_with("color="):
- var col := tag.substr(6, tag.length())
- var color := Color(col)
- label.push_color(color)
- pos = brk_end + 1
- tag_stack.push_front("color")
-
- elif tag.begins_with("font="):
- var fnt := tag.substr(5, tag.length())
- var font := load(base_path.plus_file(fnt)) as Font
- if font.is_valid():
- label.push_font(font)
- else:
- label.push_font(doc_font)
-
- pos = brk_end + 1
- tag_stack.push_front("font")
-
- else:
- label.add_text("[") #ignore
- pos = brk_pos + 1
-
-
-func sort_methods(a: Dictionary, b: Dictionary) -> bool:
- return a.name < b.name
-
diff --git a/addons/silicon.util.custom_docs/doc_item/argument_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/argument_doc_item.gd
deleted file mode 100644
index 5107bf1..0000000
--- a/addons/silicon.util.custom_docs/doc_item/argument_doc_item.gd
+++ /dev/null
@@ -1,27 +0,0 @@
-## An object that contains documentation data about an argument of a signal or method.
-## @contribute https://placeholder_contribute.com
-tool
-class_name ArgumentDocItem
-extends DocItem
-
-
-## @default ""
-## The default value of the argument.
-var default := ""
-
-## @default ""
-## The enumeration of [member default].
-var enumeration := ""
-
-## @default ""
-## The class/built-in type of [member default].
-var type := ""
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
-
-
-func _to_string() -> String:
- return "[Argument doc: " + name + "]"
diff --git a/addons/silicon.util.custom_docs/doc_item/class_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/class_doc_item.gd
deleted file mode 100644
index 6293708..0000000
--- a/addons/silicon.util.custom_docs/doc_item/class_doc_item.gd
+++ /dev/null
@@ -1,77 +0,0 @@
-## An object that contains documentation data about a class.
-## @contribute https://placeholder_contribute.com
-tool
-class_name ClassDocItem
-extends DocItem
-
-
-var base := "" ## The base class this class extends from.
-var path := "" ## The file location of this class' script.
-
-var brief := "" ## A brief description of the class.
-var description := "" ## A full description of the class.
-
-var methods := [] ## A list of method documents.
-var properties := [] ## A list of property documents.
-var signals := [] ## A list of signal documents.
-var constants := [] ## A list of constant documents, including enumerators.
-
-var tutorials := [] ## A list of tutorials that helps to understand this class.
-
-## @default ""
-## A link to where the user can contribute to the class' documentation.
-var contriute_url := ""
-
-## @default false
-## Whether the class is a singleton.
-var is_singleton := false
-var icon := "" ## A path to the class icon if any.
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
-
-
-## @args name
-## @return MethodDocItem
-## Gets a method document called [code]name[/code].
-func get_method_doc(name: String) -> MethodDocItem:
- for doc in methods:
- if doc.name == name:
- return doc
- return null
-
-
-## @args name
-## @return PropertyDocItem
-## Gets a signal document called [code]name[/code].
-func get_property_doc(name: String) -> PropertyDocItem:
- for doc in properties:
- if doc.name == name:
- return doc
- return null
-
-
-## @args name
-## @return SignalDocItem
-## Gets a signal document called [code]name[/code].
-func get_signal_doc(name: String) -> SignalDocItem:
- for doc in signals:
- if doc.name == name:
- return doc
- return null
-
-
-## @args name
-## @return ConstantlDocItem
-## Gets a signal document called [code]name[/code].
-func get_constant_doc(name: String) -> ConstantDocItem:
- for doc in constants:
- if doc.name == name:
- return doc
- return null
-
-
-func _to_string() -> String:
- return "[Class doc: " + name + "]"
diff --git a/addons/silicon.util.custom_docs/doc_item/constant_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/constant_doc_item.gd
deleted file mode 100644
index 5ff678e..0000000
--- a/addons/silicon.util.custom_docs/doc_item/constant_doc_item.gd
+++ /dev/null
@@ -1,27 +0,0 @@
-## An object that contains documentation data about a constant.
-## @contribute https://placeholder_contribute.com
-tool
-class_name ConstantDocItem
-extends DocItem
-
-
-## @default ""
-## A description of the constant.
-var description := ""
-
-## @default ""
-## The value of the constant in a string form.
-var value := ""
-
-## @default ""
-## The [member value]'s enumeration.
-var enumeration := ""
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
-
-
-func _to_string() -> String:
- return "[Constant doc: " + name + "]"
diff --git a/addons/silicon.util.custom_docs/doc_item/doc_item.gd b/addons/silicon.util.custom_docs/doc_item/doc_item.gd
deleted file mode 100644
index c1c035a..0000000
--- a/addons/silicon.util.custom_docs/doc_item/doc_item.gd
+++ /dev/null
@@ -1,13 +0,0 @@
-## The base class for all documentation items.
-tool
-class_name DocItem
-extends Reference
-
-
-## @default ""
-## The name of the documentation item.
-var name := ""
-
-## @default {}
-## The item's metadata.
-var meta := {}
diff --git a/addons/silicon.util.custom_docs/doc_item/method_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/method_doc_item.gd
deleted file mode 100644
index 756ac4b..0000000
--- a/addons/silicon.util.custom_docs/doc_item/method_doc_item.gd
+++ /dev/null
@@ -1,33 +0,0 @@
-tool
-class_name MethodDocItem
-extends DocItem
-
-
-## @default ""
-## A description of the method.
-var description := ""
-
-## @default ""
-## The return type of the method.
-var return_type := ""
-
-## @default ""
-## The enumerator of [member return_type].
-var return_enum := ""
-
-## @default []
-## A list of arguments the method takes in.
-var args := []
-
-## @default false
-## Whether the method is to be overriden in an extended class, similar to [Node._ready].
-var is_virtual := false
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
-
-
-func _to_string() -> String:
- return "[Method doc: " + name + "]"
diff --git a/addons/silicon.util.custom_docs/doc_item/property_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/property_doc_item.gd
deleted file mode 100644
index d6da050..0000000
--- a/addons/silicon.util.custom_docs/doc_item/property_doc_item.gd
+++ /dev/null
@@ -1,39 +0,0 @@
-## An object that contains documentation data about a property.
-## @contribute https://placeholder_contribute.com
-tool
-class_name PropertyDocItem
-extends DocItem
-
-
-## @default ""
-## A description of the property.
-var description := ""
-
-## @default ""
-## The default of the property in string form.
-var default := ""
-
-## @default ""
-## The enumeration of [member default].
-var enumeration := ""
-
-## @default ""
-## The class/built-in type of [member default].
-var type := ""
-
-## @default ""
-## The setter method of the property.
-var setter := ""
-
-## @default ""
-## The getter method of the property.
-var getter := ""
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
-
-
-func _to_string() -> String:
- return "[Property doc: " + name + "]"
diff --git a/addons/silicon.util.custom_docs/doc_item/signal_doc_item.gd b/addons/silicon.util.custom_docs/doc_item/signal_doc_item.gd
deleted file mode 100644
index ec775bb..0000000
--- a/addons/silicon.util.custom_docs/doc_item/signal_doc_item.gd
+++ /dev/null
@@ -1,19 +0,0 @@
-## An object that contains documentation data about a signal.
-## @contribute https://placeholder_contribute.com
-tool
-class_name SignalDocItem
-extends DocItem
-
-
-## @default ""
-## A description of the signal.
-var description := ""
-
-## @default []
-## A list of arguments the signal carries.
-var args := []
-
-
-func _init(args := {}) -> void:
- for arg in args:
- set(arg, args[arg])
diff --git a/addons/silicon.util.custom_docs/plugin.cfg b/addons/silicon.util.custom_docs/plugin.cfg
deleted file mode 100644
index 37ee41c..0000000
--- a/addons/silicon.util.custom_docs/plugin.cfg
+++ /dev/null
@@ -1,7 +0,0 @@
-[plugin]
-
-name="Custom Docs"
-description="This plugin allows you to view Custom classe documentation in the same place where the builtin class documentation is!"
-author="SIsilicon"
-version="1.0"
-script="plugin.gd"
diff --git a/addons/silicon.util.custom_docs/plugin.gd b/addons/silicon.util.custom_docs/plugin.gd
deleted file mode 100644
index 27f0d17..0000000
--- a/addons/silicon.util.custom_docs/plugin.gd
+++ /dev/null
@@ -1,630 +0,0 @@
-tool
-extends EditorPlugin
-
-# enum {
-# SEARCH_CLASS = 1,
-# SEARCH_METHOD = 2,
-# SEARCH_SIGNAL = 4,
-# SEARCH_CONSTANT = 8,
-# SEARCH_PROPERTY = 16,
-# SEARCH_THEME = 32,
-# SEARCH_CASE = 64,
-# SEARCH_TREE = 128
-# }
-
-# enum {
-# ITEM_CLASS,
-# ITEM_METHOD,
-# ITEM_SIGNAL,
-# ITEM_CONSTANT,
-# ITEM_PROPERTY
-# }
-
-# var doc_generator := preload("class_doc_generator.gd").new()
-# var doc_exporter := preload("doc_exporter/editor_help_doc_exporter.gd").new()
-
-# var script_editor: ScriptEditor
-
-# var search_help: AcceptDialog
-# var search_controls: HBoxContainer
-# var search_term: String
-# var search_flags: int
-# var tree: Tree
-
-# var script_list: ItemList
-# var script_tabs: TabContainer
-# var section_list: ItemList
-
-# var class_docs := {}
-# var doc_items := {}
-# var current_label: RichTextLabel setget set_current_label
-
-# var theme: Theme
-# var disabled_color: Color
-
-# var doc_timer: Timer
-
-# func _enter_tree() -> void:
-# theme = get_editor_interface().get_base_control().theme
-# disabled_color = theme.get_color("disabled_font_color", "Editor")
-
-# script_editor = get_editor_interface().get_script_editor()
-# script_list = find_node_by_class(script_editor, "ItemList")
-# script_tabs = get_child_chain(script_editor, [0, 1, 1])
-# search_help = find_node_by_class(script_editor, "EditorHelpSearch")
-# search_controls = find_node_by_class(search_help, "LineEdit").get_parent()
-# tree = find_node_by_class(search_help, "Tree")
-
-# if not search_help.is_connected("go_to_help", self, "_on_SearchHelp_go_to_help"):
-# search_help.connect("go_to_help", self, "_on_SearchHelp_go_to_help", [], CONNECT_DEFERRED)
-
-# section_list = ItemList.new()
-# section_list.allow_reselect = true
-# section_list.size_flags_vertical = Control.SIZE_EXPAND_FILL
-# get_child_chain(script_editor, [0, 1, 0, 1]).add_child(section_list)
-
-# if not section_list.is_connected("item_selected", self, "_on_SectionList_item_selected"):
-# section_list.connect("item_selected", self, "_on_SectionList_item_selected")
-
-# doc_exporter.plugin = self
-# doc_exporter.theme = theme
-# doc_exporter.editor_settings = get_editor_interface().get_editor_settings()
-# doc_exporter.class_docs = class_docs
-# doc_exporter.update_theme_vars()
-# doc_generator.plugin = self
-
-# doc_timer = Timer.new()
-# doc_timer.wait_time = 0.5
-# add_child(doc_timer)
-# doc_timer.start()
-# if not doc_timer.is_connected("timeout", self, "_on_DocTimer_timeout"):
-# doc_timer.connect("timeout", self, "_on_DocTimer_timeout")
-
-# # Load opened custom docs from last session.
-# var settings_path := get_editor_interface().get_editor_settings().get_project_settings_dir() + "/opened_custom_docs.json"
-# var file := File.new()
-# if not file.open(settings_path, File.READ):
-# var opened_tabs := []
-# for i in script_list.get_item_count():
-# opened_tabs.append(script_tabs.get_child(script_list.get_item_metadata(i)).name)
-
-# var selected := script_list.get_selected_items()
-# var list: Array = JSON.parse(file.get_as_text()).result
-# for item in list:
-# if not item in opened_tabs:
-# search_help.call_deferred("emit_signal", "go_to_help", "class_name:" + item)
-
-# if not selected.empty():
-# script_list.call_deferred("select", selected[0])
-# script_list.call_deferred("emit_signal", "item_selected", selected[0])
-# file.close()
-
-
-# func _exit_tree() -> void:
-# # Save opened custom docs for next session.
-# var settings_path := get_editor_interface().get_editor_settings().get_project_settings_dir() + "/opened_custom_docs.json"
-# var file := File.new()
-# if not file.open(settings_path, File.WRITE):
-# var opened_docs := []
-# for i in script_tabs.get_children():
-# if i.name in class_docs:
-# opened_docs.append(i.name)
-# file.store_string(JSON.print(opened_docs))
-# file.close()
-
-# section_list.queue_free()
-
-
-# func _process(_delta := 0.0) -> void:
-# if not tree:
-# _enter_tree()
-# if not tree:
-# return
-
-# doc_generator._update()
-
-# # Update search help tree items
-# if tree.get_root():
-# search_flags = search_controls.get_child(3).get_item_id(search_controls.get_child(3).selected)
-# search_flags |= SEARCH_CASE * int(search_controls.get_child(1).pressed)
-# search_flags |= SEARCH_TREE * int(search_controls.get_child(2).pressed)
-# search_term = search_controls.get_child(0).text
-
-# for name in class_docs:
-# if fits_search(name, ITEM_CLASS):
-# process_custom_item(name, ITEM_CLASS)
-
-# for method in class_docs[name].methods:
-# if fits_search(method.name, ITEM_METHOD):
-# process_custom_item(name + "." + method.name, ITEM_METHOD)
-
-# for _signal in class_docs[name].signals:
-# if fits_search(_signal.name, ITEM_SIGNAL):
-# process_custom_item(name + "." + _signal.name, ITEM_SIGNAL)
-
-# for constant in class_docs[name].constants:
-# if fits_search(constant.name, ITEM_CONSTANT):
-# process_custom_item(name + "." + constant.name, ITEM_CONSTANT)
-
-# for property in class_docs[name].properties:
-# if fits_search(property.name, ITEM_PROPERTY):
-# process_custom_item(name + "." + property.name, ITEM_PROPERTY)
-
-# var custom_doc_open := false
-# var doc_open := false
-# for i in script_list.get_item_count():
-# var icon := script_list.get_item_icon(i)
-# var text := script_list.get_item_text(i)
-
-# var editor_help = script_tabs.get_child(script_list.get_item_metadata(i))
-# if icon == theme.get_icon("Help", "EditorIcons"):
-# if script_list.get_selected_items()[0] == i:
-# doc_open = true
-# if editor_help.name != text:
-# text = editor_help.name
-# script_list.set_item_tooltip(i, text + " Class Reference")
-
-# if script_list.get_selected_items()[0] == i and text in class_docs:
-# custom_doc_open = true
-# set_current_label(editor_help.get_child(0))
-# # else:
-# # set_current_label(null)
-
-# script_list.call_deferred("set_item_text", i, text)
-
-# if custom_doc_open:
-# section_list.get_parent().get_child(3).set_deferred("visible", false)
-# section_list.visible = true
-# else:
-# section_list.get_parent().get_child(3).set_deferred("visible", doc_open)
-# section_list.visible = false
-
-
-# func get_parent_class(_class: String) -> String:
-# if class_docs.has(_class):
-# return class_docs[_class].base
-# return ClassDB.get_parent_class(_class)
-
-
-# func fits_search(name: String, type: int) -> bool:
-# if type == ITEM_CLASS and not (search_flags & SEARCH_CLASS):
-# return false
-# elif type == ITEM_METHOD and not (search_flags & SEARCH_METHOD) or search_term.empty():
-# return false
-# elif type == ITEM_SIGNAL and not (search_flags & SEARCH_SIGNAL) or search_term.empty():
-# return false
-# elif type == ITEM_CONSTANT and not (search_flags & SEARCH_CONSTANT) or search_term.empty():
-# return false
-# elif type == ITEM_PROPERTY and not (search_flags & SEARCH_PROPERTY) or search_term.empty():
-# return false
-
-# if not search_term.empty():
-# if (search_flags & SEARCH_CASE) and name.find(search_term) == -1:
-# return false
-# elif ~(search_flags & SEARCH_CASE) and name.findn(search_term) == -1:
-# return false
-
-# return true
-
-
-# func update_doc(label: RichTextLabel) -> void:
-# doc_exporter.label = label
-# doc_exporter._generate(class_docs[label.get_parent().name])
-
-# var section_lines := doc_exporter.section_lines
-# section_list.clear()
-# for i in len(section_lines):
-# section_list.add_item(section_lines[i][0])
-# section_list.set_item_metadata(i, section_lines[i][1])
-
-
-# func process_custom_item(name: String, type := ITEM_CLASS) -> TreeItem:
-# # Create tree item if it's not their.
-# if weakref(doc_items.get(name + str(type))).get_ref():
-# doc_items[name + str(type)].clear_custom_color(0)
-# doc_items[name + str(type)].clear_custom_color(1)
-# return doc_items[name + str(type)]
-
-# var parent := tree.get_root()
-# var sub_name: String
-# if name.find(".") != -1:
-# var split := name.split(".")
-# name = split[0]
-# sub_name = split[1]
-
-# var doc: DocItem = class_docs[name]
-
-# if search_flags & SEARCH_TREE:
-# # Get inheritance chain of the class.
-# var inherit_chain = [doc.base]
-# while not inherit_chain[-1].empty():
-# inherit_chain.append(get_parent_class(inherit_chain[-1]))
-# inherit_chain.pop_back()
-# inherit_chain.invert()
-# if not sub_name.empty():
-# inherit_chain.append(name)
-
-# # Find the tree item the class should be under.
-# for inherit in inherit_chain:
-# var failed := true
-# var child := parent.get_children()
-# while child and child.get_parent() == parent:
-# if child.get_text(0) == inherit:
-# parent = child
-# failed = false
-# break
-# child = child.get_next()
-
-# if failed:
-# var new_parent: TreeItem
-# if inherit in class_docs:
-# new_parent = process_custom_item(inherit)
-# if not new_parent:
-# new_parent = tree.create_item(parent)
-# new_parent.set_text(0, inherit)
-# new_parent.set_text(1, "Class")
-# new_parent.set_icon(0, get_class_icon(inherit))
-# new_parent.set_metadata(0, "class_name:" + inherit)
-# new_parent.set_custom_color(0, disabled_color)
-# new_parent.set_custom_color(1, disabled_color)
-# parent = new_parent
-
-# var item := tree.create_item(parent)
-# if not sub_name.empty():
-# name += "." + sub_name
-# var display_name := sub_name if search_flags & SEARCH_TREE else name
-# match type:
-# ITEM_CLASS:
-# item.set_text(0, name)
-# item.set_text(1, "Class")
-# item.set_tooltip(0, doc.brief)
-# item.set_tooltip(1, doc.brief)
-# item.set_metadata(0, "class_name:" + name)
-# item.set_icon(0, get_class_icon("Object"))
-
-# ITEM_METHOD:
-# doc = doc.get_method_doc(sub_name)
-# item.set_text(0, display_name)
-# item.set_text(1, "Method")
-# item.set_tooltip(0, doc.return_type + " " + name + "()")
-# item.set_tooltip(1, item.get_tooltip(0))
-# item.set_metadata(0, "class_method:" + name.replace(".", ":"))
-# item.set_icon(0, theme.get_icon("MemberMethod", "EditorIcons"))
-
-# ITEM_SIGNAL:
-# doc = doc.get_signal_doc(sub_name)
-# item.set_text(0, display_name)
-# item.set_text(1, "Signal")
-# item.set_tooltip(0, name + "()")
-# item.set_tooltip(1, item.get_tooltip(0))
-# item.set_metadata(0, "class_signal:" + name.replace(".", ":"))
-# item.set_icon(0, theme.get_icon("MemberSignal", "EditorIcons"))
-
-# ITEM_CONSTANT:
-# doc = doc.get_constant_doc(sub_name)
-# item.set_text(0, display_name)
-# item.set_text(1, "Constant")
-# item.set_tooltip(0, name)
-# item.set_tooltip(1, item.get_tooltip(0))
-# item.set_metadata(0, "class_constant:" + name.replace(".", ":"))
-# item.set_icon(0, theme.get_icon("MemberConstant", "EditorIcons"))
-
-# ITEM_PROPERTY:
-# doc = doc.get_property_doc(sub_name)
-# item.set_text(0, display_name)
-# item.set_text(1, "Property")
-# item.set_tooltip(0, doc.type + " " + name)
-# item.set_tooltip(1, item.get_tooltip(0))
-# item.set_metadata(0, "class_property:" + name.replace(".", ":"))
-# item.set_icon(0, theme.get_icon("MemberProperty", "EditorIcons"))
-
-# var tooltip = item.get_tooltip(0)
-# for key in doc.meta:
-# tooltip += "\n" + snakekebab2pascal(key) + ": " + doc.meta[key]
-# item.set_tooltip(0, tooltip)
-
-# doc_items[name + str(type)] = item
-# return item
-
-
-# func snakekebab2pascal(string: String) -> String:
-# var result := PoolStringArray()
-# var prev_is_underscore := true # Make false for camelCase
-# for ch in string:
-# if ch == "_" or ch == "-":
-# prev_is_underscore = true
-# else:
-# if prev_is_underscore:
-# result.append(ch.to_upper())
-# else:
-# result.append(ch)
-# prev_is_underscore = false
-
-# return result.join("")
-
-
-# func purge_duplicate_tabs() -> void:
-# var selected_duplicate := ""
-# var i := 0
-# while i < script_list.get_item_count():
-# if script_list.get_item_icon(i) != theme.get_icon("Help", "EditorIcons"):
-# i += 1
-# continue
-
-# var text := script_tabs.get_child(script_list.get_item_metadata(i)).name
-# # Possible duplicate
-# var is_duplicate := false
-# if text[-1].is_valid_integer():
-# for doc in class_docs:
-# if text.find(doc) != -1 and text.right(len(doc)).is_valid_integer():
-# text = doc
-# is_duplicate = true
-# break
-
-# if is_duplicate:
-# # HACK: Creating a couple input events to simulate deleting the duplicate tab
-# if script_list.is_visible_in_tree():
-# var prev_count := script_list.get_item_count()
-
-# if script_list.is_selected(i):
-# selected_duplicate = text
-
-# script_list.select(i)
-# var event := InputEventKey.new()
-# event.scancode = KEY_W
-# event.control = true
-# event.pressed = true
-# get_tree().input_event(event)
-# event = event.duplicate()
-# event.pressed = false
-# get_tree().input_event(event)
-
-# # Makes sure that we don't run into an infinite loop.
-# i -= prev_count - script_list.get_item_count()
-# i += 1
-
-# if not selected_duplicate.empty():
-# for j in script_list.get_item_count():
-# var editor_help := script_tabs.get_child(script_list.get_item_metadata(j))
-# if editor_help.name == selected_duplicate:
-# script_list.select(j)
-# script_list.emit_signal("item_selected", j)
-# set_current_label(editor_help.get_child(0))
-# break
-
-
-# func set_current_label(label: RichTextLabel) -> void:
-# if current_label != label:
-# if is_instance_valid(current_label):
-# current_label.disconnect("meta_clicked", self, "_on_EditorHelpLabel_meta_clicked")
-
-# if is_instance_valid(label):
-# update_doc(label)
-# current_label = label
-# current_label.connect("meta_clicked", self, "_on_EditorHelpLabel_meta_clicked", [current_label], CONNECT_DEFERRED)
-
-
-# func get_class_icon(_class: String) -> Texture:
-# if theme.has_icon(_class, "EditorIcons"):
-# return theme.get_icon(_class, "EditorIcons")
-# elif _class in class_docs:
-# var path: String = class_docs[_class].icon
-# if not path.empty() and load(path) is Texture:
-# return load(path) as Texture
-# return get_class_icon("Object")
-
-
-# func get_child_chain(node: Node, indices: Array) -> Node:
-# var child := node
-# for index in indices:
-# child = child.get_child(index)
-# if not child:
-# return null
-# return child
-
-
-# func find_node_by_class(node: Node, _class: String) -> Node:
-# if node.is_class(_class):
-# return node
-
-# for child in node.get_children():
-# var result = find_node_by_class(child, _class)
-# if result:
-# return result
-
-# return null
-
-
-# func _on_DocTimer_timeout() -> void:
-# doc_exporter.plugin = self
-# doc_exporter.theme = theme
-# doc_exporter.editor_settings = get_editor_interface().get_editor_settings()
-# doc_exporter.class_docs = class_docs
-# doc_exporter.update_theme_vars()
-# doc_generator.plugin = self
-
-# var classes: Array = ProjectSettings.get("_global_script_classes")
-# var class_icons: Dictionary = ProjectSettings.get("_global_script_class_icons")
-
-# # Include autoloads
-# var file := File.new()
-# while not file.open("res://project.godot", File.READ):
-# var project_string := file.get_as_text()
-# var autoload_loc := project_string.find("[autoload]\n")
-# if autoload_loc == -1:
-# break
-# autoload_loc += len("[autoload]\n\n")
-
-# var list := project_string.right(autoload_loc).split("\n")
-# for i in len(list):
-# var line := list[i]
-# if line.empty():
-# continue
-# if line.begins_with("["):
-# break
-
-# var entry := line.split("=")
-# # An asterisk indicates that the singleton's enabled.
-# if entry[1][1] != "*":
-# continue
-
-# # Only gdscript and scenes are supported.
-# var type := "other"
-# var base := ""
-# var path := entry[1].trim_prefix("\"*").trim_suffix("\"")
-# var script: GDScript
-
-# if path.ends_with(".tscn") or path.ends_with(".scn"):
-# type = "scene"
-# elif type.ends_with(".gd"):
-# type = "script"
-
-# if type == "other":
-# continue
-# elif type == "scene":
-# script = load(path).instance().get_script()
-# else:
-# script = load(path)
-
-# if not script:
-# continue
-# if script.resource_path.empty():
-# continue
-# else:
-# path = script.resource_path
-# base = script.get_instance_base_type()
-
-# classes.append({
-# "base": base,
-# "class": entry[0],
-# "language": "GDScript" if path.find(".gd") != -1 else "Other",
-# "path": path,
-# "is_autoload": true
-# })
-
-# break
-# file.close()
-
-# var docs := {}
-# for _class in classes:
-# if _class["language"] != "GDScript":
-# continue
-
-# # TODO: Add file path to class document item
-# var doc := doc_generator.generate(_class["class"], _class["base"], _class["path"])
-# if not doc:
-# continue
-
-# doc.icon = class_icons.get(doc.name, "")
-# doc.is_singleton = _class.has("is_autoload")
-# docs[doc.name] = doc
-# class_docs[doc.name] = doc
-# if not doc.name in doc_exporter.class_list:
-# doc_exporter.class_list.append(doc.name)
-
-# # Periodically clean up tree items
-# for name in doc_items:
-# if not doc_items[name]:
-# doc_items.erase(name)
-
-# for _class in class_docs:
-# if not docs.has(_class):
-# doc_exporter.class_list.erase(_class)
-# class_docs.erase(_class)
-
-
-# func _on_EditorHelpLabel_meta_clicked(meta: String, label: RichTextLabel) -> void:
-# if meta.begins_with("$"):
-# var select := meta.substr(1, len(meta))
-# var _class_name := ""
-# if select.find(".") != -1:
-# _class_name = select.split(".")[0]
-# else:
-# _class_name = "@GlobalScope"
-# search_help.emit_signal("go_to_help", "class_enum:" + _class_name + ":" + select)
-# elif meta.begins_with("#"):
-# search_help.emit_signal("go_to_help", "class_name:" + meta.substr(1, len(meta)))
-# elif meta.begins_with("@"):
-# var tag_end := meta.find(" ")
-# var tag := meta.substr(1, tag_end - 1)
-# var link := meta.substr(tag_end + 1, meta.length()).lstrip(" ")
-
-# var topic := ""
-# var table: Dictionary
-
-# if tag == "method":
-# topic = "class_method"
-# table = doc_exporter.method_line
-# elif tag == "member":
-# topic = "class_property"
-# table = doc_exporter.property_line
-# elif tag == "enum":
-# topic = "class_enum"
-# table = doc_exporter.enum_line
-# elif tag == "signal":
-# topic = "class_signal"
-# table = doc_exporter.signal_line
-# elif tag == "constant":
-# topic = "class_constant"
-# table = doc_exporter.constant_line
-# else:
-# return
-
-# if link.find(".") != -1:
-# search_help.emit_signal("go_to_help", topic + ":" + link.split(".")[0] + ":" + link.split(".")[1])
-# else:
-# if table.has(link):
-# # Found in the current page
-# current_label.scroll_to_line(table[link])
-# else:
-# pass # Oh well.
-
-
-# func _on_SearchHelp_go_to_help(tag: String) -> void:
-# purge_duplicate_tabs()
-# var editor_help := script_tabs.get_child(script_list.get_selected_items()[0])
-# if editor_help.name in class_docs.keys():
-# set_current_label(editor_help.get_child(0))
-
-# var what := tag.split(":")[0]
-# var clss := tag.split(":")[1]
-# var name := ""
-# if len(tag.split(":")) == 3:
-# name = tag.split(":")[2]
-
-# var de := doc_exporter
-# var line := 0
-# if what == "class_desc":
-# line = de.description_line
-# elif what == "class_signal":
-# if de.signal_line.has(name):
-# line = de.signal_line[name]
-# elif what == "class_method" or what == "class_method_desc":
-# if de.method_line.has(name):
-# line = de.method_line[name]
-# elif what == "class_property":
-# if de.property_line.has(name):
-# line = de.property_line[name]
-# elif what == "class_enum":
-# if de.enum_line.has(name):
-# line = de.enum_line[name]
-# # elif what == "class_theme_item":
-# # if (theme_property_line.has(name))
-# # line = theme_property_line[name]
-# elif what == "class_constant":
-# if de.constant_line.has(name):
-# line = de.constant_line[name]
-# elif what == "class_name":
-# pass
-# else:
-# printerr("Could not go to help: " + tag)
-
-# current_label.call_deferred("scroll_to_line", line)
-
-
-# func _on_SectionList_item_selected(index: int) -> void:
-# if not current_label:
-# return
-# current_label.scroll_to_line(section_list.get_item_metadata(index))
-
-
diff --git a/test/TestUtils.gd b/test/TestUtils.gd
deleted file mode 100644
index a109892..0000000
--- a/test/TestUtils.gd
+++ /dev/null
@@ -1,8 +0,0 @@
-class_name TestUtils
-extends Object
-
-
-static func instantiate(script: Script) -> Node:
- var o = Node.new()
- o.set_script(script)
- return o
diff --git a/test/firestore_test.gd b/test/firestore_test.gd
deleted file mode 100644
index 2e22a48..0000000
--- a/test/firestore_test.gd
+++ /dev/null
@@ -1,31 +0,0 @@
-extends Node2D
-
-export var email := ""
-export var password := ""
-
-func _ready() -> void:
- Firebase.Auth.login_with_email_and_password(email, password)
- yield(Firebase.Auth, "login_succeeded")
- print("Logged in!")
-
- var task: FirestoreTask
-
- Firebase.Firestore.disable_networking()
-
- task = Firebase.Firestore.list("test_collection", 5, "", "number")
- print(yield(task, "listed_documents"))
-
- var test : FirestoreCollection = Firebase.Firestore.collection("test_collection")
-
- for i in 5:
- var name = "some_document_%d" % hash(str(i))
- task = test.delete(name)
- task = test.update(name, {"number": i + 10})
-
- var document = yield(task, "task_finished")
-
- Firebase.Firestore.enable_networking()
-
- task = test.get("some_document_%d" % hash(str(4)))
- document = yield(task, "task_finished")
- print(document)
diff --git a/test/firestore_test.tscn b/test/firestore_test.tscn
deleted file mode 100644
index 98660a8..0000000
--- a/test/firestore_test.tscn
+++ /dev/null
@@ -1,6 +0,0 @@
-[gd_scene load_steps=2 format=2]
-
-[ext_resource path="res://test/firestore_test.gd" type="Script" id=1]
-
-[node name="Node2D" type="Node2D"]
-script = ExtResource( 1 )
diff --git a/test/storage_stress_test.gd b/test/storage_stress_test.gd
deleted file mode 100644
index 3594a37..0000000
--- a/test/storage_stress_test.gd
+++ /dev/null
@@ -1,54 +0,0 @@
-extends Node2D
-
-
-var offset := 0
-
-export var email := ""
-export var password := ""
-
-
-func _ready() -> void:
- Firebase.Auth.login_with_email_and_password(email, password)
- yield(Firebase.Auth, "login_succeeded")
- print("Logged in!")
-
- var ref = Firebase.Storage.ref("test/test_image0.png")
- var task = ref.put_file("res://icon.png")
- task.connect("task_finished", self, "_on_task_finished", [task])
-
- for i in range(10):
- task = ref.get_data()
- task.connect("task_finished", self, "_on_task_finished", [task])
-
- task = ref.delete()
- task.connect("task_finished", self, "_on_task_finished", [task])
-
-
-func _on_task_finished(task: StorageTask) -> void:
- if task.result or task.response_code >= 400:
- if typeof(task.data) == TYPE_DICTIONARY:
- printerr(task.data)
- else:
- printerr(JSON.parse(task.data.get_string_from_utf8()).result)
- return
-
- match task.action:
- StorageTask.Task.TASK_UPLOAD:
- print("%s uploaded!" % task.ref)
-
- StorageTask.Task.TASK_DOWNLOAD:
- var image := Image.new()
- image.load_png_from_buffer(task.data)
- var tex := ImageTexture.new()
- tex.create_from_image(image)
-
- var sprite := Sprite.new()
- sprite.scale *= 0.7
- sprite.centered = false
- sprite.texture = tex
- sprite.position.x = offset
- add_child(sprite)
- offset += 100
-
- StorageTask.Task.TASK_DELETE:
- print("%s deleted!" % task.ref)
diff --git a/test/storage_stress_test.tscn b/test/storage_stress_test.tscn
deleted file mode 100644
index dd8a279..0000000
--- a/test/storage_stress_test.tscn
+++ /dev/null
@@ -1,6 +0,0 @@
-[gd_scene load_steps=2 format=2]
-
-[ext_resource path="res://test/storage_stress_test.gd" type="Script" id=1]
-
-[node name="Node2D" type="Node2D"]
-script = ExtResource( 1 )
diff --git a/test/unit/test_FirebaseDatabaseStore.gd b/test/unit/test_FirebaseDatabaseStore.gd
deleted file mode 100644
index 6278b63..0000000
--- a/test/unit/test_FirebaseDatabaseStore.gd
+++ /dev/null
@@ -1,221 +0,0 @@
-extends "res://addons/gut/test.gd"
-
-
-const FirebaseDatabaseStore = preload("res://addons/godot-firebase/database/database_store.gd")
-const TestKey = "-MPrgu_F8OXiL-VpRxjq"
-const TestObject = {
- "I": "Some Value",
- "II": "Some Other Value",
- "III": [111, 222, 333, 444, 555],
- "IV": {
- "a": "Another Value",
- "b": "Yet Another Value"
- }
-}
-const TestObjectOther = {
- "a": "A Different Value",
- "b": "Another One",
- "c": "A New Value"
-}
-const TestArray = [666, 777, 888, 999]
-const TestValue = 12345.6789
-
-class TestPutOperations:
- extends "res://addons/gut/test.gd"
-
-
- func test_put_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]
-
- assert_eq_deep(store_object, TestObject)
-
- store.queue_free()
-
-
- func test_put_nested_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.put(TestKey + "/V", TestObjectOther)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["V"]
-
- assert_eq_deep(store_object, TestObjectOther)
-
- store.queue_free()
-
-
- func test_put_array_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.put(TestKey + "/III", TestArray)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["III"]
-
- assert_eq_deep(store_object, TestArray)
-
- store.queue_free()
-
-
- func test_put_normal_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.put(TestKey + "/II", TestValue)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["II"]
-
- assert_eq_deep(store_object, TestValue)
-
- store.queue_free()
-
-
- func test_put_deleted_value():
- # NOTE: Firebase Realtime Database sets values to null to indicate that they have been
- # deleted.
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.put(TestKey + "/II", null)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]
-
- assert_false(store_object.has("II"), "The value should have been deleted, but was not.")
-
- store.queue_free()
-
-
- func test_put_new_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]
-
- assert_eq_deep(store_object, TestObject)
-
- store.queue_free()
-
-
- func test_put_new_nested_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey + "/V", TestObjectOther)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["V"]
-
- assert_eq_deep(store_object, TestObjectOther)
-
- store.queue_free()
-
-
- func test_put_new_array_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey + "/III", TestArray)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["III"]
-
- assert_eq_deep(store_object, TestArray)
-
- store.queue_free()
-
-
- func test_put_new_normal_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey + "/II", TestValue)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["II"]
-
- assert_eq_deep(store_object, TestValue)
-
- store.queue_free()
-
-class TestPatchOperations:
- extends "res://addons/gut/test.gd"
-
-
- func test_patch_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.patch(TestKey, TestObject)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]
-
- assert_eq_deep(store_object, TestObject)
-
- store.queue_free()
-
-
- func test_patch_nested_object():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.patch(TestKey + "/V", TestObjectOther)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["V"]
-
- assert_eq_deep(store_object, TestObjectOther)
-
- store.queue_free()
-
-
- func test_patch_array_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.patch(TestKey + "/III", TestArray)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["III"]
-
- assert_eq_deep(store_object, TestArray)
-
- store.queue_free()
-
-
- func test_patch_normal_value():
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.patch(TestKey + "/II", TestValue)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]["II"]
-
- assert_eq_deep(store_object, TestValue)
-
- store.queue_free()
-
-
- func test_patch_deleted_value():
- # NOTE: Firebase Realtime Database sets values to null to indicate that they have been
- # deleted.
- var store = TestUtils.instantiate(FirebaseDatabaseStore)
-
- store.put(TestKey, TestObject)
- store.patch(TestKey + "/II", null)
-
- var store_data: Dictionary = store.get_data()
- var store_object = store_data[TestKey]
-
- assert_false(store_object.has("II"), "The value should have been deleted, but was not.")
-
- store.queue_free()
diff --git a/test/unit/test_FirestoreDocument.gd b/test/unit/test_FirestoreDocument.gd
deleted file mode 100644
index 3313c35..0000000
--- a/test/unit/test_FirestoreDocument.gd
+++ /dev/null
@@ -1,48 +0,0 @@
-extends "res://addons/gut/test.gd"
-
-
-const FirestoreDocument = preload("res://addons/godot-firebase/firestore/firestore_document.gd")
-
-class TestDeserialization:
- extends "res://addons/gut/test.gd"
-
-
- func test_deserialize_array_of_dicts():
- var doc_infos: Dictionary = {
- "name": "projects/godot-firebase/databases/(default)/documents/rooms/EUZT",
- "fields": {
- "code": {"stringValue": "EUZT"},
- "players": {
- "arrayValue": {
- "values": [
- {"mapValue": {"fields": {"name": {"stringValue": "Hello"}}}},
- {"mapValue": {"fields": {"name": {"stringValue": "Test"}}}}
- ]
- }
- }
- },
- "createTime": "2021-02-16T07:24:11.106522Z",
- "updateTime": "2021-02-16T08:21:32.131028Z"
- }
- var expected_doc_fields: Dictionary = {
- "code": "EUZT", "players": [{"name": "Hello"}, {"name": "Test"}]
- }
- var firestore_document: FirestoreDocument = FirestoreDocument.new(doc_infos)
-
- assert_eq_deep(firestore_document.doc_fields, expected_doc_fields)
-
-
- func test_deserialize_array_of_strings():
- var doc_infos: Dictionary = {
- "name": "projects/godot-firebase/databases/(default)/documents/rooms/EUZT",
- "fields": {
- "code": {"stringValue": "EUZT"},
- "things": {"arrayValue": {"values": [{"stringValue": "first"}, {"stringValue": "second"}]}}
- },
- "createTime": "2021-02-16T07:24:11.106522Z",
- "updateTime": "2021-02-16T08:21:32.131028Z"
- }
- var expected_doc_fields: Dictionary = {"code": "EUZT", "things": ["first", "second"]}
- var firestore_document: FirestoreDocument = FirestoreDocument.new(doc_infos)
-
- assert_eq_deep(firestore_document.doc_fields, expected_doc_fields)