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