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