1 /*
2     SPDX-FileCopyrightText: 2020 Mladen Milinkovic <max@smoothware.net>
3 
4     SPDX-License-Identifier: GPL-2.0-or-later
5 */
6 
7 #ifndef RICHDOCUMENT_H
8 #define RICHDOCUMENT_H
9 
10 #include "core/sstring.h"
11 
12 #include <QTextBlock>
13 #include <QTextCursor>
14 #include <QTextDocument>
15 #include <QObject>
16 #include <QPalette>
17 
18 QT_FORWARD_DECLARE_CLASS(QStyle)
QT_FORWARD_DECLARE_CLASS(QStyleOptionViewItem)19 QT_FORWARD_DECLARE_CLASS(QStyleOptionViewItem)
20 
21 namespace SubtitleComposer {
22 
23 class RichDocument : public QTextDocument
24 {
25 	Q_OBJECT
26 
27 public:
28 	explicit RichDocument(QObject *parent=nullptr);
29 	virtual ~RichDocument();
30 
31 	SString toRichText() const;
32 	void setRichText(const SString &text, bool resetUndo=false);
33 
34 	QString toHtml() const;
35 	void setHtml(const QString &html, bool resetUndo=false);
36 
37 	void setPlainText(const QString &text, bool resetUndo=false);
38 
39 	void setDocument(const QTextDocument *doc, bool resetUndo=false);
40 
41 	void clear(bool resetUndo);
42 	inline void clear() override { clear(false); }
43 
44 	inline int length() const { const QTextBlock &b = lastBlock(); return b.position() + b.length(); }
45 
46 	void replace(const QRegularExpression &search, const QString &replacement, bool replacementIsHtml=true);
47 	void replace(QChar before, QChar after, Qt::CaseSensitivity cs = Qt::CaseSensitive);
48 	void replace(int index, int len, const QString &replacement);
49 	int indexOf(const QRegularExpression &re, int from = 0);
50 	int cummulativeStyleFlags() const;
51 	QRgb styleColorAt(int index) const;
52 
53 	void cleanupSpaces();
54 	void fixPunctuation(bool spaces, bool quotes, bool englishI, bool ellipsis, bool *cont, bool testOnly=false);
55 	void toLower();
56 	void toUpper();
57 	void toSentenceCase(bool *isSentenceStart, bool convertLowerCase=true, bool titleCase=false, bool testOnly=false);
58 	void breakText(int minBreakLength);
59 
60 	inline QTextCursor *undoableCursor() { return &m_undoableCursor; }
61 
62 public slots:
63 	inline void undo() { QTextDocument::undo(&m_undoableCursor); }
64 	inline void redo() { QTextDocument::redo(&m_undoableCursor); }
65 
66 private:
67 	inline void setUndoRedoEnabled(bool enable) { QTextDocument::setUndoRedoEnabled(enable); }
68 	inline int length(int index, int len) const { const int dl = length(); return len < 0 || (index + len) > dl ? dl - index : len; }
69 	void linesToBlocks();
70 
71 private:
72 	QTextCursor m_undoableCursor;
73 
74 	void applyChanges(const void *changeList);
75 
76 	Q_DISABLE_COPY(RichDocument)
77 };
78 
79 }
80 
81 #endif // RICHDOCUMENT_H
82