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