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