]> git.lyx.org Git - lyx.git/blob - src/insets/Inset.h
* following Andre's advice to rename the method into
[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, e.g. if former 
226         /// insets in higher cursor slices of \c old do not exist 
227         /// anymore.
228         /// \c old is the old cursor, i.e. there is a slice pointing to this.
229         /// \c cur is the new cursor. Use the update flags to cause a redraw.
230         virtual bool notifyCursorLeaves(Cursor const & /*old*/, Cursor & /*cur*/)
231                 { return false; }
232         /// is called when the mouse enter or leave this inset
233         /// return true if this inset needs repaint
234         virtual bool setMouseHover(bool) { return false; }
235         /// return true if this inset is hovered (under mouse)
236         /// This is by now only used by mathed to draw corners 
237         /// (Inset::drawMarkers() and Inset::drawMarkers2()).
238         /// Other insets do not have to redefine this function to 
239         /// return the correct status of mouseHovered.
240         virtual bool mouseHovered() const { return false; }
241
242         /// request "external features"
243         virtual void validate(LaTeXFeatures &) const {}
244         /// Appends \c list with all labels found within this inset.
245         virtual void getLabelList(Buffer const &,
246                                   std::vector<docstring> & /* list */) const {}
247
248         /// describe content if cursor inside
249         virtual void infoize(odocstream &) const {}
250         /// describe content if cursor behind
251         virtual void infoize2(odocstream &) const {}
252
253         enum {
254                 PLAINTEXT_NEWLINE = 10000
255         };
256
257         /// plain text output in ucs4 encoding
258         /// return the number of characters; in case of multiple lines of
259         /// output, add PLAINTEXT_NEWLINE to the number of chars in the last line
260         virtual int plaintext(Buffer const &, odocstream &,
261                               OutputParams const &) const = 0;
262         /// docbook output
263         virtual int docbook(Buffer const &, odocstream & os,
264                             OutputParams const &) const;
265         /// the string that is passed to the TOC
266         virtual void textString(Buffer const &, odocstream &) const {}
267
268         /** This enum indicates by which means the inset can be modified:
269         - NOT_EDITABLE: the inset's content cannot be modified at all
270           (e.g. printindex, insetspecialchar)
271         - IS_EDITABLE: content can be edited via dialog (e.g. bibtex, index, href)
272         - HIGHLY_EDITABLE: content can be edited on screen (normally means that
273           insettext is contained, e.g. collapsables, tabular) */
274         // FIXME: This has not yet been fully implemented to math insets
275         enum EDITABLE {
276                 ///
277                 NOT_EDITABLE = 0,
278                 ///
279                 IS_EDITABLE,
280                 ///
281                 HIGHLY_EDITABLE
282         };
283         /// what appears in the minibuffer when opening
284         virtual docstring const editMessage() const;
285         ///
286         virtual EDITABLE editable() const;
287         /// can we go further down on mouse click?
288         virtual bool descendable() const { return false; }
289         /// does this contain text that can be change track marked in DVI?
290         virtual bool canTrackChanges() const { return false; }
291         /// return true if the inset should be removed automatically
292         virtual bool autoDelete() const;
293
294         class CompletionList {
295         public:
296                 ///
297                 virtual ~CompletionList() {}
298                 ///
299                 virtual size_t size() const =0;
300                 /// returns the string shown in the gui.
301                 virtual docstring data(size_t idx) const =0;
302                 /// returns the resource string used to load an icon.
303                 virtual std::string icon(size_t /*idx*/) const { return std::string(); }
304         };
305
306         /// Returns true if the inset supports completions.
307         virtual bool completionSupported(Cursor const &) const { return false; }
308         /// Returns true if the inset supports inline completions at the
309         /// cursor position. In this case the completion might be stored
310         /// in the BufferView's inlineCompletion property.
311         virtual bool inlineCompletionSupported(Cursor const & /*cur*/) const 
312                 { return false; }
313         /// Return true if the inline completion should be automatic.
314         virtual bool automaticInlineCompletion() const { return true; }
315         /// Return true if the popup completion should be automatic.
316         virtual bool automaticPopupCompletion() const { return true; }
317         /// Returns completion suggestions at cursor position. Return an
318         /// null pointer if no completion is a available or possible.
319         /// The caller is responsible to free the returned object!
320         virtual CompletionList const * createCompletionList(Cursor const &) const 
321                 { return 0; }
322         /// Returns the completion prefix to filter the suggestions for completion.
323         /// This is only called if completionList returned a non-null list.
324         virtual docstring completionPrefix(Cursor const &) const 
325                 { return docstring(); }
326         /// Do a completion at the cursor position. Return true on success.
327         /// The completion does not contain the prefix. If finished is true, the
328         /// completion is final. If finished is false, completion might only be
329         /// a partial completion.
330         virtual bool insertCompletion(Cursor & /*cur*/, 
331                 docstring const & /*completion*/, bool /*finished*/) 
332                 { return false; }
333         /// Get the completion inset position and size
334         virtual void completionPosAndDim(Cursor const &, int & /*x*/, int & /*y*/, 
335                 Dimension & /*dim*/) const {}
336
337         /// returns true if the inset can hold an inset of given type
338         virtual bool insetAllowed(InsetCode) const { return false; }
339         /// should this inset use the empty layout by default rather than 
340         /// the standard layout? (default: only if that is forced.)
341         virtual bool useEmptyLayout() const { return forceEmptyLayout(); }
342         /// if this inset has paragraphs should they be forced to use the
343         /// empty layout?
344         virtual bool forceEmptyLayout() const { return false; }
345         /// if this inset has paragraphs should the user be allowed to
346         /// customize alignment, etc?
347         virtual bool allowParagraphCustomization(idx_type) const { return true; }
348         /// Is the width forced to some value?
349         virtual bool hasFixedWidth() const { return false; }
350
351         /// \return Tool tip for this inset.
352         /// This default implementation returns an empty string.
353         virtual docstring toolTip(BufferView const & bv, int x, int y) const;
354         
355         /// \return Context menu identifier for this inset.
356         /// This default implementation returns an empty string.
357         virtual docstring contextMenu(BufferView const & bv, int x, int y) const;
358
359         // FIXME This should really disappear in favor of 
360         //      docstring name() const { return from_ascii(insetName(lyxCode()))); }
361         // There's no reason to be using different names in different places.
362         // But to do this we would need to change the file format, since the names
363         // used there don't correspond to what is used here. 
364         ///
365         virtual docstring name() const;
366         ///
367         virtual InsetLayout const & getLayout(BufferParams const & bp) const;
368         /// used to toggle insets
369         /// is the inset open?
370         /// should this inset be handled like a normal charater
371         virtual bool isChar() const { return false; }
372         /// is this equivalent to a letter?
373         virtual bool isLetter() const { return false; }
374         /// is this equivalent to a space (which is BTW different from
375         /// a line separator)?
376         virtual bool isSpace() const { return false; }
377
378         enum DisplayType {
379                 Inline = 0,
380                 AlignLeft,
381                 AlignCenter,
382                 AlignRight
383         };
384
385         /// should we have a non-filled line before this inset?
386         virtual DisplayType display() const { return Inline; }
387         /// should we break lines after this inset?
388         virtual bool isLineSeparator() const { return false; }
389         /// should paragraph indendation be ommitted in any case?
390         virtual bool neverIndent(Buffer const &) const { return false; }
391         /// dumps content to lyxerr
392         virtual void dump() const;
393         /// write inset in .lyx format
394         virtual void write(Buffer const &, std::ostream &) const {}
395         /// read inset in .lyx format
396         virtual void read(Buffer const &, Lexer &) {}
397         /** Export the inset to LaTeX.
398          *  Don't use a temporary stringstream if the final output is
399          *  supposed to go to a file.
400          *  \sa Buffer::writeLaTeXSource for the reason.
401          *  \return the number of rows (\n's) of generated LaTeX code.
402          */
403         virtual int latex(Buffer const &, odocstream &,
404                           OutputParams const &) const { return 0; }
405         /// returns true to override begin and end inset in file
406         virtual bool directWrite() const;
407         ///
408         virtual bool allowSpellCheck() const { return false; }
409
410         /// if this insets owns text cells (e.g. InsetText) return cell num
411         virtual Text * getText(int /*num*/) const { return 0; }
412
413         /** Adds a LaTeX snippet to the Preview Loader for transformation
414          *  into a bitmap image. Does not start the laoding process.
415          *
416          *  Most insets have no interest in this capability, so the method
417          *  defaults to empty.
418          */
419         virtual void addPreview(graphics::PreviewLoader &) const {}
420         /// Add an entry to the TocList
421         /// pit is the ParConstIterator of the paragraph containing the inset
422         virtual void addToToc(Buffer const &, ParConstIterator const &) const {}
423         /// report files that can be embedded with the lyx file
424         virtual void registerEmbeddedFiles(Buffer const &, EmbeddedFileList &) const {}
425         /// use embedded or external file after the embedding status of a file is changed
426         virtual void updateEmbeddedFile(Buffer const &, EmbeddedFile const &) {}
427         /// Fill keys with BibTeX information
428         virtual void fillWithBibKeys(Buffer const &,
429                 BiblioInfo &, InsetIterator const &) const {}
430         /// Update the counters of this inset and of its contents
431         virtual void updateLabels(Buffer const &, ParIterator const &) {}
432
433         /// Updates the inset's dialog
434         virtual Buffer const * updateFrontend() const;
435
436 public:
437         /// returns LyX code associated with the inset. Used for TOC, ...)
438         virtual InsetCode lyxCode() const { return NO_CODE; }
439
440         /// -1: text mode, 1: math mode, 0 undecided
441         enum mode_type {UNDECIDED_MODE, TEXT_MODE, MATH_MODE};
442         /// return text or mathmode if that is possible to determine
443         virtual mode_type currentMode() const { return UNDECIDED_MODE; }
444         /// returns whether this inset is allowed in other insets of given mode
445         virtual bool allowedIn(mode_type) const { return true; }
446         /**
447          * Is this inset allowed within a font change?
448          *
449          * FIXME: noFontChange means currently that the font change is closed
450          * in LaTeX before the inset, and that the contents of the inset
451          * will be in default font. This should be changed so that the inset
452          * changes the font again.
453          */
454         virtual bool noFontChange() const { return false; }
455
456         /// set the change for the entire inset
457         virtual void setChange(Change const &) {}
458         /// accept the changes within the inset
459         virtual void acceptChanges(BufferParams const &) {};
460         /// reject the changes within the inset
461         virtual void rejectChanges(BufferParams const &) {};
462
463         ///
464         virtual Dimension const dimension(BufferView const &) const;
465         ///
466         int scroll() const { return 0; }
467         ///
468         virtual ColorCode backgroundColor() const;
469         ///
470         enum CollapseStatus {
471                 Collapsed,
472                 Open
473         };
474         ///
475         virtual void setStatus(Cursor &, CollapseStatus) {}
476         //
477         enum { TEXT_TO_INSET_OFFSET = 4 };
478
479 protected:
480         Inset() {}
481
482         /// replicate ourselves
483         friend class InsetList;
484         friend class MathAtom;
485         virtual Inset * clone() const = 0;
486
487         /** The real dispatcher.
488          *  Gets normally called from Cursor::dispatch(). Cursor::dispatch()
489          *  assumes the common case of 'LFUN handled, need update'.
490          *  This has to be overriden by calling Cursor::undispatched() or
491          *  Cursor::noUpdate() if appropriate.
492          *  If you need to call the dispatch method of some inset directly
493          *  you may have to explicitly request an update at that place. Don't
494          *  do it in doDispatch(), since that causes nested updates when
495          *  called from Cursor::dispatch(), and these can lead to crashes.
496          *  \sa getStatus
497          */
498         virtual void doDispatch(Cursor & cur, FuncRequest & cmd);
499 };
500
501 } // namespace lyx
502
503 #endif