-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheditor_window.py
More file actions
625 lines (510 loc) · 23.7 KB
/
editor_window.py
File metadata and controls
625 lines (510 loc) · 23.7 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
# editor_window.py - POPRAWIONA WERSJA
import os
import re
from datetime import datetime
from PyQt6.QtWidgets import (QMainWindow, QTextEdit, QFileDialog, QMessageBox,
QToolBar, QStatusBar, QColorDialog, QFontDialog,
QDialog, QVBoxLayout, QLabel, QPushButton, QComboBox,
QSpinBox, QInputDialog) # USUNIĘTO QTableDialog
from PyQt6.QtGui import (QAction, QIcon, QFont, QColor, QTextCharFormat,
QTextCursor, QTextTableFormat, QTextFrameFormat,
QKeySequence)
from PyQt6.QtCore import Qt, QTimer, QSize
from autosave import AutoSaveManager
from odt_export import ODTExporter
from utils.text_to_filename import extract_title_from_text, sanitize_filename
from oneai_widget import OneAIWidget
class EditorWindow(QMainWindow):
def __init__(self):
super().__init__()
self.current_file = None
self.is_dark_mode = False
self.setWindowTitle("OneOffice 3")
self.setGeometry(100, 100, 1200, 800)
# Główny edytor tekstu
self.text_edit = QTextEdit()
self.text_edit.setFont(QFont("Segoe UI", 11))
self.text_edit.textChanged.connect(self.on_text_changed)
self.setCentralWidget(self.text_edit)
# Menedżer autosave
self.autosave_manager = AutoSaveManager(self)
self.autosave_manager.autosave_signal.connect(self.show_autosave_status)
# Eksporter ODT
self.odt_exporter = ODTExporter()
# Timer do automatycznej nazwy pliku
self.title_detection_timer = QTimer()
self.title_detection_timer.setSingleShot(True)
self.title_detection_timer.timeout.connect(self.auto_detect_filename)
# Flaga modyfikacji
self.is_modified = False
# Tworzenie UI
self.create_menubar()
self.create_toolbar()
self.create_statusbar()
# Sprawdź backup przy starcie
self.check_backup_on_startup()
# Zastosuj jasny motyw domyślnie
self.apply_light_theme()
def create_menubar(self):
menubar = self.menuBar()
# Menu Plik
file_menu = menubar.addMenu("&Plik")
new_action = QAction("&Nowy", self)
new_action.setShortcut(QKeySequence.StandardKey.New)
new_action.triggered.connect(self.new_file)
file_menu.addAction(new_action)
open_action = QAction("&Otwórz...", self)
open_action.setShortcut(QKeySequence.StandardKey.Open)
open_action.triggered.connect(self.open_file)
file_menu.addAction(open_action)
save_action = QAction("&Zapisz", self)
save_action.setShortcut(QKeySequence.StandardKey.Save)
save_action.triggered.connect(self.save_file)
file_menu.addAction(save_action)
save_as_action = QAction("Zapisz &jako...", self)
save_as_action.setShortcut(QKeySequence("Ctrl+Shift+S"))
save_as_action.triggered.connect(self.save_file_as)
file_menu.addAction(save_as_action)
file_menu.addSeparator()
exit_action = QAction("&Wyjście", self)
exit_action.setShortcut(QKeySequence.StandardKey.Quit)
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# Menu Powrót
# Menu Powrót
goback_menu = menubar.addMenu("&Powrót")
# Podmenu: Wróć do OneOffice 2
back_to_v2_action = QAction("Wróć do OneOffice 2", self)
def back_to_v2():
# Pierwsze pytanie: wpisanie powodu
reason, ok = QInputDialog.getText(
self,
"Powrót do OneOffice 2",
"Dlaczego postanowiłeś wrócić do OneOffice 2?"
)
if ok:
# Drugie okno z komunikatem i niestandardowym przyciskiem "OKPA"
msg_box = QMessageBox(self)
msg_box.setWindowTitle("Nie można wrócić")
msg_box.setText("Sory, ale se nie wrócisz bo zgubiłem kod źródłowy xd\n"
f"Twój powód: {reason} jest fajny. zrób mi issue na https://github.com/OneDevelopmentPL/oneoffice3/issues jesli jest prawdziwy")
okpa_button = msg_box.addButton("okpa", QMessageBox.ButtonRole.AcceptRole)
msg_box.exec()
back_to_v2_action.triggered.connect(back_to_v2)
goback_menu.addAction(back_to_v2_action)
# Menu Edycja
edit_menu = menubar.addMenu("&Edycja")
undo_action = QAction("&Cofnij", self)
undo_action.setShortcut(QKeySequence.StandardKey.Undo)
undo_action.triggered.connect(self.text_edit.undo)
edit_menu.addAction(undo_action)
redo_action = QAction("&Ponów", self)
redo_action.setShortcut(QKeySequence.StandardKey.Redo)
redo_action.triggered.connect(self.text_edit.redo)
edit_menu.addAction(redo_action)
edit_menu.addSeparator()
copy_action = QAction("&Kopiuj", self)
copy_action.setShortcut(QKeySequence.StandardKey.Copy)
copy_action.triggered.connect(self.text_edit.copy)
edit_menu.addAction(copy_action)
cut_action = QAction("Wy&tnij", self)
cut_action.setShortcut(QKeySequence.StandardKey.Cut)
cut_action.triggered.connect(self.text_edit.cut)
edit_menu.addAction(cut_action)
paste_action = QAction("&Wklej", self)
paste_action.setShortcut(QKeySequence.StandardKey.Paste)
paste_action.triggered.connect(self.text_edit.paste)
edit_menu.addAction(paste_action)
edit_menu.addSeparator()
select_all_action = QAction("Zaznacz &wszystko", self)
select_all_action.setShortcut(QKeySequence.StandardKey.SelectAll)
select_all_action.triggered.connect(self.text_edit.selectAll)
edit_menu.addAction(select_all_action)
# Menu Format
format_menu = menubar.addMenu("F&ormat")
bold_action = QAction("&Pogrubienie", self)
bold_action.setShortcut(QKeySequence.StandardKey.Bold)
bold_action.setCheckable(True)
bold_action.triggered.connect(self.toggle_bold)
format_menu.addAction(bold_action)
self.bold_action = bold_action
italic_action = QAction("&Kursywa", self)
italic_action.setShortcut(QKeySequence.StandardKey.Italic)
italic_action.setCheckable(True)
italic_action.triggered.connect(self.toggle_italic)
format_menu.addAction(italic_action)
self.italic_action = italic_action
underline_action = QAction("&Podkreślenie", self)
underline_action.setShortcut(QKeySequence.StandardKey.Underline)
underline_action.setCheckable(True)
underline_action.triggered.connect(self.toggle_underline)
format_menu.addAction(underline_action)
self.underline_action = underline_action
format_menu.addSeparator()
font_action = QAction("Czcionka...", self)
font_action.triggered.connect(self.change_font)
format_menu.addAction(font_action)
color_action = QAction("Kolor tekstu...", self)
color_action.triggered.connect(self.change_text_color)
format_menu.addAction(color_action)
format_menu.addSeparator()
insert_table_action = QAction("Wstaw &tabelę...", self)
insert_table_action.triggered.connect(self.insert_table)
format_menu.addAction(insert_table_action)
# Menu Widok
view_menu = menubar.addMenu("&Widok")
dark_mode_action = QAction("Tryb &ciemny", self)
dark_mode_action.setCheckable(True)
dark_mode_action.triggered.connect(self.toggle_dark_mode)
view_menu.addAction(dark_mode_action)
self.dark_mode_action = dark_mode_action
fullscreen_action = QAction("&Pełny ekran", self)
fullscreen_action.setShortcut(QKeySequence("F11"))
fullscreen_action.triggered.connect(self.toggle_fullscreen)
view_menu.addAction(fullscreen_action)
focus_mode_action = QAction("Tryb &pisania", self)
focus_mode_action.setShortcut(QKeySequence("F12"))
focus_mode_action.triggered.connect(self.toggle_focus_mode)
view_menu.addAction(focus_mode_action)
menubar = self.menuBar()
oneai_menu = menubar.addMenu("&OneCheck")
open_oneai_action = QAction("Otwórz", self)
open_oneai_action.triggered.connect(self.show_oneai_widget)
oneai_menu.addAction(open_oneai_action)
self.oneai_widget = None # zostanie utworzony przy pierwszym użyciu
# Menu Pomoc
help_menu = menubar.addMenu("Pomo&c")
about_action = QAction("&O programie", self)
about_action.triggered.connect(self.show_about)
help_menu.addAction(about_action)
def create_toolbar(self):
toolbar = QToolBar("Główny pasek narzędzi")
toolbar.setIconSize(QSize(24, 24))
toolbar.setMovable(False)
self.addToolBar(toolbar)
# Przyciski formatowania
bold_btn = QAction("B", self)
bold_btn.setFont(QFont("Arial", 12, QFont.Weight.Bold))
bold_btn.setCheckable(True)
bold_btn.triggered.connect(self.toggle_bold)
toolbar.addAction(bold_btn)
self.bold_btn = bold_btn
italic_btn = QAction("I", self)
italic_btn.setFont(QFont("Arial", 12, QFont.Weight.Normal, True))
italic_btn.setCheckable(True)
italic_btn.triggered.connect(self.toggle_italic)
toolbar.addAction(italic_btn)
self.italic_btn = italic_btn
underline_btn = QAction("U", self)
font = QFont("Arial", 12)
font.setUnderline(True)
underline_btn.setFont(font)
underline_btn.setCheckable(True)
underline_btn.triggered.connect(self.toggle_underline)
toolbar.addAction(underline_btn)
self.underline_btn = underline_btn
toolbar.addSeparator()
# Rozmiar czcionki
self.font_size_combo = QComboBox()
self.font_size_combo.addItems([str(i) for i in range(8, 73, 2)])
self.font_size_combo.setCurrentText("11")
self.font_size_combo.currentTextChanged.connect(self.change_font_size)
toolbar.addWidget(self.font_size_combo)
toolbar.addSeparator()
# Kolor tekstu
color_btn = QAction("Kolor", self)
color_btn.triggered.connect(self.change_text_color)
toolbar.addAction(color_btn)
toolbar.addSeparator()
# Tabela
table_btn = QAction("Tabela", self)
table_btn.triggered.connect(self.insert_table)
toolbar.addAction(table_btn)
toolbar.addSeparator()
# Zapisz
save_btn = QAction("💾 Zapisz", self)
save_btn.triggered.connect(self.save_file)
toolbar.addAction(save_btn)
self.main_toolbar = toolbar
def create_statusbar(self):
self.status_bar = QStatusBar()
self.setStatusBar(self.status_bar)
self.autosave_label = QLabel("Autozapis: aktywny")
self.status_bar.addPermanentWidget(self.autosave_label)
self.file_path_label = QLabel("Nowy dokument")
self.status_bar.addWidget(self.file_path_label)
self.word_count_label = QLabel("Słów: 0 | Znaków: 0")
self.status_bar.addPermanentWidget(self.word_count_label)
self.update_word_count()
def on_text_changed(self):
self.is_modified = True
self.update_word_count()
# Uruchom timer do automatycznego wykrywania nazwy
self.title_detection_timer.start(3000) # 3 sekundy
# Uruchom autosave
self.autosave_manager.schedule_autosave()
# Automatyczne formatowanie list
self.auto_format_lists()
def auto_format_lists(self):
cursor = self.text_edit.textCursor()
block = cursor.block()
text = block.text()
# Sprawdź czy linia zaczyna się od "- "
if text.strip().startswith("- ") and not cursor.currentList():
cursor.beginEditBlock()
cursor.movePosition(QTextCursor.MoveOperation.StartOfBlock)
cursor.movePosition(QTextCursor.MoveOperation.EndOfBlock,
QTextCursor.MoveMode.KeepAnchor)
# Usuń "- "
new_text = text.strip()[2:]
cursor.insertText(new_text)
# Utwórz listę
from PyQt6.QtGui import QTextListFormat
list_format = QTextListFormat()
list_format.setStyle(QTextListFormat.Style.ListDisc)
cursor.createList(list_format)
cursor.endEditBlock()
def update_word_count(self):
text = self.text_edit.toPlainText()
words = len([w for w in text.split() if w])
chars = len(text)
self.word_count_label.setText(f"Słów: {words} | Znaków: {chars}")
def auto_detect_filename(self):
"""Automatyczne wykrywanie nazwy pliku z pierwszej linii"""
if self.current_file:
return # Już mamy nazwę pliku
text = self.text_edit.toPlainText()
title = extract_title_from_text(text)
if title:
filename = sanitize_filename(title)
documents_path = os.path.expanduser("~/Documents/OneOffice")
os.makedirs(documents_path, exist_ok=True)
# Sprawdź czy plik istnieje
base_path = os.path.join(documents_path, filename)
final_path = base_path + ".odt"
counter = 2
while os.path.exists(final_path):
final_path = f"{base_path} ({counter}).odt"
counter += 1
self.current_file = final_path
self.file_path_label.setText(f"📄 {os.path.basename(final_path)}")
self.setWindowTitle(f"OneOffice 3 - {os.path.basename(final_path)}")
def toggle_bold(self):
fmt = QTextCharFormat()
fmt.setFontWeight(QFont.Weight.Bold if not self.text_edit.fontWeight() == QFont.Weight.Bold
else QFont.Weight.Normal)
self.merge_format(fmt)
def toggle_italic(self):
fmt = QTextCharFormat()
fmt.setFontItalic(not self.text_edit.fontItalic())
self.merge_format(fmt)
def toggle_underline(self):
fmt = QTextCharFormat()
fmt.setFontUnderline(not self.text_edit.fontUnderline())
self.merge_format(fmt)
def merge_format(self, fmt):
cursor = self.text_edit.textCursor()
if not cursor.hasSelection():
cursor.select(QTextCursor.SelectionType.WordUnderCursor)
cursor.mergeCharFormat(fmt)
self.text_edit.mergeCurrentCharFormat(fmt)
def change_font_size(self, size):
if size:
fmt = QTextCharFormat()
fmt.setFontPointSize(int(size))
self.merge_format(fmt)
def change_font(self):
font, ok = QFontDialog.getFont(self.text_edit.currentFont(), self)
if ok:
self.text_edit.setCurrentFont(font)
def change_text_color(self):
color = QColorDialog.getColor(self.text_edit.textColor(), self)
if color.isValid():
fmt = QTextCharFormat()
fmt.setForeground(color)
self.merge_format(fmt)
def insert_table(self):
"""Wstaw profesjonalną tabelę"""
rows, ok1 = QInputDialog.getInt(self, "Wstaw tabelę",
"Liczba wierszy:", 3, 1, 100)
if not ok1:
return
cols, ok2 = QInputDialog.getInt(self, "Wstaw tabelę",
"Liczba kolumn:", 3, 1, 100)
if not ok2:
return
cursor = self.text_edit.textCursor()
# Format tabeli
table_format = QTextTableFormat()
table_format.setCellPadding(5)
table_format.setCellSpacing(0)
table_format.setBorder(1)
table_format.setBorderStyle(QTextFrameFormat.BorderStyle.BorderStyle_Solid)
# Wstaw tabelę
table = cursor.insertTable(rows, cols, table_format)
self.status_bar.showMessage(f"Wstawiono tabelę {rows}x{cols}", 3000)
def new_file(self):
if self.is_modified:
reply = QMessageBox.question(self, "Zapisać zmiany?",
"Dokument został zmodyfikowany. Zapisać zmiany?",
QMessageBox.StandardButton.Yes |
QMessageBox.StandardButton.No |
QMessageBox.StandardButton.Cancel)
if reply == QMessageBox.StandardButton.Yes:
self.save_file()
elif reply == QMessageBox.StandardButton.Cancel:
return
self.text_edit.clear()
self.current_file = None
self.is_modified = False
self.file_path_label.setText("Nowy dokument")
self.setWindowTitle("OneOffice 3")
def open_file(self):
filename, _ = QFileDialog.getOpenFileName(self, "Otwórz plik",
os.path.expanduser("~/Documents"),
"Pliki ODT (*.odt);;Wszystkie pliki (*)")
if filename:
try:
content = self.odt_exporter.load_odt(filename)
self.text_edit.setHtml(content)
self.current_file = filename
self.is_modified = False
self.file_path_label.setText(f"📄 {os.path.basename(filename)}")
self.setWindowTitle(f"OneOffice 3 - {os.path.basename(filename)}")
self.status_bar.showMessage(f"Otwarto: {filename}", 3000)
except Exception as e:
QMessageBox.critical(self, "Błąd", f"Nie można otworzyć pliku:\n{str(e)}")
def save_file(self):
if self.current_file:
self.save_to_file(self.current_file)
else:
self.save_file_as()
def save_file_as(self):
filename, _ = QFileDialog.getSaveFileName(self, "Zapisz jako",
os.path.expanduser("~/Documents"),
"Pliki ODT (*.odt)")
if filename:
if not filename.endswith('.odt'):
filename += '.odt'
self.save_to_file(filename)
self.current_file = filename
def save_to_file(self, filename):
try:
html_content = self.text_edit.toHtml()
self.odt_exporter.save_odt(html_content, filename)
self.is_modified = False
self.file_path_label.setText(f"📄 {os.path.basename(filename)}")
self.setWindowTitle(f"OneOffice 3 - {os.path.basename(filename)}")
self.status_bar.showMessage(f"Zapisano: {filename}", 3000)
except Exception as e:
QMessageBox.critical(self, "Błąd", f"Nie można zapisać pliku:\n{str(e)}")
def show_autosave_status(self, message):
self.autosave_label.setText(message)
def check_backup_on_startup(self):
backup_dir = os.path.expanduser("~/.oneoffice_backup")
if os.path.exists(backup_dir):
backups = [f for f in os.listdir(backup_dir) if f.endswith('.odt')]
if backups:
reply = QMessageBox.question(self, "Przywrócić kopię zapasową?",
f"Znaleziono {len(backups)} kopii zapasowych. Przywrócić ostatnią?",
QMessageBox.StandardButton.Yes |
QMessageBox.StandardButton.No)
if reply == QMessageBox.StandardButton.Yes:
latest_backup = max([os.path.join(backup_dir, f) for f in backups],
key=os.path.getmtime)
self.open_file_direct(latest_backup)
def open_file_direct(self, filename):
try:
content = self.odt_exporter.load_odt(filename)
self.text_edit.setHtml(content)
self.status_bar.showMessage(f"Przywrócono kopię zapasową", 3000)
except Exception as e:
QMessageBox.warning(self, "Błąd", f"Nie można przywrócić kopii:\n{str(e)}")
def toggle_dark_mode(self):
self.is_dark_mode = not self.is_dark_mode
if self.is_dark_mode:
self.apply_dark_theme()
else:
self.apply_light_theme()
def show_oneai_widget(self):
if self.oneai_widget is None:
self.oneai_widget = OneAIWidget(parent=self)
self.oneai_widget.show()
self.oneai_widget.raise_()
self.oneai_widget.activateWindow()
def apply_dark_theme(self):
dark_style = """
QMainWindow, QTextEdit {
background-color: #1e1e1e;
color: #d4d4d4;
}
QMenuBar {
background-color: #2d2d30;
color: #d4d4d4;
}
QMenuBar::item:selected {
background-color: #3e3e42;
}
QMenu {
background-color: #2d2d30;
color: #d4d4d4;
}
QMenu::item:selected {
background-color: #3e3e42;
}
QToolBar {
background-color: #2d2d30;
border: none;
}
QStatusBar {
background-color: #007acc;
color: white;
}
"""
self.setStyleSheet(dark_style)
def apply_light_theme(self):
self.setStyleSheet("")
def toggle_fullscreen(self):
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
def toggle_focus_mode(self):
if self.main_toolbar.isVisible():
self.main_toolbar.hide()
self.menuBar().hide()
self.status_bar.hide()
else:
self.main_toolbar.show()
self.menuBar().show()
self.status_bar.show()
def show_about(self):
QMessageBox.about(self, "O programie OneOffice 3",
"<h2>OneOffice 3</h2>"
"<p>Profesjonalny edytor tekstowy dla szkół</p>"
"<p>Wersja: 3.0</p>"
"<p>© 2025 OneOffice Team</p>"
"<p>Funkcje:</p>"
"<ul>"
"<li>Automatyczny zapis</li>"
"<li>Obsługa plików ODT</li>"
"<li>Automatyczne formatowanie</li>"
"<li>Tryb ciemny</li>"
"<li>Profesjonalne tabele</li>"
"</ul>")
def closeEvent(self, event):
if self.is_modified:
reply = QMessageBox.question(self, "Zapisać zmiany?",
"Dokument został zmodyfikowany. Zapisać przed zamknięciem?",
QMessageBox.StandardButton.Yes |
QMessageBox.StandardButton.No |
QMessageBox.StandardButton.Cancel)
if reply == QMessageBox.StandardButton.Yes:
self.save_file()
event.accept()
elif reply == QMessageBox.StandardButton.No:
event.accept()
else:
event.ignore()
else:
event.accept()