]> git.lyx.org Git - features.git/blob - src/frontends/qt/GuiDelimiter.cpp
Guard against possible referencing null.
[features.git] / src / frontends / qt / GuiDelimiter.cpp
1 /**
2  * \file GuiDelimiter.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author John Levon
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "GuiDelimiter.h"
14
15 #include "GuiApplication.h"
16 #include "GuiFontLoader.h"
17 #include "GuiView.h"
18 #include "qt_helpers.h"
19
20 #include "FontEnums.h"
21 #include "FontInfo.h"
22 #include "FuncRequest.h"
23
24 #include "support/debug.h"
25 #include "support/docstring.h"
26 #include "support/gettext.h"
27 #include "support/lstrings.h"
28
29 #include <QBitmap>
30 #include <QPainter>
31 #include <QPixmap>
32 #include <QCheckBox>
33 #include <QListWidgetItem>
34 #include <QScrollBar>
35
36 #include <map>
37 #include <string>
38
39 using namespace std;
40
41 namespace lyx {
42 namespace frontend {
43
44 namespace {
45
46 static char const *  latex_delimiters[] = {
47         "(", ")", "{", "}", "[", "]",
48         "lceil", "rceil", "lfloor", "rfloor", "langle", "rangle",
49         "llbracket", "rrbracket",
50         "uparrow", "updownarrow", "Uparrow", "Updownarrow", "downarrow", "Downarrow",
51         "|", "Vert", "/", "backslash", ""
52 };
53
54
55 static int const nr_latex_delimiters =
56         sizeof(latex_delimiters) / sizeof(char const *);
57
58 static string const bigleft[]  = {"", "bigl", "Bigl", "biggl", "Biggl"};
59
60 static string const bigright[] = {"", "bigr", "Bigr", "biggr", "Biggr"};
61
62 static char const * const biggui[] = {
63         N_("big[[delimiter size]]"),
64         N_("Big[[delimiter size]]"),
65         N_("bigg[[delimiter size]]"),
66         N_("Bigg[[delimiter size]]"),
67         ""
68 };
69
70
71 // FIXME: It might be better to fix the big delim LFUN to not require
72 // additional '\' prefix.
73 static docstring fix_name(string const & str, bool big)
74 {
75         if (str.empty())
76                 return from_ascii(".");
77         if (!big || str == "(" || str == ")" || str == "[" || str == "]"
78             || str == "|" || str == "/")
79                 return from_ascii(str);
80
81         return "\\" + from_ascii(str);
82 }
83
84 struct MathSymbol {
85         MathSymbol(char_type uc = '?', string icon = string())
86                 : unicode(uc), icon(icon)
87         {}
88         char_type unicode;
89         string icon;
90 };
91
92
93 QPixmap getSelectedPixmap(QPixmap pixmap, QSize const icon_size)
94 {
95         QPalette palette = QPalette();
96         QColor text_color = (guiApp->isInDarkMode())
97                         ? palette.color(QPalette::Active, QPalette::WindowText)
98                         : Qt::black;
99         QColor highlight_color = palette.color(QPalette::Active, QPalette::HighlightedText);
100         QColor highlight_bg = palette.color(QPalette::Active, QPalette::Highlight);
101
102         // create a layer with black text turned to QPalette::HighlightedText
103         QPixmap hl_overlay(pixmap.size());
104         hl_overlay.fill(highlight_color);
105         hl_overlay.setMask(pixmap.createMaskFromColor(text_color, Qt::MaskOutColor));
106
107         // Create highlighted background
108         QPixmap hl_background(icon_size);
109         hl_background.fill(highlight_bg);
110
111         // put layers on top of existing pixmap
112         QPainter painter(&pixmap);
113         painter.drawPixmap(pixmap.rect(), hl_background);
114         painter.drawPixmap(pixmap.rect(), hl_overlay);
115
116         return pixmap;
117 }
118
119 /// TeX-name / Math-symbol map.
120 static map<std::string, MathSymbol> math_symbols_;
121 /// Math-symbol / TeX-name map.
122 /// This one is for fast search, it contains the same data as
123 /// \c math_symbols_.
124 static map<char_type, string> tex_names_;
125
126 typedef map<char_type, QListWidgetItem *> ListItems;
127 ListItems left_list_items_;
128 ListItems right_list_items_;
129
130 void initMathSymbols()
131 {
132         // FIXME: Ideally, those unicode codepoints would be defined
133         // in "lib/symbols". Unfortunately, some of those are already
134         // defined with non-unicode ids for use within mathed.
135         // FIXME 2: We should fill-in this map with the parsed "symbols"
136         // file done in MathFactory.cpp.
137         math_symbols_["("] = MathSymbol('(', "lparen");
138         math_symbols_[")"] = MathSymbol(')', "rparen");
139         math_symbols_["{"] = MathSymbol('{', "lbrace");
140         math_symbols_["}"] = MathSymbol('}', "rbrace");
141         math_symbols_["["] = MathSymbol('[', "lbracket");
142         math_symbols_["]"] = MathSymbol(']', "rbracket");
143         math_symbols_["|"] = MathSymbol('|', "mid");
144         math_symbols_["/"] = MathSymbol('/', "slash");
145         math_symbols_["backslash"] = MathSymbol('\\', "backslash");
146         math_symbols_["lceil"] = MathSymbol(0x2308, "lceil");
147         math_symbols_["rceil"] = MathSymbol(0x2309, "rceil");
148         math_symbols_["lfloor"] = MathSymbol(0x230A, "lfloor");
149         math_symbols_["rfloor"] = MathSymbol(0x230B, "rfloor");
150         math_symbols_["langle"] = MathSymbol(0x2329, "langle");
151         math_symbols_["rangle"] = MathSymbol(0x232A, "rangle");
152         math_symbols_["llbracket"] = MathSymbol(0x27e6, "llbracket");
153         math_symbols_["rrbracket"] = MathSymbol(0x27e7, "rrbracket");
154         math_symbols_["uparrow"] = MathSymbol(0x2191, "uparrow");
155         math_symbols_["Uparrow"] = MathSymbol(0x21D1, "uparrow2");
156         math_symbols_["updownarrow"] = MathSymbol(0x2195, "updownarrow");
157         math_symbols_["Updownarrow"] = MathSymbol(0x21D5, "updownarrow2");
158         math_symbols_["downarrow"] = MathSymbol(0x2193, "downarrow");
159         math_symbols_["Downarrow"] = MathSymbol(0x21D3, "downarrow2");
160         math_symbols_["downdownarrows"] = MathSymbol(0x21CA, "downdownarrows");
161         math_symbols_["downharpoonleft"] = MathSymbol(0x21C3, "downharpoonleft");
162         math_symbols_["downharpoonright"] = MathSymbol(0x21C2, "downharpoonright");
163         math_symbols_["vert"] = MathSymbol(0x007C, "vert");
164         math_symbols_["Vert"] = MathSymbol(0x2016, "vert2");
165
166         map<string, MathSymbol>::const_iterator it = math_symbols_.begin();
167         map<string, MathSymbol>::const_iterator end = math_symbols_.end();
168         for (; it != end; ++it)
169                 tex_names_[it->second.unicode] = it->first;
170 }
171
172 /// \return the math unicode symbol associated to a TeX name.
173 MathSymbol const & mathSymbol(string const & tex_name)
174 {
175         map<string, MathSymbol>::const_iterator it =
176                 math_symbols_.find(tex_name);
177
178         static MathSymbol const unknown_symbol;
179         if (it == math_symbols_.end())
180                 return unknown_symbol;
181
182         return it->second;
183 }
184
185 /// \return the TeX name associated to a math unicode symbol.
186 string const & texName(char_type math_symbol)
187 {
188         map<char_type, string>::const_iterator it =
189                 tex_names_.find(math_symbol);
190
191         static string const empty_string;
192         if (it == tex_names_.end())
193                 return empty_string;
194
195         return it->second;
196 }
197
198
199 void setDelimiterName(QListWidgetItem * lwi, string const & name)
200 {
201         lwi->setData(Qt::UserRole, toqstr(name));
202 }
203
204
205 string getDelimiterName(QListWidgetItem const * lwi)
206 {
207         return fromqstr(lwi->data(Qt::UserRole).toString());
208 }
209
210
211 } // namespace
212
213
214 GuiDelimiter::GuiDelimiter(GuiView & lv)
215         : GuiDialog(lv, "mathdelimiter", qt_("Math Delimiter"))
216 {
217         setupUi(this);
218
219         connect(buttonBox, SIGNAL(rejected()), this, SLOT(accept()));
220
221         setFocusProxy(leftLW);
222
223         leftLW->setViewMode(QListView::IconMode);
224         rightLW->setViewMode(QListView::IconMode);
225
226         leftLW->setDragDropMode(QAbstractItemView::NoDragDrop);
227         rightLW->setDragDropMode(QAbstractItemView::NoDragDrop);
228
229         left_list_items_.clear();
230         right_list_items_.clear();
231
232         initMathSymbols();
233
234         QSize icon_size(26, 26);
235
236         // we calculate the appropriate width to fit 4 icons in a row
237         leftLW->setMinimumWidth((4 * (icon_size.width() + (2 * leftLW->spacing())))
238                                 + (leftLW->frameWidth() * 2)
239                                 + leftLW->verticalScrollBar()->height());
240         rightLW->setMinimumWidth((4 * (icon_size.width() + (2 * rightLW->spacing())))
241                                  + (rightLW->frameWidth() * 2)
242                                  + rightLW->verticalScrollBar()->height());
243         leftLW->setIconSize(icon_size);
244         rightLW->setIconSize(icon_size);
245
246         // The last element is the empty one.
247         int const end = nr_latex_delimiters - 1;
248         for (int i = 0; i < end; ++i) {
249                 string const delim = latex_delimiters[i];
250                 MathSymbol const & ms = mathSymbol(delim);
251                 // get pixmap with bullets
252                 QPixmap pixmap = getPixmap("images/math/", toqstr(ms.icon), "svgz,png");
253                 QIcon icon(pixmap);
254                 icon.addPixmap(getSelectedPixmap(pixmap, icon_size), QIcon::Selected);
255                 QListWidgetItem * lwi = new QListWidgetItem(icon, QString());
256                 setDelimiterName(lwi, delim);
257                 left_list_items_[ms.unicode] = lwi;
258                 lwi->setToolTip(toqstr(delim));
259                 lwi->setSizeHint(icon_size);
260                 leftLW->addItem(lwi);
261         }
262
263         for (int i = 0; i != leftLW->count(); ++i) {
264                 MathSymbol const & ms = mathSymbol(getDelimiterName(leftLW->item(i)));
265                 QListWidgetItem * rwi = left_list_items_[doMatch(ms.unicode)]->clone();
266                 right_list_items_[ms.unicode] = rwi;
267                 rightLW->addItem(rwi);
268         }
269
270         // The last element is the empty one.
271         QListWidgetItem * lwi = new QListWidgetItem(qt_("(None)"));
272         lwi->setToolTip(qt_("No Delimiter"));
273         left_list_items_['?'] = lwi;
274         QListWidgetItem * rwi = new QListWidgetItem(qt_("(None)"));
275         rwi->setToolTip(qt_("No Delimiter"));
276         right_list_items_['?'] = rwi;
277         leftLW->addItem(lwi);
278         rightLW->addItem(rwi);
279
280         sizeCO->addItem(qt_("Variable"));
281
282         for (int i = 0; *biggui[i]; ++i)
283                 sizeCO->addItem(qt_(biggui[i]));
284
285         on_leftLW_currentRowChanged(0);
286         // synchronise the scroll bars
287         on_matchCB_stateChanged(matchCB->checkState());
288         bc().setPolicy(ButtonPolicy::IgnorantPolicy);
289 }
290
291
292 char_type GuiDelimiter::doMatch(char_type const symbol)
293 {
294         string const & str = texName(symbol);
295         string match;
296         if (str == "(")
297                 match = ")";
298         else if (str == ")")
299                 match = "(";
300         else if (str == "[")
301                 match = "]";
302         else if (str == "]")
303                 match = "[";
304         else if (str == "{")
305                 match = "}";
306         else if (str == "}")
307                 match = "{";
308         else if (str == "l")
309                 match = "r";
310         else if (str == "rceil")
311                 match = "lceil";
312         else if (str == "lceil")
313                 match = "rceil";
314         else if (str == "rfloor")
315                 match = "lfloor";
316         else if (str == "lfloor")
317                 match = "rfloor";
318         else if (str == "rangle")
319                 match = "langle";
320         else if (str == "langle")
321                 match = "rangle";
322         else if (str == "llbracket")
323                 match = "rrbracket";
324         else if (str == "rrbracket")
325                 match = "llbracket";
326         else if (str == "backslash")
327                 match = "/";
328         else if (str == "/")
329                 match = "backslash";
330         else
331                 return symbol;
332
333         return mathSymbol(match).unicode;
334 }
335
336
337 void GuiDelimiter::updateTeXCode(int size)
338 {
339         bool const bigsize = size != 0;
340
341         docstring left_str = fix_name(getDelimiterName(leftLW->currentItem()),
342                                       bigsize);
343         docstring right_str = fix_name(getDelimiterName(rightLW->currentItem()),
344                                        bigsize);
345
346         if (!bigsize)
347                 tex_code_ = left_str + ' ' + right_str;
348         else {
349                 tex_code_ = from_ascii(bigleft[size]) + ' '
350                         + left_str + ' '
351                         + from_ascii(bigright[size]) + ' '
352                         + right_str;
353         }
354
355         // Generate TeX-code for GUI display.
356         // FIXME: Instead of reconstructing the TeX code it would be nice to
357         // FIXME: retrieve the LateX code directly from mathed.
358         // In all cases, we want the '\' prefix if needed, so we pass 'true'
359         // to fix_name.
360         left_str = fix_name(getDelimiterName(leftLW->currentItem()),
361                             true);
362         right_str = fix_name(getDelimiterName(rightLW->currentItem()),
363                              true);
364         docstring code_str;
365         if (!bigsize)
366                 code_str = "\\left" + left_str + " \\right" + right_str;
367         else {
368                 // There should be nothing in the TeX-code when the delimiter is "None".
369                 if (left_str != ".")
370                         code_str = "\\" + from_ascii(bigleft[size]) + left_str + ' ';
371                 if (right_str != ".")
372                         code_str += "\\" + from_ascii(bigright[size]) + right_str;
373         }
374
375         texCodeL->setText(qt_("TeX Code: ") + toqstr(code_str));
376
377         // Enable the Swap button with non-matched pairs
378         bool const allow_swap =
379                 (doMatch(mathSymbol(getDelimiterName(leftLW->currentItem())).unicode)
380                  != mathSymbol(getDelimiterName(rightLW->currentItem())).unicode);
381         swapPB->setEnabled(allow_swap);
382 }
383
384
385 void  GuiDelimiter::on_buttonBox_clicked(QAbstractButton * button)
386 {
387         switch (buttonBox->standardButton(button)) {
388         case QDialogButtonBox::Apply:
389                 insert();
390                 break;
391         case QDialogButtonBox::Ok:
392                 insert();
393         // fall through
394         case QDialogButtonBox::Cancel:
395                 accept();
396                 break;
397         default:
398                 break;
399         }
400 }
401
402
403 void GuiDelimiter::insert()
404 {
405         if (sizeCO->currentIndex() == 0)
406                 dispatch(FuncRequest(LFUN_MATH_DELIM, tex_code_));
407         else {
408                 docstring command = '"' + tex_code_ + '"';
409                 command = support::subst(command, from_ascii(" "), from_ascii("\" \""));
410                 dispatch(FuncRequest(LFUN_MATH_BIGDELIM, command));
411         }
412         buttonBox->button(QDialogButtonBox::Cancel)->setText(qt_("Close"));
413 }
414
415
416 void GuiDelimiter::on_sizeCO_activated(int index)
417 {
418         updateTeXCode(index);
419 }
420
421
422 void GuiDelimiter::on_leftLW_itemActivated(QListWidgetItem *)
423 {
424         // do not auto-apply if !matchCB->isChecked()
425         if (!matchCB->isChecked())
426                 return;
427         insert();
428         accept();
429 }
430
431
432 void GuiDelimiter::on_rightLW_itemActivated(QListWidgetItem *)
433 {
434         // do not auto-apply if !matchCB->isChecked()
435         if (!matchCB->isChecked())
436                 return;
437         insert();
438         accept();
439 }
440
441
442 void GuiDelimiter::on_leftLW_currentRowChanged(int item)
443 {
444         if (matchCB->isChecked())
445                 rightLW->setCurrentRow(item);
446
447         updateTeXCode(sizeCO->currentIndex());
448 }
449
450
451 void GuiDelimiter::on_rightLW_currentRowChanged(int item)
452 {
453         if (matchCB->isChecked())
454                 leftLW->setCurrentRow(item);
455
456         updateTeXCode(sizeCO->currentIndex());
457 }
458
459
460 void GuiDelimiter::on_matchCB_stateChanged(int state)
461 {
462         // Synchronise the vertical scroll bars when checked
463         QScrollBar * ls = leftLW->verticalScrollBar();
464         QScrollBar * rs = rightLW->verticalScrollBar();
465
466         if (state == Qt::Checked) {
467                 on_leftLW_currentRowChanged(leftLW->currentRow());
468
469                 connect(ls, SIGNAL(valueChanged(int)), rs, SLOT(setValue(int)),
470                         Qt::UniqueConnection);
471                 connect(rs, SIGNAL(valueChanged(int)), ls, SLOT(setValue(int)),
472                         Qt::UniqueConnection);
473                 rs->setValue(ls->value());
474         } else {
475                 ls->disconnect(rs);
476                 rs->disconnect(ls);
477         }
478
479         updateTeXCode(sizeCO->currentIndex());
480 }
481
482 void GuiDelimiter::on_swapPB_clicked()
483 {
484         // Get current math symbol for each side.
485         MathSymbol const & lms =
486                 mathSymbol(getDelimiterName(leftLW->currentItem()));
487         MathSymbol const & rms =
488                 mathSymbol(getDelimiterName(rightLW->currentItem()));
489
490         // Swap and match.
491         char_type const lc = doMatch(rms.unicode);
492         char_type const rc = doMatch(lms.unicode);
493
494         // Convert back to QString to locate them in the widget.
495         MathSymbol const & nlms = mathSymbol(texName(lc));
496         MathSymbol const & nrms = mathSymbol(texName(rc));
497
498         // Locate matching QListWidgetItem.
499         QListWidgetItem * lwi = left_list_items_[nlms.unicode];
500         QListWidgetItem * rwi = right_list_items_[nrms.unicode];
501
502         // Select.
503         leftLW->setCurrentItem(lwi);
504         rightLW->setCurrentItem(rwi);
505
506         updateTeXCode(sizeCO->currentIndex());
507 }
508
509
510 } // namespace frontend
511 } // namespace lyx
512
513 #include "moc_GuiDelimiter.cpp"