-
-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathmain.py
More file actions
598 lines (475 loc) · 21.2 KB
/
main.py
File metadata and controls
598 lines (475 loc) · 21.2 KB
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
import sys
IS_WINDOWS = sys.platform == "win32"
if not IS_WINDOWS:
import pty
import os
import sys
import subprocess
import time
from PySide6.QtWidgets import (QApplication, QMainWindow, QVBoxLayout,
QWidget, QPushButton, QHBoxLayout, QTextEdit,
QSplitter, QFileDialog, QToolButton, QMenu, QDialog,
QMessageBox)
from PySide6.QtCore import QPointF, QTimer, Qt, QRectF
from PySide6.QtGui import QColor, QKeySequence, QIcon
from core.graph import Graph
from core.bash_emitter import BashEmitter
from core.serializer import Serializer
from nodes.flow_nodes import StartNode, IfNode, ForNode
from nodes.command_nodes import RunCommandNode, EchoNode, ExitNode, PipeNode
from nodes.variable_nodes import SetVariableNode, GetVariableNode, FileExistsNode
from nodes.operation_nodes import Addition
from nodes.utils_node import ToString
from ui.comment_box import COMMENT_Z_BASE, CommentBoxItem
from ui.graph_view import GraphView
from ui.property_panel import PropertyPanel
from ui.settings import SettingsDialog
from ui.menu_style import apply_btn_style, apply_menu_style, apply_icon_for_btn
from ui.about.about import AboutDialog
from ui.keyboard_shortcuts import KeyboardShortcutsDialog
from nodes.registry import NODE_REGISTRY
from core.highlights import BashHighlighter
from core.ansi_to_html import ansi_to_html
from core.config import Config, ConfigManager
from core.debug import Info, Debug
from core.logger import Logger
from core.traduction import Traduction
from core.node_color import NodeColor
from core.projects import ProjectManager
from ui.welcome import WelcomeScreen
from theme.theme_parser import load_theme, load_every_theme
class NodeFactory:
@staticmethod
def create_node(node_type: str):
entry = NODE_REGISTRY.get(node_type)
return entry["class"]() if entry else None
class VisualBashEditor(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Visual Bash Editor")
self.resize(1400, 900)
self.graph = Graph()
self.node_factory = NodeFactory()
self.project_manager = ProjectManager()
self.setup_ui()
self.create_initial_graph()
def setup_ui(self):
central_widget = QWidget()
self.setCentralWidget(central_widget)
main_layout = QVBoxLayout(central_widget)
toolbar = QHBoxLayout()
self.generate_btn = QPushButton(Traduction.get_trad("btn_generate_bash", "Generate Bash"))
self.generate_btn.clicked.connect(self.generate_bash)
apply_icon_for_btn(self.generate_btn, "generate")
toolbar.addWidget(self.generate_btn)
self.save_btn = QPushButton(Traduction.get_trad("btn_save", "Save"))
apply_icon_for_btn(self.save_btn, "save")
self.save_btn.clicked.connect(self.save_graph)
toolbar.addWidget(self.save_btn)
self.load_btn = QPushButton(Traduction.get_trad("btn_load", "Load"))
self.load_btn.clicked.connect(self.load_graph)
apply_icon_for_btn(self.load_btn, "load")
toolbar.addWidget(self.load_btn)
toolbar.addStretch()
self.run_bash_btn = QPushButton(Traduction.get_trad("btn_run_bash", "Run Bash Script"))
self.run_bash_btn.clicked.connect(self.run_bash)
apply_icon_for_btn(self.run_bash_btn, "play")
toolbar.addWidget(self.run_bash_btn)
self.copy_btn = QPushButton(Traduction.get_trad("btn_copy_clipboard", "Copy to Clipboard"))
apply_icon_for_btn(self.copy_btn, "clipboard")
self.copy_btn.clicked.connect(
lambda: QApplication.clipboard().setText(self.output_text.toPlainText())
)
toolbar.addWidget(self.copy_btn)
self.more_btn = QToolButton()
self.more_btn.setText("☰")
self.more_btn.setPopupMode(QToolButton.InstantPopup)
apply_btn_style(self.more_btn)
self.more_menu = QMenu(self)
apply_menu_style(self.more_menu)
self.settings_action = self.more_menu.addAction(
Traduction.get_trad("settings", "Settings")
)
self.settings_action.triggered.connect(self.open_settings)
apply_icon_for_btn(self.settings_action, "settings")
self.keyboard = self.more_menu.addAction(
Traduction.get_trad("keyboard_shortcuts", "Keyboard Shortcuts")
)
self.keyboard.triggered.connect(self.open_keyboard_shortcuts)
apply_icon_for_btn(self.keyboard, "keyboard")
self.full_screenfs = self.more_menu.addAction(
Traduction.get_trad("full_screen", "Full Screen")
)
self.full_screenfs.triggered.connect(self.full_screen_action)
apply_icon_for_btn(self.full_screenfs, "fullscreen")
self.about_action = self.more_menu.addAction(
Traduction.get_trad("about", "About")
)
self.about_action.triggered.connect(self.open_about)
apply_icon_for_btn(self.about_action, "about")
self.more_btn.setMenu(self.more_menu)
toolbar.addWidget(self.more_btn)
main_layout.addLayout(toolbar)
splitter = QSplitter(Qt.Horizontal)
self.graph_view = GraphView(self.graph, self)
splitter.addWidget(self.graph_view)
self.property_panel = PropertyPanel(graph_view=self.graph_view)
splitter.addWidget(self.property_panel)
self.output_splitter = QSplitter(Qt.Vertical)
self.output_text = QTextEdit()
self.output_text.setReadOnly(True)
self.output_text.setMinimumWidth(300)
self.run_output_text = QTextEdit()
self.run_output_text.setReadOnly(True)
self.run_output_text.setVisible(False)
self.run_output_text.setMinimumHeight(150)
self.run_output_text.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.run_output_text.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.run_output_text.setLineWrapMode(QTextEdit.NoWrap)
self.output_splitter.addWidget(self.output_text)
self.output_splitter.addWidget(self.run_output_text)
self.output_splitter.setSizes([300, 0])
splitter.addWidget(self.output_splitter)
self.bash_highlighter = BashHighlighter(self.output_text.document())
splitter.setSizes([900, 300, 400])
main_layout.addWidget(splitter)
self._connect_signals()
def create_initial_graph(self):
start_node = StartNode()
start_node.x = 100
start_node.y = 100
self.graph.add_node(start_node)
self.graph_view.add_node_item(start_node)
self.property_panel.set_node(start_node)
def add_node(self, node_type: str):
node = self.node_factory.create_node(node_type)
if node:
node.x = 400
node.y = 300
self.graph.add_node(node)
self.graph_view.add_node_item(node)
def generate_bash(self):
if not self.graph.nodes:
Debug.Warn(Traduction.get_trad("warn_generating_empty_graph", "Generating an empty graph."))
emitter = BashEmitter(self.graph)
bash_script = emitter.emit()
self.output_text.setPlainText(bash_script)
def open_settings(self):
dialog = SettingsDialog(self)
dialog.traduction_changed.connect(self.graph_view.update_language)
dialog.exec()
def open_about(self):
AboutDialog(self).exec()
def full_screen_action(self):
if self.windowState() & Qt.WindowState.WindowFullScreen:
self.setWindowState(Qt.WindowState.WindowNoState)
apply_icon_for_btn(self.full_screenfs, "fullscreen")
else:
self.setWindowState(Qt.WindowState.WindowFullScreen)
apply_icon_for_btn(self.full_screenfs, "windowmode")
def open_keyboard_shortcuts(self):
KeyboardShortcutsDialog(self).exec()
def open_welcome_screen(self):
welcome = WelcomeScreen(self, self.project_manager)
if welcome.exec() == QDialog.Accepted:
self.load_current_project()
else:
Debug.Log(
Traduction.get_trad(
"no_project_loaded",
"No project loaded. You can create or open a project from the welcome screen."
)
)
def save_graph(self, msg=True):
if not self.graph.nodes:
Debug.Error(Traduction.get_trad("error_cannot_save_empty_graph", "Cannot save an empty graph."))
return
if not self.project_manager.get_project_path():
if msg: # Notice that without this, this func is called every frame when having an AUTO_SAVE=True, might need to fix this in the future
Debug.Error("No project loaded.")
return
file_path = self.project_manager.get_graph_path()
json_data = Serializer.serialize(self.graph, self.graph_view)
with open(file_path, 'w') as f:
f.write(json_data)
if msg:
Debug.Log("Project saved.")
def load_graph(self):
projects_path = os.path.dirname(os.path.dirname(self.project_manager.get_graph_path()))
file_path, _ = QFileDialog.getOpenFileName(
self,
Traduction.get_trad("file_dialog_open", "Load Graph"),
f"{projects_path}/graph.json",
"JSON Files (*.json)"
)
if not file_path:
Debug.Error(Traduction.get_trad("error_no_file_selected", "No file selected."))
return
with open(file_path, "r") as f:
json_data = f.read()
self._load_graph_data(json_data)
Debug.Log(
Traduction.get_trad(
"graph_loaded_successfully",
f"Graph loaded successfully from {file_path} with {len(self.graph.nodes)} nodes and {len(self.graph.edges)} edges.",
file_path=file_path,
node_count=len(self.graph.nodes),
edge_count=len(self.graph.edges)
)
)
if Config.SYNC_NODES_AND_GEN:
self.generate_bash()
def load_current_project(self):
graph_path = self.project_manager.get_graph_path()
if not graph_path.exists():
return
with open(graph_path, "r") as f:
json_data = f.read()
self._load_graph_data(json_data)
if Config.DEBUG:
Logger.LogMessage(
f"Loaded project from {graph_path} with {len(self.graph.nodes)} nodes and {len(self.graph.edges)} edges."
)
if Config.SYNC_NODES_AND_GEN:
self.generate_bash()
def _load_graph_data(self, json_data):
try:
self.graph, comments, viewport = Serializer.deserialize(json_data, self.node_factory)
except ValueError as e:
msg_box = QMessageBox()
msg_box.setText(
f"Project contains unknown node type: '{e.args[0][1]}'\n"
"Please check if a newer version of this tool is available."
)
msg_box.setIcon(QMessageBox.Icon.Critical)
msg_box.exec()
raise
splitter = self.graph_view.parent()
old_view = self.graph_view
self.graph_view = GraphView(self.graph, self)
splitter.insertWidget(0, self.graph_view)
old_view.setParent(None)
old_view.deleteLater()
self.property_panel.graph_view = self.graph_view
self.clear_property_panel()
for node in self.graph.nodes.values():
self.graph_view.add_node_item(node)
for edge in self.graph.edges.values():
self.graph_view.graph_scene.add_core_edge(edge, self.graph_view.node_items)
comment_count = len(comments)
for index, comment in enumerate(comments):
if "z" not in comment:
comment = dict(comment)
comment["z"] = COMMENT_Z_BASE + comment_count - index - 1
self.load_comment(comment)
comment_items = [
item for item in self.graph_view.scene().items()
if isinstance(item, CommentBoxItem)
]
if comment_items:
comment_items[0].normalize_comment_z_order()
# Reset z counter based on loaded nodes to ensure new nodes are on top
max_z = max((node.z for node in self.graph.nodes.values()), default=0)
self.graph_view.graph_scene._z_counter = max_z + 1
# Restore viewport after loading graph to ensure it's centered on the correct position
if viewport:
if Config.DEBUG:
Logger.LogMessage(f"Restoring viewport position: x={viewport.get('x', 0)}, y={viewport.get('y', 0)}, zoom={viewport.get('zoom', 1.0)}")
QTimer.singleShot(0, lambda: self._restore_viewport(viewport))
self._connect_signals()
splitter.setSizes([900, 300, 400])
def _restore_viewport(self, viewport):
center = QPointF(viewport.get("x", 0), viewport.get("y", 0))
self.graph_view.set_zoom(viewport.get("zoom", 1.0))
self.graph_view.centerOn(center)
def load_comment(self, comment):
box = CommentBoxItem(
rect=QRectF(0, 0, comment["w"], comment["h"]),
title=comment["title"],
body_text=comment.get("body", "")
)
box.setPos(comment["x"], comment["y"])
box.setZValue(comment.get("z", box.zValue()))
box.set_locked(comment.get("locked", False))
box._accent_index = comment.get("color_index", 0)
box.set_title_size_index(comment.get("size_index", 2))
box.move_children = comment.get("move_children", True)
box.setRect(QRectF(0, 0, comment["w"], comment["h"]))
self.graph_view.scene().addItem(box)
def clear_property_panel(self):
self.property_panel.clear()
def auto_save(self):
if Config.AUTO_SAVE:
self.save_graph(msg=False)
def _connect_signals(self):
self.graph_view.graph_scene.graph_changed.connect(self.generate_bash)
self.graph_view.graph_scene.graph_changed.connect(self.auto_save)
self.graph_view.graph_scene.node_selected.connect(self.property_panel.set_node)
self.graph_view.graph_scene.auto_save_triggered.connect(self.auto_save)
self.graph_view.clear_property_panel_request.connect(self.clear_property_panel)
def run_pty(self, script_path: str) -> str:
master_fd, slave_fd = pty.openpty()
proc = subprocess.Popen(
["bash", "-i", script_path],
stdin=slave_fd,
stdout=slave_fd,
stderr=slave_fd,
close_fds=True,
text=False,
)
os.close(slave_fd)
output = b""
while True:
try:
chunk = os.read(master_fd, 1024)
if not chunk:
break
output += chunk
except OSError:
break
proc.wait()
os.close(master_fd)
output = output.decode(errors="replace")
filtered = []
for line in output.splitlines(): # NOTE: i have to filter some lines because bash -i outputs them
if (
"cannot set terminal process group" in line
or "no job control in this shell" in line
):
continue
filtered.append(line)
return "\n".join(filtered)
def find_bash(self):
if not IS_WINDOWS:
return "bash"
possible_paths = [
r"C:\Program Files\Git\bin\bash.exe",
r"C:\Program Files (x86)\Git\bin\bash.exe"
]
for path in possible_paths:
if os.path.exists(path):
return path
import shutil
bash_in_path = shutil.which("bash")
if bash_in_path:
return bash_in_path
return None
def run_no_pty(self, script_path: str) -> str:
bash_cmd = self.find_bash()
if not bash_cmd:
return (
"\x1b[1;31mError:\x1b[0m\n"
"No Bash executable found.\nInstall Git Bash or enable WSL."
)
result = subprocess.run(
[bash_cmd, script_path],
capture_output=True,
text=True
)
if result.stderr:
return f"\x1b[1;31mError:\x1b[0m\n{result.stderr}"
return result.stdout
def run_bash(self):
if Info.get_os() == "Windows":
Debug.Warn(Traduction.get_trad("running_windows", "It is not possible to run scripts on Windows."))
return
self.set_run_output_visible(True)
bash_script = self.output_text.toPlainText()
self.run_output_text.clear()
if not bash_script.strip() or len(bash_script) == 49: # 49 is length of the header
Debug.Warn(Traduction.get_trad("no_bash_script", "No bash script found to run the graph."))
return
temp_script_path = f"temp_script_{int(time.time())}.sh"
with open(temp_script_path, "w") as f:
f.write(bash_script)
os.chmod(temp_script_path, 0o755)
Debug.Log(Traduction.get_trad("running_generated_bash_script", "Running generated bash script..."))
try:
if Config.USING_TTY:
output = self.run_pty(temp_script_path)
else:
output = self.run_no_pty(temp_script_path)
self.run_output_text.setVisible(True)
self.output_splitter.setSizes([200, 150])
self.run_output_text.setHtml(ansi_to_html(output))
except Exception as e:
self.run_output_text.setVisible(True)
self.run_output_text.setPlainText(str(e))
finally:
os.remove(temp_script_path)
def set_run_output_visible(self, visible: bool):
self.run_output_text.setVisible(visible)
def toggle_run_output(self):
visible = self.run_output_text.isVisible()
self.run_output_text.setVisible(not visible)
if visible:
self.output_splitter.setSizes([1, 0])
else:
self.output_splitter.setSizes([200, 150])
def refresh_ui_texts(self):
self.generate_btn.setText(Traduction.get_trad("btn_generate_bash", "Generate Bash"))
self.save_btn.setText(Traduction.get_trad("btn_save", "Save"))
self.load_btn.setText(Traduction.get_trad("btn_load", "Load"))
self.run_bash_btn.setText(Traduction.get_trad("btn_run_bash", "Run Bash Script"))
self.copy_btn.setText(Traduction.get_trad("btn_copy_clipboard", "Copy to Clipboard"))
self.more_btn.setToolTip(Traduction.get_trad("more_options", "More options"))
self.settings_action.setText(Traduction.get_trad("settings", "Settings"))
self.about_action.setText(Traduction.get_trad("about", "About"))
self.keyboard.setText(Traduction.get_trad("keyboard_shortcuts", "Keyboard Shortcuts"))
apply_icon_for_btn(self.settings_action, "settings")
apply_icon_for_btn(self.about_action, "about")
apply_icon_for_btn(self.keyboard, "keyboard")
apply_icon_for_btn(self.generate_btn, "generate")
apply_icon_for_btn(self.load_btn, "load")
apply_icon_for_btn(self.run_bash_btn, "play")
apply_icon_for_btn(self.copy_btn, "clipboard")
apply_icon_for_btn(self.save_btn, "save")
apply_icon_for_btn(self.full_screenfs, "fullscreen")
def keyPressEvent(self, event):
if event.matches(QKeySequence.Save): # Ctrl+S
self.save_graph()
elif event.matches(QKeySequence.Open): # Ctrl+O
self.load_graph()
elif event.key() == Qt.Key_G and event.modifiers() & Qt.ControlModifier: # Ctrl+G
self.generate_bash()
elif event.key() == Qt.Key_R and event.modifiers() & Qt.ControlModifier: # Ctrl+R
self.run_bash()
elif event.key() == Qt.Key_W and event.modifiers() & Qt.ControlModifier: # Ctrl+W
self.open_welcome_screen()
elif event.key() == Qt.Key_F11: # F11
self.full_screen_action()
elif event.key() == Qt.Key_F1: # F1
self.open_keyboard_shortcuts()
elif event.key() == Qt.Key_F9: # F9
self.open_settings()
elif event.key() == Qt.Key_Escape: # Esc
if self.windowState() & Qt.WindowState.WindowFullScreen:
self.setWindowState(Qt.WindowState.WindowNoState)
elif event.key() == Qt.Key_L and event.modifiers() & Qt.ControlModifier and event.modifiers() & Qt.AltModifier: # Ctrl+Shift+L
Debug.Warn("Log file saved with current logs.")
Logger.save_logged_messages()
super().keyPressEvent(event)
def main():
ConfigManager.load_config() # Load config before setting theme and language
NodeColor.set_node_colors()
Traduction.set_translate_model(Config.lang)
app = QApplication(sys.argv)
load_theme(Config.theme)
app.setOrganizationName("Lluciocc")
app.setApplicationName("Vish")
icon_path = Info.resource_path("assets/icons/Vish.svg")
app.setWindowIcon(QIcon(icon_path))
editor = VisualBashEditor()
load_every_theme()
Debug.init(editor)
editor.show()
editor.open_welcome_screen()
sys.exit(app.exec())
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
Logger.LogWarning("Application interrupted by user.")
except Exception as e:
Logger.LogError(f"Fatal error: {e}")
Logger.save_logged_messages(str(e))