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