forked from JoyIfBam5/plantumlqeditor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mainwindow.cpp
1187 lines (996 loc) · 43 KB
/
mainwindow.cpp
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 file is part of PlantUML QEditor.
*
* PlantUML QEditor is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* PlantUML QEditor is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with PlantUML QEditor. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "previewwidget.h"
#include "preferencesdialog.h"
#include "assistantxmlreader.h"
#include "settingsconstants.h"
#include "filecache.h"
#include "recentdocuments.h"
#include "utils.h"
#include "textedit.h"
#include <QtGui>
#include <QtSvg>
#include <QtSingleApplication>
#include <QScrollArea>
namespace {
const int ASSISTANT_ITEM_DATA_ROLE = Qt::UserRole;
const int ASSISTANT_ITEM_NOTES_ROLE = Qt::UserRole + 1;
const int MAX_RECENT_DOCUMENT_SIZE = 10;
const int STATUSBAR_TIMEOUT = 3000; // in miliseconds
const QString TITLE_FORMAT_STRING = "%1[*] - %2";
const char *EXPORT_TO_MENU_FORMAT_STRING = QT_TRANSLATE_NOOP("MainWindow", "Export to %1");
const char *EXPORT_TO_LABEL_FORMAT_STRING = QT_TRANSLATE_NOOP("MainWindow", "Export to: %1");
const char *AUTOREFRESH_STATUS_LABEL = QT_TRANSLATE_NOOP("MainWindow", "Auto-refresh");
const char *CACHE_SIZE_FORMAT_STRING = QT_TRANSLATE_NOOP("MainWindow", "Cache: %1");
const QSize ASSISTANT_ICON_SIZE(128, 128);
QIcon iconFromSvg(QSize size, const QString& path)
{
QPixmap pixmap(size);
QPainter painter(&pixmap);
const QRect bounding_rect(QPoint(0, 0), size);
if (!path.isEmpty()) {
painter.setRenderHint(QPainter::Antialiasing, true);
painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
painter.setPen(Qt::NoPen);
painter.drawRect(bounding_rect);
QSvgRenderer svg(path);
QSize target_size = svg.defaultSize();
target_size.scale(size, Qt::KeepAspectRatio);
QRect target_rect = QRect(QPoint(0, 0), target_size);
target_rect.translate(bounding_rect.center() - target_rect.center());
svg.render(&painter, target_rect);
} else {
painter.setBrush(QBrush(Qt::white, Qt::SolidPattern));
painter.setPen(Qt::NoPen);
painter.drawRect(bounding_rect);
const int margin = 5;
QRect target_rect = bounding_rect.adjusted(margin, margin, -margin, -margin);
painter.setPen(Qt::SolidLine);
painter.drawRect(target_rect);
painter.drawLine(target_rect.topLeft(), target_rect.bottomRight() + QPoint(1, 1));
painter.drawLine(target_rect.bottomLeft() + QPoint(0, 1), target_rect.topRight() + QPoint(1, 0));
}
QIcon icon;
icon.addPixmap(pixmap);
return icon;
}
QListWidget* newAssistantListWidget(const QSize& icon_size, QWidget* parent)
{
QListWidget* view = new QListWidget(parent);
view->setUniformItemSizes(true);
view->setMovement(QListView::Static);
view->setResizeMode(QListView::Adjust);
view->setIconSize(icon_size);
view->setViewMode(QListView::IconMode);
return view;
}
} // namespace {}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, m_hasValidPaths(false)
, m_process(0)
, m_currentImageFormat(SvgFormat)
, m_needsRefresh(false)
{
setWindowTitle(TITLE_FORMAT_STRING
.arg("")
.arg(qApp->applicationName())
);
setWindowIcon(QIcon(":/icon32.png"));
m_cache = new FileCache(0, this);
m_recentDocuments = new RecentDocuments(MAX_RECENT_DOCUMENT_SIZE, this);
connect(m_recentDocuments, SIGNAL(recentDocument(QString)), this, SLOT(onRecentDocumentsActionTriggered(QString)));
m_autoRefreshTimer = new QTimer(this);
connect(m_autoRefreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
m_imageFormatNames[SvgFormat] = "svg";
m_imageFormatNames[PngFormat] = "png";
m_imageWidget = new PreviewWidget(this);
m_imageWidgetScrollArea = new QScrollArea;
m_imageWidgetScrollArea->setWidget(m_imageWidget);
m_imageWidgetScrollArea->setAlignment(Qt::AlignCenter);
m_imageWidgetScrollArea->setWidgetResizable(true);
setCentralWidget(m_imageWidgetScrollArea);
createDockWindows();
createActions();
createMenus();
createToolBars();
createStatusBar();
setUnifiedTitleAndToolBarOnMac(true);
m_assistantInsertSignalMapper = new QSignalMapper(this);
connect(m_assistantInsertSignalMapper, SIGNAL(mapped(QWidget*)),
this, SLOT(onAssistantItemInsert(QWidget*)));
readSettings();
QtSingleApplication* single_app = qobject_cast<QtSingleApplication*>(qApp);
if (single_app) {
single_app->setActivationWindow(this);
connect(single_app, SIGNAL(messageReceived(QString)),
this, SLOT(onSingleApplicationReceivedMessage(QString)));
}
}
MainWindow::~MainWindow()
{
}
void MainWindow::newDocument()
{
if (!maybeSave()) {
return;
}
m_documentPath.clear();
m_exportPath.clear();
m_cachedImage.clear();
m_exportImageAction->setText(tr(EXPORT_TO_MENU_FORMAT_STRING).arg(""));
m_exportPathLabel->setText(tr(EXPORT_TO_LABEL_FORMAT_STRING).arg(""));
m_exportPathLabel->setEnabled(false);
QString text = "@startuml\n\nclass Foo\n\n@enduml";
m_editor->setPlainText(text);
setWindowTitle(TITLE_FORMAT_STRING
.arg(tr("Untitled"))
.arg(qApp->applicationName())
);
setWindowModified(false);
refresh();
enableUndoRedoActions();
}
void MainWindow::copyImage()
{
QPixmap pixmap;
pixmap.loadFromData(m_cachedImage);
QApplication::clipboard()->setPixmap(pixmap);
qDebug() << "Image copy into Clipboard";
}
void MainWindow::undo()
{
QTextDocument *document = m_editor->document();
document->undo();
enableUndoRedoActions();
}
void MainWindow::redo()
{
QTextDocument *document = m_editor->document();
document->redo();
enableUndoRedoActions();
}
void MainWindow::about()
{
QMessageBox::about(this, tr("About %1").arg(qApp->applicationName()),
tr(
"The <i>%1</i> allows simple edit and preview of UML "
"diagrams generated with <i>%2</i>.<br>"
"<br>"
"%2, %3 and %4 must be installed before "
"using the editor.<br>"
"<br>"
"Copyright (c) 2012-2017 - Ioan Călin Borcoman"
)
.arg(qApp->applicationName())
.arg("PlantUML")
.arg("Java")
.arg("Graphiz")
);
}
QString MainWindow::makeKeyForDocument(QByteArray current_document)
{
QString key = QString("%1.%2")
.arg(QString::fromUtf8(QCryptographicHash::hash(current_document, QCryptographicHash::Md5).toHex()))
.arg(m_imageFormatNames[m_currentImageFormat])
;
return key;
}
bool MainWindow::refreshFromCache()
{
if (m_useCache) {
QByteArray current_document = m_editor->toPlainText().toUtf8().trimmed();
if (current_document.isEmpty()) {
qDebug() << "empty document. skipping...";
return true;
}
switch(m_currentImageFormat) {
case SvgFormat:
m_imageWidget->setMode(PreviewWidget::SvgMode);
break;
case PngFormat:
m_imageWidget->setMode(PreviewWidget::PngMode);
break;
}
QString key = makeKeyForDocument(current_document);
// try the cache first
const FileCacheItem* item = qobject_cast<const FileCacheItem*>(m_cache->item(key));
if (item) {
QFile file(item->path());
if (file.open(QFile::ReadOnly)) {
QByteArray cache_image = file.readAll();
if (cache_image.size()) {
m_cachedImage = cache_image;
m_imageWidget->load(m_cachedImage);
statusBar()->showMessage(tr("Cache hit: %1").arg(key), STATUSBAR_TIMEOUT);
m_needsRefresh = false;
return true;
}
}
}
}
return false;
}
void MainWindow::refresh(bool forced)
{
if (m_process) {
qDebug() << "still processing previous refresh. skipping...";
return;
}
if (!m_needsRefresh && !forced) {
return;
}
if (!m_hasValidPaths) {
qDebug() << "Please configure paths for Java and PlantUML. Aborting...";
statusBar()->showMessage(tr("Java and/or PlantUML not found. Please set them correctly in the \"Preferences\" dialog!"));
return;
}
if (!forced && refreshFromCache()) {
return;
}
QByteArray current_document = m_editor->toPlainText().toUtf8().trimmed();
if (current_document.isEmpty()) {
qDebug() << "empty document. skipping...";
return;
}
m_needsRefresh = false;
switch(m_currentImageFormat) {
case SvgFormat:
m_imageWidget->setMode(PreviewWidget::SvgMode);
break;
case PngFormat:
m_imageWidget->setMode(PreviewWidget::PngMode);
break;
}
QString key = makeKeyForDocument(current_document);
statusBar()->showMessage(tr("Refreshing..."));
QStringList arguments;
arguments
<< "-jar" << m_plantUmlPath
<< QString("-t%1").arg(m_imageFormatNames[m_currentImageFormat]);
if (m_useCustomGraphiz)
arguments << "-graphvizdot" << m_graphizPath;
arguments << "-charset" << "UTF-8" << "-pipe";
m_lastKey = key;
m_process = new QProcess(this);
QFileInfo fi(m_documentPath);
m_process->setWorkingDirectory(fi.absolutePath());
m_process->start(m_javaPath, arguments);
if (!m_process->waitForStarted()) {
qDebug() << "refresh subprocess failed to start";
return;
}
connect(m_process, SIGNAL(finished(int)), this, SLOT(refreshFinished()));
m_process->write(current_document);
m_process->closeWriteChannel();
}
void MainWindow::updateCacheSizeInfo()
{
m_cacheSizeLabel->setText(m_useCache ?
tr(CACHE_SIZE_FORMAT_STRING).arg(cacheSizeToString(m_cache->totalCost())) :
tr("NO CACHE"));
}
void MainWindow::focusAssistant()
{
QListWidget* widget = qobject_cast<QListWidget*>(m_assistantToolBox->currentWidget());
if (widget) {
widget->setFocus();
if (widget->selectedItems().count() == 0) {
widget->setCurrentItem(widget->itemAt(0, 0));
}
}
}
void MainWindow::refreshFinished()
{
m_cachedImage = m_process->readAll();
m_imageWidget->load(m_cachedImage);
m_process->deleteLater();
m_process = 0;
if (m_useCache && m_cache) {
m_cache->addItem(m_cachedImage, m_lastKey,
[](const QString& path,
const QString& key,
int cost,
const QDateTime& date_time,
QObject* parent
) { return new FileCacheItem(path, key, cost, date_time, parent); });
updateCacheSizeInfo();
}
statusBar()->showMessage(tr("Refreshed"), STATUSBAR_TIMEOUT);
}
void MainWindow::changeImageFormat()
{
ImageFormat new_format;
if (m_pngPreviewAction->isChecked()) {
new_format = PngFormat;
} else {
new_format = SvgFormat;
}
if (new_format != m_currentImageFormat) {
m_currentImageFormat = new_format;
m_needsRefresh = true;
m_currentImageFormatLabel->setText(m_imageFormatNames[m_currentImageFormat].toUpper());
refresh();
}
}
void MainWindow::onAutoRefreshActionToggled(bool state)
{
if (state) {
refresh();
m_autoRefreshTimer->start();
} else {
m_autoRefreshTimer->stop();
}
m_autoRefreshLabel->setEnabled(state);
}
void MainWindow::onEditorChanged()
{
if (!refreshFromCache()) m_needsRefresh = true;
setWindowModified(true);
enableUndoRedoActions();
}
void MainWindow::onRefreshActionTriggered()
{
m_needsRefresh = true;
refresh(true);
}
void MainWindow::onPreferencesActionTriggered()
{
writeSettings();
PreferencesDialog dialog(m_cache, this);
dialog.readSettings();
dialog.exec();
if (dialog.result() == QDialog::Accepted) {
dialog.writeSettings();
readSettings(true);
}
}
void MainWindow::onOpenDocumentActionTriggered()
{
openDocument("");
}
void MainWindow::onSaveActionTriggered()
{
saveDocument(m_documentPath);
if (m_refreshOnSave)
onRefreshActionTriggered();
}
void MainWindow::onSaveAsActionTriggered()
{
saveDocument("");
}
void MainWindow::onExportImageActionTriggered()
{
exportImage(m_exportPath);
}
void MainWindow::onExportAsImageActionTriggered()
{
exportImage("");
}
void MainWindow::onRecentDocumentsActionTriggered(const QString &path)
{
openDocument(path);
}
void MainWindow::onAssistanItemDoubleClicked(QListWidgetItem *item)
{
insertAssistantCode(item->data(Qt::UserRole).toString());
m_editor->setFocus(); // force focus to move to the editor
}
void MainWindow::onSingleApplicationReceivedMessage(const QString &message)
{
// the message is a file to open
QtSingleApplication* single_app = qobject_cast<QtSingleApplication*>(qApp);
if (single_app) {
single_app->activateWindow();
qDebug() << "single instance activated";
}
if (!message.isEmpty()) {
qDebug() << "received request to open " << message << "from another instance";
openDocument(message);
}
}
void MainWindow::onAssistantFocus()
{
focusAssistant();
}
void MainWindow::onAssistantItemInsert(QWidget *widget)
{
QListWidget* list_widget = qobject_cast<QListWidget*>(widget);
if (list_widget) {
onAssistanItemDoubleClicked(list_widget->currentItem());
}
}
void MainWindow::onNextAssistant()
{
m_assistantToolBox->setCurrentIndex((m_assistantToolBox->currentIndex() + 1) % m_assistantToolBox->count());
}
void MainWindow::onPrevAssistant()
{
const int count = m_assistantToolBox->count();
m_assistantToolBox->setCurrentIndex((count + m_assistantToolBox->currentIndex() - 1) % count);
}
void MainWindow::onAssistantItemSelectionChanged()
{
QListWidget* widget = qobject_cast<QListWidget*>(m_assistantToolBox->currentWidget());
if (widget) {
QListWidgetItem* item = widget->currentItem();
if (item) {
QString notes = item->data(ASSISTANT_ITEM_NOTES_ROLE).toString();
m_assistantPreviewNotes->setText(notes.isEmpty() ?
tr("Code:") :
tr("Notes:<br>%1<br>Code:").arg(notes));
m_assistantCodePreview->setPlainText(item->data(ASSISTANT_ITEM_DATA_ROLE).toString());
}
}
}
void MainWindow::onCurrentAssistantChanged(int /*index*/)
{
focusAssistant();
onAssistantItemSelectionChanged(); // make sure we don't show stale info
}
void MainWindow::closeEvent(QCloseEvent *event)
{
if (maybeSave()) {
writeSettings();
event->accept();
} else {
event->ignore();
}
}
bool MainWindow::maybeSave()
{
if (m_editor->document()->isModified()) {
QMessageBox::StandardButton ret;
ret = QMessageBox::warning(this, qApp->applicationName(),
tr("The document has been modified.\n"
"Do you want to save your changes?"),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
if (ret == QMessageBox::Save)
return saveDocument(m_documentPath);
else if (ret == QMessageBox::Cancel)
return false;
}
return true;
}
void MainWindow::readSettings(bool reload)
{
#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
const QString DEFAULT_CACHE_PATH = QDesktopServices::storageLocation(QDesktopServices::CacheLocation);
#else
const QString DEFAULT_CACHE_PATH = QStandardPaths::writableLocation(QStandardPaths::CacheLocation);
#endif
QSettings settings;
settings.beginGroup(SETTINGS_MAIN_SECTION);
m_useCustomJava = settings.value(SETTINGS_USE_CUSTOM_JAVA, SETTINGS_USE_CUSTOM_JAVA_DEFAULT).toBool();
m_customJavaPath = settings.value(SETTINGS_CUSTOM_JAVA_PATH, SETTINGS_CUSTOM_JAVA_PATH_DEFAULT).toString();
m_javaPath = m_useCustomJava ? m_customJavaPath : SETTINGS_CUSTOM_JAVA_PATH_DEFAULT;
m_useCustomPlantUml = settings.value(SETTINGS_USE_CUSTOM_PLANTUML, SETTINGS_USE_CUSTOM_PLANTUML_DEFAULT).toBool();
m_customPlantUmlPath = settings.value(SETTINGS_CUSTOM_PLANTUML_PATH, SETTINGS_CUSTOM_PLANTUML_PATH_DEFAULT).toString();
m_plantUmlPath = m_useCustomPlantUml ? m_customPlantUmlPath : SETTINGS_CUSTOM_PLANTUML_PATH_DEFAULT;
m_useCustomGraphiz = settings.value(SETTINGS_USE_CUSTOM_GRAPHIZ, SETTINGS_USE_CUSTOM_GRAPHIZ_DEFAULT).toBool();
m_customGraphizPath = settings.value(SETTINGS_CUSTOM_GRAPHIZ_PATH, SETTINGS_CUSTOM_GRAPHIZ_PATH_DEFAULT).toString();
m_graphizPath = m_useCustomGraphiz ? m_customGraphizPath : SETTINGS_CUSTOM_GRAPHIZ_PATH_DEFAULT;
checkPaths();
m_useCache = settings.value(SETTINGS_USE_CACHE, SETTINGS_USE_CACHE_DEFAULT).toBool();
m_useCustomCache = settings.value(SETTINGS_USE_CUSTOM_CACHE, SETTINGS_USE_CUSTOM_CACHE_DEFAULT).toBool();
m_customCachePath = settings.value(SETTINGS_CUSTOM_CACHE_PATH, DEFAULT_CACHE_PATH).toString();
m_cacheMaxSize = settings.value(SETTINGS_CACHE_MAX_SIZE, SETTINGS_CACHE_MAX_SIZE_DEFAULT).toInt();
m_cachePath = m_useCustomCache ? m_customCachePath : DEFAULT_CACHE_PATH;
m_cache->setMaxCost(m_cacheMaxSize);
m_cache->setPath(m_cachePath, [](const QString& path,
const QString& key,
int cost,
const QDateTime& date_time,
QObject* parent
) { return new FileCacheItem(path, key, cost, date_time, parent); });
reloadAssistantXml(settings.value(SETTINGS_ASSISTANT_XML_PATH).toString());
const bool autorefresh_enabled = settings.value(SETTINGS_AUTOREFRESH_ENABLED, false).toBool();
m_autoRefreshAction->setChecked(autorefresh_enabled);
m_autoRefreshTimer->setInterval(settings.value(SETTINGS_AUTOREFRESH_TIMEOUT, SETTINGS_AUTOREFRESH_TIMEOUT_DEFAULT).toInt());
if (autorefresh_enabled) {
m_autoRefreshTimer->start();
}
m_autoRefreshLabel->setEnabled(autorefresh_enabled);
m_autoSaveImageAction->setChecked(settings.value(SETTINGS_AUTOSAVE_IMAGE_ENABLED, SETTINGS_AUTOSAVE_IMAGE_ENABLED_DEFAULT).toBool());
if (!reload) {
restoreGeometry(settings.value(SETTINGS_GEOMETRY).toByteArray());
restoreState(settings.value(SETTINGS_WINDOW_STATE).toByteArray());
}
m_showMainToolbarAction->setChecked(m_mainToolBar->isVisibleTo(this)); // NOTE: works even if the current window is not yet displayed
connect(m_showMainToolbarAction, SIGNAL(toggled(bool)), m_mainToolBar, SLOT(setVisible(bool)));
const bool show_statusbar = settings.value(SETTINGS_SHOW_STATUSBAR, true).toBool();
m_showStatusBarAction->setChecked(show_statusbar);
statusBar()->setVisible(show_statusbar);
connect(m_showStatusBarAction, SIGNAL(toggled(bool)), statusBar(), SLOT(setVisible(bool)));
m_currentImageFormat = m_imageFormatNames.key(settings.value(SETTINGS_IMAGE_FORMAT, m_imageFormatNames[SvgFormat]).toString());
if (m_currentImageFormat == SvgFormat) {
m_svgPreviewAction->setChecked(true);
} else if (m_currentImageFormat == PngFormat) {
m_pngPreviewAction->setChecked(true);
}
m_currentImageFormatLabel->setText(m_imageFormatNames[m_currentImageFormat].toUpper());
m_lastDir = settings.value(SETTINGS_EDITOR_LAST_DIR, SETTINGS_EDITOR_LAST_DIR_DEFAULT).toString();
settings.endGroup();
settings.beginGroup(SETTINGS_EDITOR_SECTION);
QFont defaultFont;
QFont editorFont;
editorFont.fromString(settings.value(SETTINGS_EDITOR_FONT,
defaultFont.toString()).toString());
m_editor->setFont(editorFont);
m_editor->setAutoIndent(settings.value(SETTINGS_EDITOR_INDENT, SETTINGS_EDITOR_INDENT_DEFAULT).toBool());
m_editor->setIndentWithSpace(settings.value(SETTINGS_EDITOR_INDENT_WITH_SPACE,
SETTINGS_EDITOR_INDENT_WITH_SPACE_DEFAULT).toBool());
m_editor->setIndentSize(settings.value(SETTINGS_EDITOR_INDENT_SIZE,
SETTINGS_EDITOR_INDENT_SIZE_DEFAULT).toInt());
m_refreshOnSave = settings.value(SETTINGS_EDITOR_REFRESH_ON_SAVE, SETTINGS_EDITOR_REFRESH_ON_SAVE_DEFAULT).toBool();
settings.endGroup();
m_recentDocuments->readFromSettings(settings, SETTINGS_RECENT_DOCUMENTS_SECTION);
updateCacheSizeInfo();
}
void MainWindow::writeSettings()
{
QSettings settings;
settings.beginGroup(SETTINGS_MAIN_SECTION);
settings.setValue(SETTINGS_USE_CUSTOM_JAVA, m_useCustomJava);
settings.setValue(SETTINGS_CUSTOM_JAVA_PATH, m_customJavaPath);
settings.setValue(SETTINGS_USE_CUSTOM_PLANTUML, m_useCustomPlantUml);
settings.setValue(SETTINGS_CUSTOM_PLANTUML_PATH, m_customPlantUmlPath);
settings.setValue(SETTINGS_USE_CUSTOM_GRAPHIZ, m_useCustomGraphiz);
settings.setValue(SETTINGS_CUSTOM_GRAPHIZ_PATH, m_customGraphizPath);
settings.setValue(SETTINGS_USE_CACHE, m_useCache);
settings.setValue(SETTINGS_USE_CUSTOM_CACHE, m_useCustomCache);
settings.setValue(SETTINGS_CUSTOM_CACHE_PATH, m_customCachePath);
settings.setValue(SETTINGS_CACHE_MAX_SIZE, m_cacheMaxSize);
settings.setValue(SETTINGS_ASSISTANT_XML_PATH, m_assistantXmlPath);
settings.setValue(SETTINGS_AUTOREFRESH_TIMEOUT, m_autoRefreshTimer->interval());
settings.setValue(SETTINGS_GEOMETRY, saveGeometry());
settings.setValue(SETTINGS_WINDOW_STATE, saveState());
settings.setValue(SETTINGS_SHOW_STATUSBAR, m_showStatusBarAction->isChecked());
settings.setValue(SETTINGS_AUTOREFRESH_ENABLED, m_autoRefreshAction->isChecked());
settings.setValue(SETTINGS_AUTOSAVE_IMAGE_ENABLED, m_autoSaveImageAction->isChecked());
settings.setValue(SETTINGS_IMAGE_FORMAT, m_imageFormatNames[m_currentImageFormat]);
settings.setValue(SETTINGS_EDITOR_LAST_DIR, m_lastDir);
settings.endGroup();
m_recentDocuments->writeToSettings(settings, SETTINGS_RECENT_DOCUMENTS_SECTION);
}
void MainWindow::openDocument(const QString &name)
{
if (!maybeSave()) {
return;
}
QString tmp_name = name;
if (tmp_name.isEmpty() || QFileInfo(tmp_name).exists() == false) {
tmp_name = QFileDialog::getOpenFileName(this,
tr("Select a file to open"),
m_lastDir,
"PlantUML (*.plantuml);; All Files (*.*)"
);
if (tmp_name.isEmpty()) {
return;
} else {
QFileInfo fi(tmp_name);
m_lastDir = fi.absolutePath();
}
}
QFile file(tmp_name);
if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
return;
}
m_editor->setPlainText(QString::fromUtf8(file.readAll()));
setWindowModified(false);
m_documentPath = tmp_name;
setWindowTitle(TITLE_FORMAT_STRING
.arg(QFileInfo(tmp_name).fileName())
.arg(qApp->applicationName())
);
m_needsRefresh = true;
refresh();
m_recentDocuments->accessing(tmp_name);
}
bool MainWindow::saveDocument(const QString &name)
{
QString file_path = name;
if (file_path.isEmpty()) {
file_path = QFileDialog::getSaveFileName(this,
tr("Select where to store the document"),
m_lastDir,
"PlantUML (*.plantuml);; All Files (*.*)"
);
if (file_path.isEmpty()) {
return false;
} else {
QFileInfo fi(file_path);
m_lastDir = fi.absolutePath();
}
}
qDebug() << "saving document in:" << file_path;
QFile file(file_path);
if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
file.write(m_editor->toPlainText().toUtf8());
file.close();
m_documentPath = file_path;
setWindowTitle(TITLE_FORMAT_STRING
.arg(QFileInfo(file_path).fileName())
.arg(qApp->applicationName())
);
statusBar()->showMessage(tr("Document save in %1").arg(file_path), STATUSBAR_TIMEOUT);
m_recentDocuments->accessing(file_path);
if (m_autoSaveImageAction->isChecked()) {
QFileInfo info(file_path);
QString image_path = QString("%1/%2.%3")
.arg(info.absolutePath())
.arg(info.baseName())
.arg(m_imageFormatNames[m_currentImageFormat])
;
qDebug() << "saving image in: " << image_path;
QFile image(image_path);
if (!image.open(QIODevice::WriteOnly | QIODevice::Text)) {
return false;
}
image.write(m_cachedImage);
image.close();
}
m_editor->document()->setModified(false);
setWindowModified(false);
return true;
}
void MainWindow::exportImage(const QString &name)
{
if (m_cachedImage.isEmpty()) {
qDebug() << "no image to export. aborting...";
return;
}
QFileInfo finfo(m_documentPath);
const QString docPathWithBaseFilename = finfo.absolutePath() + QDir::separator() + finfo.baseName();
QString tmp_name = name;
if (tmp_name.isEmpty()) {
tmp_name = QFileDialog::getSaveFileName(this,
tr("Select where to export the image"),
docPathWithBaseFilename,
"Image (*.svg *.png);; All Files (*.*)"
);
if (tmp_name.isEmpty()) {
return;
}
}
qDebug() << "exporting image in:" << tmp_name;
QFile file(tmp_name);
if (!file.open(QIODevice::WriteOnly)) {
return;
}
file.write(m_cachedImage);
m_exportImageAction->setText(tr(EXPORT_TO_MENU_FORMAT_STRING).arg(tmp_name));
m_exportPath = tmp_name;
QString short_tmp_name = QFileInfo(tmp_name).fileName();
statusBar()->showMessage(tr("Image exported in %1").arg(short_tmp_name), STATUSBAR_TIMEOUT);
m_exportPathLabel->setText(tr(EXPORT_TO_LABEL_FORMAT_STRING).arg(short_tmp_name));
m_exportPathLabel->setEnabled(true);
}
void MainWindow::createActions()
{
// File menu
m_newDocumentAction = new QAction(QIcon::fromTheme("document-new"), tr("&New"), this);
m_newDocumentAction->setShortcut(QKeySequence::New);
connect(m_newDocumentAction, SIGNAL(triggered()), this, SLOT(newDocument()));
m_openDocumentAction = new QAction(QIcon::fromTheme("document-open"), tr("&Open"), this);
m_openDocumentAction->setShortcuts(QKeySequence::Open);
connect(m_openDocumentAction, SIGNAL(triggered()), this, SLOT(onOpenDocumentActionTriggered()));
m_saveDocumentAction = new QAction(QIcon::fromTheme("document-save"), tr("&Save"), this);
m_saveDocumentAction->setShortcuts(QKeySequence::Save);
connect(m_saveDocumentAction, SIGNAL(triggered()), this, SLOT(onSaveActionTriggered()));
m_saveAsDocumentAction = new QAction(QIcon::fromTheme("document-save-as"), tr("Save As..."), this);
m_saveAsDocumentAction->setShortcuts(QKeySequence::SaveAs);
connect(m_saveAsDocumentAction, SIGNAL(triggered()), this, SLOT(onSaveAsActionTriggered()));
m_exportImageAction = new QAction(tr(EXPORT_TO_MENU_FORMAT_STRING).arg(""), this);
m_exportImageAction->setShortcut(Qt::CTRL + Qt::Key_E);
connect(m_exportImageAction, SIGNAL(triggered()), this, SLOT(onExportImageActionTriggered()));
m_exportAsImageAction = new QAction(tr("Export as ..."), this);
m_exportAsImageAction->setShortcut(Qt::CTRL + Qt::SHIFT + Qt::Key_E);
connect(m_exportAsImageAction, SIGNAL(triggered()), this, SLOT(onExportAsImageActionTriggered()));
m_quitAction = new QAction(QIcon::fromTheme("application-exit"), tr("&Quit"), this);
m_quitAction->setShortcuts(QKeySequence::Quit);
m_quitAction->setStatusTip(tr("Quit the application"));
connect(m_quitAction, SIGNAL(triggered()), this, SLOT(close()));
// Edit menu
m_undoAction = new QAction(QIcon::fromTheme("edit-undo"), tr("&Undo"), this);
m_undoAction->setShortcuts(QKeySequence::Undo);
connect(m_undoAction, SIGNAL(triggered()), this, SLOT(undo()));
m_redoAction = new QAction(QIcon::fromTheme("edit-redo"), tr("&Redo"), this);
m_redoAction->setShortcuts(QKeySequence::Redo);
connect(m_redoAction, SIGNAL(triggered()), this, SLOT(redo()));
m_copyImageAction = new QAction(QIcon::fromTheme("copy"), tr("&Copy Image"), this);
m_copyImageAction->setShortcuts(QList<QKeySequence>()
<< QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_C)
<< QKeySequence::Copy
);
connect(m_copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage()) );
// Tools menu
m_pngPreviewAction = new QAction(tr("PNG"), this);
m_pngPreviewAction->setCheckable(true);
m_pngPreviewAction->setStatusTip(tr("Tell PlantUML to produce PNG output"));
connect(m_pngPreviewAction, SIGNAL(toggled(bool)), this, SLOT(changeImageFormat()));
m_svgPreviewAction = new QAction(tr("SVG"), this);
m_svgPreviewAction->setCheckable(true);
m_svgPreviewAction->setStatusTip(tr("Tell PlantUML to produce SVG output"));
connect(m_svgPreviewAction, SIGNAL(toggled(bool)), this, SLOT(changeImageFormat()));
QActionGroup* output_action_group = new QActionGroup(this);
output_action_group->setExclusive(true);
output_action_group->addAction(m_pngPreviewAction);
output_action_group->addAction(m_svgPreviewAction);
m_svgPreviewAction->setChecked(true);
m_refreshAction = new QAction(QIcon::fromTheme("view-refresh"), tr("Refresh"), this);
m_refreshAction->setShortcuts(QKeySequence::Refresh);
m_refreshAction->setStatusTip(tr("Call PlantUML to regenerate the UML image"));
connect(m_refreshAction, SIGNAL(triggered()), this, SLOT(onRefreshActionTriggered()));
m_autoRefreshAction = new QAction(tr("Auto-Refresh"), this);
m_autoRefreshAction->setCheckable(true);
m_autoSaveImageAction = new QAction(tr("Auto-Save image"), this);
m_autoSaveImageAction->setCheckable(true);
connect(m_autoRefreshAction, SIGNAL(toggled(bool)), this, SLOT(onAutoRefreshActionToggled(bool)));
// Settings menu
m_showMainToolbarAction = new QAction(tr("Show toolbar"), this);
m_showMainToolbarAction->setCheckable(true);
m_showStatusBarAction = new QAction(tr("Show statusbar"), this);
m_showStatusBarAction->setCheckable(true);
m_preferencesAction = new QAction(QIcon::fromTheme("preferences-other"), tr("Preferences"), this);
connect(m_preferencesAction, SIGNAL(triggered()), this, SLOT(onPreferencesActionTriggered()));
// Help menu
m_aboutAction = new QAction(QIcon::fromTheme("help-about"), tr("&About"), this);
m_aboutAction->setStatusTip(tr("Show the application's About box"));
connect(m_aboutAction, SIGNAL(triggered()), this, SLOT(about()));
m_aboutQtAction = new QAction(tr("About &Qt"), this);
m_aboutQtAction->setStatusTip(tr("Show the Qt library's About box"));
connect(m_aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
// focus actions
QAction* focus_action = new QAction(this);
focus_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_0));
connect(focus_action, SIGNAL(triggered()), m_editor, SLOT(setFocus()));
this->addAction(focus_action);
focus_action = new QAction(this);
focus_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_1));
connect(focus_action, SIGNAL(triggered()), this, SLOT(onAssistantFocus()));
this->addAction(focus_action);
// assistant actions
QAction* navigation_action = new QAction(this);
navigation_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Down));
connect(navigation_action, SIGNAL(triggered()), this, SLOT(onNextAssistant()));
addAction(navigation_action);
navigation_action = new QAction(this);
navigation_action->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Up));
connect(navigation_action, SIGNAL(triggered()), this, SLOT(onPrevAssistant()));
addAction(navigation_action);
// zoom action
m_zoomInAction = new QAction(QIcon::fromTheme("zoom-in"), tr("Zoom In"), this);
connect(m_zoomInAction, SIGNAL(triggered()), m_imageWidget, SLOT(zoomIn()));
m_zoomOutAction = new QAction(QIcon::fromTheme("zoom-out"), tr("Zoom Out"), this);
connect(m_zoomOutAction, SIGNAL(triggered()), m_imageWidget, SLOT(zoomOut()));
m_zoomOriginalAction = new QAction(QIcon::fromTheme("zoom-original"), tr("1:1"), this);
connect(m_zoomOriginalAction, SIGNAL(triggered()), m_imageWidget, SLOT(zoomOriginal()));
}
void MainWindow::createMenus()
{
m_fileMenu = menuBar()->addMenu(tr("&File"));
m_fileMenu->addAction(m_newDocumentAction);
m_fileMenu->addAction(m_openDocumentAction);
m_fileMenu->addAction(m_saveDocumentAction);
m_fileMenu->addAction(m_saveAsDocumentAction);
m_fileMenu->addSeparator();
QMenu *recent_documents_submenu = m_fileMenu->addMenu(tr("Recent Documents"));
recent_documents_submenu->addActions(m_recentDocuments->actions());
m_fileMenu->addSeparator();
m_fileMenu->addAction(m_exportImageAction);
m_fileMenu->addAction(m_exportAsImageAction);
m_fileMenu->addSeparator();
m_fileMenu->addAction(m_quitAction);
m_editMenu = menuBar()->addMenu(tr("&Edit"));
m_editMenu->addAction(m_undoAction);
m_editMenu->addAction(m_redoAction);
m_editMenu->addAction(m_copyImageAction);
m_editMenu->addSeparator();
m_editMenu->addAction(m_refreshAction);
m_settingsMenu = menuBar()->addMenu(tr("&Settings"));
m_settingsMenu->addAction(m_showMainToolbarAction);
m_settingsMenu->addAction(m_showStatusBarAction);
m_settingsMenu->addSeparator();
m_settingsMenu->addAction(m_showAssistantDockAction);
m_settingsMenu->addAction(m_showAssistantInfoDockAction);
m_settingsMenu->addAction(m_showEditorDockAction);
m_settingsMenu->addSeparator();
m_settingsMenu->addAction(m_pngPreviewAction);
m_settingsMenu->addAction(m_svgPreviewAction);
m_settingsMenu->addSeparator();
m_settingsMenu->addAction(m_autoRefreshAction);
m_settingsMenu->addAction(m_autoSaveImageAction);
m_settingsMenu->addSeparator();
m_settingsMenu->addAction(m_preferencesAction);
m_zoomMenu = menuBar()->addMenu(tr("&Zoom"));
addZoomActions(m_zoomMenu);
menuBar()->addSeparator();
m_helpMenu = menuBar()->addMenu(tr("&Help"));
m_helpMenu->addAction(m_aboutAction);
m_helpMenu->addAction(m_aboutQtAction);
}
void MainWindow::createToolBars()
{
m_mainToolBar = addToolBar(tr("MainToolbar"));
m_mainToolBar->setObjectName("main_toolbar");
m_mainToolBar->addAction(m_newDocumentAction);
m_mainToolBar->addAction(m_openDocumentAction);