QuiltiX Plugins 0.0.1
Custom Plugins for QuiltiX
Loading...
Searching...
No Matches
materialxjson/plugin.py
Go to the documentation of this file.
1'''
2@file materlaixjson/plugin.py
3@namespace materialxjson/plugin
4'''
5import logging
6import os
7
8# Optional syntax highlighting if pygments is installed
9have_highliting = True
10try:
11 from pygments import highlight
12 from pygments.lexers import JsonLexer
13 from pygments.formatters import HtmlFormatter
14except ImportError:
15 have_highliting = False
16
17from typing import TYPE_CHECKING
18
19from qtpy import QtCore # type: ignore
20from qtpy.QtWidgets import ( # type: ignore
21 QAction,
22 QTextEdit,
23)
24from QuiltiX import constants, qx_plugin
25
26logger = logging.getLogger(__name__)
27has_materialxjsoncore = True
28
29try:
30 import materialxjson.core as jsoncore
31except ImportError:
32 has_materialxjsoncore = False
33 logger.error("materialxjson.core module not found")
34
35if TYPE_CHECKING:
36 from QuiltiX import quiltix
37
38class JsonHighlighter:
39 '''
40 @brief Class to highlight JSON text using pygments
41 @class JsonHighlighter
42 '''
43 def __init__(self):
44 '''
45 @brief Initialize the JSON highlighter
46 '''
47 self.lexer = JsonLexer()
48 # We don't add line numbers since this get's copied with
49 # copy-paste.
50 self.formatter = HtmlFormatter(linenos=False, style='github-dark')
51
52 def highlight(self, text):
53 '''
54 @brief Highlight the given JSON text
55 @param text The JSON text to highlight
56 @return The highlighted HTML
57 '''
58 highlighted_html = highlight(text, self.lexer, self.formatter)
59 styles = (
60 f"<style>"
61 f"{self.formatter.get_style_defs('.highlight')}"
62 f"pre {{ line-height: 1.0; margin: 0; }}"
63 f"</style>"
64 )
65 full_html = f"<html><head>{styles}</head><body>{highlighted_html}</body></html>"
66 return full_html
67
69 '''
70 @brief Class to handle JSON serialization in QuiltiX
71 @class QuiltiX_JSON_serializer
72 '''
73 def __init__(self, editor, root):
74 """
75 Initialize the JSON serializer.
76 """
77 self.editor = editor
78 self.root = root
79 self.indent = 4
80
81 # Add JSON menu to the file menu
82 # ----------------------------------------
83 editor.file_menu.addSeparator()
84 gltfMenu = editor.file_menu.addMenu("JSON")
85
86 # Export JSON item
87 export_json = QAction("Save JSON...", editor)
88 export_json.triggered.connect(self.export_json_triggered)
89 gltfMenu.addAction(export_json)
90
91 # Import JSON item
92 import_json = QAction("Load JSON...", editor)
93 import_json.triggered.connect(self.import_json_triggered)
94 gltfMenu.addAction(import_json)
95
96 # Show JSON text. Does most of export, except does not write to file
97 show_json_text = QAction("Show as JSON...", editor)
98 show_json_text.triggered.connect(self.show_json_triggered)
99 gltfMenu.addAction(show_json_text)
100
101 def set_indent(self, indent):
102 """
103 Set the indent for the JSON output.
104 """
105 self.indent = indent
106
107 def get_json_from_graph(self):
108 """
109 Get the JSON for the given MaterialX document.
110 """
111 doc = self.editor.qx_node_graph.get_current_mx_graph_doc()
112 if doc:
113 exporter = jsoncore.MaterialXJson()
114 json_result = exporter.documentToJSON(doc)
115 return json_result
116 return None
117
118 def show_json_triggered(self):
119 """
120 Show the JSON for the current MaterialX document.
121 """
122 json_result = self.get_json_from_graph()
123
124 # Write JSON UI text box
125 if json_result:
126 text = jsoncore.Util.jsonToJSONString(json_result, self.indent)
127 self.show_text_box(text, "JSON Representation")
128
129 def export_json_triggered(self, editor):
130 """
131 Export the current graph to a JSON file.
132 """
133 start_path = self.editor.mx_selection_path
134 if not start_path:
135 start_path = self.editor.geometry_selection_path
136
137 if not start_path:
138 start_path = os.path.join(self.root, "resources", "materials")
139
140 path = self.editor.request_filepath(
141 title="Save JSON file",
142 start_path=start_path,
143 file_filter="JSON files (*.json)",
144 mode="save",
145 )
146
147 if not path:
148 return
149
150 json_result = self.get_json_from_graph()
151
152 # Write JSON to file
153 if json_result:
154 with open(path, "w"):
155 jsoncore.Util.writeJson(json_result, path, 2)
156 logger.info("Wrote JSON file: " + path)
157
158 self.editor.set_current_filepath(path)
159
160 def import_json_triggered(self, editor):
161 """
162 Import a JSON file into the current graph.
163 """
164 start_path = self.editor.mx_selection_path
165 if not start_path:
166 start_path = self.editor.geometry_selection_path
167
168 if not start_path:
169 start_path = os.path.join(self.root, "resources", "materials")
170
171 path = self.editor.request_filepath(
172 title="Load JSON file",
173 start_path=start_path,
174 file_filter="JSON files (*.json)",
175 mode="open",
176 )
177 if not path:
178 return
179
180 if not os.path.exists(path):
181 logger.error("Cannot find input file: " + path)
182 return
183
184 doc = jsoncore.Util.jsonFileToXml(path)
185 if doc:
186 logger.info("Loaded JSON file: " + path)
187 self.editor.mx_selection_path = path
188 self.editor.qx_node_graph.load_graph_from_mx_doc(doc)
189 self.editor.qx_node_graph.mx_file_loaded.emit(path)
190
191 # Helper functions
192 def show_text_box(self, text, title=""):
193 """
194 Show a text box with the given text.
195 """
196 te_text = QTextEdit()
197 te_text.setReadOnly(True)
198 te_text.setParent(self.editor, QtCore.Qt.Window)
199 te_text.setWindowTitle(title)
200 te_text.resize(1000, 800)
201
202 if have_highliting:
203 jsonHighlighter = JsonHighlighter()
204 highlighted_html = jsonHighlighter.highlight(text)
205 te_text.setHtml(highlighted_html)
206 else:
207 te_text.setPlainText(text)
208
209 te_text.show()
210
211
212@qx_plugin.hookimpl
213def after_ui_init(editor: "quiltix.QuiltiXWindow"):
214 editor.json_serializer = QuiltiX_JSON_serializer(editor, constants.ROOT)
215
216
217def plugin_name() -> str:
218 return "MaterialX JSON Serializer"
219
220
221def is_valid() -> bool:
222 return has_materialxjsoncore
Class to handle JSON serialization in QuiltiX.
highlight(self, text)
Highlight the given JSON text.
__init__(self)
Initialize the JSON highlighter.