]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/LayoutBox.cpp
Fix readability
[lyx.git] / src / frontends / qt / LayoutBox.cpp
1 /**
2  * \file qt/LayoutBox.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  * \author John Levon
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author Stefan Schimanski
11  * \author Abdelrazak Younes
12  *
13  * Full author contact details are available in file CREDITS.
14  */
15
16 #include <config.h>
17
18 #include "LayoutBox.h"
19
20 #include "GuiView.h"
21 #include "qt_helpers.h"
22
23 #include "Buffer.h"
24 #include "BufferParams.h"
25 #include "BufferView.h"
26 #include "Cursor.h"
27 #include "DocumentClassPtr.h"
28 #include "FuncRequest.h"
29 #include "FuncStatus.h"
30 #include "LyX.h"
31 #include "LyXRC.h"
32 #include "Paragraph.h"
33 #include "TextClass.h"
34
35 #include "insets/InsetText.h"
36
37 #include "support/debug.h"
38 #include "support/gettext.h"
39 #include "support/lassert.h"
40 #include "support/lstrings.h"
41
42 #include <QAbstractTextDocumentLayout>
43 #include <QHeaderView>
44 #include <QItemDelegate>
45 #include <QPainter>
46 #include <QSortFilterProxyModel>
47 #include <QStandardItemModel>
48 #include <QTextFrame>
49
50 using namespace std;
51 using namespace lyx::support;
52
53 namespace lyx {
54 namespace frontend {
55
56
57 class LayoutItemDelegate : public QItemDelegate {
58 public:
59         ///
60         explicit LayoutItemDelegate(LayoutBox * layout)
61                 : QItemDelegate(layout), layout_(layout)
62         {}
63         ///
64         void paint(QPainter * painter, QStyleOptionViewItem const & option,
65                 QModelIndex const & index) const override;
66         ///
67         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
68                 const QRect & /*rect*/, const QString & text ) const override;
69         ///
70         QSize sizeHint(QStyleOptionViewItem const & opt,
71                 QModelIndex const & index) const override;
72
73 private:
74         ///
75         void drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
76                 QString const & category) const;
77         ///
78         QString underlineFilter(QString const & s) const;
79         ///
80         LayoutBox * layout_;
81 };
82
83
84 class GuiLayoutFilterModel : public QSortFilterProxyModel {
85 public:
86         ///
87         GuiLayoutFilterModel(QObject * parent = nullptr)
88                 : QSortFilterProxyModel(parent)
89         {}
90
91         ///
92         void triggerLayoutChange()
93         {
94                 layoutAboutToBeChanged();
95                 layoutChanged();
96         }
97 };
98
99
100 /////////////////////////////////////////////////////////////////////
101 //
102 // LayoutBox::Private
103 //
104 /////////////////////////////////////////////////////////////////////
105
106 class LayoutBox::Private
107 {
108         /// noncopyable
109         Private(Private const &);
110         void operator=(Private const &);
111 public:
112         Private(LayoutBox * parent, GuiView & gv) : p(parent), owner_(gv),
113                 inset_(nullptr),
114                 // set the layout model with two columns
115                 // 1st: translated layout names
116                 // 2nd: raw layout names
117                 model_(new QStandardItemModel(0, 2, p)),
118                 filterModel_(new GuiLayoutFilterModel(p)),
119                 lastSel_(-1),
120                 layoutItemDelegate_(new LayoutItemDelegate(parent)),
121                 visibleCategories_(0)
122         {
123                 filterModel_->setSourceModel(model_);
124         }
125
126         void resetFilter() { setFilter(QString()); }
127         ///
128         void setFilter(QString const & s);
129         ///
130         void countCategories();
131         ///
132         LayoutBox * p;
133         ///
134         GuiView & owner_;
135         ///
136         DocumentClassConstPtr text_class_;
137         ///
138         Inset const * inset_;
139
140         /// the layout model: 1st column translated, 2nd column raw layout name
141         QStandardItemModel * model_;
142         /// the proxy model filtering \c model_
143         GuiLayoutFilterModel * filterModel_;
144         /// the (model-) index of the last successful selection
145         int lastSel_;
146         /// the character filter
147         QString filter_;
148         ///
149         LayoutItemDelegate * layoutItemDelegate_;
150         ///
151         unsigned visibleCategories_;
152 };
153
154
155 static QString category(QAbstractItemModel const & model, int row)
156 {
157         return model.data(model.index(row, 2), Qt::DisplayRole).toString();
158 }
159
160
161 static int headerHeight(QStyleOptionViewItem const & opt)
162 {
163         return opt.fontMetrics.height() * 8 / 10;
164 }
165
166
167 void LayoutItemDelegate::paint(QPainter * painter, QStyleOptionViewItem const & option,
168                                                            QModelIndex const & index) const
169 {
170         QStyleOptionViewItem opt = option;
171
172         // default background
173         painter->fillRect(opt.rect, opt.palette.color(QPalette::Base));
174
175         // category header?
176         if (lyxrc.group_layouts) {
177                 QSortFilterProxyModel const * model =
178                         static_cast<QSortFilterProxyModel const *>(index.model());
179
180                 QString stdCat = category(*model->sourceModel(), 0);
181                 QString cat = category(*index.model(), index.row());
182
183                 // not the standard layout and not the same as in the previous line?
184                 if (stdCat != cat
185                         && (index.row() == 0 || cat != category(*index.model(), index.row() - 1))) {
186                         painter->save();
187
188                         // draw unselected background
189                         QStyle::State state = opt.state;
190                         opt.state = opt.state & ~QStyle::State_Selected;
191                         drawBackground(painter, opt, index);
192                         opt.state = state;
193
194                         // draw category header
195                         drawCategoryHeader(painter, opt,
196                                 category(*index.model(), index.row()));
197
198                         // move rect down below header
199                         opt.rect.setTop(opt.rect.top() + headerHeight(opt));
200
201                         painter->restore();
202                 }
203         }
204
205         QItemDelegate::paint(painter, opt, index);
206 }
207
208
209 void LayoutItemDelegate::drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
210                                                                          const QRect & /*rect*/, const QString & text ) const
211 {
212         QString utext = underlineFilter(text);
213
214         // Draw the rich text.
215         painter->save();
216         QColor col = opt.palette.text().color();
217         if (opt.state & QStyle::State_Selected)
218                 col = opt.palette.highlightedText().color();
219         QAbstractTextDocumentLayout::PaintContext context;
220         context.palette.setColor(QPalette::Text, col);
221
222         QTextDocument doc;
223         doc.setDefaultFont(opt.font);
224         doc.setHtml(utext);
225
226         QTextFrameFormat fmt = doc.rootFrame()->frameFormat();
227         fmt.setMargin(0);
228         doc.rootFrame()->setFrameFormat(fmt);
229
230         painter->translate(opt.rect.x() + 5,
231                 opt.rect.y() + (opt.rect.height() - opt.fontMetrics.height()) / 2);
232         doc.documentLayout()->draw(painter, context);
233         painter->restore();
234 }
235
236
237 QSize LayoutItemDelegate::sizeHint(QStyleOptionViewItem const & opt,
238                                                                    QModelIndex const & index) const
239 {
240         QSize size = QItemDelegate::sizeHint(opt, index);
241         if (!lyxrc.group_layouts)
242                 return size;
243
244         // Add space for the category headers.
245         QSortFilterProxyModel const * const model =
246                 static_cast<QSortFilterProxyModel const *>(index.model());
247         QString const stdCat = category(*model->sourceModel(), 0);
248         QString const cat = category(*index.model(), index.row());
249
250         // There is no header for the stuff at the top.
251         if (stdCat == cat)
252                 return size;
253
254         if (index.row() == 0 || cat != category(*index.model(), index.row() - 1))
255                 size.setHeight(size.height() + headerHeight(opt));
256         return size;
257 }
258
259
260 void LayoutItemDelegate::drawCategoryHeader(QPainter * painter, QStyleOptionViewItem const & opt,
261                                                                                         QString const & category) const
262 {
263         // slightly blended color
264         QColor lcol = opt.palette.text().color();
265         lcol.setAlpha(127);
266         painter->setPen(lcol);
267
268         // set 80% scaled, bold font
269         QFont font = opt.font;
270         font.setBold(true);
271         font.setWeight(QFont::Black);
272         font.setPointSize(opt.font.pointSize() * 8 / 10);
273         painter->setFont(font);
274
275         // draw the centered text
276         QFontMetrics fm(font);
277         int w = fm.boundingRect(category).width();
278         int x = opt.rect.x() + (opt.rect.width() - w) / 2;
279         int y = opt.rect.y() + fm.ascent();
280         int left = x;
281         int right = x + w;
282         painter->drawText(x, y, category);
283
284         // the vertical position of the line: middle of lower case chars
285         int ymid = y - 1 - fm.xHeight() / 2; // -1 for the baseline
286
287         // draw the horizontal line
288         if (!category.isEmpty()) {
289                 painter->drawLine(opt.rect.x(), ymid, left - 1, ymid);
290                 painter->drawLine(right + 1, ymid, opt.rect.right(), ymid);
291         } else
292                 painter->drawLine(opt.rect.x(), ymid, opt.rect.right(), ymid);
293 }
294
295
296 QString LayoutItemDelegate::underlineFilter(QString const & s) const
297 {
298         QString const & f = layout_->filter();
299         if (f.isEmpty())
300                 return s;
301         QString r(s);
302         QRegularExpression pattern(charFilterRegExpC(f));
303         r.replace(pattern, "<u><b>\\1</b></u>");
304         return r;
305 }
306
307
308 void LayoutBox::Private::setFilter(QString const & s)
309 {
310         // exit early if nothing has to be done
311         if (filter_ == s)
312                 return;
313
314         bool enabled = p->view()->updatesEnabled();
315         p->view()->setUpdatesEnabled(false);
316
317         // remember old selection
318         int sel = p->currentIndex();
319         if (sel != -1)
320                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
321
322         filter_ = s;
323 #if QT_VERSION < QT_VERSION_CHECK(5, 12, 0)
324         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
325 #else
326         filterModel_->setFilterRegularExpression(charFilterRegExp(filter_));
327 #endif
328         countCategories();
329
330         // restore old selection
331         if (lastSel_ != -1) {
332                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
333                 if (i.isValid())
334                         p->setCurrentIndex(i.row());
335         }
336
337         if (p->view()->isVisible()) {
338                 p->QComboBox::showPopup();
339                 if (!s.isEmpty())
340                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
341                                                  "Press ESC to remove filter."),
342                                                qstring_to_ucs4(s)));
343                 else
344                         owner_.message(_("Enter characters to filter the layout list."));
345         }
346
347         p->view()->setUpdatesEnabled(enabled);
348 }
349
350
351 LayoutBox::LayoutBox(GuiView & owner)
352         : d(new Private(this, owner))
353 {
354         setSizeAdjustPolicy(QComboBox::AdjustToContents);
355         setFocusPolicy(Qt::ClickFocus);
356         setMinimumWidth(sizeHint().width());
357         setMaxVisibleItems(100);
358
359         setModel(d->filterModel_);
360
361         // for the filtering we have to intercept characters
362         view()->installEventFilter(this);
363         view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
364
365         QObject::connect(this, SIGNAL(activated(int)),
366                 this, SLOT(selected(int)));
367
368         updateContents(true);
369 }
370
371
372 LayoutBox::~LayoutBox() {
373         delete d;
374 }
375
376
377 void LayoutBox::Private::countCategories()
378 {
379         int n = filterModel_->rowCount();
380         visibleCategories_ = 0;
381         if (n == 0 || !lyxrc.group_layouts)
382                 return;
383
384         // skip the "Standard" category
385         QString prevCat = model_->index(0, 2).data().toString();
386
387         // count categories
388         for (int i = 0; i < n; ++i) {
389                 QString cat = filterModel_->index(i, 2).data().toString();
390                 if (cat != prevCat)
391                         ++visibleCategories_;
392                 prevCat = cat;
393         }
394 }
395
396
397 void LayoutBox::showPopup()
398 {
399         lastCurrentIndex_ = currentIndex();
400         d->owner_.message(_("Enter characters to filter the layout list."));
401
402         bool enabled = view()->updatesEnabled();
403         view()->setUpdatesEnabled(false);
404         d->resetFilter();
405         QComboBox::showPopup();
406         view()->setUpdatesEnabled(enabled);
407 }
408
409
410 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
411 {
412         if (e->type() != QEvent::KeyPress)
413                 return QComboBox::eventFilter(o, e);
414
415         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
416         bool modified = (ke->modifiers() == Qt::ControlModifier)
417                 || (ke->modifiers() == Qt::AltModifier)
418                 || (ke->modifiers() == Qt::MetaModifier);
419
420         switch (ke->key()) {
421         case Qt::Key_Escape:
422                 if (!modified && !d->filter_.isEmpty()) {
423                         d->resetFilter();
424                         setCurrentIndex(lastCurrentIndex_);
425                         return true;
426                 }
427                 break;
428         case Qt::Key_Backspace:
429                 if (!modified) {
430                         // cut off one character
431                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
432                 }
433                 break;
434         default:
435                 if (modified || ke->text().isEmpty())
436                         break;
437                 // find chars for the filter string
438                 QString s;
439                 for (int i = 0; i < ke->text().length(); ++i) {
440                         QChar c = ke->text()[i];
441                         if (c.isLetterOrNumber()
442                             || c.isSymbol()
443                             || c.isPunct()
444                             || c.category() == QChar::Separator_Space) {
445                                 s += c;
446                         }
447                 }
448                 if (!s.isEmpty()) {
449                         // append new chars to the filter string
450                         d->setFilter(d->filter_ + s);
451                         return true;
452                 }
453                 break;
454         }
455
456         return QComboBox::eventFilter(o, e);
457 }
458
459
460 void LayoutBox::setIconSize(QSize size)
461 {
462 #ifdef Q_OS_MAC
463         bool small = size.height() < 20;
464         setAttribute(Qt::WA_MacSmallSize, small);
465         setAttribute(Qt::WA_MacNormalSize, !small);
466 #else
467         (void)size; // suppress warning
468 #endif
469 }
470
471
472 void LayoutBox::set(docstring const & layout)
473 {
474         d->resetFilter();
475
476         if (!d->text_class_)
477                 return;
478
479         if (!d->text_class_->hasLayout(layout))
480                 return;
481
482         Layout const & lay = (*d->text_class_)[layout];
483         QString newLayout = toqstr(lay.name());
484
485         // If the layout is obsolete, use the new one instead.
486         docstring const & obs = lay.obsoleted_by();
487         if (!obs.empty())
488                 newLayout = toqstr(obs);
489
490         int const curItem = currentIndex();
491         QModelIndex const mindex =
492                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
493         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
494         if (newLayout == currentLayout) {
495                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
496                 return;
497         }
498
499         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
500         if (r.empty()) {
501                 LYXERR0("Trying to select non existent layout type " << newLayout);
502                 return;
503         }
504
505         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
506 }
507
508
509 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
510         bool sorted, bool sortedByCat, bool unknown)
511 {
512         QString qitem = toqstr(item);
513         docstring const loc_item = translateIfPossible(item);
514         QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
515                                 : toqstr(loc_item);
516         QString qcat = toqstr(translateIfPossible(category));
517
518         QList<QStandardItem *> row;
519         row.append(new QStandardItem(titem));
520         row.append(new QStandardItem(qitem));
521         row.append(new QStandardItem(qcat));
522
523         // the first entry is easy
524         int const end = d->model_->rowCount();
525         if (end == 0) {
526                 d->model_->appendRow(row);
527                 return;
528         }
529
530         // find category
531         int i = 0;
532         if (sortedByCat) {
533                 while (i < end && d->model_->item(i, 2)->text() != qcat)
534                         ++i;
535         }
536
537         // skip the Standard layout
538         if (i == 0)
539                 ++i;
540
541         // the simple unsorted case
542         if (!sorted) {
543                 if (sortedByCat) {
544                         // jump to the end of the category group
545                         while (i < end && d->model_->item(i, 2)->text() == qcat)
546                                 ++i;
547                         d->model_->insertRow(i, row);
548                 } else
549                         d->model_->appendRow(row);
550                 return;
551         }
552
553         // find row to insert the item, after the separator if it exists
554         if (i < end) {
555                 // find alphabetic position
556                 while (i != end
557                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
558                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
559                         ++i;
560         }
561
562         d->model_->insertRow(i, row);
563 }
564
565
566 void LayoutBox::updateContents(bool reset)
567 {
568         d->resetFilter();
569         BufferView const * bv = d->owner_.currentBufferView();
570         if (!bv) {
571                 d->model_->clear();
572                 setEnabled(false);
573                 setMinimumWidth(sizeHint().width());
574                 d->text_class_.reset();
575                 d->inset_ = nullptr;
576                 return;
577         }
578         // we'll only update the layout list if the text class has changed
579         // or we've moved from one inset to another
580         DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
581         Inset const * inset = &(bv->cursor().innerText()->inset());
582         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
583                 set(bv->cursor().innerParagraph().layout().name());
584                 return;
585         }
586
587         d->inset_ = inset;
588         d->text_class_ = text_class;
589
590         d->model_->clear();
591         DocumentClass::const_iterator lit = d->text_class_->begin();
592         DocumentClass::const_iterator len = d->text_class_->end();
593         for (; lit != len; ++lit) {
594                 docstring const & name = lit->name();
595                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
596                 // if this inset requires the empty layout, we skip the default
597                 // layout
598                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
599                         continue;
600                 // if it doesn't require the empty layout, we skip it
601                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
602                         continue;
603                 // obsoleted layouts are skipped as well
604                 if (!lit->obsoleted_by().empty())
605                         continue;
606                 addItemSort(name, lit->category(), lyxrc.sort_layouts,
607                                 lyxrc.group_layouts, lit->isUnknown());
608         }
609
610         set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
611         d->countCategories();
612
613         setMinimumWidth(sizeHint().width());
614         setEnabled(!bv->buffer().isReadonly() &&
615                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
616 }
617
618
619 void LayoutBox::selected(int index)
620 {
621         d->owner_.setFocus();
622         if (!d->text_class_) {
623                 updateContents(false);
624                 d->resetFilter();
625                 return;
626         }
627
628         // get selection
629         // get the index of the untranslated layout name (which is in column 1)
630         QModelIndex const lindex = d->filterModel_->index(index, 1);
631         QModelIndex const mindex = d->filterModel_->mapToSource(lindex);
632         QString const qlayout = d->model_->itemFromIndex(mindex)->text();
633         docstring const layoutName = qstring_to_ucs4(qlayout);
634
635         // find corresponding text class
636         if (d->text_class_->hasLayout(layoutName)) {
637                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
638                 lyx::dispatch(func);
639                 updateContents(false);
640                 d->resetFilter();
641                 return;
642         }
643         LYXERR0("ERROR (LayoutBox::Selected): layout " << layoutName << " not found!");
644 }
645
646
647 QString const & LayoutBox::filter() const
648 {
649         return d->filter_;
650 }
651
652 } // namespace frontend
653 } // namespace lyx
654
655 #include "moc_LayoutBox.cpp"