]> git.lyx.org Git - features.git/blob - src/mathed/formula.C
binom is binom is binom and choose is choose is choose ...
[features.git] / src / mathed / formula.C
1 /*
2 *  File:        formula.C
3 *  Purpose:     Implementation of formula inset
4 *  Author:      Alejandro Aguilar Sierra <asierra@servidor.unam.mx>
5 *  Created:     January 1996
6 *  Description: Allows the edition of math paragraphs inside Lyx.
7 *
8 *  Copyright: 1996-1998 Alejandro Aguilar Sierra
9 *
10 *  Version: 0.4, Lyx project.
11 *
12 *   You are free to use and modify this code under the terms of
13 *   the GNU General Public Licence version 2 or later.
14 */
15
16 #ifdef __GNUG__
17 #pragma implementation
18 #endif
19
20 #include <config.h>
21
22 #include "formula.h"
23 #include "commandtags.h"
24 #include "math_cursor.h"
25 #include "math_parser.h"
26 #include "math_charinset.h"
27 #include "math_arrayinset.h"
28 #include "math_deliminset.h"
29 #include "lyx_main.h"
30 #include "BufferView.h"
31 #include "gettext.h"
32 #include "debug.h"
33 #include "support/LOstream.h"
34 #include "support/LAssert.h"
35 #include "support/lyxlib.h"
36 #include "support/systemcall.h"
37 #include "support/filetools.h"
38 #include "frontends/Alert.h"
39 #include "frontends/LyXView.h"
40 #include "frontends/Painter.h"
41 #include "graphics/GraphicsImage.h"
42 #include "lyxrc.h"
43 #include "math_hullinset.h"
44 #include "math_support.h"
45 #include "math_mathmlstream.h"
46 #include "textpainter.h"
47
48 #include <fstream>
49 #include <boost/bind.hpp>
50 #include <boost/utility.hpp>
51
52 using std::ostream;
53 using std::ifstream;
54 using std::istream;
55 using std::pair;
56 using std::endl;
57 using std::vector;
58 using std::getline;
59
60
61
62 InsetFormula::InsetFormula()
63         : par_(MathAtom(new MathHullInset)), loader_(0)
64 {}
65
66
67 InsetFormula::InsetFormula(BufferView * bv)
68         : par_(MathAtom(new MathHullInset)), loader_(0)
69 {
70         view_ = bv;
71 }
72
73
74 InsetFormula::InsetFormula(string const & data)
75         : par_(MathAtom(new MathHullInset)), loader_(0)
76 {
77         if (!data.size())
78                 return;
79         if (!mathed_parse_normal(par_, data)) 
80                 lyxerr << "cannot interpret '" << data << "' as math\n";
81 }
82
83
84
85 Inset * InsetFormula::clone(Buffer const &, bool) const
86 {
87         return new InsetFormula(*this);
88 }
89
90
91 void InsetFormula::write(Buffer const *, ostream & os) const
92 {
93         os << "Formula ";
94         WriteStream wi(os, false, false);
95         par_->write(wi);
96 }
97
98
99 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
100 {
101         WriteStream wi(os, fragile, true);
102         par_->write(wi);
103         return wi.line();
104 }
105
106
107
108 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
109 {
110 #if 0
111         TextMetricsInfo mi;
112         par()->metricsT(mi);
113         TextPainter tpain(par()->width(), par()->height());
114         par()->drawT(tpain, 0, par()->ascent());
115         tpain.show(os);
116         // reset metrics cache to "real" values
117         metrics();
118         return tpain.textheight();
119 #else
120         WriteStream wi(os, false, true);
121         par_->write(wi);
122         return wi.line();
123 #endif
124 }
125
126
127 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
128 {
129         return docbook(buf, os, false);
130 }
131
132
133 int InsetFormula::docbook(Buffer const * buf, ostream & os, bool) const
134 {
135         MathMLStream ms(os);
136         ms << MTag("equation");
137         ms <<   MTag("alt");
138         ms <<    "<[CDATA[";
139         int res = ascii(buf, ms.os(), 0);
140         ms <<    "]]>";
141         ms <<   ETag("alt");
142         ms <<   MTag("math");
143         ms <<    par_.nucleus();
144         ms <<   ETag("math");
145         ms << ETag("equation");
146         return ms.line() + res;
147 }
148
149
150 void InsetFormula::read(Buffer const *, LyXLex & lex)
151 {
152         mathed_parse_normal(par_, lex);
153         metrics();
154         updatePreview();
155 }
156
157
158 //ostream & operator<<(ostream & os, LyXCursor const & c)
159 //{
160 //      os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
161 //      return os;
162 //}
163
164
165 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
166                         int y, float & xx, bool) const
167 {
168         int const x = int(xx);
169         int const w = width(bv, font);
170         int const d = descent(bv, font);
171         int const a = ascent(bv, font);
172         int const h = a + d;
173
174         MathPainterInfo pi(bv->painter());
175
176         if (canPreview()) {
177                 pi.pain.image(x + 1, y - a + 1, w - 2, h - 2, *(loader_->image()));
178         } else {
179                 //pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
180                 pi.base.style = LM_ST_TEXT;
181                 pi.base.font  = font;
182                 pi.base.font.setColor(LColor::math);
183                 if (lcolor.getX11Name(LColor::mathbg)
184                             != lcolor.getX11Name(LColor::background))
185                         pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
186
187                 if (mathcursor &&
188                                 const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
189                 {
190                         mathcursor->drawSelection(pi);
191                         pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
192                 }
193
194                 par_->draw(pi, x, y);
195         }
196
197         xx += w;
198         xo_ = x;
199         yo_ = y;
200
201         setCursorVisible(false);
202 }
203
204
205 vector<string> const InsetFormula::getLabelList() const
206 {
207         return hull()->getLabelList();
208 }
209
210
211 UpdatableInset::RESULT
212 InsetFormula::localDispatch(BufferView * bv, kb_action action,
213          string const & arg)
214 {
215         RESULT result = DISPATCHED;
216
217         switch (action) {
218
219                 case LFUN_BREAKLINE:
220                         bv->lockedInsetStoreUndo(Undo::INSERT);
221                         mathcursor->breakLine();
222                         mathcursor->normalize();
223                         updateLocal(bv, true);
224                         break;
225
226                 case LFUN_MATH_NUMBER:
227                 {
228                         //lyxerr << "toggling all numbers\n";
229                         if (display()) {
230                                 bv->lockedInsetStoreUndo(Undo::INSERT);
231                                 bool old = hull()->numberedType();
232                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
233                                         hull()->numbered(row, !old);
234                                 bv->owner()->message(old ? _("No number") : _("Number"));
235                                 updateLocal(bv, true);
236                         }
237                         break;
238                 }
239
240                 case LFUN_MATH_NONUMBER:
241                 {
242                         //lyxerr << "toggling line number\n";
243                         if (display()) {
244                                 bv->lockedInsetStoreUndo(Undo::INSERT);
245                                 MathCursor::row_type row = mathcursor->hullRow();
246                                 bool old = hull()->numbered(row);
247                                 bv->owner()->message(old ? _("No number") : _("Number"));
248                                 hull()->numbered(row, !old);
249                                 updateLocal(bv, true);
250                         }
251                         break;
252                 }
253
254                 case LFUN_INSERT_LABEL:
255                 {
256                         bv->lockedInsetStoreUndo(Undo::INSERT);
257
258                         MathCursor::row_type row = mathcursor->hullRow();
259                         string old_label = hull()->label(row);
260                         string new_label = arg;
261
262                         if (new_label.empty()) {
263                                 string const default_label =
264                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
265                                 pair<bool, string> const res = old_label.empty()
266                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
267                                         : Alert::askForText(_("Enter label:"), old_label);
268                                 if (!res.first)
269                                         break;
270                                 new_label = frontStrip(strip(res.second));
271                         }
272
273                         //if (new_label == old_label)
274                         //      break;  // Nothing to do
275
276                         if (!new_label.empty()) {
277                                 lyxerr << "setting label to '" << new_label << "'\n";
278                                 hull()->numbered(row, true);
279                         }
280
281 #warning FIXME: please check you really mean repaint() ... is it needed,
282 #warning and if so, should it be update() instead ? 
283                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
284                                 bv->repaint();
285
286                         hull()->label(row, new_label);
287
288                         updateLocal(bv, true);
289                         break;
290                 }
291
292                 case LFUN_MATH_MUTATE:
293                 {
294                         bv->lockedInsetStoreUndo(Undo::EDIT);
295                         int x;
296                         int y;
297                         mathcursor->getPos(x, y);
298                         mutate(arg);
299                         mathcursor->setPos(x, y);
300                         mathcursor->normalize();
301                         updateLocal(bv, true);
302                         break;
303                 }
304
305                 case LFUN_MATH_EXTERN:
306                 {
307                         bv->lockedInsetStoreUndo(Undo::EDIT);
308                         if (mathcursor)
309                                 mathcursor->handleExtern(arg);
310                         // re-compute inset dimension
311                         metrics(bv);
312                         updateLocal(bv, true);
313                         break;
314                 }
315
316                 case LFUN_MATH_DISPLAY:
317                 {
318                         int x = 0;
319                         int y = 0;
320                         mathcursor->getPos(x, y);
321                         if (hullType() == "simple")
322                                 mutate("equation");
323                         else
324                                 mutate("simple");
325                         mathcursor->setPos(x, y);
326                         mathcursor->normalize();
327                         updateLocal(bv, true);
328                         break;
329                 }
330
331                 case LFUN_PASTESELECTION:
332                 {
333                         string const clip = bv->getClipboard();
334                 if (!clip.empty())
335                                 mathed_parse_normal(par_, clip);
336                         break;
337                 }
338
339                 default:
340                         result = InsetFormulaBase::localDispatch(bv, action, arg);
341         }
342
343         //updatePreview();
344
345         return result;
346 }
347
348
349 bool InsetFormula::display() const
350 {
351         return hullType() != "simple" && hullType() != "none";
352 }
353
354
355 MathHullInset const * InsetFormula::hull() const
356 {
357         lyx::Assert(par_->asHullInset());
358         return par_->asHullInset();
359 }
360
361
362 MathHullInset * InsetFormula::hull()
363 {
364         lyx::Assert(par_->asHullInset());
365         return par_->asHullInset();
366 }
367
368
369 Inset::Code InsetFormula::lyxCode() const
370 {
371         return Inset::MATH_CODE;
372 }
373
374
375 void InsetFormula::validate(LaTeXFeatures & features) const
376 {
377         par_->validate(features);
378 }
379
380
381 bool InsetFormula::insetAllowed(Inset::Code code) const
382 {
383         return
384                 (code == Inset::LABEL_CODE && display())
385                 || code == Inset::REF_CODE      
386                 || code == Inset::ERT_CODE;
387 }
388
389
390 int InsetFormula::ascent(BufferView *, LyXFont const &) const
391 {
392         const int a = par_->ascent();
393         if (!canPreview())
394                 return a + 1;
395         return a + 1 - (par_->height() - loader_->image()->getHeight()) / 2;
396 }
397
398
399 int InsetFormula::descent(BufferView *, LyXFont const &) const
400 {
401         const int d = par_->descent();
402         if (!canPreview())
403                 return d + 1;
404         return d + 1 - (par_->height() - loader_->image()->getHeight()) / 2;
405 }
406
407
408 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
409 {
410         metrics(bv, font);
411         return canPreview() ? loader_->image()->getWidth() : par_->width();
412 }
413
414
415 string InsetFormula::hullType() const
416 {
417         return hull() ? hull()->getType() : "none";
418 }
419
420
421 void InsetFormula::mutate(string const & type )
422 {
423         if (hull())
424                 hull()->mutate(type);
425 }
426
427
428 //
429 // preview stuff
430 //
431
432 bool InsetFormula::canPreview() const
433 {
434         return lyxrc.preview && loader_ && !par_->asNestInset()->editing()
435                 && loader_->status() == grfx::Ready;
436 }
437
438
439 void InsetFormula::statusChanged()
440 {
441         lyxerr << "### InsetFormula::statusChanged called!, status: "
442                 << loader_->status() << "\n";
443         if (loader_->status() == grfx::Ready) 
444                 view()->updateInset(this, false);
445         else if (loader_->status() == grfx::WaitingToLoad)
446                 loader_->startLoading();
447 }
448
449
450 void InsetFormula::updatePreview()
451 {
452         // nothing to be done if no preview requested
453         lyxerr << "### updatePreview() called\n";
454         if (!lyxrc.preview)
455                 return;
456
457         // get LaTeX 
458         ostringstream ls;
459         WriteStream wi(ls, false, false);
460         par_->write(wi);
461         string const data = ls.str();
462
463         // the preview cache, maps contents to image loaders
464         typedef std::map<string, boost::shared_ptr<grfx::Loader> > cache_type;
465         static cache_type theCache;
466         static int theCounter = 0;
467
468         // set our loader corresponding to our current data
469         cache_type::const_iterator it = theCache.find(data);
470
471         // is this old data?
472         if (it != theCache.end()) {
473                 // we have already a loader, connect to it anyway
474                 //lyxerr << "### updatePreview(), old loader: " << loader_ << "\n";
475                 loader_ = it->second.get();
476                 loader_->statusChanged.connect
477                         (boost::bind(&InsetFormula::statusChanged, this));
478                 return;
479         }
480
481         // construct new file name
482         static string const dir = OnlyPath(lyx::tempName());
483         ostringstream os;
484         os << dir << theCounter++ << ".lyxpreview";
485         string file = os.str();
486
487         // the real work starts
488         //lyxerr << "### updatePreview(), new file " << file << "\n";
489         std::ofstream of(file.c_str());
490         of << "\\batchmode"
491                  << "\\documentclass{article}"
492                  << "\\usepackage{amssymb}"
493                  << "\\thispagestyle{empty}"
494                  << "\\pdfoutput=0"
495                  << "\\begin{document}"
496                  << data
497                  << "\\end{document}\n";
498         of.close();
499
500         // now we are done, start actual loading we will get called back via
501         // InsetFormula::statusChanged() if this is finished
502         theCache[data].reset(new grfx::Loader(file));
503         //lyxerr << "### updatePreview(), new loader: " << loader_ << "\n";
504         loader_ = theCache.find(data)->second.get();
505         loader_->startLoading();
506         loader_->statusChanged.connect(boost::bind(&InsetFormula::statusChanged, this));
507 }
508