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