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