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.
fix_name(string const & str,bool big)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 {
MathSymbollyx::frontend::__anon8ad910160111::MathSymbol83 	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 
initMathSymbols()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.
mathSymbol(string tex_name)142 MathSymbol const & mathSymbol(string 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.
texName(char_type math_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 
setDelimiterName(QListWidgetItem * lwi,string const & name)168 void setDelimiterName(QListWidgetItem * lwi, string const & name)
169 {
170 	lwi->setData(Qt::UserRole, toqstr(name));
171 }
172 
173 
getDelimiterName(QListWidgetItem const * lwi)174 string getDelimiterName(QListWidgetItem const * lwi)
175 {
176 	return fromqstr(lwi->data(Qt::UserRole).toString());
177 }
178 
179 
180 } // namespace
181 
182 
GuiDelimiter(GuiView & lv)183 GuiDelimiter::GuiDelimiter(GuiView & lv)
184 	: GuiDialog(lv, "mathdelimiter", qt_("Math Delimiter"))
185 {
186 	setupUi(this);
187 
188 	connect(closePB, SIGNAL(clicked()), 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 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 
doMatch(char_type const symbol)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 
updateTeXCode(int size)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 
on_insertPB_clicked()336 void GuiDelimiter::on_insertPB_clicked()
337 {
338 	if (sizeCO->currentIndex() == 0)
339 		dispatch(FuncRequest(LFUN_MATH_DELIM, tex_code_));
340 	else {
341 		docstring command = '"' + tex_code_ + '"';
342 		command = support::subst(command, from_ascii(" "), from_ascii("\" \""));
343 		dispatch(FuncRequest(LFUN_MATH_BIGDELIM, command));
344 	}
345 }
346 
347 
on_sizeCO_activated(int index)348 void GuiDelimiter::on_sizeCO_activated(int index)
349 {
350 	updateTeXCode(index);
351 }
352 
353 
on_leftLW_itemActivated(QListWidgetItem *)354 void GuiDelimiter::on_leftLW_itemActivated(QListWidgetItem *)
355 {
356 	// do not auto-apply if !matchCB->isChecked()
357 	if (!matchCB->isChecked())
358 		return;
359 	on_insertPB_clicked();
360 	accept();
361 }
362 
363 
on_rightLW_itemActivated(QListWidgetItem *)364 void GuiDelimiter::on_rightLW_itemActivated(QListWidgetItem *)
365 {
366 	// do not auto-apply if !matchCB->isChecked()
367 	if (!matchCB->isChecked())
368 		return;
369 	on_insertPB_clicked();
370 	accept();
371 }
372 
373 
on_leftLW_currentRowChanged(int item)374 void GuiDelimiter::on_leftLW_currentRowChanged(int item)
375 {
376 	if (matchCB->isChecked())
377 		rightLW->setCurrentRow(item);
378 
379 	updateTeXCode(sizeCO->currentIndex());
380 }
381 
382 
on_rightLW_currentRowChanged(int item)383 void GuiDelimiter::on_rightLW_currentRowChanged(int item)
384 {
385 	if (matchCB->isChecked())
386 		leftLW->setCurrentRow(item);
387 
388 	updateTeXCode(sizeCO->currentIndex());
389 }
390 
391 
on_matchCB_stateChanged(int state)392 void GuiDelimiter::on_matchCB_stateChanged(int state)
393 {
394 	// Synchronise the vertical scroll bars when checked
395 	QScrollBar * ls = leftLW->verticalScrollBar();
396 	QScrollBar * rs = rightLW->verticalScrollBar();
397 
398 	if (state == Qt::Checked) {
399 		on_leftLW_currentRowChanged(leftLW->currentRow());
400 
401 		connect(ls, SIGNAL(valueChanged(int)), rs, SLOT(setValue(int)),
402 		        Qt::UniqueConnection);
403 		connect(rs, SIGNAL(valueChanged(int)), ls, SLOT(setValue(int)),
404 		        Qt::UniqueConnection);
405 		rs->setValue(ls->value());
406 	} else {
407 		ls->disconnect(rs);
408 		rs->disconnect(ls);
409 	}
410 
411 	updateTeXCode(sizeCO->currentIndex());
412 }
413 
on_swapPB_clicked()414 void GuiDelimiter::on_swapPB_clicked()
415 {
416 	// Get current math symbol for each side.
417 	MathSymbol const & lms =
418 		mathSymbol(getDelimiterName(leftLW->currentItem()));
419 	MathSymbol const & rms =
420 		mathSymbol(getDelimiterName(rightLW->currentItem()));
421 
422 	// Swap and match.
423 	char_type const lc = doMatch(rms.unicode);
424 	char_type const rc = doMatch(lms.unicode);
425 
426 	// Convert back to QString to locate them in the widget.
427 	MathSymbol const & nlms = mathSymbol(texName(lc));
428 	MathSymbol const & nrms = mathSymbol(texName(rc));
429 	QString lqs(nlms.fontcode ?
430 		QChar(nlms.fontcode) : toqstr(docstring(1, nlms.unicode)));
431 	QString rqs(nrms.fontcode ?
432 		QChar(nrms.fontcode) : toqstr(docstring(1, nrms.unicode)));
433 
434 	// Handle unencoded "symbol" of "(None)".
435 	if (lqs == "?")
436 		lqs = qt_("(None)");
437 	if(rqs == "?")
438 		rqs = qt_("(None)");
439 
440 	// Locate matching QListWidgetItem.
441 	QList<QListWidgetItem *> lwi = leftLW->findItems(lqs, Qt::MatchExactly);
442 	QList<QListWidgetItem *> rwi = rightLW->findItems(rqs, Qt::MatchExactly);
443 
444 	// Select.
445 	leftLW->setCurrentItem(lwi.first());
446 	rightLW->setCurrentItem(rwi.first());
447 
448 	updateTeXCode(sizeCO->currentIndex());
449 }
450 
451 
createGuiDelimiter(GuiView & lv)452 Dialog * createGuiDelimiter(GuiView & lv) { return new GuiDelimiter(lv); }
453 
454 
455 } // namespace frontend
456 } // namespace lyx
457 
458 #include "moc_GuiDelimiter.cpp"
459