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