immersive-home/app/lib/stores/store.gd

98 lines
1.9 KiB
GDScript3
Raw Normal View History

2024-01-25 17:29:33 +02:00
extends RefCounted
2024-03-17 01:14:31 +02:00
## Abstract class for saving and loading data to and from a file.
2024-01-25 17:29:33 +02:00
const VariantSerializer = preload ("res://lib/utils/variant_serializer.gd")
2024-01-25 17:29:33 +02:00
2024-03-17 01:14:31 +02:00
## Signal emitted when the data is loaded.
2024-01-25 17:29:33 +02:00
signal on_loaded
2024-03-17 01:14:31 +02:00
## Signal emitted when the data is saved.
2024-01-25 17:29:33 +02:00
signal on_saved
var _loaded = false
var _save_path = null
2024-03-17 01:14:31 +02:00
## Returns true if the data has been loaded.
2024-01-25 17:29:33 +02:00
func is_loaded():
return _loaded
2024-03-17 01:14:31 +02:00
## Resets the data to its default state.
2024-01-25 17:29:33 +02:00
func clear():
pass
func create_dict():
var data: Dictionary = {}
for prop_info in get_property_list():
if prop_info.name.begins_with("_")||prop_info.hint_string != "":
2024-01-25 17:29:33 +02:00
continue
var prop = get(prop_info.name)
if prop is Store:
data[prop_info.name] = prop.create_dict()
else:
data[prop_info.name] = VariantSerializer.stringify_value(prop)
return data
func use_dict(dict: Dictionary):
for prop_info in get_property_list():
if prop_info.name.begins_with("_")||prop_info.hint_string != "":
2024-01-25 17:29:33 +02:00
continue
var prop = get(prop_info.name)
if dict.has(prop_info.name) == false:
continue
2024-01-25 17:29:33 +02:00
var prop_value = dict[prop_info.name]
if prop is Store:
prop.use_dict(prop_value)
else:
set(prop_info.name, prop_value)
func save_local(path=_save_path):
2024-01-25 17:29:33 +02:00
if path == null:
return false
var data = create_dict()
var save_file = FileAccess.open(path, FileAccess.WRITE)
if save_file == null:
return false
var json_text = JSON.stringify(data)
save_file.store_line(json_text)
2024-01-27 16:13:43 +02:00
on_saved.emit()
2024-01-25 17:29:33 +02:00
return true
func load_local(path=_save_path):
2024-01-25 17:29:33 +02:00
if path == null:
return false
var save_file = FileAccess.open(path, FileAccess.READ)
2024-03-17 18:05:45 +02:00
# In case that there is no store file yet
2024-01-25 17:29:33 +02:00
if save_file == null:
2024-03-17 18:05:45 +02:00
_loaded = true
on_loaded.emit()
return true
2024-01-25 17:29:33 +02:00
2024-01-27 16:13:43 +02:00
var json_text = save_file.get_as_text()
2024-01-25 17:29:33 +02:00
var save_data = VariantSerializer.parse_value(JSON.parse_string(json_text))
2024-01-27 16:13:43 +02:00
if save_data == null:
return false
2024-01-25 17:29:33 +02:00
use_dict(save_data)
2024-01-27 16:13:43 +02:00
_loaded = true
on_loaded.emit()
return true