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