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