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