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