]> git.lyx.org Git - features.git/blob - src/mathed/formula.C
the lfun3 patches (overall cleanup and "localizing" dispatch() in mathed)
[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(FuncRequest const & ev)
255 {
256         RESULT result = DISPATCHED;
257         BufferView *bv = ev.view();
258
259         switch (ev.action) {
260
261                 case LFUN_INSERT_LABEL:
262                 {
263                         if (!hull())
264                                 break;
265
266                         bv->lockedInsetStoreUndo(Undo::EDIT);
267
268                         MathCursor::row_type row = mathcursor->hullRow();
269                         string old_label = hull()->label(row);
270                         string new_label = ev.argument;
271
272                         if (new_label.empty()) {
273                                 string const default_label =
274                                         (lyxrc.label_init_length >= 0) ? "eq:" : "";
275                                 pair<bool, string> const res = old_label.empty()
276                                         ? Alert::askForText(_("Enter new label to insert:"), default_label)
277                                         : Alert::askForText(_("Enter label:"), old_label);
278                                 if (!res.first)
279                                         break;
280                                 new_label = trim(res.second);
281                         }
282
283                         //if (new_label == old_label)
284                         //      break;  // Nothing to do
285
286                         if (!new_label.empty()) {
287                                 lyxerr << "setting label to '" << new_label << "'\n";
288                                 hull()->numbered(row, true);
289                         }
290
291 #warning FIXME: please check you really mean repaint() ... is it needed,
292 #warning and if so, should it be update() instead ?
293                         if (!new_label.empty() && bv->ChangeRefsIfUnique(old_label, new_label))
294                                 bv->repaint();
295
296                         hull()->label(row, new_label);
297
298                         updateLocal(bv, true);
299                         break;
300                 }
301
302                 case LFUN_MATH_MUTATE:
303                 {
304                         bv->lockedInsetStoreUndo(Undo::EDIT);
305                         int x;
306                         int y;
307                         mathcursor->getPos(x, y);
308                         mutate(ev.argument);
309                         mathcursor->setPos(x, y);
310                         mathcursor->normalize();
311                         updateLocal(bv, true);
312                         break;
313                 }
314
315                 case LFUN_MATH_EXTERN:
316                 {
317                         bv->lockedInsetStoreUndo(Undo::EDIT);
318                         if (mathcursor)
319                                 mathcursor->handleExtern(ev.argument);
320                         // re-compute inset dimension
321                         metrics(bv);
322                         updateLocal(bv, true);
323                         break;
324                 }
325
326                 case LFUN_MATH_DISPLAY:
327                 {
328                         int x = 0;
329                         int y = 0;
330                         mathcursor->getPos(x, y);
331                         if (hullType() == "simple")
332                                 mutate("equation");
333                         else
334                                 mutate("simple");
335                         mathcursor->setPos(x, y);
336                         mathcursor->normalize();
337                         updateLocal(bv, true);
338                         break;
339                 }
340
341                 case LFUN_PASTESELECTION:
342                 {
343                         string const clip = bv->getClipboard();
344                         if (!clip.empty())
345                                 mathed_parse_normal(par_, clip);
346                         break;
347                 }
348
349                 default:
350                         result = InsetFormulaBase::localDispatch(ev);
351         }
352
353         return result;
354 }
355
356
357 bool InsetFormula::display() const
358 {
359         return hullType() != "simple" && hullType() != "none";
360 }
361
362
363 MathHullInset const * InsetFormula::hull() const
364 {
365         lyx::Assert(par_->asHullInset());
366         return par_->asHullInset();
367 }
368
369
370 MathHullInset * InsetFormula::hull()
371 {
372         lyx::Assert(par_->asHullInset());
373         return par_.nucleus()->asHullInset();
374 }
375
376 Inset::Code InsetFormula::lyxCode() const
377 {
378         return Inset::MATH_CODE;
379 }
380
381
382 void InsetFormula::validate(LaTeXFeatures & features) const
383 {
384         par_->validate(features);
385 }
386
387
388 bool InsetFormula::insetAllowed(Inset::Code code) const
389 {
390         return
391                 (code == Inset::LABEL_CODE && display())
392                 || code == Inset::REF_CODE
393                 || code == Inset::ERT_CODE;
394 }
395
396
397 int InsetFormula::ascent(BufferView *, LyXFont const &) const
398 {
399         return preview_->previewReady() ?
400                 preview_->pimage()->ascent() : 1 + par_->ascent();
401 }
402
403
404 int InsetFormula::descent(BufferView *, LyXFont const &) const
405 {
406         if (!preview_->previewReady())
407                 return 1 + par_->descent();
408
409         int const descent = preview_->pimage()->descent();
410         return display() ? descent + 12 : descent;
411 }
412
413
414 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
415 {
416         metrics(bv, font);
417         return preview_->previewReady() ?
418                 preview_->pimage()->width() : par_->width();
419 }
420
421
422 string InsetFormula::hullType() const
423 {
424         return par()->getType();
425 }
426
427
428 void InsetFormula::mutate(string const & type)
429 {
430         par_.nucleus()->mutate(type);
431 }
432
433
434 //
435 // preview stuff
436 //
437
438 void InsetFormula::addPreview(grfx::PreviewLoader & ploader) const
439 {
440         preview_->addPreview(ploader);
441 }
442
443
444 void InsetFormula::generatePreview() const
445 {
446         preview_->generatePreview();
447 }
448
449
450 bool InsetFormula::PreviewImpl::previewWanted() const
451 {
452         return !parent().par_->asNestInset()->editing();
453 }
454
455
456 string const InsetFormula::PreviewImpl::latexString() const
457 {
458         ostringstream ls;
459         WriteStream wi(ls, false, false);
460         parent().par_->write(wi);
461         return ls.str().c_str();
462 }