]> git.lyx.org Git - features.git/blob - src/mathed/formula.C
more const correctness
[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 "math_cursor.h"
24 #include "math_parser.h"
25 #include "math_charinset.h"
26 #include "math_arrayinset.h"
27 #include "math_metricsinfo.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 "BufferView.h"
35 #include "gettext.h"
36 #include "debug.h"
37 #include "lyxrc.h"
38 #include "funcrequest.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         InsetFormula & parent() const
77         {
78                 return *static_cast<InsetFormula*>(inset());
79         }
80 };
81
82
83
84 InsetFormula::InsetFormula()
85         : par_(MathAtom(new MathHullInset)),
86           preview_(new PreviewImpl(*this))
87 {}
88
89
90 InsetFormula::InsetFormula(InsetFormula const & other)
91         : InsetFormulaBase(other),
92           par_(other.par_),
93           preview_(new PreviewImpl(*this))
94 {}
95
96
97 InsetFormula::InsetFormula(BufferView * bv)
98         : par_(MathAtom(new MathHullInset)),
99           preview_(new PreviewImpl(*this))
100 {
101         view_ = bv->owner()->view();
102 }
103
104
105 InsetFormula::InsetFormula(string const & data)
106         : par_(MathAtom(new MathHullInset)),
107           preview_(new PreviewImpl(*this))
108 {
109         if (!data.size())
110                 return;
111         if (!mathed_parse_normal(par_, data))
112                 lyxerr << "cannot interpret '" << data << "' as math\n";
113 }
114
115
116
117 InsetFormula::~InsetFormula()
118 {}
119
120
121 Inset * InsetFormula::clone(Buffer const &, bool) const
122 {
123         return new InsetFormula(*this);
124 }
125
126
127 void InsetFormula::write(Buffer const *, ostream & os) const
128 {
129         WriteStream wi(os, false, false);
130         os << par_->fileInsetLabel() << " ";
131         par_->write(wi);
132 }
133
134
135 int InsetFormula::latex(Buffer const *, ostream & os, bool fragile, bool) const
136 {
137         WriteStream wi(os, fragile, true);
138         par_->write(wi);
139         return wi.line();
140 }
141
142
143 int InsetFormula::ascii(Buffer const *, ostream & os, int) const
144 {
145         if (display()) {
146                 TextMetricsInfo mi;
147                 par()->metricsT(mi);
148                 TextPainter tpain(par()->width(), par()->height());
149                 par()->drawT(tpain, 0, par()->ascent());
150                 tpain.show(os, 3);
151                 // reset metrics cache to "real" values
152                 metrics();
153                 return tpain.textheight();
154         } else {
155                 WriteStream wi(os, false, true);
156                 wi << ' ' << (par_->asNestInset()->cell(0)) << ' ';
157                 return wi.line();
158         }
159 }
160
161
162 int InsetFormula::linuxdoc(Buffer const * buf, ostream & os) const
163 {
164         return docbook(buf, os, false);
165 }
166
167
168 int InsetFormula::docbook(Buffer const * buf, ostream & os, bool) const
169 {
170         MathMLStream ms(os);
171         ms << MTag("equation");
172         ms <<   MTag("alt");
173         ms <<    "<[CDATA[";
174         int res = ascii(buf, ms.os(), 0);
175         ms <<    "]]>";
176         ms <<   ETag("alt");
177         ms <<   MTag("math");
178         ms <<    par_;
179         ms <<   ETag("math");
180         ms << ETag("equation");
181         return ms.line() + res;
182 }
183
184
185 void InsetFormula::read(Buffer const *, LyXLex & lex)
186 {
187         mathed_parse_normal(par_, lex);
188         metrics();
189 }
190
191
192 //ostream & operator<<(ostream & os, LyXCursor const & c)
193 //{
194 //      os << '[' << c.x() << ' ' << c.y() << ' ' << c.pos() << ']';
195 //      return os;
196 //}
197
198
199 void InsetFormula::draw(BufferView * bv, LyXFont const & font,
200                         int y, float & xx, bool) const
201 {
202         // This initiates the loading of the preview, so should come
203         // before the metrics are computed.
204         preview_->setView(bv);
205         bool const use_preview = preview_->previewReady();
206
207         int const x = int(xx);
208         int const w = width(bv, font);
209         int const d = descent(bv, font);
210         int const a = ascent(bv, font);
211         int const h = a + d;
212
213         MathPainterInfo pi(bv->painter());
214
215         if (use_preview) {
216                 pi.pain.image(x, y - a, w, h,
217                               *(preview_->pimage()->image(*this, *bv)));
218         } else {
219                 //pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
220                 pi.base.style = LM_ST_TEXT;
221                 pi.base.font  = font;
222                 pi.base.font.setColor(LColor::math);
223                 if (lcolor.getX11Name(LColor::mathbg)
224                             != lcolor.getX11Name(LColor::background))
225                         pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
226
227                 if (mathcursor &&
228                                 const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
229                 {
230                         mathcursor->drawSelection(pi);
231                         //pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
232                 }
233
234                 par_->draw(pi, x + 1, y);
235         }
236
237         xx += w;
238         xo_ = x;
239         yo_ = y;
240
241         setCursorVisible(false);
242 }
243
244
245 vector<string> const InsetFormula::getLabelList() const
246 {
247         vector<string> res;
248         par()->getLabelList(res);
249         return res;
250 }
251
252
253 UpdatableInset::RESULT
254 InsetFormula::localDispatch(BufferView * bv, FuncRequest const & ev)
255 {
256         RESULT result = DISPATCHED;
257
258         switch (ev.action) {
259
260                 case LFUN_BREAKLINE:
261                         bv->lockedInsetStoreUndo(Undo::INSERT);
262                         mathcursor->breakLine();
263                         mathcursor->normalize();
264                         updateLocal(bv, true);
265                         break;
266
267                 case LFUN_MATH_NUMBER:
268                 {
269                         if (!hull())
270                                 break;
271                         //lyxerr << "toggling all numbers\n";
272                         if (display()) {
273                                 bv->lockedInsetStoreUndo(Undo::INSERT);
274                                 bool old = par()->numberedType();
275                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
276                                         hull()->numbered(row, !old);
277                                 bv->owner()->message(old ? _("No number") : _("Number"));
278                                 updateLocal(bv, true);
279                         }
280                         break;
281                 }
282
283                 case LFUN_MATH_NONUMBER:
284                 {
285                         //lyxerr << "toggling line number\n";
286                         if (display()) {
287                                 bv->lockedInsetStoreUndo(Undo::INSERT);
288                                 MathCursor::row_type row = mathcursor->hullRow();
289                                 bool old = hull()->numbered(row);
290                                 bv->owner()->message(old ? _("No number") : _("Number"));
291                                 hull()->numbered(row, !old);
292                                 updateLocal(bv, true);
293                         }
294                         break;
295                 }
296
297                 case LFUN_INSERT_LABEL:
298                 {
299                         if (!hull())
300                                 break;
301
302                         bv->lockedInsetStoreUndo(Undo::INSERT);
303
304                         MathCursor::row_type row = mathcursor->hullRow();
305                         string old_label = hull()->label(row);
306                         string new_label = ev.argument;
307
308                         if (new_label.empty()) {
309                                 string const default_label =
310                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
311                                 pair<bool, string> const res = old_label.empty()
312                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
313                                         : Alert::askForText(_("Enter label:"), old_label);
314                                 if (!res.first)
315                                         break;
316                                 new_label = trim(res.second);
317                         }
318
319                         //if (new_label == old_label)
320                         //      break;  // Nothing to do
321
322                         if (!new_label.empty()) {
323                                 lyxerr << "setting label to '" << new_label << "'\n";
324                                 hull()->numbered(row, true);
325                         }
326
327 #warning FIXME: please check you really mean repaint() ... is it needed,
328 #warning and if so, should it be update() instead ?
329                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
330                                 bv->repaint();
331
332                         hull()->label(row, new_label);
333
334                         updateLocal(bv, true);
335                         break;
336                 }
337
338                 case LFUN_MATH_MUTATE:
339                 {
340                         bv->lockedInsetStoreUndo(Undo::EDIT);
341                         int x;
342                         int y;
343                         mathcursor->getPos(x, y);
344                         mutate(ev.argument);
345                         mathcursor->setPos(x, y);
346                         mathcursor->normalize();
347                         updateLocal(bv, true);
348                         break;
349                 }
350
351                 case LFUN_MATH_EXTERN:
352                 {
353                         bv->lockedInsetStoreUndo(Undo::EDIT);
354                         if (mathcursor)
355                                 mathcursor->handleExtern(ev.argument);
356                         // re-compute inset dimension
357                         metrics(bv);
358                         updateLocal(bv, true);
359                         break;
360                 }
361
362                 case LFUN_MATH_DISPLAY:
363                 {
364                         int x = 0;
365                         int y = 0;
366                         mathcursor->getPos(x, y);
367                         if (hullType() == "simple")
368                                 mutate("equation");
369                         else
370                                 mutate("simple");
371                         mathcursor->setPos(x, y);
372                         mathcursor->normalize();
373                         updateLocal(bv, true);
374                         break;
375                 }
376
377                 case LFUN_PASTESELECTION:
378                 {
379                         string const clip = bv->getClipboard();
380                         if (!clip.empty())
381                                 mathed_parse_normal(par_, clip);
382                         break;
383                 }
384
385                 default:
386                         result = InsetFormulaBase::localDispatch(bv, ev);
387         }
388
389         return result;
390 }
391
392
393 bool InsetFormula::display() const
394 {
395         return hullType() != "simple" && hullType() != "none";
396 }
397
398
399 MathHullInset const * InsetFormula::hull() const
400 {
401         lyx::Assert(par_->asHullInset());
402         return par_->asHullInset();
403 }
404
405
406 MathHullInset * InsetFormula::hull()
407 {
408         lyx::Assert(par_->asHullInset());
409         return par_.nucleus()->asHullInset();
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_.nucleus()->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 }