]> git.lyx.org Git - lyx.git/blob - src/insets/InsetFloat.cpp
f8807f974cc00d0641c39679d9bf6631e41a02d1
[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                         buffer().updateLabels();
156                 }
157                 break;
158         }
159
160         case LFUN_INSET_DIALOG_UPDATE: {
161                 cur.bv().updateDialog("float", params2string(params()));
162                 break;
163         }
164
165         default:
166                 InsetCollapsable::doDispatch(cur, cmd);
167                 break;
168         }
169 }
170
171
172 bool InsetFloat::getStatus(Cursor & cur, FuncRequest const & cmd,
173                 FuncStatus & flag) const
174 {
175         switch (cmd.action) {
176
177         case LFUN_INSET_MODIFY:
178         case LFUN_INSET_DIALOG_UPDATE:
179                 flag.setEnabled(true);
180                 return true;
181
182         case LFUN_INSET_SETTINGS:
183                 if (InsetCollapsable::getStatus(cur, cmd, flag)) {
184                         flag.setEnabled(flag.enabled() && !params_.subfloat);
185                         return true;
186                 } else
187                         return false;
188
189         default:
190                 return InsetCollapsable::getStatus(cur, cmd, flag);
191         }
192 }
193
194
195 void InsetFloat::updateLabels(ParIterator const & it, UpdateType utype)
196 {
197         Counters & cnts =
198                 buffer().masterBuffer()->params().documentClass().counters();
199         if (utype == OutputUpdate) {
200                 // counters are local to the float
201                 cnts.saveLastCounter();
202         }
203         string const saveflt = cnts.current_float();
204         bool const savesubflt = cnts.isSubfloat();
205
206         bool const subflt = (it.innerInsetOfType(FLOAT_CODE)
207                              || it.innerInsetOfType(WRAP_CODE));
208         // floats can only embed subfloats of their own kind
209         if (subflt)
210                 params_.type = saveflt;
211         setSubfloat(subflt);
212
213         // Tell to captions what the current float is
214         cnts.current_float(params().type);
215         cnts.isSubfloat(subflt);
216
217         InsetCollapsable::updateLabels(it, utype);
218
219         //reset afterwards
220         cnts.current_float(saveflt);
221         if (utype == OutputUpdate)
222                 cnts.restoreLastCounter();
223         cnts.isSubfloat(savesubflt);
224 }
225
226
227 void InsetFloatParams::write(ostream & os) const
228 {
229         os << type << '\n';
230
231         if (!placement.empty())
232                 os << "placement " << placement << "\n";
233
234         if (wide)
235                 os << "wide true\n";
236         else
237                 os << "wide false\n";
238
239         if (sideways)
240                 os << "sideways true\n";
241         else
242                 os << "sideways false\n";
243 }
244
245
246 void InsetFloatParams::read(Lexer & lex)
247 {
248         lex.setContext("InsetFloatParams::read");
249         lex >> type;
250         if (lex.checkFor("placement"))
251                 lex >> placement;
252         lex >> "wide" >> wide;
253         lex >> "sideways" >> sideways;
254 }
255
256
257 void InsetFloat::write(ostream & os) const
258 {
259         os << "Float ";
260         params_.write(os);
261         InsetCollapsable::write(os);
262 }
263
264
265 void InsetFloat::read(Lexer & lex)
266 {
267         params_.read(lex);
268         InsetCollapsable::read(lex);
269         // check if the float type exists
270         if (buffer().params().documentClass().floats().typeExist(params_.type))
271                 setLabel(_("float: ") + floatName(params_.type));
272         else
273                 setLabel(bformat(_("ERROR: Unknown float type: %1$s"), from_utf8(params_.type)));
274 }
275
276
277 void InsetFloat::validate(LaTeXFeatures & features) const
278 {
279         if (support::contains(params_.placement, 'H'))
280                 features.require("float");
281
282         if (params_.sideways)
283                 features.require("rotfloat");
284
285         if (features.inFloat())
286                 features.require("subfig");
287
288         features.useFloat(params_.type, features.inFloat());
289         features.inFloat(true);
290         InsetCollapsable::validate(features);
291         features.inFloat(false);
292 }
293
294
295 docstring InsetFloat::xhtml(XHTMLStream & xs, OutputParams const & rp) const
296 {
297         FloatList const & floats = buffer().params().documentClass().floats();
298         Floating const & ftype = floats.getType(params_.type);
299         string const & htmltype = ftype.htmlTag();
300         string const & attr = ftype.htmlAttrib();
301
302         odocstringstream ods;
303         XHTMLStream newxs(ods);
304         newxs << html::StartTag(htmltype, attr);
305         InsetText::XHTMLOptions const opts = 
306                 InsetText::WriteLabel | InsetText::WriteInnerTag;
307         docstring deferred = InsetText::insetAsXHTML(newxs, rp, opts);
308         newxs << html::EndTag(htmltype);
309
310         if (rp.inFloat == OutputParams::NONFLOAT)
311                 // In this case, this float needs to be deferred, but we'll put it
312                 // before anything the text itself deferred.
313                 deferred = ods.str() + '\n' + deferred;
314         else 
315                 // In this case, the whole thing is already being deferred, so
316                 // we can write to the stream.
317                 // Note that things will already have been escaped, so we do not 
318                 // want to escape them again.
319                 xs << XHTMLStream::NextRaw() << ods.str();
320         return deferred;
321 }
322
323
324 int InsetFloat::latex(odocstream & os, OutputParams const & runparams_in) const
325 {
326         if (runparams_in.inFloat != OutputParams::NONFLOAT) {
327                 if (runparams_in.moving_arg)
328                         os << "\\protect";
329                 os << "\\subfloat";
330         
331                 OutputParams rp = runparams_in;
332                 docstring const caption = getCaption(rp);
333                 if (!caption.empty()) {
334                         os << caption;
335                 }
336                 os << '{';
337                 rp.inFloat = OutputParams::SUBFLOAT;
338                 int const i = InsetText::latex(os, rp);
339                 os << "}";
340         
341                 return i + 1;
342         }
343         OutputParams runparams(runparams_in);
344         runparams.inFloat = OutputParams::MAINFLOAT;
345
346         FloatList const & floats = buffer().params().documentClass().floats();
347         string tmptype = params_.type;
348         if (params_.sideways)
349                 tmptype = "sideways" + params_.type;
350         if (params_.wide && (!params_.sideways ||
351                              params_.type == "figure" ||
352                              params_.type == "table"))
353                 tmptype += "*";
354         // Figure out the float placement to use.
355         // From lowest to highest:
356         // - float default placement
357         // - document wide default placement
358         // - specific float placement
359         string placement;
360         string const buf_placement = buffer().params().float_placement;
361         string const def_placement = floats.defaultPlacement(params_.type);
362         if (!params_.placement.empty()
363             && params_.placement != def_placement) {
364                 placement = params_.placement;
365         } else if (params_.placement.empty()
366                    && !buf_placement.empty()
367                    && buf_placement != def_placement) {
368                 placement = buf_placement;
369         }
370
371         // The \n is used to force \begin{<floatname>} to appear in a new line.
372         // The % is needed to prevent two consecutive \n chars in the case
373         // when the current output line is empty.
374         os << "%\n\\begin{" << from_ascii(tmptype) << '}';
375         // We only output placement if different from the def_placement.
376         // sidewaysfloats always use their own page
377         if (!placement.empty() && !params_.sideways) {
378                 os << '[' << from_ascii(placement) << ']';
379         }
380         os << '\n';
381
382         int const i = InsetText::latex(os, runparams);
383
384         // The \n is used to force \end{<floatname>} to appear in a new line.
385         // In this case, we do not case if the current output line is empty.
386         os << "\n\\end{" << from_ascii(tmptype) << "}\n";
387
388         return i + 4;
389 }
390
391
392 int InsetFloat::plaintext(odocstream & os, OutputParams const & runparams) const
393 {
394         os << '[' << buffer().B_("float") << ' '
395                 << floatName(params_.type) << ":\n";
396         InsetText::plaintext(os, runparams);
397         os << "\n]";
398
399         return PLAINTEXT_NEWLINE + 1; // one char on a separate line
400 }
401
402
403 int InsetFloat::docbook(odocstream & os, OutputParams const & runparams) const
404 {
405         // FIXME Implement subfloat!
406         // FIXME UNICODE
407         os << '<' << from_ascii(params_.type) << '>';
408         int const i = InsetText::docbook(os, runparams);
409         os << "</" << from_ascii(params_.type) << '>';
410
411         return i;
412 }
413
414
415 bool InsetFloat::insetAllowed(InsetCode code) const
416 {
417         // The case that code == FLOAT_CODE is handled in Text3.cpp, 
418         // because we need to know what type of float is meant.
419         switch(code) {
420         case WRAP_CODE:
421         case FOOT_CODE:
422         case MARGIN_CODE:
423                 return false;
424         default:
425                 return InsetCollapsable::insetAllowed(code);
426         }
427 }
428
429
430 bool InsetFloat::showInsetDialog(BufferView * bv) const
431 {
432         if (!InsetText::showInsetDialog(bv))
433                 bv->showDialog("float");
434         return true;
435 }
436
437
438 void InsetFloat::setWide(bool w, bool update_label)
439 {
440         params_.wide = w;
441         if (update_label)
442                 setNewLabel();
443 }
444
445
446 void InsetFloat::setSideways(bool s, bool update_label)
447 {
448         params_.sideways = s;
449         if (update_label)
450                 setNewLabel();
451 }
452
453
454 void InsetFloat::setSubfloat(bool s, bool update_label)
455 {
456         params_.subfloat = s;
457         if (update_label)
458                 setNewLabel();
459 }
460
461
462 void InsetFloat::setNewLabel()
463 {
464         docstring lab = _("float: ");
465
466         if (params_.subfloat)
467                 lab = _("subfloat: ");
468
469         lab += floatName(params_.type);
470
471         if (params_.wide)
472                 lab += '*';
473
474         if (params_.sideways)
475                 lab += _(" (sideways)");
476
477         setLabel(lab);
478 }
479
480
481 docstring InsetFloat::getCaption(OutputParams const & runparams) const
482 {
483         if (paragraphs().empty())
484                 return docstring();
485
486         InsetCaption const * ins = getCaptionInset();
487         if (ins == 0)
488                 return docstring();
489
490         odocstringstream ods;
491         ins->getOptArg(ods, runparams);
492         ods << '[';
493         ins->getArgument(ods, runparams);
494         ods << ']';
495         return ods.str();
496 }
497
498
499 void InsetFloat::string2params(string const & in, InsetFloatParams & params)
500 {
501         params = InsetFloatParams();
502         if (in.empty())
503                 return;
504
505         istringstream data(in);
506         Lexer lex;
507         lex.setStream(data);
508         lex.setContext("InsetFloat::string2params");
509         params.read(lex);
510 }
511
512
513 string InsetFloat::params2string(InsetFloatParams const & params)
514 {
515         ostringstream data;
516         params.write(data);
517         return data.str();
518 }
519
520
521 } // namespace lyx