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