]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
8d2f1f86df1735a62e0444fe43fb5c81ea11c081
[lyx.git] / src / insets / Inset.h
1 // -*- C++ -*-
2 /**
3  * \file Inset.h
4  * This file is part of LyX, the document processor.
5  * Licence details can be found in the file COPYING.
6  *
7  * \author Alejandro Aguilar Sierra
8  * \author Jürgen Vigna
9  * \author Lars Gullik Bjønnes
10  * \author Matthias Ettrich
11  *
12  * Full author contact details are available in file CREDITS.
13  */
14
15 #ifndef INSETBASE_H
16 #define INSETBASE_H
17
18 #include "ColorCode.h"
19 #include "InsetCode.h"
20 #include "Layout.h"
21
22 #include "support/strfwd.h"
23 #include "support/types.h"
24
25
26 namespace lyx {
27
28 class BiblioInfo;
29 class Buffer;
30 class BufferView;
31 class Change;
32 class CompletionList;
33 class Cursor;
34 class CursorSlice;
35 class Dimension;
36 class DocIterator;
37 class FuncRequest;
38 class FuncStatus;
39 class InsetCollapsable;
40 class InsetIterator;
41 class InsetLayout;
42 class InsetList;
43 class InsetMath;
44 class InsetTabular;
45 class InsetText;
46 class LaTeXFeatures;
47 class Lexer;
48 class MathAtom;
49 class MetricsInfo;
50 class OutputParams;
51 class PainterInfo;
52 class ParConstIterator;
53 class ParIterator;
54 class Text;
55 class TocList;
56 class XHTMLStream;
57
58 namespace graphics { class PreviewLoader; }
59
60
61 /** returns the InsetCode corresponding to the \c name.
62 *   Eg, insetCode("branch") == BRANCH_CODE
63 *   Implemented in 'Inset.cpp'.
64 */
65 InsetCode insetCode(std::string const & name);
66 /// the other way
67 std::string insetName(InsetCode);
68
69 /// Common base class to all insets
70
71 // Do not add _any_ (non-static) data members as this would inflate
72 // everything storing large quantities of insets. Mathed e.g. would
73 // suffer.
74
75 class Inset {
76 public:
77         ///
78         enum EntryDirection {
79                 ENTRY_DIRECTION_IGNORE,
80                 ENTRY_DIRECTION_RIGHT,
81                 ENTRY_DIRECTION_LEFT,
82         };
83         ///
84         typedef ptrdiff_t  difference_type;
85         /// short of anything else reasonable
86         typedef size_t     size_type;
87         /// type for cell indices
88         typedef size_t     idx_type;
89         /// type for cursor positions
90         typedef ptrdiff_t  pos_type;
91         /// type for row numbers
92         typedef size_t     row_type;
93         /// type for column numbers
94         typedef size_t     col_type;
95
96         /// virtual base class destructor
97         virtual ~Inset() {}
98
99         /// change associated Buffer
100         virtual void setBuffer(Buffer & buffer);
101         /// remove the buffer reference
102         void resetBuffer() { setBuffer( *static_cast<Buffer *>(0)); }
103         /// retrieve associated Buffer
104         virtual Buffer & buffer();
105         virtual Buffer const & buffer() const;
106         /// This checks whether the Buffer * actually points to an open 
107         /// Buffer. It might not if that Buffer has been closed.
108         bool isBufferValid() const;
109
110         /// initialize view for this inset.
111         /**
112           * This is typically used after this inset is created interactively.
113           * Intented purpose is to sanitize internal state with regard to current
114           * Buffer. The default implementation calls buffer().updateLabels() if
115           * the inset is labeled.
116           *
117           * \sa isLabeled()
118           **/
119         virtual void initView();
120         /// \return true if this inset is labeled.
121         virtual bool isLabeled() const { return false; }
122
123         /// identification as math inset
124         virtual InsetMath * asInsetMath() { return 0; }
125         /// identification as math inset
126         virtual InsetMath const * asInsetMath() const { return 0; }
127         /// true for 'math' math inset, but not for e.g. mbox
128         virtual bool inMathed() const { return false; }
129         /// is this inset based on the InsetText class?
130         virtual InsetText * asInsetText() { return 0; }
131         /// is this inset based on the InsetText class?
132         virtual InsetText const * asInsetText() const { return 0; }
133         /// is this inset based on the InsetCollapsable class?
134         virtual InsetCollapsable * asInsetCollapsable() { return 0; }
135         /// is this inset based on the InsetCollapsable class?
136         virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
137         /// is this inset based on the InsetTabular class?
138         virtual InsetTabular * asInsetTabular() { return 0; }
139         /// is this inset based on the InsetTabular class?
140         virtual InsetTabular const * asInsetTabular() const { return 0; }
141
142         /// the real dispatcher
143         void dispatch(Cursor & cur, FuncRequest & cmd);
144         /**
145          * \returns true if this function made a definitive decision on
146          * whether the inset wants to handle the request \p cmd or not.
147          * The result of this decision is put into \p status.
148          *
149          * Every request that is enabled in this method needs to be handled
150          * in doDispatch(). Normally we have a 1:1 relationship between the
151          * requests handled in getStatus() and doDispatch(), but there are
152          * some exceptions:
153          * - A request that is disabled in getStatus() does not need to
154          *   appear in doDispatch(). It is guaranteed that doDispatch()
155          *   is never called with this request.
156          * - A few requests are en- or disabled in Inset::getStatus().
157          *   These need to be handled in the doDispatch() methods of the
158          *   derived insets, since Inset::doDispatch() has not enough
159          *   information to handle them.
160          * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
161          *   are dispatched directly
162          */
163         virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
164                 FuncStatus & status) const;
165
166         /// cursor enters
167         virtual void edit(Cursor & cur, bool front, 
168                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
169         /// cursor enters
170         virtual Inset * editXY(Cursor & cur, int x, int y);
171
172         /// compute the size of the object returned in dim
173         /// \retval true if metrics changed.
174         virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
175         /// draw inset and update (xo, yo)-cache
176         virtual void draw(PainterInfo & pi, int x, int y) const = 0;
177         /// draw inset selection if necessary
178         virtual void drawSelection(PainterInfo &, int, int) const {}
179         /// draw inset background if the inset has an own background and a
180         /// selection is drawn by drawSelection.
181         virtual void drawBackground(PainterInfo &, int, int) const {}
182         ///
183         virtual bool editing(BufferView const * bv) const;
184         ///
185         virtual bool showInsetDialog(BufferView *) const { return false; }
186
187         /// draw inset decoration if necessary.
188         /// This can use \c drawMarkers() for example.
189         virtual void drawDecoration(PainterInfo &, int, int) const {}
190         /// draw four angular markers
191         void drawMarkers(PainterInfo & pi, int x, int y) const;
192         /// draw two angular markers
193         void drawMarkers2(PainterInfo & pi, int x, int y) const;
194         /// add space for markers
195         void metricsMarkers(Dimension & dim, int framesize = 1) const;
196         /// add space for markers
197         void metricsMarkers2(Dimension & dim, int framesize = 1) const;
198         /// last drawn position for 'important' insets
199         int xo(BufferView const & bv) const;
200         /// last drawn position for 'important' insets
201         int yo(BufferView const & bv) const;
202         /// set x/y drawing position cache if available
203         virtual void setPosCache(PainterInfo const &, int, int) const;
204         ///
205         void setDimCache(MetricsInfo const &, Dimension const &) const;
206         /// do we cover screen position x/y?
207         virtual bool covers(BufferView const & bv, int x, int y) const;
208         /// get the screen positions of the cursor (see note in Cursor.cpp)
209         virtual void cursorPos(BufferView const & bv,
210                 CursorSlice const & sl, bool boundary, int & x, int & y) const;
211
212         /// Allow multiple blanks
213         virtual bool isFreeSpacing() const;
214         /// Don't eliminate empty paragraphs
215         virtual bool allowEmpty() const;
216         /// Force inset into LTR environment if surroundings are RTL?
217         virtual bool forceLTR() const;
218
219         /// Where should we go when we press the up or down cursor key?
220         virtual bool idxUpDown(Cursor & cur, bool up) const;
221         /// Move one cell backwards
222         virtual bool idxBackward(Cursor &) const { return false; }
223         /// Move one cell forward
224         virtual bool idxForward(Cursor &) const { return false; }
225
226         /// Move to the next cell
227         virtual bool idxNext(Cursor &) const { return false; }
228         /// Move to the previous cell
229         virtual bool idxPrev(Cursor &) const { return false; }
230
231         /// Target pos when we enter the inset while moving forward
232         virtual bool idxFirst(Cursor &) const { return false; }
233         /// Target pos when we enter the inset while moving backwards
234         virtual bool idxLast(Cursor &) const { return false; }
235
236         /// Delete a cell and move cursor
237         virtual bool idxDelete(idx_type &) { return false; }
238         /// pulls cell after pressing erase
239         virtual void idxGlue(idx_type) {}
240         /// returns list of cell indices that are "between" from and to for
241         /// selection purposes
242         virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
243
244         /// to which column belongs a cell with a given index?
245         virtual col_type col(idx_type) const { return 0; }
246         /// to which row belongs a cell with a given index?
247         virtual row_type row(idx_type) const { return 0; }
248         /// cell index corresponding to row and column;
249         virtual idx_type index(row_type row, col_type col) const;
250         /// any additional x-offset when drawing a cell?
251         virtual int cellXOffset(idx_type) const { return 0; }
252         /// any additional y-offset when drawing a cell?
253         virtual int cellYOffset(idx_type) const { return 0; }
254         /// number of embedded cells
255         virtual size_t nargs() const { return 0; }
256         /// number of rows in gridlike structures
257         virtual size_t nrows() const { return 0; }
258         /// number of columns in gridlike structures
259         virtual size_t ncols() const { return 0; }
260         /// Is called when the cursor leaves this inset.
261         /// Returns true if cursor is now invalid, e.g. if former 
262         /// insets in higher cursor slices of \c old do not exist 
263         /// anymore.
264         /// \c old is the old cursor, the last slice points to this.
265         /// \c cur is the new cursor. Use the update flags to cause a redraw.
266         virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
267                 { return false; }
268         /// Is called when the cursor enters this inset.
269         /// Returns true if cursor is now invalid, e.g. if former 
270         /// insets in higher cursor slices of \c old do not exist 
271         /// anymore.
272         /// \c cur is the new cursor, some slice points to this. Use the update flags to cause a redraw.
273         virtual bool notifyCursorEnters(Cursor & /*cur*/)
274                 { return false; }
275         /// is called when the mouse enter or leave this inset
276         /// return true if this inset needs repaint
277         virtual bool setMouseHover(bool) { return false; }
278         /// return true if this inset is hovered (under mouse)
279         /// This is by now only used by mathed to draw corners 
280         /// (Inset::drawMarkers() and Inset::drawMarkers2()).
281         /// Other insets do not have to redefine this function to 
282         /// return the correct status of mouseHovered.
283         virtual bool mouseHovered() const { return false; }
284
285         /// request "external features"
286         virtual void validate(LaTeXFeatures &) const {}
287
288         /// describe content if cursor inside
289         virtual void infoize(odocstream &) const {}
290         /// describe content if cursor behind
291         virtual void infoize2(odocstream &) const {}
292
293         enum { PLAINTEXT_NEWLINE = 10000 };
294
295         /// plain text output in ucs4 encoding
296         /// return the number of characters; in case of multiple lines of
297         /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
298         virtual int plaintext(odocstream &, OutputParams const &) const = 0;
299         /// docbook output
300         virtual int docbook(odocstream & os, OutputParams const &) const;
301         /// XHTML output
302         /// the inset is expected to write XHTML to the XHTMLStream
303         /// \return any "deferred" material that should be written outside the
304         /// normal stream, and which will in fact be written after the current
305         /// paragraph closes. this is appropriate e.g. for floats.
306         virtual docstring xhtml(XHTMLStream & xs, OutputParams const &) const;
307         // the old one, to be removed
308         virtual docstring xhtml(odocstream & os, OutputParams const &) const;
309         /// the string that is passed to the TOC
310         virtual void tocString(odocstream &) const {}
311
312         /// can the contents of the inset be edited on screen ?
313         // true for InsetCollapsables (not ButtonOnly) (not InsetInfo), InsetText
314         virtual bool editable() const;
315         /// has the Inset settings that can be modified in a dialog ?
316         virtual bool hasSettings() const;
317         /// can we go further down on mouse click?
318         // true for InsetCaption, InsetCollapsables (not ButtonOnly), InsetTabular
319         virtual bool descendable(BufferView const &) const { return false; }
320         /// is this an inset that can be moved into?
321         /// FIXME: merge with editable()
322         // true for InsetTabular & InsetText
323         virtual bool isActive() const { return nargs() > 0; }
324
325         /// does this contain text that can be change track marked in DVI?
326         virtual bool canTrackChanges() const { return false; }
327         /// return true if the inset should be removed automatically
328         virtual bool autoDelete() const;
329
330         /// Returns true if the inset supports completions.
331         virtual bool completionSupported(Cursor const &) const { return false; }
332         /// Returns true if the inset supports inline completions at the
333         /// cursor position. In this case the completion might be stored
334         /// in the BufferView's inlineCompletion property.
335         virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const 
336                 { return false; }
337         /// Return true if the inline completion should be automatic.
338         virtual bool automaticInlineCompletion() const { return true; }
339         /// Return true if the popup completion should be automatic.
340         virtual bool automaticPopupCompletion() const { return true; }
341         /// Return true if the cursor should indicate a completion.
342         virtual bool showCompletionCursor() const { return true; }
343         /// Returns completion suggestions at cursor position. Return an
344         /// null pointer if no completion is a available or possible.
345         /// The caller is responsible to free the returned object!
346         virtual CompletionList const * createCompletionList(Cursor const &) const 
347                 { return 0; }
348         /// Returns the completion prefix to filter the suggestions for completion.
349         /// This is only called if completionList returned a non-null list.
350         virtual docstring completionPrefix(Cursor const &) const;
351         /// Do a completion at the cursor position. Return true on success.
352         /// The completion does not contain the prefix. If finished is true, the
353         /// completion is final. If finished is false, completion might only be
354         /// a partial completion.
355         virtual bool insertCompletion(Cursor & /*cur*/, 
356                 docstring const & /*completion*/, bool /*finished*/) 
357                 { return false; }
358         /// Get the completion inset position and size
359         virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/, 
360                 Dimension & /*dim*/) const {}
361
362         /// returns true if the inset can hold an inset of given type
363         virtual bool insetAllowed(InsetCode) const { return false; }
364         /// should this inset use the empty layout by default rather than 
365         /// the standard layout? (default: only if that is forced.)
366         virtual bool usePlainLayout() const { return forcePlainLayout(); }
367         /// if this inset has paragraphs should they be forced to use the
368         /// empty layout?
369         virtual bool forcePlainLayout(idx_type = 0) const { return false; }
370         /// if this inset has paragraphs should the user be allowed to
371         /// customize alignment, etc?
372         virtual bool allowParagraphCustomization(idx_type = 0) const { return true; }
373         /// Is the width forced to some value?
374         virtual bool hasFixedWidth() const { return false; }
375
376         /// Is the content of this inset part of the output document?
377         virtual bool producesOutput() const { return true; }
378
379         /// \return Tool tip for this inset.
380         /// This default implementation returns an empty string.
381         virtual docstring toolTip(BufferView const & bv, int x, int y) const;
382         
383         /// \return Context menu identifier for this inset.
384         /// This default implementation returns an empty string.
385         virtual docstring contextMenu(BufferView const & bv, int x, int y) const;
386
387         // FIXME This should really disappear in favor of 
388         //      docstring name() const { return from_ascii(insetName(lyxCode()))); }
389         // There's no reason to be using different names in different places.
390         // But to do this we would need to change the file format, since the names
391         // used there don't correspond to what is used here. 
392         ///
393         virtual docstring name() const;
394         ///
395         virtual InsetLayout const & getLayout() const;
396         /// Is this inset's layout defined in the document's textclass?
397         bool undefined() const;
398         /// used to toggle insets
399         /// is the inset open?
400         /// should this inset be handled like a normal charater
401         virtual bool isChar() const { return false; }
402         /// is this equivalent to a letter?
403         virtual bool isLetter() const { return false; }
404         /// is this equivalent to a space (which is BTW different from
405         /// a line separator)?
406         virtual bool isSpace() const { return false; }
407         /// is this an expandible space (rubber length)?
408         virtual bool isStretchableSpace() const { return false; }
409
410         enum DisplayType {
411                 Inline = 0,
412                 AlignLeft,
413                 AlignCenter,
414                 AlignRight
415         };
416
417         /// should we have a non-filled line before this inset?
418         virtual DisplayType display() const { return Inline; }
419         ///
420         virtual LyXAlignment contentAlignment() const { return LYX_ALIGN_NONE; }
421         /// should we break lines after this inset?
422         virtual bool isLineSeparator() const { return false; }
423         /// should paragraph indendation be ommitted in any case?
424         virtual bool neverIndent() const { return false; }
425         /// dumps content to lyxerr
426         virtual void dump() const;
427         /// write inset in .lyx format
428         virtual void write(std::ostream &) const {}
429         /// read inset in .lyx format
430         virtual void read(Lexer &) {}
431         /** Export the inset to LaTeX.
432          *  Don't use a temporary stringstream if the final output is
433          *  supposed to go to a file.
434          *  \sa Buffer::writeLaTeXSource for the reason.
435          *  \return the number of rows (\n's) of generated LaTeX code.
436          */
437         virtual int latex(odocstream &, OutputParams const &) const { return 0; }
438         /// returns true to override begin and end inset in file
439         virtual bool directWrite() const;
440         ///
441         virtual bool allowSpellCheck() const { return false; }
442
443         /// if this insets owns text cells (e.g. InsetText) return cell num
444         virtual Text * getText(int /*num*/) const { return 0; }
445
446         /** Adds a LaTeX snippet to the Preview Loader for transformation
447          *  into a bitmap image. Does not start the laoding process.
448          *
449          *  Most insets have no interest in this capability, so the method
450          *  defaults to empty.
451          */
452         virtual void addPreview(DocIterator const &,
453                 graphics::PreviewLoader &) const {}
454
455         /** Classifies the unicode characters appearing in a math inset
456          *  depending on whether they are to be translated as latex
457          *  math/text commands or used as math symbols without translation.
458          *
459          *  Only math insets have interest in this classification, so the
460          *  method defaults to empty.
461          */
462         virtual void initUnicodeMath() const {}
463
464         /// Add an entry to the TocList
465         /// pit is the ParConstIterator of the paragraph containing the inset
466         virtual void addToToc(DocIterator const &) {}
467         /// Fill keys with BibTeX information
468         virtual void fillWithBibKeys(BiblioInfo &, InsetIterator const &) const {}
469         /// Update the counters of this inset and of its contents.
470         /// The boolean indicates whether we are preparing for output, e.g.,
471         /// of XHTML.
472         virtual void updateLabels(ParIterator const &, bool) {}
473
474         /// Updates the inset's dialog
475         virtual Buffer const * updateFrontend() const;
476
477 public:
478         /// returns LyX code associated with the inset. Used for TOC, ...)
479         virtual InsetCode lyxCode() const { return NO_CODE; }
480
481         /// -1: text mode, 1: math mode, 0 undecided
482         enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
483         /// return text or mathmode if that is possible to determine
484         virtual mode_type currentMode() const { return UNDECIDED_MODE; }
485         /// returns whether changing mode during latex export is forbidden
486         virtual bool lockedMode() const { return false; }
487         /// returns whether this inset is allowed in other insets of given mode
488         virtual bool allowedIn(mode_type) const { return true; }
489         /**
490          * Is this inset allowed within a font change?
491          *
492          * FIXME: noFontChange means currently that the font change is closed
493          * in LaTeX before the inset, and that the contents of the inset
494          * will be in default font. This should be changed so that the inset
495          * changes the font again.
496          */
497         virtual bool noFontChange() const { return false; }
498
499         /// set the change for the entire inset
500         virtual void setChange(Change const &) {}
501         /// accept the changes within the inset
502         virtual void acceptChanges() {};
503         /// reject the changes within the inset
504         virtual void rejectChanges() {};
505
506         ///
507         virtual Dimension const dimension(BufferView const &) const;
508         ///
509         int scroll() const { return 0; }
510         ///
511         virtual ColorCode backgroundColor() const;
512         ///
513         virtual ColorCode labelColor() const;
514         //
515         enum { TEXT_TO_INSET_OFFSET = 4 };
516
517 protected:
518         /// Constructors
519         Inset(Buffer * buf) : buffer_(buf) {}
520         Inset(Inset const &) : buffer_(0) {}
521
522         /// replicate ourselves
523         friend class InsetList;
524         friend class MathAtom;
525         virtual Inset * clone() const = 0;
526
527         /** The real dispatcher.
528          *  Gets normally called from Cursor::dispatch(). Cursor::dispatch()
529          *  assumes the common case of 'LFUN handled, need update'.
530          *  This has to be overriden by calling Cursor::undispatched() or
531          *  Cursor::noUpdate() if appropriate.
532          *  If you need to call the dispatch method of some inset directly
533          *  you may have to explicitly request an update at that place. Don't
534          *  do it in doDispatch(), since that causes nested updates when
535          *  called from Cursor::dispatch(), and these can lead to crashes.
536          *  \sa getStatus
537          */
538         virtual void doDispatch(Cursor & cur, FuncRequest & cmd);
539
540         Buffer * buffer_;
541 };
542
543 } // namespace lyx
544
545 #endif