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