]> git.lyx.org Git - features.git/blob - src/mathed/formula.C
revert accidential change
[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_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         int const x = int(xx);
218         int const w = width(bv, font);
219         int const d = descent(bv, font);
220         int const a = ascent(bv, font);
221         int const h = a + d;
222
223         MathPainterInfo pi(bv->painter());
224
225         if (preview_->usePreview()) {
226                 pi.pain.image(x + 1, y - a + 1, w - 2, h - 2, 
227                               *(preview_->pimage_->image()));
228         } else {
229                 //pi.base.style = display() ? LM_ST_DISPLAY : LM_ST_TEXT;
230                 pi.base.style = LM_ST_TEXT;
231                 pi.base.font  = font;
232                 pi.base.font.setColor(LColor::math);
233                 if (lcolor.getX11Name(LColor::mathbg)
234                             != lcolor.getX11Name(LColor::background))
235                         pi.pain.fillRectangle(x, y - a, w, h, LColor::mathbg);
236
237                 if (mathcursor &&
238                                 const_cast<InsetFormulaBase const *>(mathcursor->formula()) == this)
239                 {
240                         mathcursor->drawSelection(pi);
241                         //pi.pain.rectangle(x, y - a, w, h, LColor::mathframe);
242                 }
243
244                 par_->draw(pi, x + 1, y);
245         }
246
247         xx += w;
248         xo_ = x;
249         yo_ = y;
250
251         setCursorVisible(false);
252 }
253
254
255 vector<string> const InsetFormula::getLabelList() const
256 {
257         return par()->getLabelList();
258 }
259
260
261 UpdatableInset::RESULT
262 InsetFormula::localDispatch(BufferView * bv, kb_action action,
263          string const & arg)
264 {
265         RESULT result = DISPATCHED;
266
267         switch (action) {
268
269                 case LFUN_BREAKLINE:
270                         bv->lockedInsetStoreUndo(Undo::INSERT);
271                         mathcursor->breakLine();
272                         mathcursor->normalize();
273                         updateLocal(bv, true);
274                         break;
275
276                 case LFUN_MATH_NUMBER:
277                 {
278                         //lyxerr << "toggling all numbers\n";
279                         if (display()) {
280                                 bv->lockedInsetStoreUndo(Undo::INSERT);
281                                 bool old = par()->numberedType();
282                                 for (MathInset::row_type row = 0; row < par_->nrows(); ++row)
283                                         hull()->numbered(row, !old);
284                                 bv->owner()->message(old ? _("No number") : _("Number"));
285                                 updateLocal(bv, true);
286                         }
287                         break;
288                 }
289
290                 case LFUN_MATH_NONUMBER:
291                 {
292                         //lyxerr << "toggling line number\n";
293                         if (display()) {
294                                 bv->lockedInsetStoreUndo(Undo::INSERT);
295                                 MathCursor::row_type row = mathcursor->hullRow();
296                                 bool old = hull()->numbered(row);
297                                 bv->owner()->message(old ? _("No number") : _("Number"));
298                                 hull()->numbered(row, !old);
299                                 updateLocal(bv, true);
300                         }
301                         break;
302                 }
303
304                 case LFUN_INSERT_LABEL:
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 = frontStrip(strip(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         //updatePreview();
394
395         return result;
396 }
397
398
399 bool InsetFormula::display() const
400 {
401         return hullType() != "simple" && hullType() != "none";
402 }
403
404
405 MathHullInset const * InsetFormula::hull() const
406 {
407         lyx::Assert(par_->asHullInset());
408         return par_->asHullInset();
409 }
410
411
412 MathHullInset * InsetFormula::hull()
413 {
414         lyx::Assert(par_->asHullInset());
415         return par_->asHullInset();
416 }
417
418
419 Inset::Code InsetFormula::lyxCode() const
420 {
421         return Inset::MATH_CODE;
422 }
423
424
425 void InsetFormula::validate(LaTeXFeatures & features) const
426 {
427         par_->validate(features);
428 }
429
430
431 bool InsetFormula::insetAllowed(Inset::Code code) const
432 {
433         return
434                 (code == Inset::LABEL_CODE && display())
435                 || code == Inset::REF_CODE
436                 || code == Inset::ERT_CODE;
437 }
438
439
440 int InsetFormula::ascent(BufferView *, LyXFont const &) const
441 {
442         return preview_->usePreview() ?
443                 1 + preview_->pimage_->ascent() : 1 + par_->ascent();
444 }
445
446
447 int InsetFormula::descent(BufferView *, LyXFont const &) const
448 {
449         return preview_->usePreview() ?
450                 1 + preview_->pimage_->descent() : 1 + par_->descent();
451 }
452
453
454 int InsetFormula::width(BufferView * bv, LyXFont const & font) const
455 {
456         metrics(bv, font);
457         return preview_->usePreview() ?
458                 preview_->pimage_->width() : par_->width();
459 }
460
461
462 string InsetFormula::hullType() const
463 {
464         return par()->getType();
465 }
466
467
468 void InsetFormula::mutate(string const & type)
469 {
470         par()->mutate(type);
471 }
472
473
474 //
475 // preview stuff
476 //
477
478 void InsetFormula::generatePreview(grfx::PreviewLoader & ploader) const
479 {
480         // Do nothing if no preview is desired.
481         if (!grfx::Previews::activated())
482                 return;
483
484         preview_->generatePreview(ploader);
485 }
486
487
488 void InsetFormula::PreviewImpl::generatePreview(grfx::PreviewLoader & ploader)
489 {
490         // Generate the LaTeX snippet.
491         string const snippet = latexString();
492
493         pimage_ = ploader.preview(snippet);
494         if (pimage_)
495                 return;
496
497         // If this is the first time of calling, connect to the
498         // grfx::PreviewLoader signal that'll inform us when the preview image
499         // is ready for loading.
500         if (!connection_.connected()) {
501                 connection_ = ploader.imageReady.connect(
502                         boost::bind(&PreviewImpl::previewReady, this, _1));
503         }
504
505         ploader.add(snippet);
506 }
507
508
509 bool InsetFormula::PreviewImpl::usePreview() const
510 {
511         BufferView * view = parent_.view();
512
513         if (!grfx::Previews::activated() ||
514             parent_.par_->asNestInset()->editing() ||
515             !view || !view->buffer())
516                 return false;
517
518         // If the cached grfx::PreviewImage is invalid, update it.
519         string const snippet = latexString();
520         if (!pimage_ || snippet != pimage_->snippet()) {
521                 grfx::PreviewLoader & ploader =
522                         grfx::Previews::get().loader(view->buffer());
523                 pimage_ = ploader.preview(snippet);
524         }
525
526         if (!pimage_)
527                 return false;
528
529         return pimage_->image();
530 }
531
532
533 string const InsetFormula::PreviewImpl::latexString() const
534 {
535         ostringstream ls;
536         WriteStream wi(ls, false, false);
537         parent_.par_->write(wi);
538         return ls.str().c_str();
539 }
540
541
542 void InsetFormula::PreviewImpl::previewReady(grfx::PreviewImage const & pimage)
543 {
544         // Check snippet against the Inset's current contents
545         if (latexString() != pimage.snippet())
546                 return;
547
548         pimage_ = &pimage;
549         BufferView * view = parent_.view();
550         if (view)
551                 view->updateInset(&parent_, false);
552 }