Skip to content

Commit

Permalink
ENH: Add translation for VolumeDisplayPresets.json
Browse files Browse the repository at this point in the history
See Slicer/SlicerLanguagePacks#43

Co-authored-by: Andras Lasso <[email protected]>
  • Loading branch information
mhdiop and lassoan committed Mar 20, 2024
1 parent 62ec1f5 commit 4468ef3
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 2 deletions.
5 changes: 3 additions & 2 deletions Modules/Loadable/Volumes/Logic/vtkSlicerVolumesLogic.cxx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
#include "vtkSlicerVolumesLogic.h"

// MRML logic includes
#include "vtkMRMLI18N.h"
#include "vtkMRMLColorLogic.h"
#include "vtkDataIOManagerLogic.h"
#include "vtkMRMLRemoteIOLogic.h"
Expand Down Expand Up @@ -1658,7 +1659,7 @@ void vtkSlicerVolumesLogic::InitializeDefaultVolumeDisplayPresets()
}
VolumeDisplayPreset presetObj;
presetObj.id = preset["id"].GetString();
presetObj.name = preset["name"].GetString();
presetObj.name = vtkMRMLTr("VolumeDisplayPresets", preset["name"].GetString());
presetObj.level = preset["level"].GetDouble();
presetObj.window = preset["window"].GetDouble();
presetObj.valid = true;
Expand All @@ -1682,7 +1683,7 @@ void vtkSlicerVolumesLogic::InitializeDefaultVolumeDisplayPresets()
{
if (preset["description"].IsString())
{
presetObj.description = preset["description"].GetString();
presetObj.description = vtkMRMLTr("VolumeDisplayPresets", preset["description"].GetString());
}
else
{
Expand Down
56 changes: 56 additions & 0 deletions Utilities/Scripts/update_translations.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,57 @@ def extract_translatable_from_cli_modules(input_paths, exclude_filenames=None):
_generate_translation_header_from_cli_xml(os.path.join(root, name))


def _get_string_values_from_json(data, keys):
"""Get all string values from a JSON object that matches any of the the specified keys"""
values = []
if isinstance(data, dict):
for key, value in data.items():
if isinstance(value, (dict, list)):
values.extend(_get_string_values_from_json(value, keys))
elif isinstance(value, str) and key in keys:
values.append(value)
elif isinstance(data, list):
for item in data:
values.extend(_get_string_values_from_json(item, keys))
return values

def _generate_translation_header_from_json_file(filename, property_names):
"""Generate a C++ header file from translatable properties found in a json file"""
logging.debug(f"Generating header file for Qt translation from {filename}")

file_path = os.path.abspath(filename)
if not os.path.isfile(file_path):
raise RuntimeError(f"Failed to extract translatable strings, file not found: {filename}")

with open(file_path, encoding="utf8") as file:
import json

try:
json_object = json.loads(file.read())
except json.decoder.JSONDecodeError:
raise RuntimeError(f"Failed to extract translatable strings, not a valid JSON file: {filename}")

translation_context = os.path.splitext(os.path.basename(filename))[0]

cpp_header_str = f"// Generated automatically by update_translations.py from {filename}\n\n"

translatable_strings = _get_string_values_from_json(json_object, property_names)

# Get unique strings with keeping the order
seen = set()
translatable_strings = [x for x in translatable_strings if x not in seen and not seen.add(x)]

for translatable_string in translatable_strings:
translatable_string = translatable_string.replace("\n", "\\n").replace('"', '\\"')
cpp_header_str += f'QT_TRANSLATE_NOOP("{translation_context}", "{translatable_string}")\n'

cpp_header_path = os.path.splitext(filename)[0] + "_tr.h"

logging.info("Writing output file: " + cpp_header_path)
with open(cpp_header_path, "w", encoding="utf8") as cpp_header_file:
cpp_header_file.write(cpp_header_str)


def main(argv):
parser = argparse.ArgumentParser(description="Update Qt translation files")
parser.add_argument("--lupdate", default="lupdate", dest="lupdate_path",
Expand Down Expand Up @@ -405,6 +456,11 @@ def main(argv):
"DiffusionTensorTest.xml",
]
extract_translatable_from_cli_modules(cli_input_paths, cli_exclude_names)

# Slicer presets files translation
_generate_translation_header_from_json_file(
os.path.join(args.source_code_dir, "Modules/Loadable/Volumes/Resources/VolumeDisplayPresets.json"),
["name", "description"])
else:
extract_translatable_from_cli_modules([args.source_code_dir])

Expand Down

0 comments on commit 4468ef3

Please sign in to comment.