]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Move labels and insets out of moving arguments
[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 "MetricsInfo.h"
29 #include "output_latex.h"
30 #include "output_xhtml.h"
31 #include "OutputParams.h"
32 #include "Paragraph.h"
33 #include "ParIterator.h"
34 #include "TexRow.h"
35 #include "texstream.h"
36 #include "TextClass.h"
37 #include "TextMetrics.h"
38 #include "TocBackend.h"
39
40 #include "frontends/FontMetrics.h"
41 #include "frontends/Painter.h"
42
43 #include "support/gettext.h"
44 #include "support/lstrings.h"
45
46 #include <sstream>
47
48 using namespace std;
49 using namespace lyx::support;
50
51 namespace lyx {
52
53
54 InsetCaption::InsetCaption(Buffer * buf, string const & type)
55     : InsetText(buf, InsetText::PlainLayout),
56       labelwidth_(0), is_subfloat_(false), 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         x += labelwidth_;
86 }
87
88
89 void InsetCaption::setCustomLabel(docstring const & label)
90 {
91         custom_label_ = translateIfPossible(label);
92 }
93
94
95 void InsetCaption::addToToc(DocIterator const & cpit, bool output_active,
96                                                         UpdateType utype, TocBackend & backend) const
97 {
98         string const & type = floattype_.empty() ? "senseless" : floattype_;
99         DocIterator pit = cpit;
100         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
101         int length = (utype == OutputUpdate) ?
102                 // For output (e.g. xhtml) all (bug #8603) or nothing
103                 (output_active ? INT_MAX : 0) :
104                 // TOC for LyX interface
105                 TOC_ENTRY_LENGTH;
106         docstring str;
107         if (length > 0) {
108                 str = full_label_;
109                 text().forOutliner(str, length);
110         }
111         backend.builder(type).captionItem(pit, str, output_active);
112         // Proceed with the rest of the inset.
113         InsetText::addToToc(cpit, output_active, utype, backend);
114 }
115
116
117 void InsetCaption::metrics(MetricsInfo & mi, Dimension & dim) const
118 {
119         FontInfo tmpfont = mi.base.font;
120         mi.base.font = mi.base.bv->buffer().params().getFont().fontInfo();
121         labelwidth_ = theFontMetrics(mi.base.font).width(full_label_);
122         // add some space to separate the label from the inset text
123         labelwidth_ += 2 * TEXT_TO_INSET_OFFSET;
124         dim.wid = labelwidth_;
125         Dimension textdim;
126         // Correct for button and label width
127         mi.base.textwidth -= dim.wid;
128         InsetText::metrics(mi, textdim);
129         mi.base.font = tmpfont;
130         mi.base.textwidth += dim.wid;
131         dim.des = max(dim.des - textdim.asc + dim.asc, textdim.des);
132         dim.asc = textdim.asc;
133         dim.wid += textdim.wid;
134 }
135
136
137 void InsetCaption::drawBackground(PainterInfo & pi, int x, int y) const
138 {
139         TextMetrics & tm = pi.base.bv->textMetrics(&text());
140         int const h = tm.height() + 2 * TEXT_TO_INSET_OFFSET;
141         int const yy = y - TEXT_TO_INSET_OFFSET - tm.ascent();
142         pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
143 }
144
145
146 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
147 {
148         // We must draw the label, we should get the label string
149         // from the enclosing float inset.
150         // The question is: Who should draw the label, the caption inset,
151         // the text inset or the paragraph?
152         // We should also draw the float number (Lgb)
153
154         // Answer: the text inset (in buffer_funcs.cpp: setCaption).
155
156         FontInfo tmpfont = pi.base.font;
157         pi.base.font = pi.base.bv->buffer().params().getFont().fontInfo();
158         pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
159         int const xx = x + TEXT_TO_INSET_OFFSET;
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 = true;
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 int InsetCaption::docbook(odocstream & os,
296                           OutputParams const & runparams) const
297 {
298         int ret;
299         os << "<title>";
300         ret = InsetText::docbook(os, runparams);
301         os << "</title>\n";
302         return ret;
303 }
304
305
306 docstring InsetCaption::xhtml(XHTMLStream & xs, OutputParams const & rp) const
307 {
308         if (rp.html_disable_captions)
309                 return docstring();
310         InsetLayout const & il = getLayout();
311         string const & tag = il.htmltag();
312         string attr = il.htmlattr();
313         if (!type_.empty()) {
314                 string const our_class = "float-caption-" + type_;
315                 size_t const loc = attr.find("class='");
316                 if (loc != string::npos)
317                         attr.insert(loc + 7, our_class + " ");
318                 else
319                         attr = attr + " class='" + our_class + "'";
320         }
321         xs << html::StartTag(tag, attr);
322         docstring def = getCaptionAsHTML(xs, rp);
323         xs << html::EndTag(tag);
324         return def;
325 }
326
327
328 void InsetCaption::getArgument(otexstream & os,
329                         OutputParams const & runparams) const
330 {
331         InsetLayout const & il = getLayout();
332
333         if (!il.leftdelim().empty())
334                 os << il.leftdelim();
335
336         OutputParams rp = runparams;
337         if (isPassThru())
338                 rp.pass_thru = true;
339         if (il.isNeedProtect())
340                 rp.moving_arg = true;
341         if (il.isNeedMBoxProtect())
342                 ++rp.inulemcmd;
343         rp.par_begin = 0;
344         rp.par_end = paragraphs().size();
345
346         // Output the contents of the inset
347         if (!paragraphs().empty())
348                 os.texrow().forceStart(paragraphs()[0].id(), 0);
349         latexParagraphs(buffer(), text(), os, rp);
350         runparams.encoding = rp.encoding;
351
352         if (!il.rightdelim().empty())
353                 os << il.rightdelim();
354 }
355
356
357 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
358                         OutputParams const & runparams) const
359 {
360         os << full_label_ << ' ';
361         odocstringstream ods;
362         int const retval = InsetText::plaintext(ods, runparams);
363         os << ods.str();
364         return retval;
365 }
366
367
368 docstring InsetCaption::getCaptionAsHTML(XHTMLStream & xs,
369                         OutputParams const & runparams) const
370 {
371         xs << full_label_ << ' ';
372         InsetText::XHTMLOptions const opts =
373                 InsetText::WriteLabel | InsetText::WriteInnerTag;
374         return InsetText::insetAsXHTML(xs, runparams, opts);
375 }
376
377
378 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype)
379 {
380         Buffer const & master = *buffer().masterBuffer();
381         DocumentClass const & tclass = master.params().documentClass();
382         string const & lang = it.paragraph().getParLanguage(master.params())->code();
383         Counters & cnts = tclass.counters();
384         string const & type = cnts.current_float();
385         if (utype == OutputUpdate) {
386                 // counters are local to the caption
387                 cnts.saveLastCounter();
388         }
389         // Memorize type for addToToc().
390         floattype_ = type;
391         if (type.empty() || type == "senseless")
392                 full_label_ = master.B_("Senseless!!! ");
393         else {
394                 // FIXME: life would be _much_ simpler if listings was
395                 // listed in Floating.
396                 docstring name;
397                 if (type == "listing")
398                         name = master.B_("Listing");
399                 else
400                         name = master.B_(tclass.floats().getType(type).name());
401                 docstring counter = from_utf8(type);
402                 is_subfloat_ = cnts.isSubfloat();
403                 if (is_subfloat_) {
404                         // only standard captions allowed in subfloats
405                         type_ = "Standard";
406                         counter = "sub-" + from_utf8(type);
407                         name = bformat(_("Sub-%1$s"),
408                                        master.B_(tclass.floats().getType(type).name()));
409                 }
410                 docstring sec;
411                 docstring const lstring = getLayout().labelstring();
412                 docstring const labelstring = isAscii(lstring) ?
413                                 master.B_(to_ascii(lstring)) : lstring;
414                 if (cnts.hasCounter(counter)) {
415                         // for longtables, we step the counter upstream
416                         if (!cnts.isLongtable())
417                                 cnts.step(counter, utype);
418                         sec = cnts.theCounter(counter, lang);
419                 }
420                 if (labelstring != master.B_("standard")) {
421                         if (!sec.empty())
422                                 sec += from_ascii(" ");
423                         sec += bformat(from_ascii("(%1$s)"), labelstring);
424                 }
425                 if (!sec.empty())
426                         full_label_ = bformat(from_ascii("%1$s %2$s: "), name, sec);
427                 else
428                         full_label_ = bformat(from_ascii("%1$s #: "), name);
429         }
430
431         // Do the real work now.
432         InsetText::updateBuffer(it, utype);
433         if (utype == OutputUpdate)
434                 cnts.restoreLastCounter();
435 }
436
437
438 string InsetCaption::contextMenuName() const
439 {
440         return "context-caption";
441 }
442
443
444 } // namespace lyx