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