-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathGraphite.py
More file actions
7122 lines (5962 loc) · 267 KB
/
Graphite.py
File metadata and controls
7122 lines (5962 loc) · 267 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
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
# this is now legacy code, the main file 'Graphite_app' is the source project now (vs project as well)
from datetime import datetime
from pathlib import Path
import json
import sys
import ollama
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
import qtawesome as qta
import sqlite3
import matplotlib
matplotlib.use('Agg') # Use Agg backend for off-screen rendering
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.figure import Figure
FRAME_COLORS = {
# Full frame colors
"Green": {"color": "#2ecc71", "type": "full"},
"Blue": {"color": "#3498db", "type": "full"},
"Purple": {"color": "#9b59b6", "type": "full"},
"Orange": {"color": "#e67e22", "type": "full"},
"Red": {"color": "#e74c3c", "type": "full"},
"Yellow": {"color": "#f1c40f", "type": "full"},
# Header-only colors
"Green Header": {"color": "#2ecc71", "type": "header"},
"Blue Header": {"color": "#3498db", "type": "header"},
"Purple Header": {"color": "#9b59b6", "type": "header"},
"Orange Header": {"color": "#e67e22", "type": "header"},
"Red Header": {"color": "#e74c3c", "type": "header"},
"Yellow Header": {"color": "#f1c40f", "type": "header"}
}
class StyleSheet:
DARK_THEME = """
QMainWindow, QWidget {
background-color: #1e1e1e;
color: #ffffff;
}
/* Custom Title Bar Styling */
#titleBar {
background-color: #2d2d2d;
border-bottom: 1px solid #3f3f3f;
padding: 4px;
min-height: 32px;
}
#titleBar QLabel {
color: #ffffff;
font-size: 12px;
font-weight: bold;
font-family: 'Segoe UI', sans-serif;
}
#titleBarButtons QPushButton {
background-color: transparent;
border: none;
width: 34px;
height: 26px;
padding: 4px;
border-radius: 4px;
}
#titleBarButtons QPushButton:hover {
background-color: #3f3f3f;
}
#closeButton:hover {
background-color: #c42b1c !important;
}
/* Toolbar styling */
QToolBar {
background-color: #252526;
border-bottom: 1px solid #3f3f3f;
spacing: 8px;
padding: 8px;
}
/* Toolbar buttons only */
QToolBar > QPushButton {
background-color: #1a8447; /* Darker shade of green */
color: #ffffff;
border: none;
padding: 6px 16px;
border-radius: 6px;
font-size: 12px;
font-family: 'Segoe UI', sans-serif;
min-width: 80px;
min-height: 28px;
}
QToolBar > QPushButton:hover {
background-color: #219452; /* Slightly lighter green on hover */
}
QToolBar > QPushButton:pressed {
background-color: #157a3e; /* Darker green when pressed */
}
QToolBar > QPushButton#actionButton {
background-color: #2573b3; /* Darker shade of blue */
}
QToolBar > QPushButton#actionButton:hover {
background-color: #2e82c8; /* Slightly lighter blue on hover */
}
QToolBar > QPushButton#helpButton {
background-color: #9b59b6; /* Keep the existing purple */
}
QToolBar > QPushButton#helpButton:hover {
background-color: #a66bbe; /* Slightly lighter purple on hover */
}
/* Regular button styling (for Send button etc) */
QPushButton {
background-color: #2ecc71;
color: white;
border: none;
padding: 8px 16px;
border-radius: 4px;
font-weight: bold;
font-size: 12px;
font-family: 'Segoe UI', sans-serif;
}
QPushButton:hover {
background-color: #27ae60;
}
/* Rest of the existing styles */
QComboBox {
background-color: #2ecc71;
color: white;
border: none;
border-radius: 4px;
padding: 8px;
min-width: 120px;
font-family: 'Segoe UI', sans-serif;
font-size: 12px;
font-weight: bold;
}
QComboBox:hover {
background-color: #27ae60;
}
QLineEdit {
background-color: #252526;
color: #d4d4d4;
border: 1px solid #3f3f3f;
border-radius: 4px;
padding: 8px;
selection-background-color: #264f78;
font-family: 'Segoe UI', sans-serif;
}
QLineEdit:focus {
border-color: #2ecc71;
}
"""
class CustomTitleBar(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
self.setObjectName("titleBar")
icon_path = Path(__file__).parent / "graphite.png"
self.setWindowIcon(QIcon(str(icon_path)))
layout = QHBoxLayout(self)
layout.setContentsMargins(8, 0, 0, 0)
# Add icon
icon_label = QLabel()
icon_pixmap = QPixmap(str(icon_path)).scaled(32, 32, Qt.KeepAspectRatio, Qt.SmoothTransformation)
icon_label.setPixmap(icon_pixmap)
layout.addWidget(icon_label)
# Title
self.title = QLabel("Graphite")
layout.addWidget(self.title)
layout.addStretch()
# Window controls
btn_layout = QHBoxLayout()
btn_layout.setSpacing(0)
btn_layout.setContentsMargins(0, 0, 0, 0)
self.minimize_btn = QPushButton("🗕")
self.maximize_btn = QPushButton("🗖")
self.close_btn = QPushButton("✕")
for btn in (self.minimize_btn, self.maximize_btn, self.close_btn):
btn.setFixedSize(34, 26)
btn.setObjectName("titleBarButton")
btn_layout.addWidget(btn)
self.close_btn.setObjectName("closeButton")
# Connect buttons
self.minimize_btn.clicked.connect(self.parent.showMinimized)
self.maximize_btn.clicked.connect(self.toggle_maximize)
self.close_btn.clicked.connect(self.parent.close)
button_widget = QWidget()
button_widget.setObjectName("titleBarButtons")
button_widget.setLayout(btn_layout)
layout.addWidget(button_widget)
self.pressing = False
self.start_pos = None
def toggle_maximize(self):
if self.parent.isMaximized():
self.parent.showNormal()
self.maximize_btn.setText("🗖")
else:
self.parent.showMaximized()
self.maximize_btn.setText("🗗")
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.pressing = True
self.start_pos = event.globalPos()
def mouseMoveEvent(self, event):
if self.pressing:
if self.parent.isMaximized():
self.parent.showNormal()
delta = event.globalPos() - self.start_pos
self.parent.move(self.parent.x() + delta.x(), self.parent.y() + delta.y())
self.start_pos = event.globalPos()
def mouseReleaseEvent(self, event):
self.pressing = False
class TitleGenerator:
def __init__(self):
self.system_prompt = """You are a title generation assistant. Your only job is to create short,
2-3 word titles based on conversation content. Rules:
- ONLY output the title, nothing else
- Keep it between 2-3 words
- Use title case
- Make it descriptive but concise
- NO punctuation
- NO explanations
- NO additional text"""
def generate_title(self, message):
try:
messages = [
{'role': 'system', 'content': self.system_prompt},
{'role': 'user', 'content': f"Create a 2-3 word title for this message: {message}"}
]
response = ollama.chat(model='qwen2.5:3b', messages=messages)
title = response['message']['content'].strip()
# Clean up title if needed
title = ' '.join(title.split()[:3]) # Ensure max 3 words
return title
except Exception as e:
return f"Chat {datetime.now().strftime('%Y%m%d_%H%M')}"
class ChatDatabase:
def __init__(self):
self.db_path = Path.home() / '.graphite' / 'chats.db'
self.db_path.parent.mkdir(parents=True, exist_ok=True)
self.init_database()
def init_database(self):
with sqlite3.connect(self.db_path) as conn:
# Existing chats table
conn.execute("""
CREATE TABLE IF NOT EXISTS chats (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
data TEXT NOT NULL
)
""")
# Notes table
conn.execute("""
CREATE TABLE IF NOT EXISTS notes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
content TEXT NOT NULL,
position_x REAL NOT NULL,
position_y REAL NOT NULL,
width REAL NOT NULL,
height REAL NOT NULL,
color TEXT NOT NULL,
header_color TEXT,
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE
)
""")
# Add pins table
conn.execute("""
CREATE TABLE IF NOT EXISTS pins (
id INTEGER PRIMARY KEY AUTOINCREMENT,
chat_id INTEGER NOT NULL,
title TEXT NOT NULL,
note TEXT,
position_x REAL NOT NULL,
position_y REAL NOT NULL,
FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE
)
""")
def save_pins(self, chat_id, pins_data):
"""Save pins for a chat session"""
with sqlite3.connect(self.db_path) as conn:
# First delete existing pins for this chat
conn.execute("DELETE FROM pins WHERE chat_id = ?", (chat_id,))
# Insert new pins
for pin_data in pins_data:
conn.execute("""
INSERT INTO pins (
chat_id, title, note, position_x, position_y
) VALUES (?, ?, ?, ?, ?)
""", (
chat_id,
pin_data['title'],
pin_data['note'],
pin_data['position']['x'],
pin_data['position']['y']
))
def load_pins(self, chat_id):
"""Load pins for a chat session"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
SELECT title, note, position_x, position_y
FROM pins WHERE chat_id = ?
""", (chat_id,))
pins = []
for row in cursor.fetchall():
pins.append({
'title': row[0],
'note': row[1],
'position': {'x': row[2], 'y': row[3]}
})
return pins
def save_notes(self, chat_id, notes_data):
with sqlite3.connect(self.db_path) as conn:
# First delete existing notes for this chat
conn.execute("DELETE FROM notes WHERE chat_id = ?", (chat_id,))
# Insert new notes
for note_data in notes_data:
conn.execute("""
INSERT INTO notes (
chat_id, content, position_x, position_y,
width, height, color, header_color
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
chat_id,
note_data['content'],
note_data['position']['x'],
note_data['position']['y'],
note_data['size']['width'],
note_data['size']['height'],
note_data['color'],
note_data.get('header_color')
))
def load_notes(self, chat_id):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
SELECT content, position_x, position_y, width, height,
color, header_color
FROM notes WHERE chat_id = ?
""", (chat_id,))
notes = []
for row in cursor.fetchall():
notes.append({
'content': row[0],
'position': {'x': row[1], 'y': row[2]},
'size': {'width': row[3], 'height': row[4]},
'color': row[5],
'header_color': row[6]
})
return notes
def save_chat(self, title, chat_data):
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
INSERT INTO chats (title, data, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
""", (title, json.dumps(chat_data)))
return cursor.lastrowid # Return the ID of the newly inserted chat
def get_latest_chat_id(self):
"""Get the ID of the most recently created chat"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.execute("""
SELECT id FROM chats
ORDER BY created_at DESC
LIMIT 1
""")
result = cursor.fetchone()
return result[0] if result else None
def update_chat(self, chat_id, title, chat_data):
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
UPDATE chats
SET title = ?, data = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (title, json.dumps(chat_data), chat_id))
def load_chat(self, chat_id):
with sqlite3.connect(self.db_path) as conn:
result = conn.execute("""
SELECT title, data FROM chats WHERE id = ?
""", (chat_id,)).fetchone()
if result:
return {
'title': result[0],
'data': json.loads(result[1])
}
return None
def get_all_chats(self):
with sqlite3.connect(self.db_path) as conn:
return conn.execute("""
SELECT id, title, created_at, updated_at
FROM chats
ORDER BY updated_at DESC
""").fetchall()
def delete_chat(self, chat_id):
with sqlite3.connect(self.db_path) as conn:
conn.execute("DELETE FROM chats WHERE id = ?", (chat_id,))
def rename_chat(self, chat_id, new_title):
with sqlite3.connect(self.db_path) as conn:
conn.execute("""
UPDATE chats
SET title = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (new_title, chat_id))
class ChatSessionManager:
def __init__(self, window):
self.window = window
self.db = ChatDatabase()
self.title_generator = TitleGenerator()
self.current_chat_id = None
def serialize_pin(self, pin):
"""Convert a navigation pin to a serializable dictionary"""
return {
'title': pin.title,
'note': pin.note,
'position': {'x': pin.pos().x(), 'y': pin.pos().y()}
}
def serialize_pin_layout(self, pin):
"""Convert a pin to a serializable dictionary"""
return {
'position': {'x': pin.pos().x(), 'y': pin.pos().y()}
}
def serialize_connection(self, connection):
"""Convert a connection to a serializable dictionary"""
return {
'start_node_index': self.window.chat_view.scene().nodes.index(connection.start_node),
'end_node_index': self.window.chat_view.scene().nodes.index(connection.end_node),
'pins': [self.serialize_pin_layout(pin) for pin in connection.pins]
}
def serialize_node(self, node):
"""Convert a ChatNode to a serializable dictionary"""
return {
'text': node.text,
'is_user': node.is_user,
'position': {'x': node.pos().x(), 'y': node.pos().y()},
'conversation_history': node.conversation_history,
'children_indices': [self.window.chat_view.scene().nodes.index(child) for child in node.children],
'scroll_value': node.scroll_value
}
def serialize_frame(self, frame):
"""Convert a Frame to a serializable dictionary"""
return {
'nodes': [self.window.chat_view.scene().nodes.index(node) for node in frame.nodes],
'position': {'x': frame.pos().x(), 'y': frame.pos().y()},
'note': frame.note,
'size': {
'width': frame.rect.width(),
'height': frame.rect.height()
},
'color': frame.color,
'header_color': frame.header_color
}
def serialize_note(self, note):
"""Convert a Note to a serializable dictionary"""
return {
'content': note.content,
'position': {'x': note.pos().x(), 'y': note.pos().y()},
'size': {'width': note.width, 'height': note.height},
'color': note.color,
'header_color': note.header_color
}
def serialize_chart(self, chart):
"""Convert a ChartItem to a serializable dictionary"""
return {
'data': chart.data,
'position': {'x': chart.pos().x(), 'y': chart.pos().y()},
'size': {'width': chart.width, 'height': chart.height}
}
def serialize_current_chat(self):
"""Serialize the current chat session with all elements"""
scene = self.window.chat_view.scene()
# Get all notes, pins, and charts in the scene
notes = [item for item in scene.items() if isinstance(item, Note)]
pins = [item for item in scene.items() if isinstance(item, NavigationPin)]
charts = [item for item in scene.items() if isinstance(item, ChartItem)]
chat_data = {
'nodes': [self.serialize_node(node) for node in scene.nodes],
'connections': [self.serialize_connection(conn) for conn in scene.connections],
'frames': [self.serialize_frame(frame) for frame in scene.frames],
'charts': [self.serialize_chart(chart) for chart in charts], # Add charts
'view_state': {
'zoom_factor': self.window.chat_view._zoom_factor,
'scroll_position': {
'x': self.window.chat_view.horizontalScrollBar().value(),
'y': self.window.chat_view.verticalScrollBar().value()
}
}
}
# Save chat data first
if not self.current_chat_id:
last_message = scene.nodes[-1].text if scene.nodes else "New Chat"
title = self.title_generator.generate_title(last_message)
self.current_chat_id = self.db.save_chat(title, chat_data)
else:
chat = self.db.load_chat(self.current_chat_id)
if chat:
title = chat['title']
self.db.update_chat(self.current_chat_id, title, chat_data)
# Now save notes and pins separately
if self.current_chat_id:
notes_data = [self.serialize_note(note) for note in notes]
self.db.save_notes(self.current_chat_id, notes_data)
pins_data = [self.serialize_pin(pin) for pin in pins]
self.db.save_pins(self.current_chat_id, pins_data)
return chat_data
def deserialize_chart(self, data, scene):
"""Recreate a chart from serialized data"""
chart = scene.add_chart(data['data'], QPointF(
data['position']['x'],
data['position']['y']
))
if 'size' in data:
chart.width = data['size']['width']
chart.height = data['size']['height']
chart.generate_chart() # Regenerate chart with new size
return chart
def deserialize_pin(self, data, connection):
"""Recreate a pin from serialized data"""
pin = connection.add_pin(QPointF(0, 0)) # Create pin
pin.setPos(data['position']['x'], data['position']['y'])
return pin
def deserialize_connection(self, data, scene):
"""Recreate a connection from serialized data"""
start_node = scene.nodes[data['start_node_index']]
end_node = scene.nodes[data['end_node_index']]
# Find existing connection or create new one
connection = None
for conn in scene.connections:
if conn.start_node == start_node and conn.end_node == end_node:
connection = conn
break
if connection is None:
connection = ConnectionItem(start_node, end_node)
scene.addItem(connection)
scene.connections.append(connection)
# Recreate pins
for pin_data in data['pins']:
self.deserialize_pin(pin_data, connection)
return connection
def deserialize_node(self, data, nodes_map=None):
"""Convert serialized data back to ChatNode"""
scene = self.window.chat_view.scene()
# Create node without parent initially
node = scene.add_chat_node(
data['text'],
is_user=data['is_user'],
parent_node=None, # Important: No parent node initially
conversation_history=data.get('conversation_history', [])
)
# Remove the automatically created connection since we'll restore them later
if scene.connections and node.parent_node:
for conn in scene.connections[:]: # Create a copy of the list to modify it
if conn.end_node == node:
scene.removeItem(conn)
scene.connections.remove(conn)
node.parent_node = None # Clear the parent reference
# Restore position and scroll state
node.setPos(data['position']['x'], data['position']['y'])
node.scroll_value = data.get('scroll_value', 0)
node.scrollbar.set_value(node.scroll_value)
# Store in nodes map if provided
if nodes_map is not None:
nodes_map[len(scene.nodes) - 1] = node
return node
def deserialize_frame(self, data, scene):
"""Recreate a frame from serialized data"""
nodes = [scene.nodes[i] for i in data['nodes']]
frame = Frame(nodes)
frame.setPos(data['position']['x'], data['position']['y'])
frame.note = data['note']
if 'color' in data:
frame.color = data['color']
if 'header_color' in data:
frame.header_color = data['header_color']
if 'size' in data:
frame.rect.setWidth(data['size']['width'])
frame.rect.setHeight(data['size']['height'])
scene.addItem(frame)
scene.frames.append(frame)
frame.setZValue(-2)
return frame
def load_chat(self, chat_id):
"""Load a chat session with all elements including pins, charts, and notes"""
chat = self.db.load_chat(chat_id)
if not chat:
return
# Clear current scene
scene = self.window.chat_view.scene()
scene.clear()
scene.nodes.clear()
scene.connections.clear()
scene.frames.clear()
scene.pins.clear() # Ensure pins are cleared
try:
# First pass: Create all nodes
nodes_map = {} # Map to store node indices
for node_data in chat['data']['nodes']:
node = self.deserialize_node(node_data, nodes_map)
# Second pass: Set up parent-child relationships
for i, node_data in enumerate(chat['data']['nodes']):
if 'children_indices' in node_data:
node = nodes_map[i]
for child_index in node_data['children_indices']:
child_node = nodes_map[child_index]
node.children.append(child_node)
child_node.parent_node = node
# Third pass: Create connections WITHOUT pins first
connections_map = {} # Store connections for later pin addition
if 'connections' in chat['data']:
for i, conn_data in enumerate(chat['data']['connections']):
start_node = scene.nodes[conn_data['start_node_index']]
end_node = scene.nodes[conn_data['end_node_index']]
# Check if connection already exists
existing_conn = None
for conn in scene.connections:
if (conn.start_node == start_node and
conn.end_node == end_node):
existing_conn = conn
break
if not existing_conn:
connection = ConnectionItem(start_node, end_node)
scene.addItem(connection)
scene.connections.append(connection)
connections_map[i] = connection
else:
connections_map[i] = existing_conn
# Fourth pass: Add pins to existing connections
if 'connections' in chat['data']:
for i, conn_data in enumerate(chat['data']['connections']):
if i in connections_map and 'pins' in conn_data:
connection = connections_map[i]
# Clear any existing pins first
for pin in connection.pins[:]:
connection.remove_pin(pin)
# Add stored pins
for pin_data in conn_data['pins']:
self.deserialize_pin(pin_data, connection)
# Load frames
if 'frames' in chat['data']:
for frame_data in chat['data']['frames']:
frame = self.deserialize_frame(frame_data, scene)
# Load charts
if 'charts' in chat['data']:
for chart_data in chat['data']['charts']:
self.deserialize_chart(chart_data, scene)
# Load notes with proper error handling
notes_data = self.db.load_notes(chat_id)
for note_data in notes_data:
try:
note = scene.add_note(QPointF(
note_data['position']['x'],
note_data['position']['y']
))
note.content = note_data['content']
note.width = note_data['size']['width']
note.height = note_data['size']['height']
note.color = note_data['color']
note.header_color = note_data['header_color']
except Exception as e:
print(f"Error loading note: {str(e)}")
continue
# Clear existing pins in overlay before loading new ones
if self.window and hasattr(self.window, 'pin_overlay'):
self.window.pin_overlay.clear_pins()
# Load navigation pins with validation
pins_data = self.db.load_pins(chat_id)
for pin_data in pins_data:
try:
pin = scene.add_navigation_pin(QPointF(
pin_data['position']['x'],
pin_data['position']['y']
))
pin.title = pin_data['title']
pin.note = pin_data.get('note', '')
# Add pin to overlay if window exists
if self.window and hasattr(self.window, 'pin_overlay'):
self.window.pin_overlay.add_pin_button(pin)
except Exception as e:
print(f"Error loading pin: {str(e)}")
continue
# Restore view state
if 'view_state' in chat['data']:
view_state = chat['data']['view_state']
self.window.chat_view._zoom_factor = view_state['zoom_factor']
self.window.chat_view.setTransform(QTransform().scale(
view_state['zoom_factor'],
view_state['zoom_factor']
))
self.window.chat_view.horizontalScrollBar().setValue(
view_state['scroll_position']['x']
)
self.window.chat_view.verticalScrollBar().setValue(
view_state['scroll_position']['y']
)
# Set current chat ID and update connections
self.current_chat_id = chat_id
scene.update_connections()
except Exception as e:
print(f"Error loading chat: {str(e)}")
# Clean up in case of error
scene.clear()
scene.nodes.clear()
scene.connections.clear()
scene.frames.clear()
scene.pins.clear()
if self.window and hasattr(self.window, 'pin_overlay'):
self.window.pin_overlay.clear_pins()
raise
# Return loaded chat data
return chat
def save_current_chat(self):
"""Save the current chat session"""
if not self.window.chat_view.scene().nodes:
return
try:
chat_data = self.serialize_current_chat()
# If this is a new chat, generate title from last message
if not self.current_chat_id:
last_message = self.window.chat_view.scene().nodes[-1].text
title = self.title_generator.generate_title(last_message)
self.current_chat_id = self.db.save_chat(title, chat_data)
else:
# For existing chats, fetch the current title from the database
chat = self.db.load_chat(self.current_chat_id)
if chat:
title = chat['title']
self.db.update_chat(self.current_chat_id, title, chat_data)
else:
# Fallback if chat not found - create new chat
last_message = self.window.chat_view.scene().nodes[-1].text
title = self.title_generator.generate_title(last_message)
self.current_chat_id = self.db.save_chat(title, chat_data)
except Exception as e:
print(f"Error saving chat: {str(e)}")
raise
class ChatLibraryDialog(QDialog):
def __init__(self, session_manager, parent=None):
super().__init__(parent)
self.session_manager = session_manager
self.setWindowFlags(
Qt.Window |
Qt.FramelessWindowHint |
Qt.WindowStaysOnTopHint
)
self.setAttribute(Qt.WA_DeleteOnClose)
self.setAttribute(Qt.WA_TranslucentBackground) # Enable transparent background
self.setModal(False)
self.resize(500, 600)
# Main container layout - ZERO margins to remove the black frame
self.container = QWidget(self)
dialog_layout = QVBoxLayout(self)
dialog_layout.setContentsMargins(0, 0, 0, 0)
dialog_layout.setSpacing(0)
dialog_layout.addWidget(self.container)
# Container layout
main_layout = QVBoxLayout(self.container)
main_layout.setContentsMargins(0, 0, 0, 0)
main_layout.setSpacing(0)
# Add custom title bar
self.title_bar = CustomTitleBar(self)
self.title_bar.title.setText("Chat Library")
main_layout.addWidget(self.title_bar)
# Content layout
content_widget = QWidget()
content_layout = QVBoxLayout(content_widget)
content_layout.setSpacing(10)
content_layout.setContentsMargins(10, 10, 10, 10)
# Search bar
self.search_input = QLineEdit()
self.search_input.setPlaceholderText("Search chats...")
self.search_input.textChanged.connect(self.filter_chats)
content_layout.addWidget(self.search_input)
# Toolbar with actions
toolbar = QHBoxLayout()
toolbar.setSpacing(8)
# New chat button
new_chat_btn = QPushButton(qta.icon('fa5s.plus', color='white'), "New Chat")
new_chat_btn.clicked.connect(self.new_chat)
toolbar.addWidget(new_chat_btn)
# Delete button
delete_btn = QPushButton(qta.icon('fa5s.trash', color='white'), "Delete")
delete_btn.clicked.connect(self.delete_selected)
toolbar.addWidget(delete_btn)
# Rename button
rename_btn = QPushButton(qta.icon('fa5s.edit', color='white'), "Rename")
rename_btn.clicked.connect(self.rename_selected)
toolbar.addWidget(rename_btn)
# Add toolbar to content layout
toolbar_widget = QWidget()
toolbar_widget.setLayout(toolbar)
content_layout.addWidget(toolbar_widget)
# Chat list
self.chat_list = QListWidget()
self.chat_list.setAlternatingRowColors(True)
self.chat_list.itemDoubleClicked.connect(self.load_chat)
self.chat_list.setStyleSheet("""
QListWidget {
background-color: #2d2d2d;
border: 1px solid #3f3f3f;
border-radius: 4px;
}
QListWidget::item {
padding: 8px;
border-bottom: 1px solid #3f3f3f;
}
QListWidget::item:alternate {
background-color: #333333;
}
QListWidget::item:selected {
background-color: #2ecc71;
color: white;
}
QListWidget::item:hover {
background-color: #3f3f3f;
}
""")
content_layout.addWidget(self.chat_list)
# Status bar
self.status_label = QLabel()
content_layout.addWidget(self.status_label)
# Add content widget to main layout
main_layout.addWidget(content_widget)
# Add shadow effect
shadow = QGraphicsDropShadowEffect(self)
shadow.setBlurRadius(20)
shadow.setColor(QColor(0, 0, 0, 180))
shadow.setOffset(0, 0)
self.container.setGraphicsEffect(shadow)
# Set proper styling for transparent background
self.setStyleSheet("""
ChatLibraryDialog {
background: transparent;
}
QWidget {
background-color: #1e1e1e;
border-radius: 8px;
}
QWidget#toolbar_widget, QLineEdit, QPushButton {
border-radius: 4px;
}
""")
self.refresh_chat_list()
# Center the dialog relative to the parent window
if parent:
parent_center = parent.geometry().center()
self.move(parent_center.x() - self.width() // 2,
parent_center.y() - self.height() // 2)
def closeEvent(self, event):
# Handle proper cleanup when closing
event.accept()
def moveEvent(self, event):
# Ensure the window stays within screen bounds
screen = QApplication.primaryScreen().geometry()
window = self.geometry()
if window.left() < screen.left():
self.move(screen.left(), window.top())
elif window.right() > screen.right():
self.move(screen.right() - window.width(), window.top())
if window.top() < screen.top():
self.move(window.left(), screen.top())
elif window.bottom() > screen.bottom():
self.move(window.left(), screen.bottom() - window.height())
super().moveEvent(event)
# The rest of the methods remain unchanged
def refresh_chat_list(self):
self.chat_list.clear()
chats = self.session_manager.db.get_all_chats()