]> git.lyx.org Git - lyx.git/blob - src/frontends/qt4/LayoutBox.cpp
Refactor
[lyx.git] / src / frontends / qt4 / LayoutBox.cpp
1 /**
2  * \file qt4/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;
66         ///
67         void drawDisplay(QPainter * painter, QStyleOptionViewItem const & opt,
68                 const QRect & /*rect*/, const QString & text ) const;
69         ///
70         QSize sizeHint(QStyleOptionViewItem const & opt,
71                 QModelIndex const & index) const;
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 = 0)
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_(0),
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.width(category);
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
302         // step through data item and put "(x)" for every matching character
303         QString r;
304         int lastp = -1;
305         for (int i = 0; i < f.length(); ++i) {
306                 int p = s.indexOf(f[i], lastp + 1, Qt::CaseInsensitive);
307                 if (p < 0)
308                         continue;
309                 if (lastp == p - 1 && lastp != -1) {
310                         // remove ")" and append "x)"
311                         r = r.left(r.length() - 4) + s[p] + "</u>";
312                 } else {
313                         // append "(x)"
314                         r += s.mid(lastp + 1, p - lastp - 1);
315                         r += QString("<u>") + s[p] + "</u>";
316                 }
317                 lastp = p;
318         }
319         r += s.mid(lastp + 1);
320         return r;
321 }
322
323
324 void LayoutBox::Private::setFilter(QString const & s)
325 {
326         // exit early if nothing has to be done
327         if (filter_ == s)
328                 return;
329
330         bool enabled = p->view()->updatesEnabled();
331         p->view()->setUpdatesEnabled(false);
332
333         // remember old selection
334         int sel = p->currentIndex();
335         if (sel != -1)
336                 lastSel_ = filterModel_->mapToSource(filterModel_->index(sel, 0)).row();
337
338         filter_ = s;
339         filterModel_->setFilterRegExp(charFilterRegExp(filter_));
340         countCategories();
341
342         // restore old selection
343         if (lastSel_ != -1) {
344                 QModelIndex i = filterModel_->mapFromSource(model_->index(lastSel_, 0));
345                 if (i.isValid())
346                         p->setCurrentIndex(i.row());
347         }
348
349         if (p->view()->isVisible()) {
350                 p->QComboBox::showPopup();
351                 if (!s.isEmpty())
352                         owner_.message(bformat(_("Filtering layouts with \"%1$s\". "
353                                                  "Press ESC to remove filter."),
354                                                qstring_to_ucs4(s)));
355                 else
356                         owner_.message(_("Enter characters to filter the layout list."));
357         }
358
359         p->view()->setUpdatesEnabled(enabled);
360 }
361
362
363 LayoutBox::LayoutBox(GuiView & owner)
364         : d(new Private(this, owner))
365 {
366         setSizeAdjustPolicy(QComboBox::AdjustToContents);
367         setFocusPolicy(Qt::ClickFocus);
368         setMinimumWidth(sizeHint().width());
369         setMaxVisibleItems(100);
370
371         setModel(d->filterModel_);
372
373         // for the filtering we have to intercept characters
374         view()->installEventFilter(this);
375         view()->setItemDelegateForColumn(0, d->layoutItemDelegate_);
376
377         QObject::connect(this, SIGNAL(activated(int)),
378                 this, SLOT(selected(int)));
379
380         updateContents(true);
381 }
382
383
384 LayoutBox::~LayoutBox() {
385         delete d;
386 }
387
388
389 void LayoutBox::Private::countCategories()
390 {
391         int n = filterModel_->rowCount();
392         visibleCategories_ = 0;
393         if (n == 0 || !lyxrc.group_layouts)
394                 return;
395
396         // skip the "Standard" category
397         QString prevCat = model_->index(0, 2).data().toString();
398
399         // count categories
400         for (int i = 0; i < n; ++i) {
401                 QString cat = filterModel_->index(i, 2).data().toString();
402                 if (cat != prevCat)
403                         ++visibleCategories_;
404                 prevCat = cat;
405         }
406 }
407
408
409 void LayoutBox::showPopup()
410 {
411         d->owner_.message(_("Enter characters to filter the layout list."));
412
413         bool enabled = view()->updatesEnabled();
414         view()->setUpdatesEnabled(false);
415         d->resetFilter();
416         QComboBox::showPopup();
417         view()->setUpdatesEnabled(enabled);
418 }
419
420
421 bool LayoutBox::eventFilter(QObject * o, QEvent * e)
422 {
423         if (e->type() != QEvent::KeyPress)
424                 return QComboBox::eventFilter(o, e);
425
426         QKeyEvent * ke = static_cast<QKeyEvent*>(e);
427         bool modified = (ke->modifiers() == Qt::ControlModifier)
428                 || (ke->modifiers() == Qt::AltModifier)
429                 || (ke->modifiers() == Qt::MetaModifier);
430
431         switch (ke->key()) {
432         case Qt::Key_Escape:
433                 if (!modified && !d->filter_.isEmpty()) {
434                         d->resetFilter();
435                         return true;
436                 }
437                 break;
438         case Qt::Key_Backspace:
439                 if (!modified) {
440                         // cut off one character
441                         d->setFilter(d->filter_.left(d->filter_.length() - 1));
442                 }
443                 break;
444         default:
445                 if (modified || ke->text().isEmpty())
446                         break;
447                 // find chars for the filter string
448                 QString s;
449                 for (int i = 0; i < ke->text().length(); ++i) {
450                         QChar c = ke->text()[i];
451                         if (c.isLetterOrNumber()
452                             || c.isSymbol()
453                             || c.isPunct()
454                             || c.category() == QChar::Separator_Space) {
455                                 s += c;
456                         }
457                 }
458                 if (!s.isEmpty()) {
459                         // append new chars to the filter string
460                         d->setFilter(d->filter_ + s);
461                         return true;
462                 }
463                 break;
464         }
465
466         return QComboBox::eventFilter(o, e);
467 }
468
469
470 void LayoutBox::setIconSize(QSize size)
471 {
472 #ifdef Q_OS_MAC
473         bool small = size.height() < 20;
474         setAttribute(Qt::WA_MacSmallSize, small);
475         setAttribute(Qt::WA_MacNormalSize, !small);
476 #else
477         (void)size; // suppress warning
478 #endif
479 }
480
481
482 void LayoutBox::set(docstring const & layout)
483 {
484         d->resetFilter();
485
486         if (!d->text_class_)
487                 return;
488
489         if (!d->text_class_->hasLayout(layout))
490                 return;
491
492         Layout const & lay = (*d->text_class_)[layout];
493         QString newLayout = toqstr(lay.name());
494
495         // If the layout is obsolete, use the new one instead.
496         docstring const & obs = lay.obsoleted_by();
497         if (!obs.empty())
498                 newLayout = toqstr(obs);
499
500         int const curItem = currentIndex();
501         QModelIndex const mindex =
502                 d->filterModel_->mapToSource(d->filterModel_->index(curItem, 1));
503         QString const & currentLayout = d->model_->itemFromIndex(mindex)->text();
504         if (newLayout == currentLayout) {
505                 LYXERR(Debug::GUI, "Already had " << newLayout << " selected.");
506                 return;
507         }
508
509         QList<QStandardItem *> r = d->model_->findItems(newLayout, Qt::MatchExactly, 1);
510         if (r.empty()) {
511                 LYXERR0("Trying to select non existent layout type " << newLayout);
512                 return;
513         }
514
515         setCurrentIndex(d->filterModel_->mapFromSource(r.first()->index()).row());
516 }
517
518
519 void LayoutBox::addItemSort(docstring const & item, docstring const & category,
520         bool sorted, bool sortedByCat, bool unknown)
521 {
522         QString qitem = toqstr(item);
523         docstring const loc_item = translateIfPossible(item);
524         QString titem = unknown ? toqstr(bformat(_("%1$s (unknown)"), loc_item))
525                                 : toqstr(loc_item);
526         QString qcat = toqstr(translateIfPossible(category));
527
528         QList<QStandardItem *> row;
529         row.append(new QStandardItem(titem));
530         row.append(new QStandardItem(qitem));
531         row.append(new QStandardItem(qcat));
532
533         // the first entry is easy
534         int const end = d->model_->rowCount();
535         if (end == 0) {
536                 d->model_->appendRow(row);
537                 return;
538         }
539
540         // find category
541         int i = 0;
542         if (sortedByCat) {
543                 while (i < end && d->model_->item(i, 2)->text() != qcat)
544                         ++i;
545         }
546
547         // skip the Standard layout
548         if (i == 0)
549                 ++i;
550
551         // the simple unsorted case
552         if (!sorted) {
553                 if (sortedByCat) {
554                         // jump to the end of the category group
555                         while (i < end && d->model_->item(i, 2)->text() == qcat)
556                                 ++i;
557                         d->model_->insertRow(i, row);
558                 } else
559                         d->model_->appendRow(row);
560                 return;
561         }
562
563         // find row to insert the item, after the separator if it exists
564         if (i < end) {
565                 // find alphabetic position
566                 while (i != end
567                        && d->model_->item(i, 0)->text().localeAwareCompare(titem) < 0
568                        && (!sortedByCat || d->model_->item(i, 2)->text() == qcat))
569                         ++i;
570         }
571
572         d->model_->insertRow(i, row);
573 }
574
575
576 void LayoutBox::updateContents(bool reset)
577 {
578         d->resetFilter();
579         BufferView const * bv = d->owner_.currentBufferView();
580         if (!bv) {
581                 d->model_->clear();
582                 setEnabled(false);
583                 setMinimumWidth(sizeHint().width());
584                 d->text_class_.reset();
585                 d->inset_ = 0;
586                 return;
587         }
588         // we'll only update the layout list if the text class has changed
589         // or we've moved from one inset to another
590         DocumentClassConstPtr text_class = bv->buffer().params().documentClassPtr();
591         Inset const * inset = &(bv->cursor().innerText()->inset());
592         if (!reset && d->text_class_ == text_class && d->inset_ == inset) {
593                 set(bv->cursor().innerParagraph().layout().name());
594                 return;
595         }
596
597         d->inset_ = inset;
598         d->text_class_ = text_class;
599
600         d->model_->clear();
601         DocumentClass::const_iterator lit = d->text_class_->begin();
602         DocumentClass::const_iterator len = d->text_class_->end();
603
604         for (; lit != len; ++lit) {
605                 docstring const & name = lit->name();
606                 bool const useEmpty = d->inset_->forcePlainLayout() || d->inset_->usePlainLayout();
607                 // if this inset requires the empty layout, we skip the default
608                 // layout
609                 if (name == d->text_class_->defaultLayoutName() && d->inset_ && useEmpty)
610                         continue;
611                 // if it doesn't require the empty layout, we skip it
612                 if (name == d->text_class_->plainLayoutName() && d->inset_ && !useEmpty)
613                         continue;
614                 // obsoleted layouts are skipped as well
615                 if (!lit->obsoleted_by().empty())
616                         continue;
617                 addItemSort(name, lit->category(), lyxrc.sort_layouts,
618                                 lyxrc.group_layouts, lit->isUnknown());
619         }
620
621         set(d->owner_.currentBufferView()->cursor().innerParagraph().layout().name());
622         d->countCategories();
623
624         setMinimumWidth(sizeHint().width());
625         setEnabled(!bv->buffer().isReadonly() &&
626                 lyx::getStatus(FuncRequest(LFUN_LAYOUT)).enabled());
627 }
628
629
630 void LayoutBox::selected(int index)
631 {
632         // get selection
633         QModelIndex mindex = d->filterModel_->mapToSource(
634                 d->filterModel_->index(index, 1));
635         docstring layoutName = qstring_to_ucs4(
636                 d->model_->itemFromIndex(mindex)->text());
637         d->owner_.setFocus();
638
639         if (!d->text_class_) {
640                 updateContents(false);
641                 d->resetFilter();
642                 return;
643         }
644
645         // find corresponding text class
646         if (d->text_class_->hasLayout(layoutName)) {
647                 FuncRequest const func(LFUN_LAYOUT, layoutName, FuncRequest::TOOLBAR);
648                 lyx::dispatch(func);
649                 updateContents(false);
650                 d->resetFilter();
651                 return;
652         }
653         LYXERR0("ERROR (layoutSelected): layout " << layoutName << " not found!");
654 }
655
656
657 QString const & LayoutBox::filter() const
658 {
659         return d->filter_;
660 }
661
662 } // namespace frontend
663 } // namespace lyx
664
665 #include "moc_LayoutBox.cpp"