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