]> git.lyx.org Git - lyx.git/blob - src/frontends/qt/GuiDelimiter.cpp
Improve some debug messages
[lyx.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 <QPixmap>
30 #include <QCheckBox>
31 #include <QListWidgetItem>
32 #include <QScrollBar>
33
34 #include <map>
35 #include <string>
36
37 using namespace std;
38
39 namespace lyx {
40 namespace frontend {
41
42 namespace {
43
44 static char const *  latex_delimiters[] = {
45         "(", ")", "{", "}", "[", "]",
46         "lceil", "rceil", "lfloor", "rfloor", "langle", "rangle",
47         "llbracket", "rrbracket",
48         "uparrow", "updownarrow", "Uparrow", "Updownarrow", "downarrow", "Downarrow",
49         "|", "Vert", "/", "backslash", ""
50 };
51
52
53 static int const nr_latex_delimiters =
54         sizeof(latex_delimiters) / sizeof(char const *);
55
56 static string const bigleft[]  = {"", "bigl", "Bigl", "biggl", "Biggl"};
57
58 static string const bigright[] = {"", "bigr", "Bigr", "biggr", "Biggr"};
59
60 static char const * const biggui[] = {
61         N_("big[[delimiter size]]"),
62         N_("Big[[delimiter size]]"),
63         N_("bigg[[delimiter size]]"),
64         N_("Bigg[[delimiter size]]"),
65         ""
66 };
67
68
69 // FIXME: It might be better to fix the big delim LFUN to not require
70 // additional '\' prefix.
71 static docstring fix_name(string const & str, bool big)
72 {
73         if (str.empty())
74                 return from_ascii(".");
75         if (!big || str == "(" || str == ")" || str == "[" || str == "]"
76             || str == "|" || str == "/")
77                 return from_ascii(str);
78
79         return "\\" + from_ascii(str);
80 }
81
82 struct MathSymbol {
83         MathSymbol(char_type uc = '?', unsigned char fc = 0,
84                 FontFamily ff = SYMBOL_FAMILY)
85                 : unicode(uc), fontcode(fc), fontfamily(ff)
86         {}
87         char_type unicode;
88         unsigned char fontcode;
89         FontFamily fontfamily;
90 };
91
92 /// TeX-name / Math-symbol map.
93 static map<std::string, MathSymbol> math_symbols_;
94 /// Math-symbol / TeX-name map.
95 /// This one is for fast search, it contains the same data as
96 /// \c math_symbols_.
97 static map<char_type, string> tex_names_;
98
99 void initMathSymbols()
100 {
101         // FIXME: Ideally, those unicode codepoints would be defined
102         // in "lib/symbols". Unfortunately, some of those are already
103         // defined with non-unicode ids for use within mathed.
104         // FIXME 2: We should fill-in this map with the parsed "symbols"
105         // file done in MathFactory.cpp.
106         math_symbols_["("] = MathSymbol('(', 40, CMR_FAMILY);
107         math_symbols_[")"] = MathSymbol(')', 41, CMR_FAMILY);
108         math_symbols_["{"] = MathSymbol('{', 102, CMSY_FAMILY);
109         math_symbols_["}"] = MathSymbol('}', 103, CMSY_FAMILY);
110         math_symbols_["["] = MathSymbol('[', 91, CMR_FAMILY);
111         math_symbols_["]"] = MathSymbol(']', 93, CMR_FAMILY);
112         math_symbols_["|"] = MathSymbol('|', 106, CMSY_FAMILY);
113         math_symbols_["/"] = MathSymbol('/', 47, CMR_FAMILY);
114         math_symbols_["backslash"] = MathSymbol('\\', 110, CMSY_FAMILY);
115         math_symbols_["lceil"] = MathSymbol(0x2308, 100, CMSY_FAMILY);
116         math_symbols_["rceil"] = MathSymbol(0x2309, 101, CMSY_FAMILY);
117         math_symbols_["lfloor"] = MathSymbol(0x230A, 98, CMSY_FAMILY);
118         math_symbols_["rfloor"] = MathSymbol(0x230B, 99, CMSY_FAMILY);
119         math_symbols_["langle"] = MathSymbol(0x2329, 104, CMSY_FAMILY);
120         math_symbols_["rangle"] = MathSymbol(0x232A, 105, CMSY_FAMILY);
121         math_symbols_["llbracket"] = MathSymbol(0x27e6, 74, STMARY_FAMILY);
122         math_symbols_["rrbracket"] = MathSymbol(0x27e7, 75, STMARY_FAMILY);
123         math_symbols_["uparrow"] = MathSymbol(0x2191, 34, CMSY_FAMILY);
124         math_symbols_["Uparrow"] = MathSymbol(0x21D1, 42, CMSY_FAMILY);
125         math_symbols_["updownarrow"] = MathSymbol(0x2195, 108, CMSY_FAMILY);
126         math_symbols_["Updownarrow"] = MathSymbol(0x21D5, 109, CMSY_FAMILY);
127         math_symbols_["downarrow"] = MathSymbol(0x2193, 35, CMSY_FAMILY);
128         math_symbols_["Downarrow"] = MathSymbol(0x21D3, 43, CMSY_FAMILY);
129         math_symbols_["downdownarrows"] = MathSymbol(0x21CA, 184, MSA_FAMILY);
130         math_symbols_["downharpoonleft"] = MathSymbol(0x21C3, 188, MSA_FAMILY);
131         math_symbols_["downharpoonright"] = MathSymbol(0x21C2, 186, MSA_FAMILY);
132         math_symbols_["vert"] = MathSymbol(0x007C, 106, CMSY_FAMILY);
133         math_symbols_["Vert"] = MathSymbol(0x2016, 107, CMSY_FAMILY);
134
135         map<string, MathSymbol>::const_iterator it = math_symbols_.begin();
136         map<string, MathSymbol>::const_iterator end = math_symbols_.end();
137         for (; it != end; ++it)
138                 tex_names_[it->second.unicode] = it->first;
139 }
140
141 /// \return the math unicode symbol associated to a TeX name.
142 MathSymbol const & mathSymbol(string const & tex_name)
143 {
144         map<string, MathSymbol>::const_iterator it =
145                 math_symbols_.find(tex_name);
146
147         static MathSymbol const unknown_symbol;
148         if (it == math_symbols_.end())
149                 return unknown_symbol;
150
151         return it->second;
152 }
153
154 /// \return the TeX name associated to a math unicode symbol.
155 string const & texName(char_type math_symbol)
156 {
157         map<char_type, string>::const_iterator it =
158                 tex_names_.find(math_symbol);
159
160         static string const empty_string;
161         if (it == tex_names_.end())
162                 return empty_string;
163
164         return it->second;
165 }
166
167
168 void setDelimiterName(QListWidgetItem * lwi, string const & name)
169 {
170         lwi->setData(Qt::UserRole, toqstr(name));
171 }
172
173
174 string getDelimiterName(QListWidgetItem const * lwi)
175 {
176         return fromqstr(lwi->data(Qt::UserRole).toString());
177 }
178
179
180 } // namespace
181
182
183 GuiDelimiter::GuiDelimiter(GuiView & lv)
184         : GuiDialog(lv, "mathdelimiter", qt_("Math Delimiter"))
185 {
186         setupUi(this);
187
188         connect(buttonBox, SIGNAL(rejected()), this, SLOT(accept()));
189
190         setFocusProxy(leftLW);
191
192         leftLW->setViewMode(QListView::IconMode);
193         rightLW->setViewMode(QListView::IconMode);
194
195         leftLW->setDragDropMode(QAbstractItemView::NoDragDrop);
196         rightLW->setDragDropMode(QAbstractItemView::NoDragDrop);
197
198         initMathSymbols();
199
200         FontInfo lyxfont;
201         lyxfont.setFamily(CMR_FAMILY);
202         QFontMetrics fm(frontend::getFont(lyxfont));
203         QSize item_size(fm.maxWidth(), fm.height() + 8);
204
205         leftLW->setMinimumWidth(5 * item_size.width());
206         rightLW->setMinimumWidth(5 * item_size.width());
207
208         typedef map<char_type, QListWidgetItem *> ListItems;
209         ListItems list_items;
210         // The last element is the empty one.
211         int const end = nr_latex_delimiters - 1;
212         for (int i = 0; i < end; ++i) {
213                 string const delim = latex_delimiters[i];
214                 MathSymbol const & ms = mathSymbol(delim);
215                 QString symbol(ms.fontcode?
216                         QChar(ms.fontcode) : toqstr(docstring(1, ms.unicode)));
217                 QListWidgetItem * lwi = new QListWidgetItem(symbol);
218                 lyxfont.setFamily(ms.fontfamily);
219                 QFont const & font = frontend::getFont(lyxfont);
220                 lwi->setFont(font);
221                 setDelimiterName(lwi, delim);
222                 lwi->setToolTip(toqstr(delim));
223                 lwi->setSizeHint(item_size);
224                 switch (ms.fontfamily) {
225                 case CMSY_FAMILY:
226                 case STMARY_FAMILY:
227                         // Hack to work around the broken metrics of these fonts
228                         // FIXME: Better fix the fonts or use fonts that are not broken
229                         lwi->setTextAlignment(Qt::AlignTop | Qt::AlignHCenter);
230                         break;
231                 default:
232                         lwi->setTextAlignment(Qt::AlignCenter);
233                 }
234                 list_items[ms.unicode] = lwi;
235                 leftLW->addItem(lwi);
236         }
237
238         for (int i = 0; i != leftLW->count(); ++i) {
239                 MathSymbol const & ms = mathSymbol(getDelimiterName(leftLW->item(i)));
240                 rightLW->addItem(list_items[doMatch(ms.unicode)]->clone());
241         }
242
243         // The last element is the empty one.
244         QListWidgetItem * lwi = new QListWidgetItem(qt_("(None)"));
245         QListWidgetItem * rwi = new QListWidgetItem(qt_("(None)"));
246         leftLW->addItem(lwi);
247         rightLW->addItem(rwi);
248
249         sizeCO->addItem(qt_("Variable"));
250
251         for (int i = 0; *biggui[i]; ++i)
252                 sizeCO->addItem(qt_(biggui[i]));
253
254         on_leftLW_currentRowChanged(0);
255         // synchronise the scroll bars
256         on_matchCB_stateChanged(matchCB->checkState());
257         bc().setPolicy(ButtonPolicy::IgnorantPolicy);
258 }
259
260
261 char_type GuiDelimiter::doMatch(char_type const symbol)
262 {
263         string const & str = texName(symbol);
264         string match;
265         if (str == "(") match = ")";
266         else if (str == ")") match = "(";
267         else if (str == "[") match = "]";
268         else if (str == "]") match = "[";
269         else if (str == "{") match = "}";
270         else if (str == "}") match = "{";
271         else if (str == "l") match = "r";
272         else if (str == "rceil") match = "lceil";
273         else if (str == "lceil") match = "rceil";
274         else if (str == "rfloor") match = "lfloor";
275         else if (str == "lfloor") match = "rfloor";
276         else if (str == "rangle") match = "langle";
277         else if (str == "langle") match = "rangle";
278         else if (str == "llbracket") match = "rrbracket";
279         else if (str == "rrbracket") match = "llbracket";
280         else if (str == "backslash") match = "/";
281         else if (str == "/") match = "backslash";
282         else return symbol;
283
284         return mathSymbol(match).unicode;
285 }
286
287
288 void GuiDelimiter::updateTeXCode(int size)
289 {
290         bool const bigsize = size != 0;
291
292         docstring left_str = fix_name(getDelimiterName(leftLW->currentItem()),
293                                       bigsize);
294         docstring right_str = fix_name(getDelimiterName(rightLW->currentItem()),
295                                        bigsize);
296
297         if (!bigsize)
298                 tex_code_ = left_str + ' ' + right_str;
299         else {
300                 tex_code_ = from_ascii(bigleft[size]) + ' '
301                         + left_str + ' '
302                         + from_ascii(bigright[size]) + ' '
303                         + right_str;
304         }
305
306         // Generate TeX-code for GUI display.
307         // FIXME: Instead of reconstructing the TeX code it would be nice to
308         // FIXME: retrieve the LateX code directly from mathed.
309         // In all cases, we want the '\' prefix if needed, so we pass 'true'
310         // to fix_name.
311         left_str = fix_name(getDelimiterName(leftLW->currentItem()),
312                             true);
313         right_str = fix_name(getDelimiterName(rightLW->currentItem()),
314                              true);
315         docstring code_str;
316         if (!bigsize)
317                 code_str = "\\left" + left_str + " \\right" + right_str;
318         else {
319                 // There should be nothing in the TeX-code when the delimiter is "None".
320                 if (left_str != ".")
321                         code_str = "\\" + from_ascii(bigleft[size]) + left_str + ' ';
322                 if (right_str != ".")
323                         code_str += "\\" + from_ascii(bigright[size]) + right_str;
324         }
325
326         texCodeL->setText(qt_("TeX Code: ") + toqstr(code_str));
327
328         // Enable the Swap button with non-matched pairs
329         bool const allow_swap =
330                 (doMatch(mathSymbol(getDelimiterName(leftLW->currentItem())).unicode)
331                  != mathSymbol(getDelimiterName(rightLW->currentItem())).unicode);
332         swapPB->setEnabled(allow_swap);
333 }
334
335
336 void  GuiDelimiter::on_buttonBox_clicked(QAbstractButton * button)
337 {
338         switch (buttonBox->standardButton(button)) {
339         case QDialogButtonBox::Apply:
340                 insert();
341                 break;
342         case QDialogButtonBox::Ok:
343                 insert();
344         // fall through
345         case QDialogButtonBox::Cancel:
346                 accept();
347                 break;
348         default:
349                 break;
350         }
351 }
352
353
354 void GuiDelimiter::insert()
355 {
356         if (sizeCO->currentIndex() == 0)
357                 dispatch(FuncRequest(LFUN_MATH_DELIM, tex_code_));
358         else {
359                 docstring command = '"' + tex_code_ + '"';
360                 command = support::subst(command, from_ascii(" "), from_ascii("\" \""));
361                 dispatch(FuncRequest(LFUN_MATH_BIGDELIM, command));
362         }
363         buttonBox->button(QDialogButtonBox::Cancel)->setText(qt_("Close"));
364 }
365
366
367 void GuiDelimiter::on_sizeCO_activated(int index)
368 {
369         updateTeXCode(index);
370 }
371
372
373 void GuiDelimiter::on_leftLW_itemActivated(QListWidgetItem *)
374 {
375         // do not auto-apply if !matchCB->isChecked()
376         if (!matchCB->isChecked())
377                 return;
378         insert();
379         accept();
380 }
381
382
383 void GuiDelimiter::on_rightLW_itemActivated(QListWidgetItem *)
384 {
385         // do not auto-apply if !matchCB->isChecked()
386         if (!matchCB->isChecked())
387                 return;
388         insert();
389         accept();
390 }
391
392
393 void GuiDelimiter::on_leftLW_currentRowChanged(int item)
394 {
395         if (matchCB->isChecked())
396                 rightLW->setCurrentRow(item);
397
398         updateTeXCode(sizeCO->currentIndex());
399 }
400
401
402 void GuiDelimiter::on_rightLW_currentRowChanged(int item)
403 {
404         if (matchCB->isChecked())
405                 leftLW->setCurrentRow(item);
406
407         updateTeXCode(sizeCO->currentIndex());
408 }
409
410
411 void GuiDelimiter::on_matchCB_stateChanged(int state)
412 {
413         // Synchronise the vertical scroll bars when checked
414         QScrollBar * ls = leftLW->verticalScrollBar();
415         QScrollBar * rs = rightLW->verticalScrollBar();
416
417         if (state == Qt::Checked) {
418                 on_leftLW_currentRowChanged(leftLW->currentRow());
419
420                 connect(ls, SIGNAL(valueChanged(int)), rs, SLOT(setValue(int)),
421                         Qt::UniqueConnection);
422                 connect(rs, SIGNAL(valueChanged(int)), ls, SLOT(setValue(int)),
423                         Qt::UniqueConnection);
424                 rs->setValue(ls->value());
425         } else {
426                 ls->disconnect(rs);
427                 rs->disconnect(ls);
428         }
429
430         updateTeXCode(sizeCO->currentIndex());
431 }
432
433 void GuiDelimiter::on_swapPB_clicked()
434 {
435         // Get current math symbol for each side.
436         MathSymbol const & lms =
437                 mathSymbol(getDelimiterName(leftLW->currentItem()));
438         MathSymbol const & rms =
439                 mathSymbol(getDelimiterName(rightLW->currentItem()));
440
441         // Swap and match.
442         char_type const lc = doMatch(rms.unicode);
443         char_type const rc = doMatch(lms.unicode);
444
445         // Convert back to QString to locate them in the widget.
446         MathSymbol const & nlms = mathSymbol(texName(lc));
447         MathSymbol const & nrms = mathSymbol(texName(rc));
448         QString lqs(nlms.fontcode ?
449                 QChar(nlms.fontcode) : toqstr(docstring(1, nlms.unicode)));
450         QString rqs(nrms.fontcode ?
451                 QChar(nrms.fontcode) : toqstr(docstring(1, nrms.unicode)));
452
453         // Handle unencoded "symbol" of "(None)".
454         if (lqs == "?")
455                 lqs = qt_("(None)");
456         if(rqs == "?")
457                 rqs = qt_("(None)");
458
459         // Locate matching QListWidgetItem.
460         QList<QListWidgetItem *> lwi = leftLW->findItems(lqs, Qt::MatchExactly);
461         QList<QListWidgetItem *> rwi = rightLW->findItems(rqs, Qt::MatchExactly);
462
463         // Select.
464         leftLW->setCurrentItem(lwi.first());
465         rightLW->setCurrentItem(rwi.first());
466
467         updateTeXCode(sizeCO->currentIndex());
468 }
469
470
471 Dialog * createGuiDelimiter(GuiView & lv) { return new GuiDelimiter(lv); }
472
473
474 } // namespace frontend
475 } // namespace lyx
476
477 #include "moc_GuiDelimiter.cpp"