From 6a8c213503f1b938a625c9d6d266a0355e4d5b79 Mon Sep 17 00:00:00 2001 From: Emilio Coppola Date: Sat, 1 Oct 2022 18:50:50 +0200 Subject: [PATCH 1/2] Replacing File for FileAccess and Directory with DirAccess Initial work Update CharacterResourceSaver.gd Some progress Replacements in more places --- .../Editor/CharacterEditor/CharacterEditor.gd | 28 ++-- addons/dialogic/Editor/EditorView.gd | 3 +- .../Editor/Settings/Settings_Translations.gd | 24 +--- .../Events/Converter/Settings_Converter.gd | 59 +++------ .../Glossary/SettingsEditor/GlossaryEditor.gd | 4 +- addons/dialogic/Events/Save/Subsystem_Save.gd | 109 +++++++--------- addons/dialogic/Other/DialogicUtil.gd | 27 ++-- .../Resources/CharacterResourceLoader.gd | 20 +-- .../Resources/CharacterResourceSaver.gd | 20 +-- .../Resources/TimelineResourceLoader.gd | 49 +++---- .../Resources/TimelineResourceSaver.gd | 123 ++++++++---------- 11 files changed, 194 insertions(+), 272 deletions(-) diff --git a/addons/dialogic/Editor/CharacterEditor/CharacterEditor.gd b/addons/dialogic/Editor/CharacterEditor/CharacterEditor.gd index 1336c119c..e159753c9 100644 --- a/addons/dialogic/Editor/CharacterEditor/CharacterEditor.gd +++ b/addons/dialogic/Editor/CharacterEditor/CharacterEditor.gd @@ -178,26 +178,25 @@ func open_portrait_folder_select() -> void: func import_portraits_from_folder(path:String) -> void: - var dir := Directory.new() - if dir.open(path) == OK: - dir.list_dir_begin() - var file_name :String = dir.get_next() - while file_name != "": - if not dir.current_is_dir(): - var file_lower = file_name.to_lower() - if '.svg' in file_lower or '.png' in file_lower: - if not '.import' in file_lower: - var final_name :String= path+ "/" + file_name - add_portrait(file_name.trim_suffix('.'+file_name.get_extension()), {'scene':"",'image':final_name, 'scale':1, 'offset':Vector2(), 'mirror':false}) - file_name = dir.get_next() - else: - print("An error occurred when trying to access the path.") + var dir := DirAccess.open(path) + dir.list_dir_begin() + var file_name :String = dir.get_next() + while file_name != "": + if not dir.current_is_dir(): + var file_lower = file_name.to_lower() + if '.svg' in file_lower or '.png' in file_lower: + if not '.import' in file_lower: + var final_name :String= path+ "/" + file_name + add_portrait(file_name.trim_suffix('.'+file_name.get_extension()), {'scene':"",'image':final_name, 'scale':1, 'offset':Vector2(), 'mirror':false}) + file_name = dir.get_next() + func add_portrait(portrait_name:String='New portrait', portrait_data:Dictionary={'scene':"", 'image':'', 'scale':1, 'offset':Vector2(), 'mirror':false}) -> void: var root = %PortraitTree.get_root() add_portrait_item(portrait_name, portrait_data, root).select(0) something_changed() + func load_portrait_tree() -> void: %PortraitTree.clear() var root = %PortraitTree.create_item() @@ -208,6 +207,7 @@ func load_portrait_tree() -> void: if root.get_child_count(): root.get_first_child().select(0) + func filter_portrait_list(filter_term:String = '') -> void: var item : TreeItem = %PortraitTree.get_root().get_first_child() while true: diff --git a/addons/dialogic/Editor/EditorView.gd b/addons/dialogic/Editor/EditorView.gd index 2e0299509..f5e9cb7ff 100644 --- a/addons/dialogic/Editor/EditorView.gd +++ b/addons/dialogic/Editor/EditorView.gd @@ -54,9 +54,8 @@ func _exit_tree(): func open_last_resource(): if ProjectSettings.has_setting('dialogic/editor/last_resources'): - var directory := Directory.new(); var path :String= ProjectSettings.get_setting('dialogic/editor/last_resources')[0] - if directory.file_exists(path): + if FileAccess.file_exists(path): DialogicUtil.get_dialogic_plugin().editor_interface.inspect_object(load(path)) diff --git a/addons/dialogic/Editor/Settings/Settings_Translations.gd b/addons/dialogic/Editor/Settings/Settings_Translations.gd index 6601c6ec5..c3cde2fa9 100644 --- a/addons/dialogic/Editor/Settings/Settings_Translations.gd +++ b/addons/dialogic/Editor/Settings/Settings_Translations.gd @@ -56,10 +56,9 @@ func _on_TransInitialize_pressed(): if %TransOrigLanguage.text.is_empty(): %TransOrigLanguage.text = ProjectSettings.get_setting('locale/fallback') var orig_locale = %TransOrigLanguage.text.strip_edges() - var file = File.new() if %TransFileMode.selected == 0: - file.open('res://dialogic_translation.csv', File.WRITE) + var file := FileAccess.open('res://dialogic_translation.csv', FileAccess.WRITE) ProjectSettings.set_setting('dialogic/translation_path', 'res://dialogic_translation.csv') file.store_csv_line(['keys', orig_locale]) else: @@ -68,8 +67,8 @@ func _on_TransInitialize_pressed(): for timeline_path in DialogicUtil.list_resources_of_type('.dtl'): + var file := FileAccess.open(timeline_path.trim_suffix('.dtl')+'_translation.csv', FileAccess.WRITE) if %TransFileMode.selected == 1: - file.open(timeline_path.trim_suffix('.dtl')+'_translation.csv', File.WRITE) file.store_csv_line(['keys', orig_locale]) var tml:DialogicTimeline = load(timeline_path) @@ -77,15 +76,8 @@ func _on_TransInitialize_pressed(): #if event. if event.can_be_translated(): file.store_csv_line([event.add_translation_id(), event.get_original_translation_text()]) - + ResourceSaver.save(tml, timeline_path) - - if %TransFileMode.selected == 1: - file.close() - - if %TransFileMode.selected == 0: - file.close() - ProjectSettings.set_setting('dialogic/translation_enabled', true) ProjectSettings.save() @@ -96,26 +88,24 @@ func _on_TransRemove_pressed(): func erase_translations(): ProjectSettings.set_setting('dialogic/translation_enabled', false) - var file = File.new() - var dir = Directory.new() var trans_files = Array(ProjectSettings.get_setting('locale/translations')) var trans_path = DialogicUtil.get_project_setting('dialogic/translation_path', '') if trans_path.ends_with('.csv'): for x_file in DialogicUtil.listdir(trans_path.get_base_dir()): if x_file.ends_with('.translation'): trans_files.erase(trans_path.get_base_dir().path_join(x_file)) - dir.remove(trans_path.get_base_dir().path_join(x_file)) - dir.remove(DialogicUtil.get_project_setting('dialogic/translation_path', '')) + DirAccess.remove_absolute(trans_path.get_base_dir().path_join(x_file)) + DirAccess.remove_absolute(DialogicUtil.get_project_setting('dialogic/translation_path', '')) ProjectSettings.set_setting('dialogic/translation_path', null) for timeline_path in DialogicUtil.list_resources_of_type('.dtl'): if trans_path == '': - dir.remove(timeline_path.trim_suffix('.dtl')+'_translation.csv') + DirAccess.remove_absolute(timeline_path.trim_suffix('.dtl')+'_translation.csv') for x_file in DialogicUtil.listdir(timeline_path.get_base_dir()): if x_file.ends_with('.translation'): trans_files.erase(timeline_path.get_base_dir().path_join(x_file)) - dir.remove(timeline_path.get_base_dir().path_join(x_file)) + DirAccess.remove_absolute(timeline_path.get_base_dir().path_join(x_file)) var tml:DialogicTimeline = load(timeline_path) for event in tml.get_events(): diff --git a/addons/dialogic/Events/Converter/Settings_Converter.gd b/addons/dialogic/Events/Converter/Settings_Converter.gd index 63ee0eaf1..b6a19ee3a 100644 --- a/addons/dialogic/Events/Converter/Settings_Converter.gd +++ b/addons/dialogic/Events/Converter/Settings_Converter.gd @@ -25,21 +25,19 @@ func refresh(): func _on_verify_pressed(): - var file = File.new() - %OutputLog.text = "" - if file.file_exists("res://dialogic/settings.cfg"): + if FileAccess.file_exists("res://dialogic/settings.cfg"): %OutputLog.text += "[√] Dialogic 1.x data [color=green]found![/color]\r\n" - if file.file_exists("res://dialogic/definitions.json"): + if FileAccess.file_exists("res://dialogic/definitions.json"): %OutputLog.text += "[√] Dialogic 1.x definitions [color=green]found![/color]\r\n" else: %OutputLog.text += "[X] Dialogic 1.x definitions [color=red]not found![/color]\r\n" %OutputLog.text += "Please copy the res://dialogic folder from your Dialogic 1.x project into this project and try again.\r\n" return - if file.file_exists("res://dialogic/settings.cfg"): + if FileAccess.file_exists("res://dialogic/settings.cfg"): %OutputLog.text += "[√] Dialogic 1.x settings [color=green]found![/color]\r\n" else: %OutputLog.text += "[X] Dialogic 1.x settings [color=red]not found![/color]\r\n" @@ -49,7 +47,7 @@ func _on_verify_pressed(): %OutputLog.text += "\r\n" %OutputLog.text += "Verifying data:\r\n" - file.open("res://dialogic/folder_structure.json",File.READ) + var file := FileAccess.open("res://dialogic/folder_structure.json", FileAccess.READ) var fileContent = file.get_as_text() var json_object = JSON.new() @@ -99,7 +97,7 @@ func _on_verify_pressed(): %OutputLog.text += "[color=yellow]There may be an issue, please check in Dialogic 1.x to make sure that is correct![/color]\r\n" - file.open("res://dialogic/definitions.json",File.READ) + file = FileAccess.open("res://dialogic/definitions.json",FileAccess.READ) fileContent = file.get_as_text() json_object = JSON.new() @@ -163,15 +161,13 @@ func _on_verify_pressed(): %OutputLog.text += "Initial integrity check completed!\r\n" - var directory = Directory.new() - var directoryCheck = directory.dir_exists(conversionRootFolder) - if directoryCheck: + if DirAccess.dir_exists_absolute(conversionRootFolder): %OutputLog.text += "[color=yellow]Conversion folder already exists, coverting will overwrite existing files.[/color]\r\n" else: %OutputLog.text += conversionRootFolder %OutputLog.text += "Folders are being created in " + conversionRootFolder + ". Converted files will be located there.\r\n" - directory.open("res://") + var directory = DirAccess.open("res://") directory.make_dir(conversionRootFolder) directory.open(conversionRootFolder) directory.make_dir("characters") @@ -188,8 +184,7 @@ func _on_verify_pressed(): func list_files_in_directory(path): var files = [] - var dir = Directory.new() - dir.open(path) + var dir = DirAccess.open(path) dir.list_dir_begin() while true: @@ -244,8 +239,7 @@ func convertTimelines(): var folderPath = timelineFolderBreakdown[item] %OutputLog.text += "Timeline " + folderPath + item +": " var jsonData = {} - var file = File.new() - file.open("res://dialogic/timelines/" + item,File.READ) + var file := FileAccess.open("res://dialogic/timelines/" + item, FileAccess.READ) var fileContent = file.get_as_text() var json_object = JSON.new() @@ -256,10 +250,9 @@ func convertTimelines(): var fileName = contents["metadata"]["name"] %OutputLog.text += "Name: " + fileName + ", " + str(contents["events"].size()) + " timeline events" - var directory = Directory.new() - var directoryCheck = directory.dir_exists(conversionRootFolder + "/timelines" + folderPath) - if !directoryCheck: - directory.open(conversionRootFolder + "/timelines") + + if not DirAccess.dir_exists_absolute(conversionRootFolder + "/timelines" + folderPath): + var directory = DirAccess.open(conversionRootFolder + "/timelines") var progresiveDirectory = "" for pathItem in folderPath.split('/'): @@ -274,7 +267,8 @@ func convertTimelines(): folderPath = folderPath.left(-1) # we will save it as an intermediary file first, then on second pass cleanup make it the .dtl var newFilePath = conversionRootFolder + "/timelines" + folderPath + "/" + fileName + ".cnv" - file.open(newFilePath,File.WRITE) + + file = FileAccess.open(newFilePath, FileAccess.WRITE) # update the new location so we know where second pass items are @@ -663,7 +657,6 @@ func convertTimelines(): file.store_string(eventLine) file.store_string("\r\n\r\n") - file.close() @@ -677,11 +670,8 @@ func convertTimelines(): for item in timelineFolderBreakdown: %OutputLog.text += "Verifying file: " + timelineFolderBreakdown[item] + "\r\n" - var oldFile = File.new() - oldFile.open(timelineFolderBreakdown[item] ,File.READ) - - var newFile = File.new() - newFile.open(timelineFolderBreakdown[item].replace(".cnv", ".dtl") ,File.WRITE) + var oldFile = FileAccess.open(timelineFolderBreakdown[item], FileAccess.READ) + var newFile = FileAccess.open(timelineFolderBreakdown[item].replace(".cnv", ".dtl"), FileAccess.WRITE) var regex = RegEx.new() regex.compile('(<.*?>)') @@ -725,14 +715,10 @@ func convertTimelines(): newFile.store_string(line) else: newFile.store_string(line) - - oldFile.close() - newFile.close() - var dir = Directory.new() var fileDirectory = timelineFolderBreakdown[item].replace(timelineFolderBreakdown[item].split("/")[-1], "") - dir.open(fileDirectory) + var dir = DirAccess.open(fileDirectory) dir.remove(timelineFolderBreakdown[item]) %OutputLog.text += "Completed conversion of file: " + timelineFolderBreakdown[item].replace(".cnv", ".dtl") + "\r\n" @@ -748,8 +734,7 @@ func convertCharacters(): var folderPath = characterFolderBreakdown[item] %OutputLog.text += "Character " + folderPath + item +": " var jsonData = {} - var file = File.new() - file.open("res://dialogic/characters/" + item,File.READ) + var file := FileAccess.open("res://dialogic/characters/" + item, FileAccess.READ) var fileContent = file.get_as_text() var json_object = JSON.new() @@ -766,10 +751,9 @@ func convertCharacters(): - var directory = Directory.new() - var directoryCheck = directory.dir_exists(conversionRootFolder + "/characters" + folderPath) - if !directoryCheck: - directory.open(conversionRootFolder + "/characters") + + if not DirAccess.dir_exists_absolute(conversionRootFolder + "/characters" + folderPath): + var directory = DirAccess.open(conversionRootFolder + "/characters") var progresiveDirectory = "" for pathItem in folderPath.split('/'): @@ -854,7 +838,6 @@ func convertCharacters(): else: %OutputLog.text += "[color=red]There was a problem parsing this file![/color]\r\n" - file.close() # Second pass, shorten all of the paths, so they match the character dictionary in Dialogic itself # Temporarily need an array to be able to sort diff --git a/addons/dialogic/Events/Glossary/SettingsEditor/GlossaryEditor.gd b/addons/dialogic/Events/Glossary/SettingsEditor/GlossaryEditor.gd index df49da3db..39e0169e1 100644 --- a/addons/dialogic/Events/Glossary/SettingsEditor/GlossaryEditor.gd +++ b/addons/dialogic/Events/Glossary/SettingsEditor/GlossaryEditor.gd @@ -32,7 +32,7 @@ func refresh() -> void: %GlossaryList.clear() var idx := 0 for file in DialogicUtil.get_project_setting('dialogic/glossary/glossary_files', []): - if Directory.new().file_exists(file): + if FileAccess.file_exists(file): %GlossaryList.add_item(DialogicUtil.pretty_name(file), get_theme_icon('FileList', 'EditorIcons')) else: %GlossaryList.add_item(DialogicUtil.pretty_name(file), get_theme_icon('FileDead', 'EditorIcons')) @@ -54,7 +54,7 @@ func refresh() -> void: ################################################################################ func _on_GlossaryList_item_selected(idx:int) -> void: %EntryList.clear() - if Directory.new().file_exists(%GlossaryList.get_item_tooltip(idx)): + if FileAccess.file_exists(%GlossaryList.get_item_tooltip(idx)): current_glossary = load(%GlossaryList.get_item_tooltip(idx)) if not current_glossary is DialogicGlossary: return diff --git a/addons/dialogic/Events/Save/Subsystem_Save.gd b/addons/dialogic/Events/Save/Subsystem_Save.gd index 278878836..43ac1d7d7 100644 --- a/addons/dialogic/Events/Save/Subsystem_Save.gd +++ b/addons/dialogic/Events/Save/Subsystem_Save.gd @@ -39,87 +39,78 @@ func load(slot_name:String): set_latest_slot(slot_name) dialogic.load_full_state(load_file(slot_name, 'state.txt', {})) -func save_file(slot_name:String, file_name:String, data) -> int: +func save_file(slot_name:String, file_name:String, data) -> void: slot_name = this_or_current_slot(slot_name) - if slot_name.is_empty(): return ERR_BUG - - if slot_name.is_empty() in get_slot_names(): - add_empty_slot(slot_name) - - var file = File.new() - var err = file.open(SAVE_SLOTS_DIR.path_join(slot_name).path_join(file_name), File.WRITE) - if err == OK: + if not slot_name.is_empty(): + if slot_name.is_empty() in get_slot_names(): + add_empty_slot(slot_name) + + var file = FileAccess.open(SAVE_SLOTS_DIR.path_join(slot_name).path_join(file_name), FileAccess.WRITE) file.store_var(data, true) - file.close() - return err + func load_file(slot_name:String, file_name:String, default): slot_name = this_or_current_slot(slot_name) - if slot_name.is_empty(): return - - var file := File.new() - if file.open(get_slot_path(slot_name).path_join(file_name), File.READ) != OK: - file.close() - return default + if slot_name.is_empty(): + return - var data = file.get_var(true) - file.close() + var path := get_slot_path(slot_name).path_join(file_name) - return data + if FileAccess.file_exists(path): + var data = FileAccess.open(path, FileAccess.READ).get_var(true) + return data + return default + #################################################################################################### ## SLOT HELPERS #################################################################################################### func get_slot_names() -> Array: - var save_folders = [] - var directory := Directory.new() - if directory.open(SAVE_SLOTS_DIR) != OK: - print("[Dialogic] Error: Failed to access save directory.") - return [] + var save_folders := [] + + if DirAccess.dir_exists_absolute(SAVE_SLOTS_DIR): + var directory := DirAccess.open(SAVE_SLOTS_DIR) + directory.list_dir_begin() + var file_name := directory.get_next() + while file_name != "": + if directory.current_is_dir() and not file_name.begins_with("."): + save_folders.append(file_name) + file_name = directory.get_next() + return save_folders - directory.list_dir_begin() - var file_name = directory.get_next() - while file_name != "": - if directory.current_is_dir() and not file_name.begins_with("."): - save_folders.append(file_name) - file_name = directory.get_next() + return [] - return save_folders func has_slot(slot_name:String) -> bool: return slot_name in get_slot_names() func remove_slot(slot_name:String) -> void: - var directory := Directory.new() - if directory.open(SAVE_SLOTS_DIR.path_join(slot_name)) != OK: - print("[D] Error: Failed to access save folder '"+slot_name+"'.") - return + var path := SAVE_SLOTS_DIR.path_join(slot_name) - # first remove the content, becaus deleting filled folders isn't allowed - directory.list_dir_begin() - var file_name = directory.get_next() - while file_name != "": - directory.remove(file_name) - file_name = directory.get_next() - # then delete folder - directory.remove(SAVE_SLOTS_DIR.path_join(slot_name)) + if DirAccess.dir_exists_absolute(path): + var directory := DirAccess.open(path) + directory.list_dir_begin() + var file_name := directory.get_next() + while file_name != "": + directory.remove(file_name) + file_name = directory.get_next() + # then delete folder + directory.remove(SAVE_SLOTS_DIR.path_join(slot_name)) + # this adds a new save folder with the given name func add_empty_slot(slot_name: String) -> void: - var directory := Directory.new() - if directory.open(SAVE_SLOTS_DIR) != OK: - print("[D] Error: Failed to access working directory.") - return - directory.make_dir(slot_name) + if DirAccess.dir_exists_absolute(SAVE_SLOTS_DIR): + var directory := DirAccess.open(SAVE_SLOTS_DIR) + directory.make_dir(slot_name) + # reset the state of the given save folder (or default) func reset_slot(slot_name: String = '') -> void: slot_name = this_or_current_slot(slot_name) if slot_name.is_empty(): return - - var file = File.new() - file.store_var({}) - save_file(slot_name, 'state.txt', file) + + save_file(slot_name, 'state.txt', {}) func get_slot_path(slot_name:String) -> String: return SAVE_SLOTS_DIR.path_join(slot_name) @@ -134,9 +125,8 @@ func set_latest_slot(slot_name:String) -> void: func _make_sure_slot_dir_exists() -> void: - var directory := Directory.new() - if not directory.dir_exists(SAVE_SLOTS_DIR): - directory.make_dir_recursive(SAVE_SLOTS_DIR) + if not DirAccess.dir_exists_absolute(SAVE_SLOTS_DIR): + DirAccess.make_dir_recursive_absolute(SAVE_SLOTS_DIR) func this_or_current_slot(slot_name:String): if slot_name: set_latest_slot(slot_name) @@ -170,10 +160,11 @@ func store_slot_image(slot_name:String) -> void: func get_slot_image(slot_name:String) -> ImageTexture: slot_name = this_or_current_slot(slot_name) if slot_name.is_empty(): return null - var file = File.new() - if file.open(get_slot_path(slot_name).path_join('thumbnail.png'), File.READ) == OK: + + var path := get_slot_path(slot_name).path_join('thumbnail.png') + if FileAccess.file_exists(path): + var file := FileAccess.open(path, FileAccess.READ) var buffer = file.get_buffer(file.get_len()) - file.close() var image = Image.new() image.load_png_from_buffer(buffer) diff --git a/addons/dialogic/Other/DialogicUtil.gd b/addons/dialogic/Other/DialogicUtil.gd index 3fb549576..cd38c550e 100644 --- a/addons/dialogic/Other/DialogicUtil.gd +++ b/addons/dialogic/Other/DialogicUtil.gd @@ -6,12 +6,9 @@ static func get_editor_scale() -> float: static func listdir(path: String, files_only: bool = true, throw_error:bool = true, full_file_path:bool = false) -> Array: - - # https://docs.godotengine.org/en/stable/classes/class_directory.html#description var files: Array = [] - var dir := Directory.new() - var err = dir.open(path) - if err == OK: + if DirAccess.dir_exists_absolute(path): + var dir := DirAccess.open(path) dir.list_dir_begin() var file_name = dir.get_next() while file_name != "": @@ -29,8 +26,6 @@ static func listdir(path: String, files_only: bool = true, throw_error:bool = tr files.append(file_name) file_name = dir.get_next() dir.list_dir_end() - else: - if throw_error: printerr("[Dialogic] Error while accessing path " + path + " - Error: " + str(err)) return files @@ -44,22 +39,19 @@ static func list_resources_of_type(extension): return all_resources -static func scan_folder(folder_path:String, extension:String) -> Array: - #print(str(Time.get_ticks_msec()) + ": DialogicUtil.scan_folder") - var dir:Directory = Directory.new() +static func scan_folder(path:String, extension:String) -> Array: var list: Array = [] - if dir.open(folder_path) == OK: + if DirAccess.dir_exists_absolute(path): + var dir := DirAccess.open(path) dir.list_dir_begin() var file_name := dir.get_next() while file_name != "": if dir.current_is_dir() and not file_name.begins_with("."): - list += scan_folder(folder_path+"/"+file_name, extension) + list += scan_folder(path + "/" + file_name, extension) else: if file_name.ends_with(extension): - list.append(folder_path+"/"+file_name) + list.append(path + "/" + file_name) file_name = dir.get_next() - else: - printerr("[Dialogic] Error while accessing path " + folder_path) return list @@ -90,19 +82,18 @@ static func get_project_setting(setting:String, default = null): static func get_event_scripts(include_custom_events:bool = true) -> Array: var event_scripts = [] - var directory:Directory = Directory.new() var file_list = listdir("res://addons/dialogic/Events/", false) for file in file_list: var possible_script:String = "res://addons/dialogic/Events/" + file + "/event.gd" - if directory.file_exists(possible_script): + if FileAccess.file_exists(possible_script): event_scripts.append(possible_script) if include_custom_events: file_list = listdir("res://addons/dialogic_additions/Events/", false, false) for file in file_list: var possible_script: String = "res://addons/dialogic_additions/Events/" + file + "/event.gd" - if directory.file_exists(possible_script): + if FileAccess.file_exists(possible_script): event_scripts.append(possible_script) return event_scripts diff --git a/addons/dialogic/Resources/CharacterResourceLoader.gd b/addons/dialogic/Resources/CharacterResourceLoader.gd index 64f86d9d5..280b5c4f1 100644 --- a/addons/dialogic/Resources/CharacterResourceLoader.gd +++ b/addons/dialogic/Resources/CharacterResourceLoader.gd @@ -27,19 +27,13 @@ func _handles_type(typename: StringName) -> bool: # parse the file and return a resource func _load(path: String, original_path: String, use_sub_threads: bool, cache_mode: int): print('[Dialogic] Reimporting character "' , path, '"') - var file := File.new() - - var err:int - - err = file.open(path, File.READ) - if err != OK: - push_error("For some reason, loading custom resource failed with error code: %s"%err) - return err - - var res = dict_to_inst(str_to_var(file.get_as_text())) - - # Everything went well, and you parsed your file data into your resource. Life is good, return it - return res + if FileAccess.file_exists(path): + var file = FileAccess.open(path, FileAccess.READ) + return dict_to_inst(str_to_var(file.get_as_text())) + else: + push_error("File does not exists") + return false + func _get_dependencies(path:String, add_type:bool): var depends_on : PackedStringArray diff --git a/addons/dialogic/Resources/CharacterResourceSaver.gd b/addons/dialogic/Resources/CharacterResourceSaver.gd index 38cabba04..a8a87e5f4 100644 --- a/addons/dialogic/Resources/CharacterResourceSaver.gd +++ b/addons/dialogic/Resources/CharacterResourceSaver.gd @@ -19,17 +19,9 @@ func _recognize(resource: Resource) -> bool: # Save the resource -func _save(resource: Resource, path: String = '', flags: int = 0) -> int: - var err:int - var file:File = File.new() - err = file.open(path, File.WRITE) - if err != OK: - printerr('Can\'t write file: "%s"! code: %d.' % [path, err]) - return err - - var result = var_to_str(inst_to_dict(resource)) - - file.store_string(result) - file.close() - print('[Dialogic] Saved character "' , path, '"') - return OK +func _save(resource: Resource, path: String = '', flags: int = 0): + if FileAccess.file_exists(path): + var file := FileAccess.open(path, FileAccess.READ) + var result := var_to_str(inst_to_dict(resource)) + file.store_string(result) + print('[Dialogic] Saved character "' , path, '"') diff --git a/addons/dialogic/Resources/TimelineResourceLoader.gd b/addons/dialogic/Resources/TimelineResourceLoader.gd index 7267825c1..b2e529701 100644 --- a/addons/dialogic/Resources/TimelineResourceLoader.gd +++ b/addons/dialogic/Resources/TimelineResourceLoader.gd @@ -27,37 +27,30 @@ func _handles_type(typename: StringName) -> bool: # parse the file and return a resource func _load(path: String, original_path: String, use_sub_threads: bool, cache_mode: int): print('[Dialogic] Reimporting timeline "' , path, '"') - - var file := File.new() - var err:int - - err = file.open(path, File.READ) - if err != OK: - push_error("For some reason, loading custom resource failed with error code: %s"%err) - return err + if FileAccess.file_exists(path): + var file := FileAccess.open(path, FileAccess.READ) + var res = DialogicTimeline.new() + var text = file.get_as_text() - var res = DialogicTimeline.new() - - var text = file.get_as_text() - # Parse the lines as seperate events and insert them in an array, so they can be converted to DialogicEvent's when processed later - var prev_indent := "" - var events := [] - - var lines := text.split('\n', true) - var idx := -1 - - while idx < len(lines)-1: - idx += 1 - var line :String = lines[idx] - var line_stripped :String = line.strip_edges(true, true) - if line_stripped.is_empty(): - continue - events.append(line) + # Parse the lines as seperate events and insert them in an array, so they can be converted to DialogicEvent's when processed later + var prev_indent := "" + var events := [] + + var lines := text.split('\n', true) + var idx := -1 + + while idx < len(lines)-1: + idx += 1 + var line :String = lines[idx] + var line_stripped :String = line.strip_edges(true, true) + if line_stripped.is_empty(): + continue + events.append(line) - res.events = events - res.events_processed = false - return res + res.events = events + res.events_processed = false + return res func _get_dependencies(path:String, add_type:bool): diff --git a/addons/dialogic/Resources/TimelineResourceSaver.gd b/addons/dialogic/Resources/TimelineResourceSaver.gd index 99878040f..393eb6c76 100644 --- a/addons/dialogic/Resources/TimelineResourceSaver.gd +++ b/addons/dialogic/Resources/TimelineResourceSaver.gd @@ -27,54 +27,50 @@ func _save(resource: Resource, path: String = '', flags: int = 0) -> int: # Do not do this if the timeline's not in a ready state, so it doesn't accidentally save it blank elif !resource.events_processed: print('[Dialogic] Saving timeline...') - var err:int - var file:File = File.new() - err = file.open(path, File.WRITE) - - if err != OK: - printerr('Can\'t write file: "%s"! code: %d.' % [path, err]) - return err - - #var result = events_to_text(resource.events) - var result := "" - var indent := 0 - - for idx in range(0, len(resource.events)): - var event = resource.events[idx] + if FileAccess.file_exists(path): + var file := FileAccess.open(path, FileAccess.WRITE) + #var result = events_to_text(resource.events) + var result := "" + var indent := 0 + + for idx in range(0, len(resource.events)): + var event = resource.events[idx] + - if event['event_name'] == 'End Branch': - indent -=1 - continue + if event['event_name'] == 'End Branch': + indent -=1 + continue + + if event != null: + result += "\t".repeat(indent)+ event['event_node_as_text'] + "\n" + if event.can_contain_events: + indent += 1 + if indent < 0: + indent = 0 + result += "\t".repeat(indent)+"\n" + + file.store_string(result) - if event != null: - result += "\t".repeat(indent)+ event['event_node_as_text'] + "\n" - if event.can_contain_events: - indent += 1 - if indent < 0: - indent = 0 - result += "\t".repeat(indent)+"\n" + print('[Dialogic] Saved timeline "' , path, '"') - file.store_string(result) - file.close() - print('[Dialogic] Saved timeline "' , path, '"') - - # Checking for translation updates - var trans_updates := {} - var translate :bool= DialogicUtil.get_project_setting('dialogic/translation_enabled', false) - for idx in range(0, len(resource.events)): - var event = resource.events[idx] + # Checking for translation updates + var trans_updates := {} + var translate :bool= DialogicUtil.get_project_setting('dialogic/translation_enabled', false) + for idx in range(0, len(resource.events)): + var event = resource.events[idx] - if event != null: - if translate and event.can_be_translated(): - if event.translation_id: - trans_updates[event.translation_id] = event.get_original_translation_text() - else: - trans_updates[event.add_translation_id()] = event.get_original_translation_text() + if event != null: + if translate and event.can_be_translated(): + if event.translation_id: + trans_updates[event.translation_id] = event.get_original_translation_text() + else: + trans_updates[event.add_translation_id()] = event.get_original_translation_text() - # if translate: - # update_translations(path, trans_updates) - return OK + # if translate: + # update_translations(path, trans_updates) + return OK + return ERR_FILE_NOT_FOUND else: printerr(path + ": Timeline was not in ready state for saving! Timeline was not saved!") return ERR_INVALID_DATA @@ -84,33 +80,26 @@ func _save(resource: Resource, path: String = '', flags: int = 0) -> int: func update_translations(path:String, translation_updates:Dictionary): if translation_updates.is_empty(): return - var err:int - var trans_file := File.new() - var file_path :String = "" + + var file_path :String = path.trim_suffix('.dtl')+'_translation.csv' if DialogicUtil.get_project_setting('dialogic/translation_path', '').ends_with('.csv'): file_path = ProjectSettings.get_setting('dialogic/translation_path') - else: - file_path = path.trim_suffix('.dtl')+'_translation.csv' - err = trans_file.open(file_path, File.READ) - if err != OK: - printerr('[Dialogic] Can\'t read translation file: "%s"! code: %d.' % [file_path, err]) - return var csv_lines := [] - while !trans_file.eof_reached(): - csv_lines.append(trans_file.get_csv_line()) - if csv_lines[-1][0] in translation_updates.keys(): - csv_lines[-1][1] = translation_updates[csv_lines[-1][0]] - translation_updates.erase(csv_lines[-1][0]) - - - trans_file.close() - trans_file.open(file_path, File.WRITE) - for line in csv_lines: - if line and line[0]: - trans_file.store_csv_line(line) - for key in translation_updates.keys(): - trans_file.store_csv_line([key, translation_updates[key]]) - trans_file.close() - print('[Dialogic] Updated translations for "', path ,'"') + if FileAccess.file_exists(file_path): + var trans_file := FileAccess.open(file_path, FileAccess.READ) + + while !trans_file.eof_reached(): + csv_lines.append(trans_file.get_csv_line()) + if csv_lines[-1][0] in translation_updates.keys(): + csv_lines[-1][1] = translation_updates[csv_lines[-1][0]] + translation_updates.erase(csv_lines[-1][0]) + else: + var trans_file := FileAccess.open(file_path, FileAccess.WRITE) + for line in csv_lines: + if line and line[0]: + trans_file.store_csv_line(line) + for key in translation_updates.keys(): + trans_file.store_csv_line([key, translation_updates[key]]) + print('[Dialogic] Updated translations for "', path ,'"') From c1f25f824a295e6f12c7a2ef0360eb7e1d20bcbe Mon Sep 17 00:00:00 2001 From: Emi Date: Sun, 2 Oct 2022 19:44:36 +0200 Subject: [PATCH 2/2] Replacing do and undo methods --- .../Editor/VisualEditor/VisualEditor.gd | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/addons/dialogic/Editor/VisualEditor/VisualEditor.gd b/addons/dialogic/Editor/VisualEditor/VisualEditor.gd index 7c353b583..ab7ab2458 100644 --- a/addons/dialogic/Editor/VisualEditor/VisualEditor.gd +++ b/addons/dialogic/Editor/VisualEditor/VisualEditor.gd @@ -330,14 +330,14 @@ func _on_event_block_gui_input(event, item: Node): var to_position = moving_piece.get_index() if move_start_position != to_position: TimelineUndoRedo.create_action("[D] Moved event (type '"+moving_piece.resource.to_string()+"').") - TimelineUndoRedo.add_do_method(self, "move_block_to_index", move_start_position, to_position) - TimelineUndoRedo.add_undo_method(self, "move_block_to_index", to_position, move_start_position) + TimelineUndoRedo.add_do_method(move_block_to_index.call(move_start_position, to_position)) + TimelineUndoRedo.add_undo_method(move_block_to_index.call(to_position, move_start_position)) # in case a something like a choice or condition was moved BELOW it's end node the end_node is moved as well!!! if moving_piece.resource.can_contain_events: if moving_piece.end_node.get_index() < to_position: - TimelineUndoRedo.add_do_method(self, "move_block_to_index", moving_piece.end_node.get_index(), to_position) - TimelineUndoRedo.add_undo_method(self, "move_block_to_index", to_position+1, moving_piece.end_node.get_index()) + TimelineUndoRedo.add_do_method(move_block_to_index.call(moving_piece.end_node.get_index(), to_position)) + TimelineUndoRedo.add_undo_method(move_block_to_index.call(to_position+1, moving_piece.end_node.get_index())) # move it back so the DO action works. (Kinda stupid but whatever) move_block_to_index(to_position, move_start_position) @@ -411,8 +411,8 @@ func _input(event): if (len(selected_items) != 0): var events_indexed = get_events_indexed(selected_items) TimelineUndoRedo.create_action("[D] Deleting "+str(len(selected_items))+" event(s).") - TimelineUndoRedo.add_do_method(self, "delete_events_indexed", events_indexed) - TimelineUndoRedo.add_undo_method(self, "add_events_indexed", events_indexed) + TimelineUndoRedo.add_do_method(delete_events_indexed.call(events_indexed)) + TimelineUndoRedo.add_undo_method(add_events_indexed.call(events_indexed)) TimelineUndoRedo.commit_action() get_viewport().set_input_as_handled() @@ -456,8 +456,8 @@ func _input(event): paste_position = %Timeline.get_child_count()-1 if events_list: TimelineUndoRedo.create_action("[D] Pasting "+str(len(events_list))+" event(s).") - TimelineUndoRedo.add_do_method(self, "add_events_at_index", events_list, paste_position) - TimelineUndoRedo.add_undo_method(self, "remove_events_at_index", paste_position+1, len(events_list)) + TimelineUndoRedo.add_do_method(add_events_at_index.call(events_list, paste_position)) + TimelineUndoRedo.add_undo_method(remove_events_at_index.call(paste_position+1, len(events_list))) TimelineUndoRedo.commit_action() get_viewport().set_input_as_handled() @@ -465,8 +465,8 @@ func _input(event): if is_event_pressed(event, KEY_X, false, false, true): var events_indexed = get_events_indexed(selected_items) TimelineUndoRedo.create_action("[D] Cut "+str(len(selected_items))+" event(s).") - TimelineUndoRedo.add_do_method(self, "cut_events_indexed", events_indexed) - TimelineUndoRedo.add_undo_method(self, "add_events_indexed", events_indexed) + TimelineUndoRedo.add_do_method(cut_events_indexed.call(events_indexed)) + TimelineUndoRedo.add_undo_method(add_events_indexed.call(events_indexed)) TimelineUndoRedo.commit_action() get_viewport().set_input_as_handled() @@ -476,8 +476,8 @@ func _input(event): var events = get_events_indexed(selected_items).values() var at_index = selected_items[-1].get_index() TimelineUndoRedo.create_action("[D] Duplicate "+str(len(events))+" event(s).") - TimelineUndoRedo.add_do_method(self, "add_events_at_index", events, at_index) - TimelineUndoRedo.add_undo_method(self, "remove_events_at_index", at_index, len(events)) + TimelineUndoRedo.add_do_method(add_events_at_index.call(events, at_index)) + TimelineUndoRedo.add_undo_method(remove_events_at_index.call(at_index, len(events))) TimelineUndoRedo.commit_action() get_viewport().set_input_as_handled() @@ -753,13 +753,13 @@ func _add_event_button_pressed(event_script): if event_script.can_contain_events: TimelineUndoRedo.create_action("[D] Add event.") - TimelineUndoRedo.add_do_method(self, "add_event_with_end_branch", event_script.duplicate(), at_index, true, true) - TimelineUndoRedo.add_undo_method(self, "remove_events_at_index", at_index, 2) + TimelineUndoRedo.add_do_method(add_event_with_end_branch.call(event_script.duplicate(), at_index, true, true)) + TimelineUndoRedo.add_undo_method(remove_events_at_index.call(at_index, 2)) TimelineUndoRedo.commit_action() else: TimelineUndoRedo.create_action("[D] Add event.") - TimelineUndoRedo.add_do_method(self, "add_event_node", event_script.duplicate(), at_index, true, true) - TimelineUndoRedo.add_undo_method(self, "remove_events_at_index", at_index, 1) + TimelineUndoRedo.add_do_method(add_event_node.call(event_script.duplicate(), at_index, true, true)) + TimelineUndoRedo.add_undo_method(remove_events_at_index.call(at_index, 1)) TimelineUndoRedo.commit_action() something_changed() scroll_to_piece(at_index)