forked from KDE/ghostwriter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDocumentManager.cpp
More file actions
882 lines (756 loc) · 22 KB
/
Copy pathDocumentManager.cpp
File metadata and controls
882 lines (756 loc) · 22 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
/***********************************************************************
*
* Copyright (C) 2014-2020 wereturtle
*
* This program 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.
*
* This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*
***********************************************************************/
#include <QApplication>
#include <QDir>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QFileSystemWatcher>
#include <QFuture>
#include <QFutureWatcher>
#include <QMessageBox>
#include <QPair>
#include <QString>
#include <QtConcurrentRun>
#include <QTextDocument>
#include <QTextStream>
#include <QTimer>
#include "DocumentHistory.h"
#include "DocumentManager.h"
#include "ExportDialog.h"
#include "Exporter.h"
#include "ExporterFactory.h"
#include "MarkdownDocument.h"
#include "MarkdownEditor.h"
#include "MessageBoxHelper.h"
#include "ThemeFactory.h"
const QString DocumentManager::FILE_CHOOSER_FILTER =
QString("%1 (*.md *.markdown *.txt);;%2 (*.txt);;%3 (*)")
.arg(QObject::tr("Markdown"))
.arg(QObject::tr("Text"))
.arg(QObject::tr("All"));
DocumentManager::DocumentManager
(
MarkdownEditor* editor,
Outline* outline,
DocumentStatistics* documentStats,
SessionStatistics* sessionStats,
QWidget* parent
)
: QObject(parent), parentWidget(parent), editor(editor),
outline(outline), documentStats(documentStats),
sessionStats(sessionStats), fileHistoryEnabled(true),
createBackupOnSave(true), saveInProgress(false),
autoSaveEnabled(false), documentModifiedNotifVisible(false)
{
saveFutureWatcher = new QFutureWatcher<QString>(this);
fileWatcher = new QFileSystemWatcher(this);
document = (MarkdownDocument*) editor->document();
connect(document, SIGNAL(modificationChanged(bool)), this, SLOT(onDocumentModifiedChanged(bool)));
// Set up auto-save timer to save the file once every minute.
autoSaveTimer = new QTimer(this);
autoSaveTimer->start(60000);
connect
(
autoSaveTimer,
SIGNAL(timeout()),
this,
SLOT(autoSaveFile())
);
connect(saveFutureWatcher, SIGNAL(finished()), this, SLOT(onSaveCompleted()));
connect(fileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(onFileChangedExternally(QString)));
}
DocumentManager::~DocumentManager()
{
this->saveFutureWatcher->waitForFinished();
}
MarkdownDocument* DocumentManager::getDocument() const
{
return this->document;
}
bool DocumentManager::getAutoSaveEnabled() const
{
return autoSaveEnabled;
}
bool DocumentManager::getFileBackupEnabled() const
{
return createBackupOnSave;
}
void DocumentManager::setFileHistoryEnabled(bool enabled)
{
fileHistoryEnabled = enabled;
}
void DocumentManager::setAutoSaveEnabled(bool enabled)
{
autoSaveEnabled = enabled;
if (enabled)
{
emit documentModifiedChanged(false);
}
else if (document->isModified())
{
document->setModified(false);
}
}
void DocumentManager::setFileBackupEnabled(bool enabled)
{
this->createBackupOnSave = enabled;
}
void DocumentManager::open(const QString& filePath)
{
if (checkSaveChanges())
{
QString path;
if (!filePath.isNull() && !filePath.isEmpty())
{
path = filePath;
}
else
{
QString startingDirectory = QString();
if (!document->isNew())
{
startingDirectory = QFileInfo(document->getFilePath()).dir().path();
}
path =
QFileDialog::getOpenFileName
(
parentWidget,
tr("Open File"),
startingDirectory,
FILE_CHOOSER_FILTER
);
}
if (!path.isNull() && !path.isEmpty())
{
QFileInfo fileInfo(path);
if (!fileInfo.isReadable())
{
MessageBoxHelper::critical
(
parentWidget,
tr("Could not open %1").arg(path),
tr("Permission denied.")
);
return;
}
QString oldFilePath = document->getFilePath();
int oldCursorPosition = editor->textCursor().position();
bool oldFileWasNew = document->isNew();
if (!loadFile(path))
{
// The error dialog should already have been displayed
// in loadFile().
//
return;
}
else if (oldFilePath == document->getFilePath())
{
editor->navigateDocument(oldCursorPosition);
}
else if (fileHistoryEnabled)
{
if (!oldFileWasNew)
{
DocumentHistory history;
history.add
(
oldFilePath,
oldCursorPosition
);
}
// Always emit a documentClosed() signal, even if the document
// was new and untitled. This is so that if a file from the
// displayed history is being loaded, its path will be
// guaranteed to be removed from the "Open Recent" file list
// displayed to the user (because it's already opened).
//
emit documentClosed();
}
}
}
}
void DocumentManager::reopenLastClosedFile()
{
if (fileHistoryEnabled)
{
DocumentHistory history;
QStringList recentFiles = history.getRecentFiles(2);
if (!document->isNew())
{
recentFiles.removeAll(document->getFilePath());
}
if (!recentFiles.isEmpty())
{
open(recentFiles.first());
emit documentClosed();
}
}
}
void DocumentManager::reload()
{
if (!document->isNew())
{
if (document->isModified())
{
// Prompt user if he wants to save changes.
int response =
MessageBoxHelper::question
(
parentWidget,
tr("The document has been modified."),
tr("Discard changes?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No
);
if (QMessageBox::No == response)
{
return;
}
}
QTextCursor cursor = editor->textCursor();
int pos = cursor.position();
if (loadFile(document->getFilePath()))
{
cursor.setPosition(pos);
editor->setTextCursor(cursor);
}
}
}
void DocumentManager::rename()
{
if (document->isNew())
{
saveAs();
}
else
{
QString filePath =
QFileDialog::getSaveFileName
(
parentWidget,
tr("Rename File"),
QString(),
FILE_CHOOSER_FILTER
);
if (!filePath.isNull() && !filePath.isEmpty())
{
QFile file(document->getFilePath());
bool success = file.rename(filePath);
if (!success)
{
MessageBoxHelper::critical
(
parentWidget,
tr("Failed to rename %1").arg(document->getFilePath()),
file.errorString()
);
return;
}
setFilePath(filePath);
save();
}
}
}
bool DocumentManager::save()
{
if (document->isNew() || !checkPermissionsBeforeSave())
{
return saveAs();
}
else
{
saveFile();
return true;
}
}
bool DocumentManager::saveAs()
{
QString startingDirectory = QString();
if (!document->isNew())
{
startingDirectory = QFileInfo(document->getFilePath()).dir().path();
}
QString filePath =
QFileDialog::getSaveFileName
(
parentWidget,
tr("Save File"),
startingDirectory,
FILE_CHOOSER_FILTER
);
if (!filePath.isNull() && !filePath.isEmpty())
{
setFilePath(filePath);
saveFile();
return true;
}
return false;
}
bool DocumentManager::close()
{
if (checkSaveChanges())
{
if (saveFutureWatcher->isRunning() || saveFutureWatcher->isStarted())
{
this->saveFutureWatcher->waitForFinished();
}
// Get the document's information before closing it out
// so we can store history information about it.
//
QString filePath = document->getFilePath();
int cursorPosition = editor->textCursor().position();
bool documentIsNew = document->isNew();
// Set up a new, untitled document. Note that the document
// needs to be wiped clean before emitting the documentClosed()
// signal, because slots accepting this signal may check the
// new (replacement) document's status.
//
// NOTE: Must set editor's text cursor to the beginning
// of the document before clearing the document/editor
// of text to prevent a crash in Qt 5.10 on opening or
// reloading a file if a file has already been previously
// opened in the editor.
//
QTextCursor cursor(document);
cursor.setPosition(0);
editor->setTextCursor(cursor);
document->setPlainText("");
document->clearUndoRedoStacks();
editor->setReadOnly(false);
document->setReadOnly(false);
setFilePath(QString());
document->setModified(false);
sessionStats->startNewSession(0);
if (fileHistoryEnabled && !documentIsNew)
{
DocumentHistory history;
history.add
(
filePath,
cursorPosition
);
emit documentClosed();
}
return true;
}
return false;
}
void DocumentManager::exportFile()
{
ExportDialog exportDialog(document);
connect(&exportDialog, SIGNAL(exportStarted(QString)), this, SIGNAL(operationStarted(QString)));
connect(&exportDialog, SIGNAL(exportComplete()), this, SIGNAL(operationFinished()));
exportDialog.exec();
}
void DocumentManager::onDocumentModifiedChanged(bool modified)
{
if (document->isNew() || document->isReadOnly() || !autoSaveEnabled)
{
emit documentModifiedChanged(modified);
}
}
void DocumentManager::onSaveCompleted()
{
QString err = this->saveFutureWatcher->result();
if (!err.isNull() && !err.isEmpty())
{
MessageBoxHelper::critical
(
parentWidget,
tr("Error saving %1").arg(document->getFilePath()),
err
);
}
else if (!fileWatcher->files().contains(document->getFilePath()))
{
fileWatcher->addPath(document->getFilePath());
}
document->setTimestamp(QDateTime::currentDateTime());
saveInProgress = false;
}
void DocumentManager::onFileChangedExternally(const QString& path)
{
QFileInfo fileInfo(path);
if (!fileInfo.exists())
{
emit documentModifiedChanged(true);
// Make sure autosave knows the document is modified so it can
// save it.
//
document->setModified(true);
}
else
{
if (fileInfo.isWritable() && document->isReadOnly())
{
document->setReadOnly(false);
if (autoSaveEnabled)
{
emit documentModifiedChanged(false);
}
}
else if (!fileInfo.isWritable() && !document->isReadOnly())
{
document->setReadOnly(true);
if (document->isModified())
{
emit documentModifiedChanged(true);
}
}
// Need to guard against the QFileSystemWatcher from signalling a
// file change when we're the one who changed the file by saving.
// Thus, check the saveInProgress flag before prompting.
//
if
(
!saveInProgress &&
(fileInfo.lastModified() > document->getTimestamp()) &&
!documentModifiedNotifVisible
)
{
documentModifiedNotifVisible = true;
int response =
MessageBoxHelper::question
(
parentWidget,
tr("The document has been modified by another program."),
tr("Would you like to reload the document?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes
);
documentModifiedNotifVisible = false;
if (QMessageBox::Yes == response)
{
reload();
}
}
}
}
void DocumentManager::autoSaveFile()
{
if
(
autoSaveEnabled &&
!document->isNew() &&
!document->isReadOnly() &&
document->isModified()
)
{
save();
}
}
void DocumentManager::saveFile()
{
document->setModified(false);
emit documentModifiedChanged(false);
if
(
this->saveFutureWatcher->isRunning() ||
this->saveFutureWatcher->isStarted()
)
{
this->saveFutureWatcher->waitForFinished();
}
saveInProgress = true;
if (fileWatcher->files().contains(document->getFilePath()))
{
this->fileWatcher->removePath(document->getFilePath());
}
document->setTimestamp(QDateTime::currentDateTime());
QFuture<QString> future =
QtConcurrent::run
(
this,
&DocumentManager::saveToDisk,
document->getFilePath(),
document->toPlainText(),
createBackupOnSave
);
this->saveFutureWatcher->setFuture(future);
}
bool DocumentManager::loadFile(const QString& filePath)
{
QFileInfo fileInfo(filePath);
QFile inputFile(filePath);
if (!inputFile.open(QIODevice::ReadOnly))
{
MessageBoxHelper::critical
(
parentWidget,
tr("Could not read %1").arg(filePath),
inputFile.errorString()
);
return false;
}
outline->clear();
// NOTE: Must set editor's text cursor to the beginning
// of the document before clearing the document/editor
// of text to prevent a crash in Qt 5.10 on opening or
// reloading a file if a file has already been previously
// opened in the editor.
//
QTextCursor cursor(document);
cursor.setPosition(0);
editor->setTextCursor(cursor);
document->clearUndoRedoStacks();
document->setUndoRedoEnabled(false);
document->setPlainText("");
QApplication::setOverrideCursor(Qt::WaitCursor);
emit operationStarted(tr("opening %1").arg(filePath));
QTextStream inStream(&inputFile);
// Markdown files need to be in UTF-8 format, so assume that is
// what the user is opening by default. Enable autodection
// of of UTF-16 or UTF-32 BOM in case the file isn't UTF-8 encoded.
//
inStream.setCodec("UTF-8");
inStream.setAutoDetectUnicode(true);
QString text = inStream.readAll();
editor->setPlainText(text);
editor->navigateDocument(0);
emit operationUpdate();
document->setUndoRedoEnabled(true);
if (QFile::NoError != inputFile.error())
{
MessageBoxHelper::critical
(
parentWidget,
tr("Could not read %1").arg(filePath),
inputFile.errorString()
);
inputFile.close();
return false;
}
inputFile.close();
if (fileHistoryEnabled)
{
DocumentHistory history;
editor->navigateDocument(history.getCursorPosition(filePath));
}
else
{
editor->navigateDocument(0);
}
setFilePath(filePath);
editor->setReadOnly(false);
if (!fileInfo.isWritable())
{
document->setReadOnly(true);
}
else
{
document->setReadOnly(false);
}
document->setModified(false);
document->setTimestamp(fileInfo.lastModified());
QString watchedFile;
foreach (watchedFile, fileWatcher->files())
{
fileWatcher->removePath(watchedFile);
}
fileWatcher->addPath(filePath);
emit operationFinished();
emit documentModifiedChanged(false);
QApplication::restoreOverrideCursor();
editor->centerCursor();
sessionStats->startNewSession(documentStats->getWordCount());
return true;
}
void DocumentManager::setFilePath(const QString& filePath)
{
if (!document->isNew())
{
fileWatcher->removePath(document->getFilePath());
}
document->setFilePath(filePath);
if (!filePath.isNull() && !filePath.isEmpty())
{
QFileInfo fileInfo(filePath);
if (fileInfo.exists())
{
document->setReadOnly(!fileInfo.isWritable());
}
else
{
document->setReadOnly(false);
}
}
else
{
document->setReadOnly(false);
}
emit documentDisplayNameChanged(document->getDisplayName());
}
bool DocumentManager::checkSaveChanges()
{
if (document->isModified())
{
if (autoSaveEnabled && !document->isNew() && !document->isReadOnly())
{
return save();
}
else
{
// Prompt user if he wants to save changes.
QString text;
if (document->isNew())
{
text = tr("File has been modified.");
}
else
{
text = (tr("%1 has been modified.")
.arg(document->getDisplayName()));
}
int response =
MessageBoxHelper::question
(
parentWidget,
text,
tr("Would you like to save your changes?"),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,
QMessageBox::Save
);
switch (response)
{
case QMessageBox::Save:
if (document->isNew())
{
return saveAs();
}
else
{
return save();
}
break;
case QMessageBox::Cancel:
return false;
default:
break;
}
}
}
return true;
}
bool DocumentManager::checkPermissionsBeforeSave()
{
if (document->isReadOnly())
{
int response =
MessageBoxHelper::question
(
parentWidget,
tr("%1 is read only.").arg(document->getFilePath()),
tr("Overwrite protected file?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::Yes
);
if (QMessageBox::No == response)
{
return false;
}
else
{
QFile file(document->getFilePath());
fileWatcher->removePath(document->getFilePath());
if (!file.remove())
{
if (file.setPermissions(QFile::WriteUser | QFile::ReadUser) && file.remove())
{
document->setReadOnly(false);
return true;
}
else
{
MessageBoxHelper::critical
(
parentWidget,
tr("Overwrite failed."),
tr("Please save file to another location.")
);
fileWatcher->addPath(document->getFilePath());
return false;
}
}
else
{
document->setReadOnly(false);
}
}
}
return true;
}
QString DocumentManager::saveToDisk
(
const QString& filePath,
const QString& text,
bool createBackup
) const
{
QString err;
if (filePath.isNull() || filePath.isEmpty())
{
return QObject::tr("Null or empty file path provided for writing.");
}
QFile outputFile(filePath);
if (createBackup && outputFile.exists())
{
backupFile(filePath);
}
if (!outputFile.open(QIODevice::WriteOnly | QIODevice::Truncate | QIODevice::Text))
{
return outputFile.errorString();
}
// Write contents to disk.
QTextStream outStream(&outputFile);
// Markdown files need to be in UTF-8, since most Markdown processors
// (i.e., Pandoc, et. al.) can only read UTF-8 encoded text files.
//
outStream.setCodec("UTF-8");
outStream << text;
if (QFile::NoError != outputFile.error())
{
err = outputFile.errorString();
}
// Close the file. All done!
outputFile.close();
return err;
}
void DocumentManager::backupFile(const QString& filePath) const
{
QString backupFilePath = filePath + ".backup";
QFile backupFile(backupFilePath);
if (backupFile.exists())
{
if (!backupFile.remove())
{
qCritical("Could not remove backup file %s before saving: %s",
backupFilePath.toLatin1().data(),
backupFile.errorString().toLatin1().data());
return;
}
}
QFile file(filePath);
if (!file.copy(backupFilePath))
{
qCritical("Failed to backup file to %s: %s",
backupFilePath.toLatin1().data(),
file.errorString().toLatin1().data());
}
}