]> git.lyx.org Git - features.git/blob - src/insets/InsetCaption.cpp
Fix bug #7948 by not hardcoding XHTML info for captions but instead
[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 "TextClass.h"
35 #include "TextMetrics.h"
36 #include "TocBackend.h"
37
38 #include "frontends/FontMetrics.h"
39 #include "frontends/Painter.h"
40
41 #include "support/gettext.h"
42 #include "support/lstrings.h"
43
44 #include <sstream>
45
46 using namespace std;
47 using namespace lyx::support;
48
49 namespace lyx {
50
51
52 InsetCaption::InsetCaption(Buffer * buf, string const & type)
53     : InsetText(buf, InsetText::PlainLayout), type_(type)
54 {
55         setAutoBreakRows(true);
56         setDrawFrame(true);
57         setFrameColor(Color_collapsableframe);
58 }
59
60
61 void InsetCaption::write(ostream & os) const
62 {
63         os << "Caption";
64         if (!type_.empty()) {
65                 os << " "
66                    << type_;
67         }
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         if (!isAscii(label) || label.empty())
92                 // This must be a user defined layout. We cannot translate
93                 // this, since gettext accepts only ascii keys.
94                 custom_label_ = label;
95         else
96                 custom_label_ = _(to_ascii(label));
97 }
98
99
100 void InsetCaption::addToToc(DocIterator const & cpit) const
101 {
102         if (floattype_.empty())
103                 return;
104
105         DocIterator pit = cpit;
106         pit.push_back(CursorSlice(const_cast<InsetCaption &>(*this)));
107
108         Toc & toc = buffer().tocBackend().toc(floattype_);
109         docstring str = full_label_;
110         text().forToc(str, TOC_ENTRY_LENGTH);
111         toc.push_back(TocItem(pit, 0, str));
112
113         // Proceed with the rest of the inset.
114         InsetText::addToToc(cpit);
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                 string const first_arg = cmd.getArg(0);
206                 bool const change_type = first_arg == "changetype";
207                 if (change_type) {
208                         cur.recordUndoInset(ATOMIC_UNDO, this);
209                         type_ = cmd.getArg(1);
210                         cur.forceBufferUpdate();
211                         break;
212                 }
213         }
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 = true;
233                         // check if the immediate parent inset allows caption variation
234                         if (cur.depth() > 1) {
235                                 if (&cur[cur.depth() - 2].inset()
236                                     && !cur[cur.depth() - 2].inset().allowsCaptionVariation())
237                                         varia = false;
238                         }
239                         status.setEnabled(varia
240                                           && buffer().params().documentClass().hasInsetLayout(
241                                                 from_ascii("Caption:" + type)));
242                         return true;
243                 }
244                 return InsetText::getStatus(cur, cmd, status);
245         }
246
247         case LFUN_PARAGRAPH_BREAK:
248                 status.setEnabled(false);
249                 return true;
250
251         case LFUN_INSET_TOGGLE:
252                 // pass back to owner
253                 cur.undispatched();
254                 return false;
255
256         default:
257                 return InsetText::getStatus(cur, cmd, status);
258         }
259 }
260
261
262 void InsetCaption::latex(otexstream & os,
263                          OutputParams const & runparams_in) const
264 {
265         if (runparams_in.inFloat == OutputParams::SUBFLOAT)
266                 // caption is output as an optional argument
267                 return;
268         // This is a bit too simplistic to take advantage of
269         // caption options we must add more later. (Lgb)
270         // This code is currently only able to handle the simple
271         // \caption{...}, later we will make it take advantage
272         // of the one of the caption packages. (Lgb)
273         OutputParams runparams = runparams_in;
274         // FIXME: actually, it is moving only when there is no
275         // optional argument.
276         runparams.moving_arg = !runparams.inTableCell;
277         InsetText::latex(os, runparams);
278         runparams_in.encoding = runparams.encoding;
279 }
280
281
282 int InsetCaption::plaintext(odocstream & os,
283                             OutputParams const & runparams) const
284 {
285         os << '[' << full_label_ << "\n";
286         InsetText::plaintext(os, runparams);
287         os << "\n]";
288
289         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
290 }
291
292
293 int InsetCaption::docbook(odocstream & os,
294                           OutputParams const & runparams) const
295 {
296         int ret;
297         os << "<title>";
298         ret = InsetText::docbook(os, runparams);
299         os << "</title>\n";
300         return ret;
301 }
302
303
304 docstring InsetCaption::xhtml(XHTMLStream & xs, OutputParams const & rp) const
305 {
306         if (rp.html_disable_captions)
307                 return docstring();
308         InsetLayout const & il = getLayout();
309         string const tag = il.htmltag();
310         string attr = il.htmlattr();
311         if (!type_.empty()) {
312                 string const our_class = "float-caption-" + type_;
313                 size_t const loc = attr.find("class='");
314                 if (loc != string::npos)
315                         attr.insert(loc + 1, our_class);
316         }
317         xs << html::StartTag(tag, attr);
318         docstring def = getCaptionAsHTML(xs, rp);
319         xs << html::EndTag(tag);
320         return def;
321 }
322
323
324 void InsetCaption::getArgument(otexstream & os,
325                         OutputParams const & runparams) const
326 {
327         InsetLayout const & il = getLayout();
328
329         if (!il.leftdelim().empty())
330                 os << il.leftdelim();
331   
332         OutputParams rp = runparams;
333         if (isPassThru())
334                 rp.pass_thru = true;
335         if (il.isNeedProtect())
336                 rp.moving_arg = true;
337         rp.par_begin = 0;
338         rp.par_end = paragraphs().size();
339
340         // Output the contents of the inset
341         latexParagraphs(buffer(), text(), os, rp);
342         runparams.encoding = rp.encoding;
343
344         if (!il.rightdelim().empty())
345                 os << il.rightdelim();
346 }
347
348
349 int InsetCaption::getCaptionAsPlaintext(odocstream & os,
350                         OutputParams const & runparams) const
351 {
352         os << full_label_ << ' ';
353         return InsetText::plaintext(os, runparams);
354 }
355
356
357 docstring InsetCaption::getCaptionAsHTML(XHTMLStream & xs,
358                         OutputParams const & runparams) const
359 {
360         xs << full_label_ << ' ';
361         InsetText::XHTMLOptions const opts = 
362                 InsetText::WriteLabel | InsetText::WriteInnerTag;
363         return InsetText::insetAsXHTML(xs, runparams, opts);
364 }
365
366
367 void InsetCaption::updateBuffer(ParIterator const & it, UpdateType utype)
368 {
369         Buffer const & master = *buffer().masterBuffer();
370         DocumentClass const & tclass = master.params().documentClass();
371         string const & lang = it.paragraph().getParLanguage(master.params())->code();
372         Counters & cnts = tclass.counters();
373         string const & type = cnts.current_float();
374         if (utype == OutputUpdate) {
375                 // counters are local to the caption
376                 cnts.saveLastCounter();
377         }
378         // Memorize type for addToToc().
379         floattype_ = type;
380         if (type.empty())
381                 full_label_ = master.B_("Senseless!!! ");
382         else {
383                 // FIXME: life would be _much_ simpler if listings was
384                 // listed in Floating.
385                 docstring name;
386                 if (type == "listing")
387                         name = master.B_("Listing");
388                 else
389                         name = master.B_(tclass.floats().getType(type).name());
390                 docstring counter = from_utf8(type);
391                 if (cnts.isSubfloat()) {
392                         // only standard captions allowed in subfloats
393                         type_ = "Standard";
394                         counter = "sub-" + from_utf8(type);
395                         name = bformat(_("Sub-%1$s"),
396                                        master.B_(tclass.floats().getType(type).name()));
397                 }
398                 docstring sec;
399                 if (cnts.hasCounter(counter)) {
400                         cnts.step(counter, utype);
401                         sec = cnts.theCounter(counter, lang);
402                 }
403                 if (getLayout().labelstring() != master.B_("standard")) {
404                         if (!sec.empty())
405                                 sec += from_ascii(" ");
406                         sec += bformat(from_ascii("(%1$s)"), getLayout().labelstring());
407                 }
408                 if (!sec.empty())
409                         full_label_ = bformat(from_ascii("%1$s %2$s:"), name, sec);
410                 else
411                         full_label_ = bformat(from_ascii("%1$s #:"), name);
412         }
413
414         // Do the real work now.
415         InsetText::updateBuffer(it, utype);
416         if (utype == OutputUpdate)
417                 cnts.restoreLastCounter();
418 }
419
420
421 string InsetCaption::contextMenuName() const
422 {
423         return "context-caption";
424 }
425
426
427 } // namespace lyx