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