forked from nplathe/pyJSON-Schema-Loader-and-JSON-Editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyJSON.py
1198 lines (1055 loc) · 51.4 KB
/
pyJSON.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ----------------------------------------
# pyJSON Schema Loader and JSON Editor - Main Module
# author: N. Plathe
# ----------------------------------------
"""
This is the main module, extending on the interface and implementing functions that call on the modules.
"""
# ----------------------------------------
# pyJSONs main repo:
# https://github.com/nplathe/pyJSON-Schema-Loader-and-JSON-Editor
# ----------------------------------------
# Music recommendation (albums):
# Feuerschwanz - Memento Mori
# Bullet for my Valentine - Bullet for my Valentine
# Callejon - Metropolis
# Tallah - The Generation Of Danger
# ----------------------------------------
# Libraries
# ----------------------------------------
# import 3rd party and system libraries
import json
import logging
import os
import platform
import regex as re
import shutil
import subprocess
from datetime import datetime
# import PySide libraries
from PySide6 import QtCore, QtWidgets, QtGui
from PySide6.QtCore import QModelIndex, Qt, QPoint
from PySide6.QtGui import QBrush, QColor, QGuiApplication, QStandardItemModel, QStandardItem, QIcon
from PySide6.QtWidgets import QMainWindow, QStyledItemDelegate, QStyle, QWidget, QVBoxLayout, \
QFileDialog, QMessageBox, QStyleOptionViewItem
# import of modules
from Modules import jsonio_lib, jsonsearch_lib
from Modules.deploy_files import deploy_schema, deploy_config, save_config, save_main_index
from Modules.ModifiedTreeModel import ModifiedTreeClass as TreeClass
# import the converted user interface
from UserInterfaces.pyJSON_interface import Ui_MainWindow
from Modules.pref_ui import ui_preferences
# ----------------------------------------
# Variables and Functions
# ----------------------------------------
# Special delegator for the tree model in order to handle enums in the schema
class EnumDropDownDelegate(QStyledItemDelegate):
"""
A custom delegate class based off QStyledItemDelegate. Passes most data to the standard editor, except for
enumerators, which is noted down in the schema.
"""
def __init__(self):
"""
Constructor
"""
super(EnumDropDownDelegate, self).__init__()
def createEditor(self, parent, option, index):
"""
When data is to be edited, the delegate provides an Editor, which is, most of the time, a QWidget.
Args:
parent (QWidget): parent of the QWidget to be.
option (object): option that might be passed to the constructor of the QWidget
index (QModelIndex): the QModelIndex of the item that was clicked
Returns:
QWidget: the editor QWidget - a drop down menu for enumerators, a line edit (the standard) otherwise
"""
cur_item = index.model().getItem(index)
value_type = cur_item.get_data(3)
cur_meta = cur_item.all_metadata()
value_type2 = cur_item.get_metadata("type")
if value_type2 is not None:
lg.debug("Last Type fetched: " + value_type2)
lg.debug("Type of item in model: " + value_type)
if "enum" in cur_meta.keys():
lg.debug("custom delegate editor selected...")
dropDownEnum = QtWidgets.QComboBox(parent)
dropDownEnum.setFrame(False)
dropDownEnum.addItem("(none)")
for i in cur_meta["enum"]:
dropDownEnum.addItem(i)
return dropDownEnum
else:
widget = QStyledItemDelegate.createEditor(QStyledItemDelegate(), parent, option, index)
return widget
else:
widget = QStyledItemDelegate.createEditor(QStyledItemDelegate(), parent, option, index)
return widget
def setEditorData(self, editor, index):
"""
Passes the data from the model to the editor
Args:
editor (QWidget): the QWidget for which the data needs to be set
index (QModelIndex): the index of the item to be edited
"""
item = index.model().getItem(index)
value = item.get_data_array()[2]
value_type = item.get_data(3)
if isinstance(editor, QtWidgets.QComboBox):
if value_type != "boolean":
if value == '':
editor.setCurrentText("(none)")
else:
editor.setCurrentText(value)
else:
QStyledItemDelegate.setEditorData(QStyledItemDelegate(), editor, index)
def setModelData(self, editor, model, index):
"""
Passes data from the editor to the model
Args:
editor (QWidget): the QWidget for which the data needs to be set
model (TreeClass): the model of the TreeView
index (QModelIndex): the index of the item to be edited
"""
if isinstance(editor, QtWidgets.QComboBox): # handle combobox data
value = editor.currentText()
if value == "(none)":
model.setData(index, "", Qt.EditRole)
else:
# boolean values cause the editor to be confused and create a QComboBox - we need to retranslate
# the values back properly.
if model.getItem(index).get_data(3) == 'boolean':
if value == "True":
model.setData(index, True, Qt.EditRole)
else:
model.setData(index, False, Qt.EditRole)
else:
model.setData(index, value, Qt.EditRole)
else: # handle arrays and everything else
# array value insertion
if model.getItem(index).get_data(3) == 'array':
if editor.text() != '':
model.beginInsertRows(index, index.row(), index.row() + 1)
lg.info("[pyJSON.EnumDropDownDelegate.setModelData/INFO]: Detected an entry for an array."
+ " Inserting the entry as a child node...")
model.add_node(parent = model.getItem(index), data = ["", "", editor.text(), "string", "Array Item"])
model.endInsertRows()
ui.TreeView.expandAll() #todo: move this out and split delegate into own file
else:
lg.info("[pyJSON.EnumDropDownDelegate.setModelData/INFO]: Will not add a node since text is empty.")
# array value removal
elif (editor.text() == '' and
model.getItem(index).get_parent().get_data(3) == 'array' and
model.getItem(index).get_data(3) != 'object'):
lg.info("[pyJSON.EnumDropDownDelegate.setModelData/INFO]: Detected an empty entry of an array."
+ " Removing node from TreeView...")
model.beginRemoveRows(index, index.row(), index.row() + 1)
model.removeRows(index.row(), 1, index.parent())
model.endRemoveRows()
# editing objects mess with the structure...
elif model.getItem(index).get_data(3) == 'object':
lg.info("[pyJSON.EnumDropDownDelegate.setModelData/INFO]: Tried to edit an object."
+ " Ommiting input.")
pass # so we just don't touch it.
else: # pass everything else to the standard delegate function
QStyledItemDelegate.setModelData(QStyledItemDelegate(), editor, model, index)
def updateEditorGeometry(self, editor, option, index):
"""
updates the QWidget, e.g. when the size of the window changes
Args:
editor (QWidget): the QWidget which needs to get updated
option (Object): option that needs to be passed to setGeometry
index (QModelIndex): the index of the item the editor is located at
"""
QStyledItemDelegate.updateEditorGeometry(QStyledItemDelegate(), editor, option, index)
class BackgroundBrushDelegate(QStyledItemDelegate):
"""
Another QStyledItemDelegate inheriting class for coloring the not-to-be-edited columns
"""
def __init__(self, brush: QBrush, parent):
"""
Constructor
Args:
brush (QBrush): a brush containing specific parameters, like colors.
parent (object): the Parent Object.
"""
super(BackgroundBrushDelegate, self).__init__()
self.brush = brush
def initStyleOption(self, option: QStyleOptionViewItem, index: QtCore.QModelIndex) -> None:
"""
sets the color to the cells the delegate is assigned to
Args:
option (QStyleOptionViewItem): passes other options
index (QModelIndex): the QModelIndex to be modified
"""
super(BackgroundBrushDelegate, self).initStyleOption(option, index)
option.backgroundBrush = self.brush
# class for a small additional window showing search results.
class SearchWindow(QWidget):
"""
The SearchWindow Class is a simple QWidget for showing search results in a list-view.
"""
def __init__(self):
"""
Constructor containing all the signal-slot-connections and information about the window
"""
super(SearchWindow, self).__init__()
# Layout, Formatting
layout = QVBoxLayout()
self.setLayout(layout)
self.setWindowTitle("pyJSON - Search Results")
# Widgets
self.searchListView = QtWidgets.QListView()
self.searchListView.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)
self.searchListView.setContextMenuPolicy(Qt.CustomContextMenu)
self.searchListView.customContextMenuRequested.connect(self.on_custom_context_menu)
# Add Widgets to layout
layout.addWidget(self.searchListView)
def on_custom_context_menu(self, index):
"""
Custom context Menu
Args:
index (QPoint): The QPoint the right click was executed at.
"""
list_index = self.searchListView.indexAt(index)
if list_index.isValid():
item_menu = QtWidgets.QMenu("Item menu")
entry1 = item_menu.addAction("Open in pyJSON...")
entry1.triggered.connect(self.open_in_pyjson)
entry2 = item_menu.addAction("Open in Editor...")
entry2.triggered.connect(self.open_file)
entry3 = item_menu.addAction("Open File Location...")
entry3.triggered.connect(self.open_file_location)
item_menu.exec(self.searchListView.viewport().mapToGlobal(index))
def open_in_pyjson(self):
"""
A function for opening a JSON in the pyJSON window itself
"""
index = self.searchListView.selectedIndexes()[0]
item = self.searchListView.model().itemFromIndex(index)
if ui:
ui.jsonopener(filepath_str = item.text())
def open_file(self):
"""
A function to initialise opening the selected path in the ListView with the associated tool. Conveniently enough
with Windows, explorer.exe passes the attempt of opening a file to the app for us.
"""
index = self.searchListView.selectedIndexes()[0]
item = self.searchListView.model().itemFromIndex(index)
if platform.system() == "Windows":
subprocess.Popen('explorer '+item.text())
def open_file_location(self):
"""
Opens the path to the file.
"""
index = self.searchListView.selectedIndexes()[0]
item = self.searchListView.model().itemFromIndex(index)
if platform.system() == "Windows":
path = os.path.dirname(item.text())
lg.info(path)
subprocess.Popen('explorer '+path)
# class extension of my GUI, containing all functions related to the GUI
class UiRunnerInstance(QMainWindow, Ui_MainWindow):
"""
The main window class, which is a subclass of the converted interface class generated from the ui XML file. It contains
all the slots for functionality of the ui.
"""
def __init__(self, config = None, script_dir = "", index_dict = None):
"""
Constructor. Sets up all signals and slots, decorates the buttons, creates status tips, links the deleagte to
the 2nd column, etc...
Args:
config (dict): handover config from loading before entering the loop.
script_dir (str): the script directory.
index_dict: handover index_dict from loading.
"""
# we first call init from the super class, then load the translated py file file from designer
super(UiRunnerInstance, self).__init__()
self.setupUi(self)
# init dicts and script_dir variable
if config is None:
self.config = {
"last_dir": os.getcwd(),
"last_schema": "default.json",
"last_JSON": None,
"verbose_logging": False,
"show_error_representation": True
}
else:
self.config = config
if script_dir is None:
self.script_dir = os.getcwd()
else:
self.script_dir = script_dir
if index_dict is None:
self.index_dict = {
"cur_index": 0
}
else:
self.index_dict = index_dict
# window decoration
title = "pyJSON Schema Loader and JSON Editor"
self.setWindowTitle(title)
self.setWindowIcon(QIcon("./icon.ico"))
# adding in the signals for the buttons
self.pushButton_dirSel.clicked.connect(self.diropener)
self.pixmap_dirOpen = getattr(QStyle, "SP_FileDialogNewFolder")
self.icon_dirOpen = self.style().standardIcon(self.pixmap_dirOpen)
self.pushButton_dirSel.setIcon(self.icon_dirOpen)
self.pushButton_dirSel.setText("")
self.pushButton_new.clicked.connect(self.set_blank_from_schema)
self.pixmap_new = getattr(QStyle, "SP_FileIcon")
self.icon_new = self.style().standardIcon(self.pixmap_new)
self.pushButton_new.setIcon(self.icon_new)
self.pushButton_new.setText("")
self.pushButton_open.clicked.connect(self.jsonopener)
self.pixmap_open = getattr(QStyle, "SP_DirOpenIcon")
self.icon_open = self.style().standardIcon(self.pixmap_open)
self.pushButton_open.setIcon(self.icon_open)
self.pushButton_open.setText("")
self.pushButton_save.clicked.connect(self.save_function)
self.pixmap_save = getattr(QStyle, "SP_DialogSaveButton")
self.icon_save = self.style().standardIcon(self.pixmap_save)
self.pushButton_save.setIcon(self.icon_save)
self.pushButton_save.setText("")
self.pushButton_search.clicked.connect(self.search_dirs)
self.pixmap_search = getattr(QStyle, "SP_FileDialogContentsView")
self.icon_search = self.style().standardIcon(self.pixmap_search)
self.pushButton_search.setIcon(self.icon_search)
self.pushButton_search.setText("")
self.pushButton_addSchema.clicked.connect(self.copy_schema_to_storage)
self.pixmap_addSchema = getattr(QStyle, "SP_FileDialogDetailedView")
self.icon_addSchema = self.style().standardIcon(self.pixmap_addSchema)
self.pushButton_addSchema.setIcon(self.icon_addSchema)
self.pushButton_addSchema.setText("")
# JSON related functions in the menu bar
self.actionOpen_JSON.triggered.connect(self.jsonopener)
self.actionSave_as.triggered.connect(self.save_as_function)
self.actionSave.triggered.connect(self.save_function)
self.actionReload_JSON_and_drop_Changes.triggered.connect(self.reloader_function)
# Schema related functions in the menu bar
self.actionAdd_Schema.triggered.connect(self.copy_schema_to_storage)
self.actionCreate_JSON_from_selected_Schema.triggered.connect(self.set_blank_from_schema)
self.actionLoad_default_for_selected_schema.triggered.connect(self.load_default)
self.actionSave_as_default.triggered.connect(self.save_default)
self.actionValidate_input_against_selected_schema.triggered.connect(self.validate_function)
# Index related functions in the menu bar
self.actionCheck_indexes.triggered.connect(self.call_watchdog)
# other menu bar entries
self.actionPreferences.triggered.connect(self.call_prefdiag)
# Drop-Down Menu
self.current_schema_combo_box.currentTextChanged.connect(self.combobox_selected)
self.searchList = None
self.prefdiag = None
# set the delegate for the view
self.delegate = EnumDropDownDelegate()
self.TreeView.setItemDelegateForColumn(2, self.delegate)
# right click context menu
self.TreeView.setContextMenuPolicy(Qt.CustomContextMenu)
self.TreeView.customContextMenuRequested.connect(self.on_custom_context_menu)
# load data from the config, if present.
if config["last_JSON"] is not None:
self.jsonopener(filepath_str = config["last_JSON"])
else:
self.set_blank_from_schema()
# setting the column width for each column after setting the model.
self.TreeView.setColumnWidth(0, 200)
self.TreeView.setColumnWidth(1, 150)
self.TreeView.setColumnWidth(2, 350)
self.TreeView.setColumnWidth(3, 50)
self.TreeView.setColumnWidth(4, 500)
# column colors using several delegates
delegate1 = BackgroundBrushDelegate(brush = QBrush(QColor(240, 240, 240, 255)), parent = QBrush(Qt.white))
self.TreeView.setItemDelegateForColumn(0, delegate1)
self.TreeView.setItemDelegateForColumn(1, delegate1)
self.TreeView.setItemDelegateForColumn(3, delegate1)
self.TreeView.setItemDelegateForColumn(4, delegate1)
self.TreeView.expandAll()
self.combobox_repopulate()
self.dirselect_repopulate()
self.current_schema_combo_box.blockSignals(True)
self.current_schema_combo_box.setCurrentText(self.config["last_schema"])
self.current_schema_combo_box.blockSignals(False)
# call the show function
self.show()
def on_custom_context_menu(self, index): #todo: either fill this with life or throw it out!
"""
Custom context menu for the tree view widget.
Args:
index (QPoint): The QPoint the right click was executed at.
"""
list_index = self.TreeView.indexAt(index)
if list_index.isValid():
item_type = self.TreeView.model().getItem(list_index).get_data(3)
item_menu = QtWidgets.QMenu("Item menu")
entry1 = item_menu.addAction("Remove this node...")
if item_type == 'array':
entry2 = item_menu.addAction("Add entries to this array...")
item_menu.exec(self.TreeView.viewport().mapToGlobal(index))
def diropener(self): # Button Function Definitions
"""
lets the user open a directory to be indexed.
"""
dir_path = os.path.normpath(
QFileDialog.getExistingDirectory(
caption = "Select Directory for indexing",
dir = self.config["last_dir"]
)
)
try:
os.chdir(dir_path)
if dir_path == '' or dir_path == '.':
raise OSError("[pyJSON.diropener/WARN]: Directory selection aborted!")
config["last_dir"] = dir_path
save_config(self.script_dir, self.config)
jsonsearch_lib.start_index(self.script_dir, dir_path, self.index_dict)
except (FileNotFoundError, OSError) as err:
lg.error(err)
if isinstance(err, FileNotFoundError):
QMessageBox.critical(
self,
"[pyJSON.diropener/ERROR]",
"Directory does not exist."
)
self.dirselect_repopulate()
def jsonopener(self, filepath_str = None): # Definition Actions MenuBar
"""
Reads a JSON document, prepares the model for the TreeView widget and attaches it to said view.
Args:
filepath_str(str): If set, the path to use gets overwritten and QFileDialog is not called
"""
try:
if not filepath_str:
filepath_str = QFileDialog.getOpenFileName(
caption = "Open a JSON Document...",
dir = self.config["last_dir"],
filter = "Java Script Object Notation (*.json);; All Files (*.*)"
)[0]
if filepath_str == '':
raise OSError("[pyJSON.jsonopener/WARN]: File Selection aborted!")
if not os.path.isfile(filepath_str):
raise FileNotFoundError("[pyJSON.jsonopener/ERROR]: Specified file does not exist.")
filepath = os.path.normpath(filepath_str)
read_frame = jsonio_lib.decode_function(filepath)
if type(read_frame) is int and read_frame == -999:
raise FileNotFoundError("[pyJSON.jsonopener/ERROR]: Specified file does not exist.")
# TODO: VALIDATION TESTING HERE
schema_read = jsonio_lib.decode_function(os.path.join(self.script_dir, "Schemas", self.config["last_schema"]))
schema_meta = jsonio_lib.schema_to_py_gen(schema_read, mode = "meta")
new_tree = jsonio_lib.py_to_tree(read_frame, schema_meta,
TreeClass(data=["JSON Structure", "Title", "Value", "Type", "Description"]),
self.config["show_error_representation"])
self.TreeView.reset()
self.TreeView.setModel(new_tree)
self.TreeView.expandAll()
new_tree.dataChanged.emit(QModelIndex(), QModelIndex())
if new_tree:
self.config["last_JSON"] = filepath
save_config(self.script_dir, self.config)
self.curr_json_label.setText(filepath)
except (FileNotFoundError, OSError) as err:
lg.error(err)
if isinstance(err, FileNotFoundError):
QMessageBox.warning(
self,
"[pyJSON.jsonopener/ERROR]",
"[pyJSON.jsonopener/ERROR]: Specified file does not exist.",
)
def combobox_repopulate(self):
"""
sets up the QComboBox for schemas and updates its entries, if a schema gets added.
"""
self.current_schema_combo_box.blockSignals(True)
if self.current_schema_combo_box.count != 0:
self.current_schema_combo_box.clear()
schema_list = os.listdir(os.path.join(self.script_dir, "Schemas"))
for x in schema_list:
self.current_schema_combo_box.addItem(x)
self.current_schema_combo_box.update()
self.current_schema_combo_box.blockSignals(False)
def dirselect_repopulate(self):
"""
Sets up the other QCombobox utilised for the indexed directories and updates its entries accordingly.
"""
selection_list = list(self.index_dict.keys())
selection_list.remove("cur_index")
self.curr_dir_comboBox.blockSignals(True)
if self.curr_dir_comboBox.count != 0:
self.curr_dir_comboBox.clear()
self.curr_dir_comboBox.addItem(" (none)")
if selection_list is not None and type(selection_list) is list:
for i in selection_list:
self.curr_dir_comboBox.addItem(i)
else:
if selection_list is not None:
self.curr_dir_comboBox.addItem(selection_list)
if self.config["last_dir"] is not None:
self.curr_dir_comboBox.setCurrentText(self.config["last_dir"])
else:
self.curr_dir_comboBox.setCurrentText(" (none)")
self.curr_dir_comboBox.blockSignals(False)
def combobox_selected(self):
"""
A slot that gets triggered when the QComboBox emits a changed-Signal. Sets the new schema and reconstructs
the model for the TreeView
"""
lg.info("\n----------\nswapped schema!\n----------")
selected = self.current_schema_combo_box.currentText()
try:
schema = jsonio_lib.decode_function(os.path.join(self.script_dir, "Schemas", selected))
if type(schema) is int and schema == -999:
self.combobox_repopulate()
raise FileNotFoundError("[pyJSON.combobox_selected/ERROR]: Schema File is missing!")
schema_meta = jsonio_lib.schema_to_py_gen(schema, mode = "meta")
if not self.config["last_JSON"] is None:
read_frame = jsonio_lib.decode_function(self.config["last_JSON"])
new_tree = jsonio_lib.py_to_tree(read_frame, schema_meta,
TreeClass(data=["JSON Structure", "Title", "Value", "Type", "Description"]),
self.config["show_error_representation"])
self.TreeView.reset()
self.TreeView.setModel(new_tree)
self.TreeView.expandAll()
new_tree.dataChanged.emit(QModelIndex(), QModelIndex())
if new_tree:
self.config["last_schema"] = selected
save_config(self.script_dir, self.config)
else:
self.config["last_schema"] = selected
save_config(self.script_dir, self.config)
self.set_blank_from_schema()
except FileNotFoundError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.copy_schema_to_storage/ERROR]",
str(err)
)
def copy_schema_to_storage(self):
"""
creates an internal copy of said schema. Fail-safes in not overwriting existing schemas.
"""
lg.info("\n----------\nCopy function - schema to tool storage\n-----------")
try:
filepath = QFileDialog.getOpenFileName(
caption = "Select a JSON Schema for Import...",
dir = self.config["last_dir"],
filter = "Java Script Object Notation (*.json);; All Files (*.*)"
)[0]
if filepath == '':
raise OSError("[pyJSON.copy_schema_to_storage/WARN]: File Selection aborted!")
if not os.path.isfile(filepath):
raise FileNotFoundError("[pyJSON.copy_schema_to_storage/ERROR]: Specified file does not exist.")
if filepath == os.path.join(self.script_dir, "Schemas", os.path.basename(filepath)):
QMessageBox.warning(
self,
"[pyJSON.copy_schema_to_storage/WARN]",
"Source schema seems to be already in the schema folder. It will not be copied."
)
else:
shutil.copyfile(filepath, os.path.join(self.script_dir, "Schemas", os.path.basename(filepath)))
self.combobox_repopulate()
except (FileNotFoundError, OSError) as err:
lg.error(err)
if isinstance(err, FileNotFoundError):
QMessageBox.critical(
self,
"[pyJSON.copy_schema_to_storage/ERROR]",
"Specified file does not exist."
)
def save_as_function(self):
"""
first, calls a dialog for saving a file, then creates a dictionary from the TreeView model and writes it as
JSON Document to the file system at the given path.
"""
selected_path = QFileDialog.getSaveFileName(
caption = "Save as...",
dir = self.config["last_dir"] + "/_meta.json",
filter = "Java Script Object Notation (*.json);; All Files (*.*)",
)[0]
if selected_path == '' or selected_path == ".":
lg.info("[pyJSON.save_curr_json/INFO]: Either file selection aborted or you have selected a very odd path.")
else:
if re.match(pattern=re.compile(".*\.json$"), string=selected_path) is None:
selected_path = selected_path + ".json"
tree = self.TreeView.model()
json_frame = jsonio_lib.tree_to_py(tree.root_node.childItems)
try:
with open(selected_path, "w", encoding='utf8') as out:
json.dump(json_frame, out, indent=4, ensure_ascii=False)
self.config["last_JSON"] = selected_path
save_config(self.script_dir, self.config)
self.curr_json_label.setText(selected_path)
self.call_watchdog()
except OSError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.save_curr_json/ERROR]",
"File seems to neither exist nor writable!"
)
def save_function(self):
"""
Writes changes of a JSON document to the file system. Calls save_as_function(), if not saved yet.
"""
if self.config["last_JSON"] is None:
self.save_as_function()
else:
tree = self.TreeView.model()
json_frame = jsonio_lib.tree_to_py(tree.root_node.childItems)
try:
with open(self.config["last_JSON"], "w", encoding='utf8') as out:
json.dump(json_frame, out, indent=4, ensure_ascii=False)
except OSError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.save_curr_json/ERROR]",
"File seems to neither exist nor writable!"
)
def set_blank_from_schema(self):
"""
Creates a TreeView model with empty value fields to be edited and exported as JSON document.
"""
lg.info("\n----------\nGenerating Blank from Schema\n----------")
try:
curr_schem = jsonio_lib.decode_function(
os.path.join(
self.script_dir,
"Schemas",
self.config["last_schema"]
)
)
if type(curr_schem) is int and curr_schem == -999:
self.combobox_repopulate()
raise FileNotFoundError("[pyJSON.combobox_selected/ERROR]: Schema File is missing!")
pre_json = jsonio_lib.schema_to_py_gen(curr_schem)
pre_meta = jsonio_lib.schema_to_py_gen(curr_schem, mode = "meta")
new_tree = jsonio_lib.py_to_tree(pre_json, pre_meta,
TreeClass(data=["JSON Structure", "Title", "Value", "Type", "Description"]),
self.config["show_error_representation"])
self.TreeView.reset()
self.TreeView.setModel(new_tree)
self.TreeView.expandAll()
new_tree.dataChanged.emit(QModelIndex(), QModelIndex())
if new_tree:
self.config["last_JSON"] = None
save_config(self.script_dir, self.config)
self.curr_json_label.setText("None")
except (FileNotFoundError, OSError) as err:
lg.error(err)
if isinstance(err, FileNotFoundError):
QMessageBox.critical(
self,
"[pyJSON.set_blank_from_schema/ERROR]",
"Specified schema does not exist.\nPlease select another schema and repeat!"
)
# saves default values into the default folder.
def save_default(self):
"""
stores a copy of the current JSON on a schema basis in the "Default" directory, which can be loaded later on.
"""
lg.info("\n----------\nSaving default for Schema " + self.config["last_schema"] + "\n----------")
tree = self.TreeView.model()
json_frame = jsonio_lib.tree_to_py(tree.root_node.childItems)
try:
with open(os.path.join(self.script_dir, "Default", self.config["last_schema"]), "w", encoding='utf8') as out:
json.dump(json_frame, out, indent=4, ensure_ascii=False)
except OSError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.save_default/ERROR]",
"File seems to neither exist nor writable!"
)
def load_default(self):
"""
creates a TreeView model from the default that was stored in the tools directory structure
"""
lg.info("\n----------\nLoading default for Schema " + self.config["last_schema"] + "\n----------")
try:
if not os.path.isfile(os.path.join(self.script_dir, "Default", self.config["last_schema"])):
raise FileNotFoundError("[pyJSON.load_default/ERROR]: No default file found!")
if not os.path.isfile(os.path.join(self.script_dir, "Schemas", self.config["last_schema"])):
self.combobox_repopulate()
raise FileNotFoundError("[pyJSON.load_default/ERROR]: Selected schema not found!")
default_values = jsonio_lib.decode_function(os.path.join(self.script_dir, "Default", self.config["last_schema"]))
schema_read = jsonio_lib.decode_function(os.path.join(self.script_dir, "Schemas", self.config["last_schema"]))
schema_meta = jsonio_lib.schema_to_py_gen(schema_read, mode = "meta")
new_tree = jsonio_lib.py_to_tree(default_values, schema_meta,
TreeClass(data=["JSON Structure", "Title", "Value", "Type", "Description"]),
self.config["show_error_representation"])
self.TreeView.reset()
self.TreeView.setModel(new_tree)
self.TreeView.expandAll()
new_tree.dataChanged.emit(QModelIndex(), QModelIndex())
if new_tree:
self.config["last_JSON"] = None
save_config(self.script_dir, self.config)
self.curr_json_label.setText("None")
except FileNotFoundError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.load_default/ERROR]",
str(err)
)
def reloader_function(self):
"""
drops all changes made and reverts to the last known saved state or a blank.
"""
lg.info("\n----------\nLoading default for Schema " + self.config["last_schema"] + "\n----------")
if self.config["last_JSON"] is None:
lg.warning("No last JSON found, defaulting to Blank.")
self.set_blank_from_schema()
else:
try:
if not self.config["last_JSON"] is None:
if not os.path.isfile(self.config["last_JSON"]):
raise FileNotFoundError("[pyJSON.reloader_function/ERROR]: Last JSON file not found!")
if not os.path.isfile(os.path.join(self.script_dir, "Schemas", self.config["last_schema"])):
self.combobox_repopulate()
raise FileNotFoundError("[pyJSON.reloader_function/ERROR]: Selected schema not found!")
values = jsonio_lib.decode_function(os.path.join(self.config["last_JSON"]))
schema_read = jsonio_lib.decode_function(os.path.join(self.script_dir, "Schemas", self.config["last_schema"]))
schema_meta = jsonio_lib.schema_to_py_gen(schema_read, mode = "meta")
new_tree = jsonio_lib.py_to_tree(values, schema_meta,
TreeClass(data=["JSON Structure", "Title", "Value", "Type", "Description"]),
self.config["show_error_representation"])
self.TreeView.reset()
self.TreeView.setModel(new_tree)
self.TreeView.expandAll()
new_tree.dataChanged.emit(QModelIndex(), QModelIndex())
else:
self.set_blank_from_schema()
except FileNotFoundError as err:
lg.error(err)
QMessageBox.critical(
self,
"[pyJSON.load_default/ERROR]",
str(err)
)
def validate_function(self):
"""
converts the tree keys and values to JSON and validates the JSON document agains the selected schema
"""
tree = self.TreeView.model()
curr_json_py = jsonio_lib.tree_to_py(tree.root_node.childItems)
curr_json = json.dumps(curr_json_py)
result = jsonio_lib.validator_vars(curr_json, os.path.join(self.script_dir, "Schemas", self.config["last_schema"]))
match result:
case 0:
QMessageBox.information(
self,
"[pyJSON.validate_function/INFO]",
"The JSON is valid against the schema!"
)
case 1:
QMessageBox.warning(
self,
"[pyJSON.validate_Function/ERROR]",
"The JSON is not valid against the schema!"
)
case 2:
QMessageBox.warning(
self,
"[pyJSON.validate_Function/ERROR]",
"The schema is not valid against its meta schema!"
)
case -999:
QMessageBox.critical(
self,
"[pyJSON.validate_Function/ERROR]",
"The schema is not accessible!"
)
# SEARCH RELATED FUNCTIONS
def search_dirs(self):
"""
initialises the search and instances and/or opens the widget containing the search results
Returns:
"""
if self.searchList is None:
self.searchList = SearchWindow()
if not self.searchList.isVisible():
# get geometries
main_curr_w = self.geometry().width()
main_curr_h = self.geometry().height()
main_curr_x = self.geometry().x()
main_curr_y = self.geometry().y()
curr_screen = QGuiApplication.screenAt(QPoint(main_curr_x, main_curr_y))
desktop_w = curr_screen.availableGeometry().width()
# multi desktop setups handling
if desktop_w < main_curr_x:
desktop_w += QGuiApplication.screenAt(QPoint(1, 1)).availableGeometry().width()
if main_curr_x + main_curr_w + 315 > desktop_w:
offsetX = main_curr_x + main_curr_w - 315
else:
offsetX = main_curr_x + main_curr_w + 15
# call the window
self.searchList.setGeometry(offsetX, main_curr_y, 300, main_curr_h)
self.searchList.show()
if self.curr_dir_comboBox.currentText() != " (none)":
path = self.curr_dir_comboBox.currentText()
curr_schem = self.current_schema_combo_box.currentText()
if self.index_dict[path] and os.path.exists(path):
index_json_file = os.path.join(self.script_dir, "Indexes", "index" + str(self.index_dict[path]) + ".json")
file_index = json.load(open(index_json_file, encoding = "utf8"))
lg.info("[pyJSON.search_Dirs/INFO]: Retrieved index of " + path + ".")
result_index = jsonsearch_lib.schema_matching_search(file_index["files"], curr_schem, self.script_dir)
tree = self.TreeView.model()
json_frame = jsonio_lib.tree_to_py(tree.root_node.childItems)
flattened_frame = {}
flattened_frame = jsonsearch_lib.dict_flatten_dict(json_frame, flattened_frame)
for i in list(flattened_frame.keys()):
if flattened_frame[i] == "":
del flattened_frame[i]
if len(flattened_frame) > 0:
result_index = jsonsearch_lib.f_search(result_index, flattened_frame)
if len(result_index) != 0:
result_model = QStandardItemModel()
for i in result_index:
item = QStandardItem(i)
result_model.appendRow(item)
self.searchList.searchListView.setModel(result_model)
self.searchList.searchListView.activateWindow() # set focus on this widget
else:
lg.warning("[pyJSON.search_Dirs/WARN]: No results found!")
QMessageBox.warning(
self,
"[pyJSON.search_Dirs/WARN]",
"No results found! Search result list is not updated."
)
else:
lg.warning("[pyJSON.search_Dirs/WARN]: No directory for search selected!")
QMessageBox.warning(
self,
"[pyJSON.search_Dirs/WARN]",
"No directory for search selected!"
)
def call_watchdog(self):
"""
function responsible for executing the re-indexing on a regular basis
"""
jsonsearch_lib.watchdog(self.script_dir, self.index_dict)
if self.sender() and isinstance(self.sender(), QtGui.QAction):
QMessageBox.information(
self,
"[pyJSON.call_watchdog/INFO]",
"Checked indexed directories and reindexed, if needed."
)
def call_prefdiag(self):
if self.prefdiag is None:
self.prefdiag = ui_preferences(self.script_dir)
else:
self.prefdiag.config = self.config.copy()
self.prefdiag.exec()
self.config = json.load(open(os.path.join(self.script_dir, "pyJSON_conf.json"), encoding = "utf8"),
cls = json.JSONDecoder)
def closeEvent(self, event):
"""
a specific handler receiving QCloseEvents of the main window in order
to not only closing it, but all windows of the app.
Args:
event (QCloseEvent): the close event to be processed
"""
if self.searchList:
self.searchList.close()
# ----------------------------------------
# Execution
# ----------------------------------------
if __name__ == "__main__":
import sys
import argparse
import inspect
# initialize the QtWidget
app = QtWidgets.QApplication(sys.argv)
# parser arguments
parser = argparse.ArgumentParser(
description = "pyJSON Schema Loader and JSON Editor - a tool for editing and generating JSON files utilizing " +
"JSON Schema.\n Use the command-line interface to automate interaction with pyJSON. " +
"You can provide a schema (based on file name), a JSON file and a directory to use. " +
"Note that erroneous CLI input gets omitted."
)
parser.add_argument('-d', '--directory',
dest = "path",
help = "This parameter overwrites the last used directory, if present.")
parser.add_argument('-f', '--file',
dest = "file",