summaryrefslogtreecommitdiff
path: root/src/texteditor.cpp
blob: e015dc910953d151a26bc38ffbefcce780c900a7 (plain)
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
#include "texteditor.h"
#include "utility.h"
#include <QSplitter>
#include <log.h>

using namespace MOBase;

TextEditor::TextEditor(QWidget* parent)
    : QPlainTextEdit(parent), m_toolbar(nullptr), m_lineNumbers(nullptr),
      m_highlighter(nullptr), m_dirty(false), m_loading(false)
{
  m_toolbar     = new TextEditorToolbar(*this);
  m_lineNumbers = new TextEditorLineNumbers(*this);
  m_highlighter = new TextEditorHighlighter(document());

  setDefaultStyle();
  wordWrap(true);

  emit modified(false);

  connect(document(), &QTextDocument::modificationChanged, [&](bool b) {
    onModified(b);
  });

  connect(this, &QPlainTextEdit::cursorPositionChanged, [&] {
    highlightCurrentLine();
  });
}

void TextEditor::setDefaultStyle()
{
  const auto font = QFontDatabase::systemFont(QFontDatabase::FixedFont);

  setFont(font);
  m_lineNumbers->setFont(font);

  QColor textColor(Qt::black);
  QColor altTextColor(Qt::darkGray);
  QColor backgroundColor(Qt::white);

  {
    auto w = std::make_unique<QWidget>();

    if (auto* s = style()) {
      s->polish(w.get());
    }

    textColor       = w->palette().color(QPalette::WindowText);
    altTextColor    = w->palette().color(QPalette::Disabled, QPalette::WindowText);
    backgroundColor = w->palette().color(QPalette::Window);
  }

  setTextColor(textColor);
  m_lineNumbers->setTextColor(altTextColor);

  setBackgroundColor(backgroundColor);
  m_lineNumbers->setBackgroundColor(backgroundColor);

  setHighlightBackgroundColor(backgroundColor);
}

void TextEditor::clear()
{
  QScopedValueRollback loading(m_loading, true);

  m_filename.clear();
  m_encoding.clear();
  m_needsBOM = false;
  setPlainText("");
  dirty(false);
  document()->setModified(false);

  emit loaded("");
}

bool TextEditor::load(const QString& filename)
{
  clear();

  QScopedValueRollback loading(m_loading, true);

  m_filename = filename;

  const QString s = MOBase::readFileText(filename, &m_encoding, &m_needsBOM);

  setPlainText(s);
  document()->setModified(false);

  if (s.isEmpty()) {
    // the modificationChanged even is not fired by the setModified() call
    // above when the text being set is empty
    onModified(false);
  }

  emit loaded(m_filename);

  return true;
}

bool TextEditor::save()
{
  if (m_filename.isEmpty() || m_encoding.isEmpty()) {
    return false;
  }

  QFile file(m_filename);
  file.open(QIODevice::WriteOnly);
  file.resize(0);

  auto codec = QStringConverter::encodingForName(m_encoding.toUtf8());
  if (!codec.has_value())
    return false;
  QStringConverter::Flags flags = QStringEncoder::Flag::Default;
  if (m_needsBOM)
    flags |= QStringConverter::Flag::WriteBom;
  QStringEncoder encoder(codec.value(), flags);

  QString data = toPlainText().replace("\n", "\r\n");

  file.write(encoder.encode(data));
  document()->setModified(false);

  return true;
}

const QString& TextEditor::filename() const
{
  return m_filename;
}

void TextEditor::wordWrap(bool b)
{
  if (b) {
    setLineWrapMode(QPlainTextEdit::WidgetWidth);
  } else {
    setLineWrapMode(QPlainTextEdit::NoWrap);
  }

  emit wordWrapChanged(b);
}

void TextEditor::toggleWordWrap()
{
  wordWrap(!wordWrap());
}

bool TextEditor::wordWrap() const
{
  return (lineWrapMode() == QPlainTextEdit::WidgetWidth);
}

void TextEditor::dirty(bool b)
{
  m_dirty = b;
}

bool TextEditor::dirty() const
{
  return m_dirty;
}

QColor TextEditor::backgroundColor() const
{
  return m_highlighter->backgroundColor();
}

void TextEditor::setBackgroundColor(const QColor& c)
{
  if (m_highlighter->backgroundColor() == c) {
    return;
  }

  m_highlighter->setBackgroundColor(c);

  setStyleSheet(QString("QPlainTextEdit{ background-color: rgba(%1, %2, %3, %4); }")
                    .arg(c.redF() * 255)
                    .arg(c.greenF() * 255)
                    .arg(c.blueF() * 255)
                    .arg(c.alphaF()));
}

QColor TextEditor::textColor() const
{
  return m_highlighter->textColor();
}

void TextEditor::setTextColor(const QColor& c)
{
  m_highlighter->setTextColor(c);
}

QColor TextEditor::highlightBackgroundColor() const
{
  return m_highlightBackground;
}

void TextEditor::setHighlightBackgroundColor(const QColor& c)
{
  m_highlightBackground = c;
  update();
}

void TextEditor::explore()
{
  if (m_filename.isEmpty()) {
    return;
  }

  shell::Explore(m_filename);
}

void TextEditor::onModified(bool b)
{
  if (m_loading) {
    return;
  }

  dirty(b);
  emit modified(b);
}

void TextEditor::setupToolbar()
{
  auto* widget = wrapEditWidget();
  if (!widget) {
    return;
  }

  auto* layout = new QVBoxLayout(widget);

  // adding toolbar and edit
  layout->addWidget(m_toolbar);
  layout->addWidget(this);

  // make the edit stretch
  layout->setStretch(0, 0);
  layout->setStretch(1, 1);

  // visuals
  layout->setContentsMargins(0, 0, 0, 0);
  widget->show();
}

QWidget* TextEditor::wrapEditWidget()
{
  auto widget = std::make_unique<QWidget>();

  // wrapping the QPlainTextEdit into a new widget so the toolbar can be
  // displayed above it

  if (auto* parentLayout = parentWidget()->layout()) {
    // the edit's parent has a regular layout, replace the edit by the new
    // widget and delete the QLayoutItem that's returned as it's not needed
    delete parentLayout->replaceWidget(this, widget.get());

  } else if (auto* splitter = qobject_cast<QSplitter*>(parentWidget())) {
    // the edit's parent is a QSplitter, which doesn't have a layout; replace
    // the edit by using its index in the splitter
    auto index = splitter->indexOf(this);

    if (index == -1) {
      log::error("TextEditor: cannot wrap edit widget to display a toolbar, "
                 "parent is a splitter, but widget isn't in it");

      return nullptr;
    }

    splitter->replaceWidget(index, widget.get());

  } else {
    // unknown parent
    log::error("TextEditor: cannot wrap edit widget to display a toolbar, "
               "no parent or parent has no layout");

    return nullptr;
  }

  return widget.release();
}

void TextEditor::resizeEvent(QResizeEvent* e)
{
  QPlainTextEdit::resizeEvent(e);

  QRect cr = contentsRect();
  m_lineNumbers->setGeometry(
      QRect(cr.left(), cr.top(), m_lineNumbers->areaWidth(), cr.height()));
}

void TextEditor::paintLineNumbers(QPaintEvent* e, const QColor& textColor)
{
  QStyleOption opt;
  opt.initFrom(m_lineNumbers);

  QPainter painter(m_lineNumbers);

  QTextBlock block = firstVisibleBlock();
  int blockNumber  = block.blockNumber();
  int top    = (int)blockBoundingGeometry(block).translated(contentOffset()).top();
  int bottom = top + (int)blockBoundingRect(block).height();

  while (block.isValid() && top <= e->rect().bottom()) {
    if (block.isVisible() && bottom >= e->rect().top()) {
      QString number = QString::number(blockNumber + 1);
      painter.setPen(textColor);

      painter.drawText(0, top, m_lineNumbers->width() - 3, fontMetrics().height(),
                       Qt::AlignRight, number);
    }

    block  = block.next();
    top    = bottom;
    bottom = top + (int)blockBoundingRect(block).height();
    ++blockNumber;
  }
}

void TextEditor::highlightCurrentLine()
{
  QList<QTextEdit::ExtraSelection> extraSelections;

  if (!isReadOnly()) {
    QTextEdit::ExtraSelection selection;

    QColor lineColor = QColor(Qt::yellow).lighter(160);

    selection.format.setBackground(m_highlightBackground);
    selection.format.setProperty(QTextFormat::FullWidthSelection, true);
    selection.cursor = textCursor();
    selection.cursor.clearSelection();
    extraSelections.append(selection);
  }

  setExtraSelections(extraSelections);
}

TextEditorHighlighter::TextEditorHighlighter(QTextDocument* doc)
    : QSyntaxHighlighter(doc), m_background(QColor("transparent")),
      m_text(QColor("black"))
{}

QColor TextEditorHighlighter::backgroundColor() const
{
  return m_background;
}

void TextEditorHighlighter::setBackgroundColor(const QColor& c)
{
  m_background = c;
  changed();
}

QColor TextEditorHighlighter::textColor() const
{
  return m_text;
}

void TextEditorHighlighter::setTextColor(const QColor& c)
{
  m_text = c;
  changed();
}

void TextEditorHighlighter::highlightBlock(const QString& s)
{
  QTextCharFormat f;
  f.setBackground(m_background);
  f.setForeground(m_text);

  setFormat(0, s.size(), f);
}

void TextEditorHighlighter::changed()
{
  rehighlight();
}

TextEditorLineNumbers::TextEditorLineNumbers(TextEditor& editor)
    : QFrame(&editor), m_editor(editor)
{
  setFont(editor.font());

  connect(&m_editor, &QPlainTextEdit::blockCountChanged, [&] {
    updateAreaWidth();
  });
  connect(&m_editor, &QPlainTextEdit::updateRequest, [&](auto&& rect, int dy) {
    updateArea(rect, dy);
  });

  updateAreaWidth();
}

QSize TextEditorLineNumbers::sizeHint() const
{
  return QSize(areaWidth(), 0);
}

int TextEditorLineNumbers::areaWidth() const
{
  int digits = 1;
  int max    = std::max(1, m_editor.blockCount());

  while (max >= 10) {
    max /= 10;
    ++digits;
  }

  digits = std::max(3, digits);

  int space = 3 + fontMetrics().horizontalAdvance(QLatin1Char('9')) * digits + 3;

  return space;
}

QColor TextEditorLineNumbers::textColor() const
{
  return m_text;
}

void TextEditorLineNumbers::setTextColor(const QColor& c)
{
  m_text = c;
  m_editor.update();
}

QColor TextEditorLineNumbers::backgroundColor() const
{
  return m_background;
}

void TextEditorLineNumbers::setBackgroundColor(const QColor& c)
{
  m_background = c;
  m_editor.update();
}

void TextEditorLineNumbers::paintEvent(QPaintEvent* e)
{
  QPainter painter(this);
  painter.fillRect(e->rect(), m_background);

  QFrame::paintEvent(e);
  m_editor.paintLineNumbers(e, m_text);
}

void TextEditorLineNumbers::updateAreaWidth()
{
  m_editor.setViewportMargins(areaWidth(), 0, 0, 0);
}

void TextEditorLineNumbers::updateArea(const QRect& rect, int dy)
{
  if (dy) {
    scroll(0, dy);
  } else {
    update(0, rect.y(), width(), rect.height());
  }

  if (rect.contains(m_editor.viewport()->rect())) {
    updateAreaWidth();
  }
}

TextEditorToolbar::TextEditorToolbar(TextEditor& editor)
    : m_editor(editor), m_save(nullptr), m_wordWrap(nullptr), m_explore(nullptr),
      m_path(nullptr)
{
  m_save = new QAction(QIcon(":/MO/gui/save"), QObject::tr("&Save"), &editor);

  m_save->setShortcutContext(Qt::WidgetWithChildrenShortcut);
  m_save->setShortcut(Qt::CTRL + Qt::Key_S);
  m_editor.addAction(m_save);

  m_wordWrap =
      new QAction(QIcon(":/MO/gui/word-wrap"), QObject::tr("&Word wrap"), &editor);

  m_wordWrap->setCheckable(true);

  m_explore = new QAction(QObject::tr("&Open in Explorer"), &editor);

  m_path = new QLineEdit;
  m_path->setReadOnly(true);

  QObject::connect(m_save, &QAction::triggered, [&] {
    m_editor.save();
  });
  QObject::connect(m_wordWrap, &QAction::triggered, [&] {
    m_editor.toggleWordWrap();
  });
  QObject::connect(m_explore, &QAction::triggered, [&] {
    m_editor.explore();
  });

  auto* layout = new QHBoxLayout(this);
  layout->setContentsMargins(0, 0, 0, 0);
  layout->setAlignment(Qt::AlignLeft);

  auto* b = new QToolButton;
  b->setDefaultAction(m_save);
  layout->addWidget(b);

  b = new QToolButton;
  b->setDefaultAction(m_wordWrap);
  layout->addWidget(b);

  b = new QToolButton;
  b->setDefaultAction(m_explore);
  layout->addWidget(b);

  layout->addWidget(m_path);

  QObject::connect(&m_editor, &TextEditor::modified, [&](bool b) {
    onTextModified(b);
  });
  QObject::connect(&m_editor, &TextEditor::wordWrapChanged, [&](bool b) {
    onWordWrap(b);
  });
  QObject::connect(&m_editor, &TextEditor::loaded, [&](QString f) {
    onLoaded(f);
  });
}

void TextEditorToolbar::onTextModified(bool b)
{
  m_save->setEnabled(b);
}

void TextEditorToolbar::onWordWrap(bool b)
{
  m_wordWrap->setChecked(b);
}

void TextEditorToolbar::onLoaded(const QString& path)
{
  const auto hasDoc = !path.isEmpty();

  m_explore->setEnabled(hasDoc);
  m_wordWrap->setEnabled(hasDoc);
  m_path->setEnabled(hasDoc);
  m_path->setText(path);
}

void HTMLEditor::focusOutEvent(QFocusEvent* e)
{
  if (document() && document()->isModified()) {
    emit editingFinished();
  }

  QTextEdit::focusInEvent(e);
}