]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Rename XHTMLStream to XMLStream, move it to another file, and prepare for DocBook...
[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 "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), is_deleted_(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::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         pi.pain.fillRectangle(x, yy, labelwidth_, h, pi.backgroundColor(this));
138 }
139
140
141 void InsetCaption::draw(PainterInfo & pi, int x, int y) const
142 {
143         // We must draw the label, we should get the label string
144         // from the enclosing float inset.
145         // The question is: Who should draw the label, the caption inset,
146         // the text inset or the paragraph?
147         // We should also draw the float number (Lgb)
148
149         // Answer: the text inset (in buffer_funcs.cpp: setCaption).
150
151         FontInfo tmpfont = pi.base.font;
152         pi.base.font = pi.base.bv->buffer().params().getFont().fontInfo();
153         pi.base.font.setColor(pi.textColor(pi.base.font.color()).baseColor);
154         if (is_deleted_)
155                 pi.base.font.setStrikeout(FONT_ON);
156         else if (isChanged() && lyxrc.ct_additions_underlined)
157                 pi.base.font.setUnderbar(FONT_ON);
158         int const xx = x + leftOffset(pi.base.bv);
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         // no "changetype":
211         // fall through
212
213         default:
214                 InsetText::doDispatch(cur, cmd);
215                 break;
216         }
217 }
218
219
220 bool InsetCaption::getStatus(Cursor & cur, FuncRequest const & cmd,
221         FuncStatus & status) const
222 {
223         switch (cmd.action()) {
224
225         case LFUN_INSET_MODIFY: {
226                 string const first_arg = cmd.getArg(0);
227                 if (first_arg == "changetype") {
228                         string const type = cmd.getArg(1);
229                         status.setOnOff(type == type_);
230                         bool varia = type != "Unnumbered";
231                         // check if the immediate parent inset allows caption variation
232                         if (cur.depth() > 1) {
233                                 varia = cur[cur.depth() - 2].inset().allowsCaptionVariation(type);
234                         }
235                         status.setEnabled(varia
236                                           && buffer().params().documentClass().hasInsetLayout(
237                                                 from_ascii("Caption:" + type)));
238                         return true;
239                 }
240                 return InsetText::getStatus(cur, cmd, status);
241         }
242
243         case LFUN_INSET_TOGGLE:
244                 // pass back to owner
245                 cur.undispatched();
246                 return false;
247
248         default:
249                 return InsetText::getStatus(cur, cmd, status);
250         }
251 }
252
253
254 void InsetCaption::latex(otexstream & os,
255                          OutputParams const & runparams_in) const
256 {
257         if (runparams_in.inFloat == OutputParams::SUBFLOAT)
258                 // caption is output as an optional argument
259                 return;
260         // This is a bit too simplistic to take advantage of
261         // caption options we must add more later. (Lgb)
262         // This code is currently only able to handle the simple
263         // \caption{...}, later we will make it take advantage
264         // of the one of the caption packages. (Lgb)
265         OutputParams runparams = runparams_in;
266         // Some fragile commands (labels, index entries)
267         // are output after the caption (#2154)
268         runparams.postpone_fragile_stuff = buffer().masterParams().postpone_fragile_content;
269         InsetText::latex(os, runparams);
270         if (!runparams.post_macro.empty()) {
271                 // Output the stored fragile commands (labels, indices etc.)
272                 // that need to be output after the caption.
273                 os << runparams.post_macro;
274                 runparams.post_macro.clear();
275         }
276         // Backwards compatibility: We always had a linebreak after
277         // the caption (see #8514)
278         os << breakln;
279         runparams_in.encoding = runparams.encoding;
280 }
281
282
283 int InsetCaption::plaintext(odocstringstream & os,
284                             OutputParams const & runparams, size_t max_length) const
285 {
286         os << '[' << full_label_ << "\n";
287         InsetText::plaintext(os, runparams, max_length);
288         os << "\n]";
289
290         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
291 }
292
293
294 int InsetCaption::docbook(odocstream & os,
295                           OutputParams const & runparams) const
296 {
297         int ret;
298         os << "<title>";
299         ret = InsetText::docbook(os, runparams);
300         os << "</title>\n";
301         return ret;
302 }
303
304
305 docstring InsetCaption::xhtml(XMLStream & xs, OutputParams const & rp) const
306 {
307         if (rp.html_disable_captions)
308                 return docstring();
309         InsetLayout const & il = getLayout();
310         string const & tag = il.htmltag();
311         string attr = il.htmlattr();
312         if (!type_.empty()) {
313                 string const our_class = "float-caption-" + type_;
314                 size_t const loc = attr.find("class='");
315                 if (loc != string::npos)
316                         attr.insert(loc + 7, our_class + " ");
317                 else
318                         attr = attr + " class='" + our_class + "'";
319         }
320         xs << xml::StartTag(tag, attr);
321         docstring def = getCaptionAsHTML(xs, rp);
322         xs << xml::EndTag(tag);
323         return def;
324 }
325
326
327 void InsetCaption::getArgument(otexstream & os,
328                         OutputParams const & runparams) const
329 {
330         InsetLayout const & il = getLayout();
331
332         if (!il.leftdelim().empty())
333                 os << il.leftdelim();
334
335         OutputParams rp = runparams;
336         if (isPassThru())
337                 rp.pass_thru = true;
338         if (il.isNeedProtect())
339                 rp.moving_arg = true;
340         if (il.isNeedMBoxProtect())
341                 ++rp.inulemcmd;
342         rp.par_begin = 0;
343         rp.par_end = paragraphs().size();
344
345         // Output the contents of the inset
346         if (!paragraphs().empty())
347                 os.texrow().forceStart(paragraphs()[0].id(), 0);
348         latexParagraphs(buffer(), text(), os, rp);
349         runparams.encoding = rp.encoding;
350
351         if (!il.rightdelim().empty())
352                 os << il.rightdelim();
353 }
354
355
356 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
357                         OutputParams const & runparams) const
358 {
359         os << full_label_ << ' ';
360         odocstringstream ods;
361         int const retval = InsetText::plaintext(ods, runparams);
362         os << ods.str();
363         return retval;
364 }
365
366
367 docstring InsetCaption::getCaptionAsHTML(XMLStream & xs,
368                         OutputParams const & runparams) const
369 {
370         xs << full_label_ << ' ';
371         InsetText::XHTMLOptions const opts =
372                 InsetText::WriteLabel | InsetText::WriteInnerTag;
373         return InsetText::insetAsXHTML(xs, runparams, opts);
374 }
375
376
377 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype, bool const deleted)
378 {
379         Buffer const & master = *buffer().masterBuffer();
380         DocumentClass const & tclass = master.params().documentClass();
381         string const & lang = it.paragraph().getParLanguage(master.params())->code();
382         Counters & cnts = tclass.counters();
383         string const & type = cnts.current_float();
384         if (utype == OutputUpdate) {
385                 // counters are local to the caption
386                 cnts.saveLastCounter();
387         }
388         is_deleted_ = deleted;
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                         int val = cnts.value(counter);
416                         // for longtables, we step the counter upstream
417                         if (!cnts.isLongtable())
418                                 cnts.step(counter, utype);
419                         sec = cnts.theCounter(counter, lang);
420                         if (deleted && !cnts.isLongtable())
421                                 // un-step after deleted counter
422                                 cnts.set(counter, val);
423                 }
424                 if (labelstring != master.B_("standard")) {
425                         if (!sec.empty())
426                                 sec += from_ascii(" ");
427                         sec += bformat(from_ascii("(%1$s)"), labelstring);
428                 }
429                 if (!sec.empty())
430                         full_label_ = bformat(from_ascii("%1$s %2$s: "), name, sec);
431                 else
432                         full_label_ = bformat(from_ascii("%1$s #: "), name);
433         }
434
435         // Do the real work now.
436         InsetText::updateBuffer(it, utype, deleted);
437         if (utype == OutputUpdate)
438                 cnts.restoreLastCounter();
439 }
440
441
442 string InsetCaption::contextMenuName() const
443 {
444         return "context-caption";
445 }
446
447
448 } // namespace lyx