]> git.lyx.org Git - lyx.git/blob - src/insets/InsetCaption.cpp
Fix logic of new InsetFlex::updateBuffer() routine from a9614f1.
[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         runparams_in.encoding = runparams.encoding;
280 }
281
282
283 int InsetCaption::plaintext(odocstringstream & os,
284                             OutputParams const & runparams, size_t max_length) const
285 {
286         os << '[' << full_label_ << "\n";
287         InsetText::plaintext(os, runparams, max_length);
288         os << "\n]";
289
290         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
291 }
292
293
294 int InsetCaption::docbook(odocstream & os,
295                           OutputParams const & runparams) const
296 {
297         int ret;
298         os << "<title>";
299         ret = InsetText::docbook(os, runparams);
300         os << "</title>\n";
301         return ret;
302 }
303
304
305 docstring InsetCaption::xhtml(XHTMLStream & xs, OutputParams const & rp) const
306 {
307         if (rp.html_disable_captions)
308                 return docstring();
309         InsetLayout const & il = getLayout();
310         string const tag = il.htmltag();
311         string attr = il.htmlattr();
312         if (!type_.empty()) {
313                 string const our_class = "float-caption-" + type_;
314                 size_t const loc = attr.find("class='");
315                 if (loc != string::npos)
316                         attr.insert(loc + 1, 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                 if (cnts.hasCounter(counter)) {
404                         cnts.step(counter, utype);
405                         sec = cnts.theCounter(counter, lang);
406                 }
407                 if (getLayout().labelstring() != master.B_("standard")) {
408                         if (!sec.empty())
409                                 sec += from_ascii(" ");
410                         sec += bformat(from_ascii("(%1$s)"), getLayout().labelstring());
411                 }
412                 if (!sec.empty())
413                         full_label_ = bformat(from_ascii("%1$s %2$s:"), name, sec);
414                 else
415                         full_label_ = bformat(from_ascii("%1$s #:"), name);
416         }
417
418         // Do the real work now.
419         InsetText::updateBuffer(it, utype);
420         if (utype == OutputUpdate)
421                 cnts.restoreLastCounter();
422 }
423
424
425 string InsetCaption::contextMenuName() const
426 {
427         return "context-caption";
428 }
429
430
431 } // namespace lyx