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