forked from linuxdeepin/deepin-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow.cpp
More file actions
4321 lines (3763 loc) · 168 KB
/
window.cpp
File metadata and controls
4321 lines (3763 loc) · 168 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
// SPDX-FileCopyrightText: 2011 - 2026 UnionTech Software Technology Co., Ltd.
//
// SPDX-License-Identifier: GPL-3.0-or-later
#include "window.h"
#include "pathsettintwgt.h"
#include <DTitlebar>
#include <DAnchors>
#include <DSettingsWidgetFactory>
#include <DSettingsGroup>
#include <DSettings>
#include <DSettingsOption>
#include <QApplication>
#include <QPrintDialog>
#include <QPrintPreviewDialog>
#include <QPrinter>
#include <QScreen>
#include <QStyleFactory>
#include <QEvent>
#include <QDebug>
#include <DDialog>
#include <QStackedWidget>
#include <QResizeEvent>
#include <QVBoxLayout>
#include <DGuiApplicationHelper>
#include <DMessageManager>
#include <DGuiApplicationHelper>
#include <DPrintPreviewDialog>
#include <QGuiApplication>
#include <QWindow>
#include <DWidgetUtil>
#include <QTextDocumentFragment>
#include <dprintpreviewwidget.h>
#ifdef DTKWIDGET_CLASS_DFileDialog
#include <DFileDialog>
#else
#include <QFileDialog>
#endif
#define PRINT_FLAG 2
#define PRINT_ACTION 8
#define PRINT_FORMAT_MARGIN 10
#define FLOATTIP_MARGIN 95
/**
* @brief 根据传入的源文档 \a doc 创建新的文档
* @param doc 源文档指针
* @return 创建的新文档,用于拷贝数据
*/
static QTextDocument *createNewDocument(QTextDocument *doc)
{
qDebug() << "createNewDocument called";
QTextDocument *createDoc = new QTextDocument(doc);
// 不记录撤销信息
createDoc->setUndoRedoEnabled(false);
createDoc->setMetaInformation(QTextDocument::DocumentTitle,
doc->metaInformation(QTextDocument::DocumentTitle));
createDoc->setMetaInformation(QTextDocument::DocumentUrl,
doc->metaInformation(QTextDocument::DocumentUrl));
createDoc->setDefaultFont(doc->defaultFont());
createDoc->setDefaultStyleSheet(doc->defaultStyleSheet());
createDoc->setIndentWidth(doc->indentWidth());
// 设置固定为从左向右布局,降低后续高亮等操作导致更新计算布局方向
auto textOption = createDoc->defaultTextOption();
textOption.setTextDirection(Qt::LeftToRight);
textOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere);
createDoc->setDefaultTextOption(textOption);
qDebug() << "createNewDocument end";
return createDoc;
}
/*!
* \~chinese \brief printPage 绘制每一页文本纸张到打印机
* \~chinese \param index 纸张索引
* \~chinese \param doc 文本文件
* \~chinese \param body 范围大小
* \~chinese \param pageCountBox 绘制页码的范围
*/
void Window::printPage(int index, QPainter *painter, const QTextDocument *doc,
const QRectF &body, const QRectF &pageCountBox)
{
qDebug() << "printPage called";
painter->save();
painter->translate(body.left(), body.top() - (index - 1) * body.height());
const QRectF view(0, (index - 1) * body.height(), body.width(), body.height());
QAbstractTextDocumentLayout *layout = doc->documentLayout();
QAbstractTextDocumentLayout::PaintContext ctx;
painter->setFont(QFont(doc->defaultFont()));
const QRectF box = pageCountBox.translated(0, view.top());
const QString pageString = QString::number(index);
painter->drawText(box, Qt::AlignRight, pageString);
painter->setClipRect(view);
ctx.clip = view;
ctx.palette.setColor(QPalette::Text, Qt::black);
layout->draw(painter, ctx);
painter->restore();
qDebug() << "printPage end";
}
/**
* @brief 使用多组文档打印,用于超大文档的情况
* @param index 纸张索引
* @param painter 打印指针
* @param printInfo 多组文档信息
* @param body 范围大小
* @param pageCountBox 绘制页码的范围
*/
void Window::printPageWithMultiDoc(
int index, QPainter *painter, const QVector<Window::PrintInfo> &printInfo, const QRectF &body, const QRectF &pageCountBox)
{
painter->save();
int docIndex = index;
for (auto info : printInfo) {
if (docIndex <= info.doc->pageCount()) {
// 调整绘制工具坐标到当前页面顶部
painter->translate(body.left(), body.top() - (docIndex - 1) * body.height());
// 绘制页码
painter->setFont(QFont(info.doc->defaultFont()));
const QRectF box = pageCountBox.translated(0, (docIndex - 1) * body.height());
const QString pageString = QString::number(index);
painter->drawText(box, Qt::AlignRight, pageString);
// 设置文档裁剪区域
const QRectF docView(0, (docIndex - 1) * body.height(), body.width(), body.height());
QAbstractTextDocumentLayout *layout = info.doc->documentLayout();
// 大文本的高亮单独处理
if (info.highlighter) {
// 提前两页拷贝数据,用于处理高亮计算时连续处理
qreal offsetHeight = qMax<qreal>(0, (qMin(2, docIndex - 1) * body.height()));
QPointF point = docView.topLeft() - QPointF(0, offsetHeight);
int pos = layout->hitTest(point, Qt::FuzzyHit);
QTextCursor cursor(info.doc);
cursor.setPosition(pos);
// 选取后续内容
int endPos = layout->hitTest(docView.bottomLeft(), Qt::FuzzyHit);
endPos = qMin(endPos + 1000, info.doc->characterCount() - 1);
cursor.setPosition(endPos, QTextCursor::KeepAnchor);
cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
// 创建临时文档
QTextDocument *tmpDoc = createNewDocument(info.doc);
QTextCursor insertCursor(tmpDoc);
insertCursor.beginEditBlock();
insertCursor.insertFragment(QTextDocumentFragment(cursor));
insertCursor.endEditBlock();
auto margin = info.doc->rootFrame()->frameFormat().margin();
auto fmt = tmpDoc->rootFrame()->frameFormat();
fmt.setMargin(margin);
tmpDoc->rootFrame()->setFrameFormat(fmt);
tmpDoc->setPageSize(body.size());
// 重新高亮文本
auto newHighlighter = new CSyntaxHighlighter(tmpDoc);
newHighlighter->setDefinition(info.highlighter->definition());
newHighlighter->setTheme(info.highlighter->theme());
rehighlightPrintDoc(tmpDoc, newHighlighter);
// 确保布局完成
tmpDoc->pageCount();
// 调整显示位置
painter->resetTransform();
painter->translate(body.left(), body.top() - offsetHeight);
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.clip = QRectF(0, offsetHeight, body.width(), body.height());
ctx.palette.setColor(QPalette::Text, Qt::black);
tmpDoc->documentLayout()->setPaintDevice(painter->device());
tmpDoc->documentLayout()->draw(painter, ctx);
delete newHighlighter;
delete tmpDoc;
} else {
QAbstractTextDocumentLayout::PaintContext ctx;
ctx.clip = docView;
ctx.palette.setColor(QPalette::Text, Qt::black);
// 绘制文档
layout->draw(painter, ctx);
}
break;
}
docIndex -= info.doc->pageCount();
}
painter->restore();
}
Window::Window(DMainWindow *parent)
: DMainWindow(parent),
m_centralWidget(new QWidget),
m_editorWidget(new QStackedWidget),
m_centralLayout(new QVBoxLayout(m_centralWidget)),
m_tabbar(new Tabbar),
m_jumpLineBar(new JumpLineBar()),
m_replaceBar(new ReplaceBar(this)),
m_themePanel(new ThemePanel(this)),
m_findBar(new FindBar(this)),
m_menu(new DMenu),
m_blankFileDir(QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("blank-files")),
m_backupDir(QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("backup-files")),
m_autoBackupDir(QDir(Utils::cleanPath(QStandardPaths::standardLocations(QStandardPaths::AppDataLocation)).first()).filePath("autoBackup-files")),
m_titlebarStyleSheet(titlebar()->styleSheet()),
m_themePath(Settings::instance()->settings->option("advance.editor.theme")->value().toString())
{
qDebug() << "Window constructor called";
qRegisterMetaType<TextEdit *>("TextEdit");
m_rootSaveDBus = new DBusDaemon::dbus("com.deepin.editor.daemon", "/", QDBusConnection::systemBus(), this);
m_settings = Settings::instance();
// Init.
setAcceptDrops(true);
loadTheme(m_themePath);
DGuiApplicationHelper *guiAppHelp = DGuiApplicationHelper::instance();
slotLoadContentTheme(guiAppHelp->themeType());
//关闭 替换 查找 跳行bar
connect(this, &Window::pressEsc, m_replaceBar, &ReplaceBar::pressEsc, Qt::QueuedConnection);
connect(this, &Window::pressEsc, m_findBar, &FindBar::pressEsc, Qt::QueuedConnection);
connect(this, &Window::pressEsc, m_jumpLineBar, &JumpLineBar::pressEsc, Qt::QueuedConnection);
// Init settings.
connect(m_settings, &Settings::sigAdjustFont, this, &Window::slotSigAdjustFont);
connect(m_settings, &Settings::sigAdjustFontSize, this, &Window::slotSigAdjustFontSize);
connect(m_settings, &Settings::sigAdjustTabSpaceNumber, this, &Window::slotSigAdjustTabSpaceNumber);
connect(m_settings, &Settings::sigThemeChanged, this, &Window::slotSigThemeChanged);
connect(m_settings, &Settings::sigAdjustWordWrap, this, &Window::slotSigAdjustWordWrap);
connect(m_settings, &Settings::sigSetLineNumberShow, this, &Window::slotSigSetLineNumberShow);
connect(m_settings, &Settings::sigAdjustBookmark, this, &Window::slotSigAdjustBookmark);
connect(m_settings, &Settings::sigShowBlankCharacter, this, &Window::slotSigShowBlankCharacter);
connect(m_settings, &Settings::sigHightLightCurrentLine, this, &Window::slotSigHightLightCurrentLine);
connect(m_settings, &Settings::sigShowCodeFlodFlag, this, &Window::slotSigShowCodeFlodFlag);
/* 设置页面里窗口模式的设置是针对新创建窗口的设置,本窗口不需要实时响应,暂且屏蔽此信号的绑定 */
//connect(m_settings, &Settings::sigChangeWindowSize, this, &Window::slotSigChangeWindowSize);
// Init layout and editor.
m_centralLayout->setContentsMargins(0, 0, 0, 0);
m_centralLayout->setSpacing(0);
m_centralLayout->addWidget(m_editorWidget);
setWindowIcon(QIcon::fromTheme("deepin-editor"));
setCentralWidget(m_centralWidget);
// Init titlebar.
if (titlebar()) {
qDebug() << "init titlebar";
initTitlebar();
}
// window minimum size.
setMinimumSize(680, 300);
// resize window size.
int window_width = Settings::instance()->settings->option("advance.window.window_width")->value().toInt();
int window_height = Settings::instance()->settings->option("advance.window.window_height")->value().toInt();
window_height == 1 ? window_height = 600 : window_height;
window_width == 1 ? window_width = 1000 : window_width;
resize(window_width, window_height);
//设置函数最大化或者正常窗口的初始化 2021.4.26 ut002764 lxp fix bug:74774
showCenterWindow(true);
// Init find bar.
connect(m_findBar, &FindBar::findNext, this, &Window::handleFindNextSearchKeyword, Qt::QueuedConnection);
connect(m_findBar, &FindBar::findPrev, this, &Window::handleFindPrevSearchKeyword, Qt::QueuedConnection);
connect(m_findBar, &FindBar::removeSearchKeyword, this, &Window::handleRemoveSearchKeyword, Qt::QueuedConnection);
connect(m_findBar, &FindBar::updateSearchKeyword, this, [ = ](QString file, QString keyword) {
handleUpdateSearchKeyword(m_findBar, file, keyword);
});
connect(m_findBar, &FindBar::sigFindbarClose, this, &Window::slotFindbarClose, Qt::QueuedConnection);
connect(m_findBar, &FindBar::sigSwitchToReplaceBar, this, &Window::slotSwitchToReplaceBar, Qt::QueuedConnection);
// Init replace bar.
//connect(m_replaceBar, &ReplaceBar::removeSearchKeyword, this, &Window::handleRemoveSearchKeyword, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::beforeReplace, this, &Window::slot_beforeReplace, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::replaceAll, this, &Window::handleReplaceAll, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::replaceNext, this, &Window::handleReplaceNext, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::replaceRest, this, &Window::handleReplaceRest, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::replaceSkip, this, &Window::handleReplaceSkip, Qt::QueuedConnection);
connect(m_replaceBar, &ReplaceBar::updateSearchKeyword, this, [ = ](QString file, QString keyword) {
handleUpdateSearchKeyword(m_replaceBar, file, keyword);
});
connect(m_replaceBar, &ReplaceBar::sigReplacebarClose, this, &Window::slotReplacebarClose, Qt::QueuedConnection);
// Init jump line bar.
//QTimer::singleShot(0, m_jumpLineBar, SLOT(hide()));
m_jumpLineBar->hide();
m_jumpLineBar->setParent(this);
connect(m_jumpLineBar, &JumpLineBar::jumpToLine, this, &Window::handleJumpLineBarJumpToLine, Qt::QueuedConnection);
connect(m_jumpLineBar, &JumpLineBar::backToPosition, this, &Window::handleBackToPosition, Qt::QueuedConnection);
connect(m_jumpLineBar, &JumpLineBar::lostFocusExit, this, &Window::handleJumpLineBarExit, Qt::QueuedConnection);
// Make jump line bar pop at top-right of editor.
//DAnchorsBase::setAnchor(m_jumpLineBar, Qt::AnchorTop, m_centralWidget, Qt::AnchorTop);
//DAnchorsBase::setAnchor(m_jumpLineBar, Qt::AnchorRight, m_centralWidget, Qt::AnchorRight);
DAnchors<JumpLineBar> anchors_jumpLineBar(m_jumpLineBar);
anchors_jumpLineBar.setAnchor(Qt::AnchorTop, m_centralWidget, Qt::AnchorTop);
anchors_jumpLineBar.setAnchor(Qt::AnchorRight, m_centralWidget, Qt::AnchorRight);
anchors_jumpLineBar.setTopMargin(5);
anchors_jumpLineBar.setRightMargin(5);
m_jumpLineBar->raise();
// Init findbar panel.
static DAnchors<FindBar> anchors_findbar(m_findBar);
anchors_findbar.setAnchor(Qt::AnchorBottom, m_centralWidget, Qt::AnchorBottom);
anchors_findbar.setAnchor(Qt::AnchorHorizontalCenter, m_centralWidget, Qt::AnchorHorizontalCenter);
anchors_findbar.setBottomMargin(1);
//m_findBar->move(QPoint(10, height() - 5));
m_findBar->raise();
// Init replaceBar panel.
DAnchors<ReplaceBar> anchors_replaceBar(m_replaceBar);
anchors_replaceBar.setAnchor(Qt::AnchorBottom, m_centralWidget, Qt::AnchorBottom);
anchors_replaceBar.setAnchor(Qt::AnchorHorizontalCenter, m_centralWidget, Qt::AnchorHorizontalCenter);
anchors_replaceBar.setBottomMargin(1);
//m_replaceBar->move(QPoint(10, height() - 57));
m_replaceBar->raise();
// Init theme panel.
DAnchorsBase::setAnchor(m_themePanel, Qt::AnchorTop, m_centralWidget, Qt::AnchorTop);
DAnchorsBase::setAnchor(m_themePanel, Qt::AnchorBottom, m_centralWidget, Qt::AnchorBottom);
DAnchorsBase::setAnchor(m_themePanel, Qt::AnchorRight, m_centralWidget, Qt::AnchorRight);
// for the first time open the need be init.
m_themePanel->setSelectionTheme(m_themePath);
connect(m_themePanel, &ThemePanel::themeChanged, this, &Window::themeChanged);
connect(this, &Window::requestDragEnterEvent, this, &Window::dragEnterEvent);
connect(this, &Window::requestDropEvent, this, &Window::dropEvent);
connect(qApp, &QGuiApplication::focusWindowChanged, this, &Window::handleFocusWindowChanged);
connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::themeTypeChanged, this, &Window::slotLoadContentTheme);
//setChildrenFocus(false);
Utils::clearChildrenFocus(m_tabbar);//使用此函数把tabbar的组件焦点去掉(左右箭头不能focus)
#ifdef DTKWIDGET_CLASS_DSizeMode
// 适配紧凑模式更新,注意 Qt::QueuedConnection 需要在其他子组件更新后触发
connect(DGuiApplicationHelper::instance(), &DGuiApplicationHelper::sizeModeChanged, this, &Window::updateSizeMode, Qt::QueuedConnection);
#endif
qDebug() << "Window constructor end";
}
Window::~Window()
{
qDebug() << "Window destructor called";
// We don't need clean pointers because application has exit here.
if (nullptr != m_shortcutViewProcess) {
qDebug() << "delete m_shortcutViewProcess";
delete (m_shortcutViewProcess);
m_shortcutViewProcess = nullptr;
}
clearPrintTextDocument();
qDebug() << "Window destructor end";
}
void Window::loadIflytekaiassistantConfig()
{
qDebug() << "loadIflytekaiassistantConfig";
QString configPath = QString("%1/%2")
.arg(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation))
.arg("iflytek");
QDir dir(configPath);
if (!dir.exists()) {
qDebug() << "iflytekaiassistant config dir not exist, return";
return;
}
QString key = "base/enable";
dir.setFilter(QDir::Files);
QStringList nameList = dir.entryList();
for (auto name : nameList) {
if (name.contains("-iat") || name.contains("-tts") || name.contains("-trans")) {
QString filename = configPath + "/" + name;
QSettings file(filename, QSettings::IniFormat);
m_IflytekAiassistantState[name.split(".").first()] = file.value(key).toBool();
}
}
qDebug() << "loadIflytekaiassistantConfig end";
}
bool Window::getIflytekaiassistantConfig(const QString &mode_name)
{
qDebug() << "getIflytekaiassistantConfig";
if (m_IflytekAiassistantState.contains(mode_name)) {
qDebug() << "getIflytekaiassistantConfig end";
return m_IflytekAiassistantState[mode_name];
} else {
qWarning() << "mode_name is not valid";
return false;
}
}
void Window::updateModifyStatus(const QString &path, bool isModified)
{
qDebug() << "updateModifyStatus";
int tabIndex = m_tabbar->indexOf(path);
if (tabIndex == -1) {
qWarning() << "Failed to get tab index for path:" << path;
return;
}
QString tabName;
QString filePath = m_tabbar->truePathAt(tabIndex);
if (filePath.isNull() || filePath.length() <= 0 || Utils::isDraftFile(filePath)) {
qDebug() << "Failed to get true path for tab index:" << tabIndex;
tabName = m_tabbar->textAt(tabIndex);
if (isModified) {
qDebug() << "Modified but not saved, add * to tab name";
if (!tabName.contains('*')) {
tabName.prepend('*');
}
} else {
QRegularExpression reg("[^*](.+)");
QRegularExpressionMatch match = reg.match(tabName);
if (match.hasMatch()) {
qDebug() << "Tab name does not contain *, remove * from tab name";
tabName = match.captured(0);
}
}
} else {
qDebug() << "File path is valid, updating tab name";
QFileInfo fileInfo(filePath);
tabName = fileInfo.fileName();
if (isModified) {
qDebug() << "Modified but not saved, add * to tab name";
tabName.prepend('*');
}
}
m_tabbar->setTabText(tabIndex, tabName);
//判断是否需要阻塞系统关机
emit sigJudgeBlockShutdown();
qDebug() << "updateModifyStatus end";
}
void Window::updateSaveAsFileName(QString strOldFilePath, QString strNewFilePath)
{
qDebug() << "updateSaveAsFileName called with old path:" << strOldFilePath << "new path:" << strNewFilePath;
int tabIndex = m_tabbar->indexOf(strOldFilePath);
EditWrapper *wrapper = m_wrappers.value(strOldFilePath);
if (!wrapper) {
qWarning() << "Failed to get wrapper for old path";
return;
}
m_tabbar->updateTab(tabIndex, strNewFilePath, QFileInfo(strNewFilePath).fileName());
wrapper->updatePath(strNewFilePath);
//tabbar中存在和strNewFilePath同名的tab
if (m_wrappers.contains(strNewFilePath)) {
qDebug() << "Tab with new file path already exists, closing old tab.";
closeTab(strNewFilePath);
}
m_wrappers.remove(strOldFilePath);
m_wrappers.insert(strNewFilePath, wrapper);
qDebug() << "updateSaveAsFileName end";
}
void Window::updateSabeAsFileNameTemp(QString strOldFilePath, QString strNewFilePath)
{
qDebug() << "updateSabeAsFileNameTemp called with old path:" << strOldFilePath << "new path:" << strNewFilePath;
int tabIndex = m_tabbar->indexOf(strOldFilePath);
EditWrapper *wrapper = m_wrappers.value(strOldFilePath);
if (!wrapper) {
qWarning() << "Failed to get wrapper for old path";
return;
}
m_tabbar->updateTab(tabIndex, strNewFilePath, QFileInfo(strNewFilePath).fileName());
wrapper->updatePath(strNewFilePath);
m_wrappers.remove(strOldFilePath);
m_wrappers.insert(strNewFilePath, wrapper);
qDebug() << "updateSabeAsFileNameTemp end";
}
void Window::showCenterWindow(bool bIsCenter)
{
qDebug() << "Window::showCenterWindow() - bIsCenter:" << bIsCenter;
// Init window state with config.
// Below code must before this->titlebar()->setMenu, otherwise main menu can't display pre-build-in menu items by dtk.
QString windowState = Settings::instance()->settings->option("advance.window.windowstate")->value().toString();
if (bIsCenter) {
qDebug() << "Window::showCenterWindow() - bIsCenter is true";
Dtk::Widget::moveToCenter(this);
}
// init window state.
if (windowState == "window_maximum") {
qDebug() << "Window::showCenterWindow() - setting window to maximized state";
showMaximized();
m_needMoveToCenter = true;
} else if (windowState == "fullscreen") {
qDebug() << "Window::showCenterWindow() - setting window to fullscreen state";
showFullScreen();
m_needMoveToCenter = true;
} else {
qDebug() << "Window::showCenterWindow() - setting window to normal state";
showNormal();
}
qDebug() << "Window::showCenterWindow() - end";
}
void Window::initTitlebar()
{
qDebug() << "initTitlebar called";
QAction *newWindowAction(new QAction(tr("New window"), this));
QAction *newTabAction(new QAction(tr("New tab"), this));
QAction *openFileAction(new QAction(tr("Open file"), this));
QAction *saveAction(new QAction(tr("Save"), this));
QAction *saveAsAction(new QAction(tr("Save as"), this));
QAction *printAction(new QAction(tr("Print"), this));
QAction *switchThemeAction(new QAction(tr("Switch theme"), this));
QAction *settingAction(new QAction(tr("Settings"), this));
QAction *findAction(new QAction(QApplication::translate("TextEdit", "Find"), this));
QAction *replaceAction(new QAction(QApplication::translate("TextEdit", "Replace"), this));
m_menu->addAction(newWindowAction);
m_menu->addAction(newTabAction);
m_menu->addAction(openFileAction);
m_menu->addSeparator();
m_menu->addAction(findAction);
m_menu->addAction(replaceAction);
m_menu->addAction(saveAction);
m_menu->addAction(saveAsAction);
m_menu->addAction(printAction);
//此接口不可删除,预留的编辑器内部主题选择接口
//m_menu->addAction(switchThemeAction);
m_menu->addSeparator();
m_menu->addAction(settingAction);
m_menu->setMinimumWidth(150);
titlebar()->addWidget(m_tabbar);
titlebar()->setCustomWidget(m_tabbar, false);
titlebar()->setSeparatorVisible(false);
titlebar()->setMenu(m_menu);
titlebar()->setIcon(QIcon::fromTheme("deepin-editor"));
titlebar()->setFocusPolicy(Qt::NoFocus); //设置titlebar无焦点,点击titlebar时光标不移动
DIconButton *addButton = m_tabbar->findChild<DIconButton *>("AddButton");
addButton->setFocusPolicy(Qt::NoFocus);
DIconButton *optionBtn = titlebar()->findChild<DIconButton *>("DTitlebarDWindowOptionButton");
optionBtn->setFocusPolicy(Qt::NoFocus);
DIconButton *minBtn = titlebar()->findChild<DIconButton *>("DTitlebarDWindowMinButton");
minBtn->setFocusPolicy(Qt::NoFocus);
DIconButton *quitFullBtn = titlebar()->findChild<DIconButton *>("DTitlebarDWindowQuitFullscreenButton");
quitFullBtn->setFocusPolicy(Qt::NoFocus);
DIconButton *maxBtn = titlebar()->findChild<DIconButton *>("DTitlebarDWindowMaxButton");
maxBtn->setFocusPolicy(Qt::NoFocus);
DIconButton *closeBtn = titlebar()->findChild<DIconButton *>("DTitlebarDWindowCloseButton");
closeBtn->setFocusPolicy(Qt::NoFocus);
connect(m_tabbar, &DTabBar::tabBarDoubleClicked, titlebar(), &DTitlebar::doubleClicked, Qt::QueuedConnection);
connect(m_tabbar, &Tabbar::closeTabs, this, &Window::handleTabsClosed, Qt::QueuedConnection);
connect(m_tabbar, &Tabbar::requestHistorySaved, this, [ = ](const QString & filePath) {
// 单个Tab页关闭文件时记录文件信息
if (StartManager::instance()->checkPath(filePath)) {
qDebug() << "Recording close file history for file:" << filePath;
Utils::recordCloseFile(filePath);
}
if (QFileInfo(filePath).dir().absolutePath() == m_blankFileDir) {
qDebug() << "File is a blank file, not recording in history:" << filePath;
return;
}
if (!m_closeFileHistory.contains(filePath)) {
qDebug() << "Adding file to close file history:" << filePath;
m_closeFileHistory << filePath;
}
});
connect(m_tabbar, &DTabBar::tabCloseRequested, this, &Window::handleTabCloseRequested, Qt::QueuedConnection);
connect(m_tabbar, &DTabBar::tabAddRequested, this, static_cast<void (Window::*)()>(&Window::addBlankTab), Qt::QueuedConnection);
connect(m_tabbar, &DTabBar::currentChanged, this, &Window::handleCurrentChanged, Qt::QueuedConnection);
// 当标签页新增、删除时触发变更信号(用于备份当前打开文件信息)
connect(m_tabbar, &DTabBar::tabIsInserted, this, &Window::tabChanged, Qt::QueuedConnection);
connect(m_tabbar, &DTabBar::tabIsRemoved, this, &Window::tabChanged, Qt::QueuedConnection);
connect(newWindowAction, &QAction::triggered, this, &Window::newWindow);
connect(newTabAction, &QAction::triggered, this, static_cast<void (Window::*)()>(&Window::addBlankTab));
connect(openFileAction, &QAction::triggered, this, &Window::openFile);
connect(findAction, &QAction::triggered, this, &Window::popupFindBar);
connect(replaceAction, &QAction::triggered, this, &Window::popupReplaceBar);
connect(saveAction, &QAction::triggered, this, &Window::saveFile);
connect(saveAsAction, &QAction::triggered, this, &Window::saveAsFile);
connect(printAction, &QAction::triggered, this, &Window::popupPrintDialog);
connect(settingAction, &QAction::triggered, this, &Window::popupSettingsDialog);
connect(switchThemeAction, &QAction::triggered, this, &Window::popupThemePanel);
qDebug() << "initTitlebar end";
}
bool Window::checkBlockShutdown()
{
qDebug() << "checkBlockShutdown called";
//判断是否有未保存的tab项
for (int i = 0; i < m_tabbar->count(); i++) {
if (m_tabbar->textAt(i).isNull()) {
qDebug() << "Tab name is null, return false";
return false;
}
//如果有未保存的tab项,return true阻塞系统关机
if (m_tabbar->textAt(i).at(0) == '*') {
qDebug() << "There are unsaved tabs, return true";
return true;
}
}
qDebug() << "There are no unsaved tabs, return false";
return false;
}
int Window::getTabIndex(const QString &file)
{
qDebug() << "getTabIndex called with file:" << file;
return m_tabbar->indexOf(file);
}
void Window::activeTab(int index)
{
qDebug() << "activeTab called with index:" << index;
DMainWindow::activateWindow();
m_tabbar->setCurrentIndex(index);
qDebug() << "activeTab end";
}
Tabbar *Window::getTabbar()
{
return m_tabbar;
}
void Window::addTab(const QString &filepath, bool activeTab)
{
qDebug() << "Enter addTab, filepath:" << filepath << "activeTab:" << activeTab;
// check whether it is an editable file thround mimeType.
if (Utils::isMimeTypeSupport(filepath)) {
const QFileInfo fileInfo(filepath);
QString tabName = fileInfo.fileName();
qDebug() << "File is supported, name:" << tabName << "writable:" << fileInfo.isWritable() << "readable:" << fileInfo.isReadable();
EditWrapper *curWrapper = currentWrapper();
if (!fileInfo.isWritable() && fileInfo.isReadable()) {
tabName += QString(" (%1)").arg(tr("Read-Only"));
qDebug() << "File is read-only, updated tab name:" << tabName;
}
if (curWrapper) {
// if the current page is a draft file and is empty
if (m_tabbar->indexOf(filepath) != -1) {
qDebug() << "File already open in tab index:" << m_tabbar->indexOf(filepath) << ", activating tab";
m_tabbar->setCurrentIndex(m_tabbar->indexOf(filepath));
}
}
// check if have permission to read the file.
bool bIsReadable = fileInfo.isReadable();
qDebug() << "File readable:" << bIsReadable;
if (fileInfo.exists() && !bIsReadable) {
qWarning() << "No permission to read file:" << filepath;
DMessageManager::instance()->sendMessage(m_editorWidget->currentWidget(), QIcon(":/images/warning.svg")
, QString(tr("You do not have permission to open %1")).arg(filepath));
return;
}
if (StartManager::instance()->checkPath(filepath)) {
qDebug() << "Path check passed, adding tab for file";
m_tabbar->addTab(filepath, tabName, filepath);
if (!m_wrappers.contains(filepath)) {
qDebug() << "Creating new editor wrapper for file";
EditWrapper *wrapper = createEditor();
showNewEditor(wrapper);
m_wrappers[filepath] = wrapper;
if (!fileInfo.isWritable() && fileInfo.isReadable()) {
qDebug() << "Setting read-only permission for editor";
wrapper->textEditor()->setReadOnlyPermission(true);
}
qDebug() << "Opening file in editor";
wrapper->openFile(filepath, filepath);
// 查找文件是否存在书签
auto bookmarkInfo = StartManager::instance()->findBookmark(filepath);
wrapper->textEditor()->setBookMarkList(bookmarkInfo);
}
// Activate window.
activateWindow();
qDebug() << "Window activated";
} else {
qDebug() << "Path check failed, file may already be open in another window";
}
// Active tab if activeTab is true.
if (activeTab) {
int tabIndex = m_tabbar->indexOf(filepath);
if (tabIndex != -1) {
qDebug() << "Activating tab at index:" << tabIndex;
m_tabbar->setCurrentIndex(tabIndex);
} else {
qWarning() << "Failed to find tab for filepath:" << filepath;
}
}
} else {
qWarning() << "File is not supported by MIME type:" << filepath;
if (currentWrapper() == nullptr) {
qDebug() << "No current wrapper, adding blank tab";
this->addBlankTab();
}
QString strFileName = QFileInfo(filepath).fileName();
strFileName = tr("Invalid file: %1").arg(strFileName);
strFileName = Utils::lineFeed(strFileName, m_editorWidget->currentWidget()->width() - FLOATTIP_MARGIN, m_editorWidget->currentWidget()->font(), 2);
qDebug() << "Showing invalid file notification";
DMessageManager::instance()->sendMessage(m_editorWidget->currentWidget(), QIcon(":/images/warning.svg"), strFileName);
}
qDebug() << "Exit addTab";
}
void Window::addTabWithWrapper(EditWrapper *wrapper, const QString &filepath, const QString &qstrTruePath, const QString &tabName, int index)
{
qDebug() << "Enter addTabWithWrapper, filepath:" << filepath << "truePath:" << qstrTruePath << "tabName:" << tabName << "index:" << index;
if (index == -1) {
index = m_tabbar->count();
qDebug() << "Index not specified, using tab count:" << index;
}
//这里会重复连接信号和槽,先全部取消
QDBusConnection dbus = QDBusConnection::sessionBus();
qDebug() << "Disconnecting previous DBus signals for gesture events";
switch (Utils::getSystemVersion()) {
case Utils::V23:
qDebug() << "Using V23 DBus path for gesture events";
dbus.systemBus().disconnect("org.deepin.dde.Gesture1",
"/org/deepin/dde/Gesture1", "org.deepin.dde.Gesture1",
"Event",
wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int)));
break;
default:
qDebug() << "Using default DBus path for gesture events";
dbus.systemBus().disconnect("com.deepin.daemon.Gesture",
"/com/deepin/daemon/Gesture", "com.deepin.daemon.Gesture",
"Event",
wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int)));
break;
}
qDebug() << "Disconnecting all signals from text editor";
wrapper->textEditor()->disconnect();
qDebug() << "Connecting signals to text editor";
connect(wrapper->textEditor(), &TextEdit::cursorModeChanged, wrapper, &EditWrapper::handleCursorModeChanged);
connect(wrapper->textEditor(), &TextEdit::clickFindAction, this, &Window::popupFindBar, Qt::QueuedConnection);
connect(wrapper->textEditor(), &TextEdit::clickReplaceAction, this, &Window::popupReplaceBar, Qt::QueuedConnection);
connect(wrapper->textEditor(), &TextEdit::clickJumpLineAction, this, &Window::popupJumpLineBar, Qt::QueuedConnection);
connect(wrapper->textEditor(), &TextEdit::clickFullscreenAction, this, &Window::toggleFullscreen, Qt::QueuedConnection);
connect(wrapper->textEditor(), &TextEdit::popupNotify, this, &Window::showNotify, Qt::QueuedConnection);
connect(wrapper->textEditor(), &TextEdit::signal_setTitleFocus, this, &Window::slot_setTitleFocus, Qt::QueuedConnection);
qDebug() << "Reconnecting DBus signals for gesture events";
switch (Utils::getSystemVersion()) {
case Utils::V23:
qDebug() << "Connecting to V23 DBus path for gesture events";
dbus.systemBus().connect("org.deepin.dde.Gesture1",
"/org/deepin/dde/Gesture1", "org.deepin.dde.Gesture1",
"Event",
wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int)));
break;
default:
qDebug() << "Connecting to default DBus path for gesture events";
dbus.systemBus().connect("com.deepin.daemon.Gesture",
"/com/deepin/daemon/Gesture", "com.deepin.daemon.Gesture",
"Event",
wrapper->textEditor(), SLOT(fingerZoom(QString, QString, int)));
break;
}
connect(wrapper->textEditor(), &QPlainTextEdit::cursorPositionChanged, wrapper->textEditor(), &TextEdit::cursorPositionChanged);
connect(wrapper->textEditor(), &QPlainTextEdit::textChanged, wrapper->textEditor(), [ = ]() {
wrapper->UpdateBottomBarWordCnt(wrapper->textEditor()->characterCount());
});
qDebug() << "Adding tab to tabbar at index:" << index << "with filepath:" << filepath << "tabName:" << tabName;
// add wrapper to this window.
m_tabbar->addTabWithIndex(index, filepath, tabName, qstrTruePath);
m_wrappers[filepath] = wrapper;
wrapper->updatePath(filepath, qstrTruePath);
qDebug() << "Showing new editor and applying theme";
showNewEditor(wrapper);
wrapper->OnThemeChangeSlot(m_themePath);
qDebug() << "Exit addTabWithWrapper";
}
/**
* @return 关闭当前焦点的标签页并返回是否成功关闭。
*/
bool Window::closeTab()
{
qDebug() << "Enter closeTab (no arguments)";
const QString &filePath = m_tabbar->currentPath();
// 避免异常情况重入时当前已无标签页的情况
if (filePath.isEmpty()) {
qWarning() << "Current tab path is empty, cannot close tab";
return false;
}
qDebug() << "Closing current tab with path:" << filePath;
return closeTab(filePath);
}
bool Window::closeTab(const QString &filePath)
{
qDebug() << "Enter closeTab with path:" << filePath;
EditWrapper *wrapper = m_wrappers.value(filePath);
if (!wrapper) {
qWarning() << "No wrapper found for path:" << filePath;
return false;
}
if (!currentWrapper()) {
qWarning() << "No current wrapper, cannot close tab";
return false;
}
if (m_reading_list.contains(currentWrapper()->textEditor())) {
qDebug() << "Current editor is in reading list, syncing settings";
if (m_settings->settings) {
m_settings->settings->sync();
}
if (IflytekAiAssistant::instance()->valid()) {
qDebug() << "Stopping TTS playback";
IflytekAiAssistant::instance()->stopTtsDirectly();
}
}
// 当前窗口为打印文本窗口
if (wrapper == m_printWrapper) {
qDebug() << "Closing print wrapper, exiting print mode";
// 退出打印
m_bPrintProcessing = false;
}
qDebug() << "Disconnecting all signals from wrapper";
disconnect(wrapper, nullptr);
disconnect(wrapper->textEditor(), &TextEdit::textChanged, nullptr, nullptr);
// this property holds whether the document has been modified by the user
bool isModified = wrapper->isModified();
bool isDraftFile = wrapper->isDraftFile();
bool bIsBackupFile = false;
qDebug() << "Tab state - modified:" << isModified << "draft file:" << isDraftFile;
if (wrapper->isTemFile()) {
bIsBackupFile = true;
qDebug() << "Tab is a temporary backup file";
}
if (wrapper->getFileLoading()) {
qDebug() << "File is still loading, setting modified to false";
isModified = false;
}
// 关闭标签页前,记录全局的书签信息
QList<int> bookmarkInfo = wrapper->textEditor()->getBookmarkInfo();
if (!bookmarkInfo.isEmpty()) {
qDebug() << "Saving bookmarks for file:" << bookmarkInfo;
QString localPath = wrapper->textEditor()->getTruePath();
StartManager::instance()->recordBookmark(localPath, bookmarkInfo);
}
if (isDraftFile) {
if (isModified) {
qDebug() << "Draft file is modified, prompting to save";
DDialog *dialog = createDialog(tr("Do you want to save this file?"), "");
int res = dialog->exec();
//取消或关闭弹窗不做任务操作
if (res == 0 || res == -1) {
qDebug() << "Dialog cancelled or closed, not performing any actions";
return false;
}
//不保存
if (res == 1) {
qDebug() << "User chose not to save, removing wrapper and closing tab";
removeWrapper(filePath, true);
m_tabbar->closeCurrentTab(filePath);
QFile(filePath).remove();
return true;
}
//保存
if (res == 2) {
QFileInfo fileInfo(filePath);
QString newFilePath;
if (wrapper->saveDraftFile(newFilePath)) {
qDebug() << "Draft file saved, removing wrapper and closing tab";
removeWrapper(filePath, true);
// 保存临时文件后已更新tab页的文件路径,使用新的文件路径删除窗口
m_tabbar->closeCurrentTab(newFilePath);
QFile(filePath).remove();
} else {
// 保存不成功时不关闭窗口
qDebug() << "Draft file save failed, not closing tab";
return false;
}
}
} else {
qDebug() << "Draft file is not modified, removing wrapper and closing tab";
removeWrapper(filePath, true);
m_tabbar->closeCurrentTab(filePath);
QFile(filePath).remove();
}
}
// document has been modified or unsaved draft document.
// need to prompt whether to save.
else {
QFileInfo fileInfo(filePath);
isModified = false;
if (m_tabbar->textAt(m_tabbar->currentIndex()).front() == "*") {
qDebug() << "Tab name starts with '*', indicating modified state";
isModified = true;
}
if (isModified) {
qDebug() << "File is modified, prompting to save";
DDialog *dialog = createDialog(tr("Do you want to save this file?"), "");
int res = dialog->exec();
//取消或关闭弹窗不做任务操作
if (res == 0 || res == -1) {
qDebug() << "Dialog cancelled or closed, not performing any actions";
return false;
}
//不保存
if (res == 1) {
qDebug() << "User chose not to save, removing wrapper and closing tab";
removeWrapper(filePath, true);
m_tabbar->closeCurrentTab(filePath);
//删除备份文件
if (bIsBackupFile) {
qDebug() << "Deleting backup file";
QFile(filePath).remove();
}
//删除自动备份文件
if (QFileInfo(m_autoBackupDir).exists()) {
qDebug() << "Deleting auto backup file";
fileInfo.setFile(wrapper->textEditor()->getTruePath());
QString name = fileInfo.absolutePath().replace("/", "_");
QDir(m_autoBackupDir).remove(fileInfo.baseName() + "." + name + "." + fileInfo.suffix());
}
qDebug() << "Exit closeTab, return true";
return true;
}
//保存
if (res == 2) {
if (bIsBackupFile) {
if (wrapper->saveFile()) {
qDebug() << "File saved, removing wrapper and closing tab";
removeWrapper(filePath, true);
m_tabbar->closeCurrentTab(filePath);
QFile(filePath).remove();
} else {
qDebug() << "File save failed, not closing tab";
saveAsFile();
}
} else {
qDebug() << "File is not a backup file, saving normally";