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