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