]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
* simplify notifyCursorLeaves logic: We now only call it from strategic
[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 DocIterator;
38 class FuncRequest;
39 class FuncStatus;
40 class InsetCollapsable;
41 class InsetIterator;
42 class InsetLayout;
43 class InsetList;
44 class InsetMath;
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 EmbeddedFile;
57 class EmbeddedFileList;
58
59
60 namespace graphics { class PreviewLoader; }
61
62
63 /// Common base class to all insets
64
65 // Do not add _any_ (non-static) data members as this would inflate
66 // everything storing large quantities of insets. Mathed e.g. would
67 // suffer.
68
69 class Inset {
70 public:
71         ///
72         enum EntryDirection {
73                 ENTRY_DIRECTION_IGNORE,
74                 ENTRY_DIRECTION_RIGHT,
75                 ENTRY_DIRECTION_LEFT,
76         };
77         ///
78         typedef ptrdiff_t  difference_type;
79         /// short of anything else reasonable
80         typedef size_t     size_type;
81         /// type for cell indices
82         typedef size_t     idx_type;
83         /// type for cursor positions
84         typedef ptrdiff_t  pos_type;
85         /// type for row numbers
86         typedef size_t     row_type;
87         /// type for column numbers
88         typedef size_t     col_type;
89
90         /// virtual base class destructor
91         virtual ~Inset() {}
92
93         /// identification as math inset
94         virtual InsetMath * asInsetMath() { return 0; }
95         /// true for 'math' math inset, but not for e.g. mbox
96         virtual bool inMathed() const { return false; }
97         /// is this inset based on the InsetText class?
98         virtual InsetText * asInsetText() { return 0; }
99         /// is this inset based on the InsetText class?
100         virtual InsetText const * asInsetText() const { return 0; }
101         /// is this inset based on the InsetCollapsable class?
102         virtual InsetCollapsable * asInsetCollapsable() { return 0; }
103         /// is this inset based on the InsetCollapsable class?
104         virtual InsetCollapsable const * asInsetCollapsable() const { return 0; }
105
106         /// the real dispatcher
107         void dispatch(Cursor & cur, FuncRequest & cmd);
108         /**
109          * \returns true if this function made a definitive decision on
110          * whether the inset wants to handle the request \p cmd or not.
111          * The result of this decision is put into \p status.
112          *
113          * Every request that is enabled in this method needs to be handled
114          * in doDispatch(). Normally we have a 1:1 relationship between the
115          * requests handled in getStatus() and doDispatch(), but there are
116          * some exceptions:
117          * - A request that is disabled in getStatus() does not need to
118          *   appear in doDispatch(). It is guaranteed that doDispatch()
119          *   is never called with this request.
120          * - A few requests are en- or disabled in Inset::getStatus().
121          *   These need to be handled in the doDispatch() methods of the
122          *   derived insets, since Inset::doDispatch() has not enough
123          *   information to handle them.
124          * - LFUN_MOUSE_* need not to be handled in getStatus(), because these
125          *   are dispatched directly
126          */
127         virtual bool getStatus(Cursor & cur, FuncRequest const & cmd,
128                 FuncStatus & status) const;
129
130         /// cursor enters
131         virtual void edit(Cursor & cur, bool front, 
132                 EntryDirection entry_from = ENTRY_DIRECTION_IGNORE);
133         /// cursor enters
134         virtual Inset * editXY(Cursor & cur, int x, int y);
135
136         /// compute the size of the object returned in dim
137         /// \retval true if metrics changed.
138         virtual void metrics(MetricsInfo & mi, Dimension & dim) const = 0;
139         /// draw inset and update (xo, yo)-cache
140         virtual void draw(PainterInfo & pi, int x, int y) const = 0;
141         /// draw inset selection if necessary
142         virtual void drawSelection(PainterInfo &, int, int) const {}
143         ///
144         virtual bool editing(BufferView const * bv) const;
145         ///
146         virtual bool showInsetDialog(BufferView *) const { return false; }
147
148         /// draw inset decoration if necessary.
149         /// This can use \c drawMarkers() for example.
150         virtual void drawDecoration(PainterInfo &, int, int) const {}
151         /// draw four angular markers
152         void drawMarkers(PainterInfo & pi, int x, int y) const;
153         /// draw two angular markers
154         void drawMarkers2(PainterInfo & pi, int x, int y) const;
155         /// add space for markers
156         void metricsMarkers(Dimension & dim, int framesize = 1) const;
157         /// add space for markers
158         void metricsMarkers2(Dimension & dim, int framesize = 1) const;
159         /// last drawn position for 'important' insets
160         int xo(BufferView const & bv) const;
161         /// last drawn position for 'important' insets
162         int yo(BufferView const & bv) const;
163         /// set x/y drawing position cache if available
164         virtual void setPosCache(PainterInfo const &, int, int) const;
165         ///
166         void setDimCache(MetricsInfo const &, Dimension const &) const;
167         /// do we cover screen position x/y?
168         virtual bool covers(BufferView const & bv, int x, int y) const;
169         /// get the screen positions of the cursor (see note in Cursor.cpp)
170         virtual void cursorPos(BufferView const & bv,
171                 CursorSlice const & sl, bool boundary, int & x, int & y) const;
172
173         ///
174         virtual bool isFreeSpacing() const { return false; }
175         ///
176         virtual bool allowEmpty() const { return false; }
177         /// Force inset into LTR environment if surroundings are RTL?
178         virtual bool forceLTR() const { return false; }
179
180         /// is this an inset that can be moved into?
181         /// FIXME: merge with editable()
182         virtual bool isActive() const { return nargs() > 0; }
183         /// Where should we go when we press the up or down cursor key?
184         virtual bool idxUpDown(Cursor & cur, bool up) const;
185         /// Move one cell backwards
186         virtual bool idxBackward(Cursor &) const { return false; }
187         /// Move one cell forward
188         virtual bool idxForward(Cursor &) const { return false; }
189
190         /// Move to the next cell
191         virtual bool idxNext(Cursor &) const { return false; }
192         /// Move to the previous cell
193         virtual bool idxPrev(Cursor &) const { return false; }
194
195         /// Target pos when we enter the inset while moving forward
196         virtual bool idxFirst(Cursor &) const { return false; }
197         /// Target pos when we enter the inset while moving backwards
198         virtual bool idxLast(Cursor &) const { return false; }
199
200         /// Delete a cell and move cursor
201         virtual bool idxDelete(idx_type &) { return false; }
202         /// pulls cell after pressing erase
203         virtual void idxGlue(idx_type) {}
204         /// returns list of cell indices that are "between" from and to for
205         /// selection purposes
206         virtual bool idxBetween(idx_type idx, idx_type from, idx_type to) const;
207
208         /// to which column belongs a cell with a given index?
209         virtual col_type col(idx_type) const { return 0; }
210         /// to which row belongs a cell with a given index?
211         virtual row_type row(idx_type) const { return 0; }
212         /// cell idex corresponding to row and column;
213         virtual idx_type index(row_type row, col_type col) const;
214         /// any additional x-offset when drawing a cell?
215         virtual int cellXOffset(idx_type) const { return 0; }
216         /// any additional y-offset when drawing a cell?
217         virtual int cellYOffset(idx_type) const { return 0; }
218         /// number of embedded cells
219         virtual size_t nargs() const { return 0; }
220         /// number of rows in gridlike structures
221         virtual size_t nrows() const { return 0; }
222         /// number of columns in gridlike structures
223         virtual size_t ncols() const { return 0; }
224         /// is called when the cursor leaves this inset
225         /// returns true if cursor is now invalid.
226         virtual bool notifyCursorLeaves(Cursor const &, 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