]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
Revert "Do not crash is release mode if we stumble across an unrealized font."
[lyx.git] / src / insets / InsetFloat.cpp
1 /**
2  * \file InsetFloat.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Jürgen Vigna
7  * \author Lars Gullik Bjønnes
8  * \author Jürgen Spitzmüller
9  *
10  * Full author contact details are available in file CREDITS.
11  */
12
13 #include <config.h>
14
15 #include "InsetFloat.h"
16 #include "InsetCaption.h"
17
18 #include "Buffer.h"
19 #include "BufferParams.h"
20 #include "BufferView.h"
21 #include "Counters.h"
22 #include "Cursor.h"
23 #include "DispatchResult.h"
24 #include "Floating.h"
25 #include "FloatList.h"
26 #include "FuncRequest.h"
27 #include "FuncStatus.h"
28 #include "LaTeXFeatures.h"
29 #include "Lexer.h"
30 #include "output_xhtml.h"
31 #include "ParIterator.h"
32 #include "TexRow.h"
33 #include "texstream.h"
34 #include "TextClass.h"
35
36 #include "support/debug.h"
37 #include "support/docstream.h"
38 #include "support/gettext.h"
39 #include "support/lstrings.h"
40
41 #include "frontends/Application.h"
42
43 using namespace std;
44 using namespace lyx::support;
45
46
47 namespace lyx {
48
49 // With this inset it will be possible to support the latex package
50 // float.sty, and I am sure that with this and some additional support
51 // classes we can support similar functionality in other formats
52 // (read DocBook).
53 // By using float.sty we will have the same handling for all floats, both
54 // for those already in existance (table and figure) and all user created
55 // ones¹. So suddenly we give the users the possibility of creating new
56 // kinds of floats on the fly. (and with a uniform look)
57 //
58 // API to float.sty:
59 //   \newfloat{type}{placement}{ext}[within]
60 //     type      - The "type" of the new class of floats, like program or
61 //                 algorithm. After the appropriate \newfloat, commands
62 //                 such as \begin{program} or \end{algorithm*} will be
63 //                 available.
64 //     placement - The default placement for the given class of floats.
65 //                 They are like in standard LaTeX: t, b, p and h for top,
66 //                 bottom, page, and here, respectively. On top of that
67 //                 there is a new type, H, which does not really correspond
68 //                 to a float, since it means: put it "here" and nowhere else.
69 //                 Note, however that the H specifier is special and, because
70 //                 of implementation details cannot be used in the second
71 //                 argument of \newfloat.
72 //     ext       - The file name extension of an auxiliary file for the list
73 //                 of figures (or whatever). LaTeX writes the captions to
74 //                 this file.
75 //     within    - This (optional) argument determines whether floats of this
76 //                 class will be numbered within some sectional unit of the
77 //                 document. For example, if within is equal to chapter, the
78 //                 floats will be numbered within chapters.
79 //   \floatstyle{style}
80 //     style -  plain, boxed, ruled
81 //   \floatname{float}{floatname}
82 //     float     -
83 //     floatname -
84 //   \floatplacement{float}{placement}
85 //     float     -
86 //     placement -
87 //   \restylefloat{float}
88 //     float -
89 //   \listof{type}{title}
90 //     title -
91
92 // ¹ the algorithm float is defined using the float.sty package. Like this
93 //   \floatstyle{ruled}
94 //   \newfloat{algorithm}{htbp}{loa}[<sect>]
95 //   \floatname{algorithm}{Algorithm}
96 //
97 // The intention is that floats should be definable from two places:
98 //          - layout files
99 //          - the "gui" (i.e. by the user)
100 //
101 // From layout files.
102 // This should only be done for floats defined in a documentclass and that
103 // does not need any additional packages. The two most known floats in this
104 // category is "table" and "figure". Floats defined in layout files are only
105 // stored in lyx files if the user modifies them.
106 //
107 // By the user.
108 // There should be a gui dialog (and also a collection of lyxfuncs) where
109 // the user can modify existing floats and/or create new ones.
110 //
111 // The individual floats will also have some settable
112 // variables: wide and placement.
113 //
114 // Lgb
115
116 //FIXME: why do we set in stone the type here?
117 InsetFloat::InsetFloat(Buffer * buf, string params_str)
118         : InsetCaptionable(buf)
119 {
120         string2params(params_str, params_);
121         setCaptionType(params_.type);
122 }
123
124
125 // Enforce equality of float type and caption type.
126 void InsetFloat::setCaptionType(std::string const & type)
127 {
128         InsetCaptionable::setCaptionType(type); 
129         params_.type = captionType();
130         // check if the float type exists
131         if (buffer().params().documentClass().floats().typeExist(params_.type))
132                 setLabel(_("float: ") + floatName(params_.type));
133         else
134                 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
135 }
136
137
138 docstring InsetFloat::layoutName() const
139
140         return "Float:" + from_utf8(params_.type);
141 }
142
143
144 docstring InsetFloat::toolTip(BufferView const & bv, int x, int y) const
145 {
146         if (isOpen(bv))
147                 return InsetCaptionable::toolTip(bv, x, y);
148
149         OutputParams rp(&buffer().params().encoding());
150         return getCaptionText(rp);
151 }
152
153
154 void InsetFloat::doDispatch(Cursor & cur, FuncRequest & cmd)
155 {
156         switch (cmd.action()) {
157
158         case LFUN_INSET_MODIFY: {
159                 InsetFloatParams params;
160                 string2params(to_utf8(cmd.argument()), params);
161                 cur.recordUndoInset(this);
162
163                 // placement, wide and sideways are not used for subfloats
164                 if (!params_.subfloat) {
165                         params_.placement = params.placement;
166                         params_.wide      = params.wide;
167                         params_.sideways  = params.sideways;
168                 }
169                 setNewLabel();
170                 if (params_.type != params.type)
171                         setCaptionType(params.type);
172                 // what we really want here is a TOC update, but that means
173                 // a full buffer update
174                 cur.forceBufferUpdate();
175                 break;
176         }
177
178         case LFUN_INSET_DIALOG_UPDATE: {
179                 cur.bv().updateDialog("float", params2string(params()));
180                 break;
181         }
182
183         default:
184                 InsetCaptionable::doDispatch(cur, cmd);
185                 break;
186         }
187 }
188
189
190 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
191                 FuncStatus & flag) const
192 {
193         switch (cmd.action()) {
194
195         case LFUN_INSET_MODIFY:
196         case LFUN_INSET_DIALOG_UPDATE:
197                 flag.setEnabled(true);
198                 return true;
199
200         case LFUN_INSET_SETTINGS:
201                 if (InsetCaptionable::getStatus(cur, cmd, flag)) {
202                         flag.setEnabled(flag.enabled() && !params_.subfloat);
203                         return true;
204                 } else
205                         return false;
206         
207         case LFUN_NEWLINE_INSERT:
208                 if (params_.subfloat) {
209                         flag.setEnabled(false);
210                         return true;
211                 }
212
213         default:
214                 return InsetCaptionable::getStatus(cur, cmd, flag);
215         }
216 }
217
218
219 bool InsetFloat::hasSubCaptions(ParIterator const & it) const
220 {
221         return (it.innerInsetOfType(FLOAT_CODE) || it.innerInsetOfType(WRAP_CODE));
222 }
223
224
225 void InsetFloatParams::write(ostream & os) const
226 {
227         if (type.empty()) {
228                 // Better this than creating a parse error. This in fact happens in the
229                 // parameters dialog via InsetFloatParams::params2string.
230                 os << "senseless" << '\n';
231         } else
232                 os << type << '\n';
233
234         if (!placement.empty())
235                 os << "placement " << placement << "\n";
236
237         if (wide)
238                 os << "wide true\n";
239         else
240                 os << "wide false\n";
241
242         if (sideways)
243                 os << "sideways true\n";
244         else
245                 os << "sideways false\n";
246 }
247
248
249 void InsetFloatParams::read(Lexer & lex)
250 {
251         lex.setContext("InsetFloatParams::read");
252         lex >> type;
253         if (lex.checkFor("placement"))
254                 lex >> placement;
255         lex >> "wide" >> wide;
256         lex >> "sideways" >> sideways;
257 }
258
259
260 void InsetFloat::write(ostream & os) const
261 {
262         os << "Float ";
263         params_.write(os);
264         InsetCaptionable::write(os);
265 }
266
267
268 void InsetFloat::read(Lexer & lex)
269 {
270         params_.read(lex);
271         InsetCaptionable::read(lex);
272         setCaptionType(params_.type);
273 }
274
275
276 void InsetFloat::validate(LaTeXFeatures & features) const
277 {
278         if (support::contains(params_.placement, 'H'))
279                 features.require("float");
280
281         if (params_.sideways)
282                 features.require("rotfloat");
283
284         if (features.inFloat())
285                 features.require("subfig");
286
287         features.useFloat(params_.type, features.inFloat());
288         features.inFloat(true);
289         InsetCaptionable::validate(features);
290         features.inFloat(false);
291 }
292
293
294 docstring InsetFloat::xhtml(XHTMLStream & xs, OutputParams const & rp) const
295 {
296         FloatList const & floats = buffer().params().documentClass().floats();
297         Floating const & ftype = floats.getType(params_.type);
298         string const & htmltype = ftype.htmlTag();
299         string const & attr = ftype.htmlAttrib();
300
301         odocstringstream ods;
302         XHTMLStream newxs(ods);
303         newxs << html::StartTag(htmltype, attr);
304         InsetText::XHTMLOptions const opts = 
305                 InsetText::WriteLabel | InsetText::WriteInnerTag;
306         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
307         newxs << html::EndTag(htmltype);
308
309         if (rp.inFloat == OutputParams::NONFLOAT)
310                 // In this case, this float needs to be deferred, but we'll put it
311                 // before anything the text itself deferred.
312                 deferred = ods.str() + '\n' + deferred;
313         else 
314                 // In this case, the whole thing is already being deferred, so
315                 // we can write to the stream.
316                 // Note that things will already have been escaped, so we do not 
317                 // want to escape them again.
318                 xs << XHTMLStream::ESCAPE_NONE << ods.str();
319         return deferred;
320 }
321
322
323 void InsetFloat::latex(otexstream & os, OutputParams const & runparams_in) const
324 {
325         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
326                 if (runparams_in.moving_arg)
327                         os << "\\protect";
328                 os << "\\subfloat";
329
330                 OutputParams rp = runparams_in;
331                 rp.moving_arg = true;
332                 getCaption(os, rp);
333                 os << '{';
334                 // The main argument is the contents of the float. This is not a moving argument.
335                 if (!paragraphs().empty())
336                         os.texrow().forceStart(paragraphs()[0].id(), 0);
337                 rp.moving_arg = false;
338                 rp.inFloat = OutputParams::SUBFLOAT;
339                 InsetText::latex(os, rp);
340                 os << "}";
341
342                 return;
343         }
344         OutputParams runparams(runparams_in);
345         runparams.inFloat = OutputParams::MAINFLOAT;
346
347         FloatList const & floats = buffer().params().documentClass().floats();
348         string tmptype = params_.type;
349         if (params_.sideways && floats.allowsSideways(params_.type))
350                 tmptype = "sideways" + params_.type;
351         if (params_.wide && floats.allowsWide(params_.type)
352                 && (!params_.sideways ||
353                      params_.type == "figure" ||
354                      params_.type == "table"))
355                 tmptype += "*";
356         // Figure out the float placement to use.
357         // From lowest to highest:
358         // - float default placement
359         // - document wide default placement
360         // - specific float placement
361         string tmpplacement;
362         string const buf_placement = buffer().params().float_placement;
363         string const def_placement = floats.defaultPlacement(params_.type);
364         if (!params_.placement.empty()
365             && params_.placement != def_placement) {
366                 tmpplacement = params_.placement;
367         } else if (params_.placement.empty()
368                    && !buf_placement.empty()
369                    && buf_placement != def_placement) {
370                 tmpplacement = buf_placement;
371         }
372
373         // Check if placement is allowed by this float
374         string const allowed_placement =
375                 floats.allowedPlacement(params_.type);
376         string placement;
377         string::const_iterator lit = tmpplacement.begin();
378         string::const_iterator end = tmpplacement.end();
379         for (; lit != end; ++lit) {
380                 if (contains(allowed_placement, *lit))
381                         placement += *lit;
382         }
383
384         // Force \begin{<floatname>} to appear in a new line.
385         os << breakln << "\\begin{" << from_ascii(tmptype) << '}';
386         if (runparams.lastid != -1)
387                 os.texrow().start(runparams.lastid, runparams.lastpos);
388         // We only output placement if different from the def_placement.
389         // sidewaysfloats always use their own page
390         if (!placement.empty() && !params_.sideways)
391                 os << '[' << from_ascii(placement) << ']';
392         os << '\n';
393
394         InsetText::latex(os, runparams);
395
396         // Force \end{<floatname>} to appear in a new line.
397         os << breakln << "\\end{" << from_ascii(tmptype) << "}\n";
398 }
399
400
401 int InsetFloat::plaintext(odocstringstream & os, OutputParams const & runparams, size_t max_length) const
402 {
403         os << '[' << buffer().B_("float") << ' '
404                 << floatName(params_.type) << ":\n";
405         InsetText::plaintext(os, runparams, max_length);
406         os << "\n]";
407
408         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
409 }
410
411
412 int InsetFloat::docbook(odocstream & os, OutputParams const & runparams) const
413 {
414         // FIXME Implement subfloat!
415         // FIXME UNICODE
416         os << '<' << from_ascii(params_.type) << '>';
417         int const i = InsetText::docbook(os, runparams);
418         os << "</" << from_ascii(params_.type) << '>';
419
420         return i;
421 }
422
423
424 bool InsetFloat::insetAllowed(InsetCode code) const
425 {
426         // The case that code == FLOAT_CODE is handled in Text3.cpp, 
427         // because we need to know what type of float is meant.
428         switch(code) {
429         case WRAP_CODE:
430         case FOOT_CODE:
431         case MARGIN_CODE:
432                 return false;
433         default:
434                 return InsetCaptionable::insetAllowed(code);
435         }
436 }
437
438
439 void InsetFloat::setWide(bool w, bool update_label)
440 {
441         if (!buffer().params().documentClass().floats().allowsWide(params_.type))
442                 params_.wide = false;
443         else
444             params_.wide = w;
445         if (update_label)
446                 setNewLabel();
447 }
448
449
450 void InsetFloat::setSideways(bool s, bool update_label)
451 {
452         if (!buffer().params().documentClass().floats().allowsSideways(params_.type))
453                 params_.sideways = false;
454         else
455                 params_.sideways = s;
456         if (update_label)
457                 setNewLabel();
458 }
459
460
461 void InsetFloat::setSubfloat(bool s, bool update_label)
462 {
463         params_.subfloat = s;
464         if (update_label)
465                 setNewLabel();
466 }
467
468
469 void InsetFloat::setNewLabel()
470 {
471         docstring lab = _("float: ");
472
473         if (params_.subfloat)
474                 lab = _("subfloat: ");
475
476         lab += floatName(params_.type);
477
478         FloatList const & floats = buffer().params().documentClass().floats();
479
480         if (params_.wide && floats.allowsWide(params_.type))
481                 lab += '*';
482
483         if (params_.sideways && floats.allowsSideways(params_.type))
484                 lab += _(" (sideways)");
485
486         setLabel(lab);
487 }
488
489
490 bool InsetFloat::allowsCaptionVariation(std::string const & newtype) const
491 {
492         return !params_.subfloat && newtype != "Unnumbered";
493 }
494
495
496 docstring InsetFloat::getCaption(OutputParams const & runparams) const
497 {
498         odocstringstream ods;
499         otexstream os(ods, false);
500         getCaption(os, runparams);
501         return ods.str();
502 }
503
504
505 void InsetFloat::getCaption(otexstream & os,
506                                                         OutputParams const & runparams) const
507 {
508         if (paragraphs().empty())
509                 return;
510
511         InsetCaption const * ins = getCaptionInset();
512         if (ins == 0)
513                 return;
514
515         ins->getArgs(os, runparams);
516
517         os << '[';
518         odocstringstream ods;
519         otexstream oss(ods);
520         ins->getArgument(oss, runparams);
521         docstring arg = ods.str();
522         // Protect ']'
523         if (arg.find(']') != docstring::npos)
524                 arg = '{' + arg + '}';
525         os.append(arg, move(oss.texrow()));
526         os << ']';
527 }
528
529
530 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
531 {
532         params = InsetFloatParams();
533         if (in.empty())
534                 return;
535
536         istringstream data(in);
537         Lexer lex;
538         lex.setStream(data);
539         lex.setContext("InsetFloat::string2params");
540         params.read(lex);
541 }
542
543
544 string InsetFloat::params2string(InsetFloatParams const & params)
545 {
546         ostringstream data;
547         params.write(data);
548         return data.str();
549 }
550
551
552 } // namespace lyx