]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Fix a crash when closing tabs
[lyx.git] / src / insets / InsetCaption.cpp
1 /**
2  * \file InsetCaption.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Lars Gullik Bjønnes
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "InsetCaption.h"
14 #include "InsetFloat.h"
15 #include "InsetWrap.h"
16
17 #include "Buffer.h"
18 #include "BufferParams.h"
19 #include "BufferView.h"
20 #include "Cursor.h"
21 #include "Dimension.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "FuncRequest.h"
25 #include "FuncStatus.h"
26 #include "InsetList.h"
27 #include "Language.h"
28 #include "LyXRC.h"
29 #include "MetricsInfo.h"
30 #include "xml.h"
31 #include "output_latex.h"
32 #include "output_xhtml.h"
33 #include "Paragraph.h"
34 #include "ParIterator.h"
35 #include "TexRow.h"
36 #include "texstream.h"
37 #include "TextClass.h"
38 #include "TextMetrics.h"
39 #include "TocBackend.h"
40
41 #include "frontends/FontMetrics.h"
42 #include "frontends/Painter.h"
43
44 #include "support/gettext.h"
45 #include "support/lstrings.h"
46
47 #include <sstream>
48
49 using namespace std;
50 using namespace lyx::support;
51
52 namespace lyx {
53
54
55 InsetCaption::InsetCaption(Buffer * buf, string const & type)
56     : InsetText(buf, InsetText::PlainLayout), type_(type)
57 {
58         setDrawFrame(true);
59         setFrameColor(Color_collapsibleframe);
60 }
61
62
63 void InsetCaption::write(ostream & os) const
64 {
65         os << "Caption";
66         if (!type_.empty())
67                 os << ' ' << type_;
68         os << '\n';
69         text().write(os);
70 }
71
72
73 docstring InsetCaption::layoutName() const
74 {
75         if (type_.empty())
76                 return from_ascii("Caption");
77         return from_utf8("Caption:" + type_);
78 }
79
80
81 void InsetCaption::cursorPos(BufferView const & bv,
82                 CursorSlice const & sl, bool boundary, int & x, int & y) const
83 {
84         InsetText::cursorPos(bv, sl, boundary, x, y);
85         if (!rtl_)
86                 x += labelwidth_;
87 }
88
89
90 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active,
91                                                         UpdateType utype, TocBackend & backend) const
92 {
93         string const & type = floattype_.empty() ? "senseless" : floattype_;
94         DocIterator pit = cpit;
95         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
96         int length = (utype == OutputUpdate) ?
97                 // For output (e.g. xhtml) all (bug #8603) or nothing
98                 (output_active ? INT_MAX : 0) :
99                 // TOC for LyX interface
100                 TOC_ENTRY_LENGTH;
101         docstring str;
102         if (length > 0) {
103                 str = full_label_;
104                 text().forOutliner(str, length);
105         }
106         backend.builder(type).captionItem(pit, str, output_active);
107         // Proceed with the rest of the inset.
108         InsetText::addToToc(cpit, output_active, utype, backend);
109 }
110
111
112 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
113 {
114         FontInfo tmpfont = mi.base.font;
115         mi.base.font = mi.base.bv->buffer().params().getFont().fontInfo();
116         labelwidth_ = theFontMetrics(mi.base.font).width(full_label_);
117         // add some space to separate the label from the inset text
118         labelwidth_ += leftOffset(mi.base.bv) + rightOffset(mi.base.bv);
119         dim.wid = labelwidth_;
120         Dimension textdim;
121         // Correct for button and label width
122         mi.base.textwidth -= dim.wid;
123         InsetText::metrics(mi, textdim);
124         mi.base.font = tmpfont;
125         mi.base.textwidth += dim.wid;
126         dim.des = max(dim.des - textdim.asc + dim.asc, textdim.des);
127         dim.asc = textdim.asc;
128         dim.wid += textdim.wid;
129 }
130
131
132 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
133 {
134         TextMetrics & tm = pi.base.bv->textMetrics(&text());
135         int const h = tm.height() + topOffset(pi.base.bv) + bottomOffset(pi.base.bv);
136         int const yy = y - topOffset(pi.base.bv) - tm.ascent();
137         if (rtl_)
138                 x+= + dimension(*pi.base.bv).wid - labelwidth_;
139         pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
140 }
141
142
143 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
144 {
145         // We must draw the label, we should get the label string
146         // from the enclosing float inset.
147         // The question is: Who should draw the label, the caption inset,
148         // the text inset or the paragraph?
149         // We should also draw the float number (Lgb)
150
151         // Answer: the text inset (in buffer_funcs.cpp: setCaption).
152
153         rtl_ = !pi.ltr_pos;
154         FontInfo tmpfont = pi.base.font;
155         pi.base.font = pi.base.bv->buffer().params().getFont().fontInfo();
156         pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
157         if (is_deleted_)
158                 pi.base.font.setStrikeout(FONT_ON);
159         else if (isChanged() && lyxrc.ct_additions_underlined)
160                 pi.base.font.setUnderbar(FONT_ON);
161         int const lo = leftOffset(pi.base.bv);
162         if (rtl_) {
163                 InsetText::draw(pi, x, y);
164                 pi.pain.text(x + dimension(*pi.base.bv).wid - labelwidth_ + lo,
165                              y, full_label_, pi.base.font);
166         } else {
167                 pi.pain.text(x + lo, y, full_label_, pi.base.font);
168                 InsetText::draw(pi, x + labelwidth_, y);
169         }
170         pi.base.font = tmpfont;
171 }
172
173
174 void InsetCaption::edit(Cursor & cur, bool front, EntryDirection entry_from)
175 {
176         cur.push(*this);
177         InsetText::edit(cur, front, entry_from);
178 }
179
180
181 Inset * InsetCaption::editXY(Cursor & cur, int x, int y)
182 {
183         cur.push(*this);
184         return InsetText::editXY(cur, x, y);
185 }
186
187
188 bool InsetCaption::insetAllowed(InsetCode code) const
189 {
190         switch (code) {
191         // code that is not allowed in a caption
192         case CAPTION_CODE:
193         case FLOAT_CODE:
194         case FOOT_CODE:
195         case NEWPAGE_CODE:
196         case MARGIN_CODE:
197         case MATHMACRO_CODE:
198         case TABULAR_CODE:
199         case WRAP_CODE:
200                 return false;
201         default:
202                 return InsetText::insetAllowed(code);
203         }
204 }
205
206
207 void InsetCaption::doDispatch(Cursor & cur, FuncRequest & cmd)
208 {
209         switch (cmd.action()) {
210
211         case LFUN_INSET_MODIFY: {
212                 if (cmd.getArg(0) == "changetype") {
213                         cur.recordUndoInset(this);
214                         type_ = cmd.getArg(1);
215                         cur.forceBufferUpdate();
216                         break;
217                 }
218         }
219         // no "changetype":
220         // fall through
221
222         default:
223                 InsetText::doDispatch(cur, cmd);
224                 break;
225         }
226 }
227
228
229 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
230         FuncStatus & status) const
231 {
232         switch (cmd.action()) {
233
234         case LFUN_INSET_MODIFY: {
235                 string const first_arg = cmd.getArg(0);
236                 if (first_arg == "changetype") {
237                         string const type = cmd.getArg(1);
238                         status.setOnOff(type == type_);
239                         bool varia = type != "Unnumbered";
240                         // check if the immediate parent inset allows caption variation
241                         if (cur.depth() > 1) {
242                                 varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
243                         }
244                         status.setEnabled(!is_subfloat_ && varia
245                                           && buffer().params().documentClass().hasInsetLayout(
246                                                 from_ascii("Caption:" + type)));
247                         return true;
248                 }
249                 return InsetText::getStatus(cur, cmd, status);
250         }
251
252         case LFUN_INSET_TOGGLE:
253                 // pass back to owner
254                 cur.undispatched();
255                 return false;
256
257         default:
258                 return InsetText::getStatus(cur, cmd, status);
259         }
260 }
261
262
263 void InsetCaption::latex(otexstream & os,
264                          OutputParams const & runparams_in) const
265 {
266         if (runparams_in.inFloat == OutputParams::SUBFLOAT)
267                 // caption is output as an optional argument
268                 return;
269         // This is a bit too simplistic to take advantage of
270         // caption options we must add more later. (Lgb)
271         // This code is currently only able to handle the simple
272         // \caption{...}, later we will make it take advantage
273         // of the one of the caption packages. (Lgb)
274         OutputParams runparams = runparams_in;
275         // Some fragile commands (labels, index entries)
276         // are output after the caption (#2154)
277         runparams.postpone_fragile_stuff = buffer().masterParams().postpone_fragile_content;
278         InsetText::latex(os, runparams);
279         if (!runparams.post_macro.empty()) {
280                 // Output the stored fragile commands (labels, indices etc.)
281                 // that need to be output after the caption.
282                 os << runparams.post_macro;
283                 runparams.post_macro.clear();
284         }
285         // Backwards compatibility: We always had a linebreak after
286         // the caption (see #8514)
287         os << breakln;
288         runparams_in.encoding = runparams.encoding;
289 }
290
291
292 int InsetCaption::plaintext(odocstringstream & os,
293                             OutputParams const & runparams, size_t max_length) const
294 {
295         os << '[' << full_label_ << "\n";
296         InsetText::plaintext(os, runparams, max_length);
297         os << "\n]";
298
299         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
300 }
301
302
303 void InsetCaption::docbook(XMLStream &, OutputParams const &) const
304 {
305         // This function should never be called (rather InsetFloat::docbook, the titles should be skipped in floats).
306 }
307
308
309 docstring InsetCaption::xhtml(XMLStream & xs, OutputParams const & rp) const
310 {
311         if (rp.html_disable_captions)
312                 return docstring();
313         InsetLayout const & il = getLayout();
314         string const & tag = il.htmltag();
315         string attr = il.htmlattr();
316         if (!type_.empty()) {
317                 string const our_class = "float-caption-" + type_;
318                 size_t const loc = attr.find("class='");
319                 if (loc != string::npos)
320                         attr.insert(loc + 7, our_class + " ");
321                 else
322                         attr = attr + " class='" + our_class + "'";
323         }
324         xs << xml::StartTag(tag, attr);
325         docstring def = getCaptionAsHTML(xs, rp);
326         xs << xml::EndTag(tag);
327         return def;
328 }
329
330
331 void InsetCaption::getArgument(otexstream & os,
332                         OutputParams const & runparams) const
333 {
334         InsetLayout const & il = getLayout();
335
336         if (!il.leftdelim().empty())
337                 os << il.leftdelim();
338
339         OutputParams rp = runparams;
340         if (isPassThru())
341                 rp.pass_thru = true;
342         if (il.isNeedProtect())
343                 rp.moving_arg = true;
344         if (il.isNeedMBoxProtect())
345                 ++rp.inulemcmd;
346         rp.par_begin = 0;
347         rp.par_end = paragraphs().size();
348
349         // Output the contents of the inset
350         if (!paragraphs().empty())
351                 os.texrow().forceStart(paragraphs()[0].id(), 0);
352         latexParagraphs(buffer(), text(), os, rp);
353         runparams.encoding = rp.encoding;
354
355         if (!il.rightdelim().empty())
356                 os << il.rightdelim();
357 }
358
359
360 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
361                         OutputParams const & runparams) const
362 {
363         os << full_label_ << ' ';
364         odocstringstream ods;
365         int const retval = InsetText::plaintext(ods, runparams);
366         os << ods.str();
367         return retval;
368 }
369
370
371 void InsetCaption::getCaptionAsDocBook(XMLStream & xs,
372                                                                                  OutputParams const & runparams) const
373 {
374         if (runparams.docbook_in_float)
375                 return;
376
377         // Ignore full_label_, as the DocBook processor will deal with the numbering.
378         InsetText::XHTMLOptions opts = InsetText::WriteInnerTag;
379         InsetText::docbook(xs, runparams, opts);
380 }
381
382
383 docstring InsetCaption::getCaptionAsHTML(XMLStream & xs,
384                         OutputParams const & runparams) const
385 {
386         xs << full_label_ << ' ';
387         InsetText::XHTMLOptions const opts =
388                 InsetText::WriteLabel | InsetText::WriteInnerTag;
389         return InsetText::insetAsXHTML(xs, runparams, opts);
390 }
391
392
393 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
394 {
395         Buffer const & master = *buffer().masterBuffer();
396         DocumentClass const & tclass = master.params().documentClass();
397         string const & lang = it.paragraph().getParLanguage(master.params())->code();
398         Counters & cnts = tclass.counters();
399         string const & type = cnts.current_float();
400         if (utype == OutputUpdate) {
401                 // counters are local to the caption
402                 cnts.saveLastCounter();
403         }
404         is_deleted_ = deleted;
405         // Memorize type for addToToc().
406         floattype_ = type;
407         if (type.empty() || type == "senseless")
408                 full_label_ = master.B_("Senseless!!! ");
409         else {
410                 // FIXME: life would be _much_ simpler if listings was
411                 // listed in Floating.
412                 docstring name;
413                 if (type == "listing")
414                         name = master.B_("Listing");
415                 else
416                         name = master.B_(tclass.floats().getType(type).name());
417                 docstring counter = from_utf8(type);
418                 is_subfloat_ = cnts.isSubfloat();
419                 if (is_subfloat_) {
420                         // only standard captions allowed in subfloats
421                         type_ = "Standard";
422                         counter = "sub-" + from_utf8(type);
423                         name = bformat(_("Sub-%1$s"),
424                                        master.B_(tclass.floats().getType(type).name()));
425                 }
426                 docstring sec;
427                 docstring const lstring = getLayout().labelstring();
428                 docstring const labelstring = isAscii(lstring) ?
429                                 master.B_(to_ascii(lstring)) : lstring;
430                 if (cnts.hasCounter(counter)) {
431                         int val = cnts.value(counter);
432                         // for longtables, we step the counter upstream
433                         if (!cnts.isLongtable())
434                                 cnts.step(counter, utype);
435                         sec = cnts.theCounter(counter, lang);
436                         if (deleted && !cnts.isLongtable())
437                                 // un-step after deleted counter
438                                 cnts.set(counter, val);
439                 }
440                 if (labelstring != master.B_("standard")) {
441                         if (!sec.empty())
442                                 sec += from_ascii(" ");
443                         sec += bformat(from_ascii("(%1$s)"), labelstring);
444                 }
445                 if (sec.empty())
446                         sec = from_ascii("#");
447                 full_label_ = bformat(master.B_("%1$s %2$s: [[Caption label (ex. Figure 1: )]]"), name, sec);
448         }
449
450         // Do the real work now.
451         InsetText::updateBuffer(it, utype, deleted);
452         if (utype == OutputUpdate)
453                 cnts.restoreLastCounter();
454 }
455
456
457 string InsetCaption::contextMenuName() const
458 {
459         return "context-caption";
460 }
461
462
463 } // namespace lyx