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