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