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