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