]> git.lyx.org Git - lyx.git/blob - src/insets/insetfloat.C
fix the float bug.
[lyx.git] / src / insets / insetfloat.C
1 /**
2  * \file insetfloat.C
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  *
9  * Full author contact details are available in file CREDITS.
10  */
11
12 #include <config.h>
13
14 #include "insetfloat.h"
15
16 #include "buffer.h"
17 #include "bufferparams.h"
18 #include "BufferView.h"
19 #include "cursor.h"
20 #include "debug.h"
21 #include "dispatchresult.h"
22 #include "Floating.h"
23 #include "FloatList.h"
24 #include "funcrequest.h"
25 #include "gettext.h"
26 #include "LaTeXFeatures.h"
27 #include "LColor.h"
28 #include "lyxlex.h"
29 #include "outputparams.h"
30 #include "paragraph.h"
31 #include "pariterator.h"
32
33 #include "support/lstrings.h"
34 #include "support/tostr.h"
35 #include "support/std_sstream.h"
36
37 using lyx::support::contains;
38
39 using std::endl;
40 using std::string;
41 using std::auto_ptr;
42 using std::istringstream;
43 using std::ostream;
44 using std::ostringstream;
45
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 namespace {
115
116 // this should not be hardcoded, but be part of the definition
117 // of the float (JMarc)
118 string const caplayout("Caption");
119
120 string floatname(string const & type, BufferParams const & bp)
121 {
122         FloatList const & floats = bp.getLyXTextClass().floats();
123         FloatList::const_iterator it = floats[type];
124         if (it == floats.end())
125                 return type;
126
127         return _(it->second.name());
128 }
129
130 } // namespace anon
131
132
133 InsetFloat::InsetFloat(BufferParams const & bp, string const & type)
134         : InsetCollapsable(bp)
135 {
136         setLabel(_("float: ") + floatname(type, bp));
137         LyXFont font(LyXFont::ALL_SANE);
138         font.decSize();
139         font.decSize();
140         font.setColor(LColor::collapsable);
141         setLabelFont(font);
142         params_.type = type;
143         setInsetName(type);
144         LyXTextClass const & tclass = bp.getLyXTextClass();
145         if (tclass.hasLayout(caplayout))
146                 paragraphs().begin()->layout(tclass[caplayout]);
147 }
148
149
150 InsetFloat::~InsetFloat()
151 {
152         InsetFloatMailer(*this).hideDialog();
153 }
154
155
156 void InsetFloat::priv_dispatch(LCursor & cur, FuncRequest & cmd)
157 {
158         switch (cmd.action) {
159
160         case LFUN_INSET_MODIFY: {
161                 InsetFloatParams params;
162                 InsetFloatMailer::string2params(cmd.argument, params);
163                 params_.placement = params.placement;
164                 params_.wide      = params.wide;
165                 params_.sideways  = params.sideways;
166                 wide(params_.wide, cur.bv().buffer()->params());
167                 sideways(params_.sideways, cur.bv().buffer()->params());
168                 cur.bv().update();
169                 break;
170         }
171
172         case LFUN_INSET_DIALOG_UPDATE: {
173                 InsetFloatMailer(*this).updateDialog(&cur.bv());
174                 break;
175         }
176
177         case LFUN_MOUSE_RELEASE: {
178                 if (cmd.button() == mouse_button::button3 && hitButton(cmd)) {
179                         InsetFloatMailer(*this).showDialog(&cur.bv());
180                         break;
181                 }
182                 InsetCollapsable::priv_dispatch(cur, cmd);
183                 break;
184         }
185         
186         default:
187                 InsetCollapsable::priv_dispatch(cur, cmd);
188                 break;
189         }
190 }
191
192
193 void InsetFloatParams::write(ostream & os) const
194 {
195         os << "Float " // getInsetName()
196            << type << '\n';
197
198         if (!placement.empty())
199                 os << "placement " << placement << "\n";
200
201         if (wide)
202                 os << "wide true\n";
203         else
204                 os << "wide false\n";
205                 
206         if (sideways)
207                 os << "sideways true\n";
208         else
209                 os << "sideways false\n";
210 }
211
212
213 void InsetFloatParams::read(LyXLex & lex)
214 {
215         if (lex.isOK()) {
216                 lex.next();
217                 type = lex.getString();
218         }
219         if (!lex.isOK())
220                 return;
221         lex.next();
222         string token = lex.getString();
223         if (token == "placement") {
224                 lex.next();
225                 placement = lex.getString();
226         } else {
227                 // take countermeasures
228                 lex.pushToken(token);
229         }
230         if (!lex.isOK())
231                 return;
232         lex.next();
233         token = lex.getString();
234         if (token == "wide") {
235                 lex.next();
236                 string const tmptoken = lex.getString();
237                 wide = (tmptoken == "true");
238         } else {
239                 lyxerr << "InsetFloat::Read:: Missing wide!"
240                 << endl;
241                 // take countermeasures
242                 lex.pushToken(token);
243         }
244         if (!lex.isOK())
245                 return;
246         lex.next();
247         token = lex.getString();
248         if (token == "sideways") {
249                 lex.next();
250                 string const tmptoken = lex.getString();
251                 sideways = (tmptoken == "true");
252         } else {
253                 lyxerr << "InsetFloat::Read:: Missing sideways!"
254                 << endl;
255                 // take countermeasures
256                 lex.pushToken(token);
257         }
258 }
259
260
261 void InsetFloat::write(Buffer const & buf, ostream & os) const
262 {
263         params_.write(os);
264         InsetCollapsable::write(buf, os);
265 }
266
267
268 void InsetFloat::read(Buffer const & buf, LyXLex & lex)
269 {
270         params_.read(lex);
271         wide(params_.wide, buf.params());
272         sideways(params_.sideways, buf.params());
273         InsetCollapsable::read(buf, lex);
274 }
275
276
277 void InsetFloat::validate(LaTeXFeatures & features) const
278 {
279         if (contains(params_.placement, 'H')) {
280                 features.require("float");
281         }
282         
283         if (params_.sideways)
284                 features.require("rotating");
285
286         features.useFloat(params_.type);
287         InsetCollapsable::validate(features);
288 }
289
290
291 auto_ptr<InsetBase> InsetFloat::clone() const
292 {
293         return auto_ptr<InsetBase>(new InsetFloat(*this));
294 }
295
296
297 string const InsetFloat::editMessage() const
298 {
299         return _("Opened Float Inset");
300 }
301
302
303 int InsetFloat::latex(Buffer const & buf, ostream & os,
304                       OutputParams const & runparams) const
305 {
306         FloatList const & floats = buf.params().getLyXTextClass().floats();
307         string tmptype = (params_.wide ? params_.type + "*" : params_.type);
308         if (params_.sideways) {
309                 if (params_.type == "table")
310                         tmptype = "sidewaystable";
311                 else if (params_.type == "figure")
312                         tmptype = "sidewaysfigure";
313         }
314         // Figure out the float placement to use.
315         // From lowest to highest:
316         // - float default placement
317         // - document wide default placement
318         // - specific float placement
319         string placement;
320         string const buf_placement = buf.params().float_placement;
321         string const def_placement = floats.defaultPlacement(params_.type);
322         if (!params_.placement.empty()
323             && params_.placement != def_placement) {
324                 placement = params_.placement;
325         } else if (params_.placement.empty()
326                    && !buf_placement.empty()
327                    && buf_placement != def_placement) {
328                 placement = buf_placement;
329         }
330
331         // The \n is used to force \begin{<floatname>} to appear in a new line.
332         // The % is needed to prevent two consecutive \n chars in the case
333         // when the current output line is empty.
334         os << "%\n\\begin{" << tmptype << '}';
335         // We only output placement if different from the def_placement.
336         // sidewaysfloats always use their own page
337         if (!placement.empty() && !params_.sideways) {
338                 os << '[' << placement << ']';
339         }
340         os << '\n';
341
342         int const i = InsetText::latex(buf, os, runparams);
343
344         // The \n is used to force \end{<floatname>} to appear in a new line.
345         // In this case, we do not case if the current output line is empty.
346         os << "\n\\end{" << tmptype << "}\n";
347
348         return i + 4;
349 }
350
351
352 int InsetFloat::linuxdoc(Buffer const & buf, ostream & os,
353                          OutputParams const & runparams) const
354 {
355         FloatList const & floats = buf.params().getLyXTextClass().floats();
356         string const tmptype =  params_.type;
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         // This is the same as latex, as linuxdoc is modeled after latex.
363
364         string placement;
365         string const buf_placement = buf.params().float_placement;
366         string const def_placement = floats.defaultPlacement(params_.type);
367         if (!params_.placement.empty()
368             && params_.placement != def_placement) {
369                 placement = params_.placement;
370         } else if (params_.placement.empty()
371                    && !buf_placement.empty()
372                    && buf_placement != def_placement) {
373                 placement = buf_placement;
374         }
375
376         os << "\n<" << tmptype ;
377         // We only output placement if different from the def_placement.
378         if (!placement.empty()) {
379                 os << " loc=\"" << placement << '"';
380         }
381         os << ">";
382
383         int const i = InsetText::linuxdoc(buf, os, runparams);
384         os << "</" << tmptype << ">\n";
385
386         return i;
387 }
388
389
390 int InsetFloat::docbook(Buffer const & buf, ostream & os,
391                         OutputParams const & runparams) const
392 {
393         os << '<' << params_.type << '>';
394         int const i = InsetText::docbook(buf, os, runparams);
395         os << "</" << params_.type << '>';
396
397         return i;
398 }
399
400
401 bool InsetFloat::insetAllowed(InsetOld::Code code) const
402 {
403         return code != InsetOld::FLOAT_CODE
404             && code != InsetOld::FOOT_CODE
405             && code != InsetOld::MARGIN_CODE;
406 }
407
408
409 bool InsetFloat::showInsetDialog(BufferView * bv) const
410 {
411         if (!InsetText::showInsetDialog(bv))
412                 InsetFloatMailer(const_cast<InsetFloat &>(*this)).showDialog(bv);
413         return true;
414 }
415
416
417 void InsetFloat::wide(bool w, BufferParams const & bp)
418 {
419         params_.wide = w;
420         string lab = _("float: ") + floatname(params_.type, bp);
421         if (params_.wide)
422                 lab += '*';
423         setLabel(lab);
424 }
425
426
427 void InsetFloat::sideways(bool s, BufferParams const & bp)
428 {
429         params_.sideways = s;
430         string lab = _("float: ") + floatname(params_.type, bp);
431         if (params_.sideways)
432                 lab += _(" (sideways)");
433         setLabel(lab);
434 }
435
436
437 void InsetFloat::addToToc(lyx::toc::TocList & toclist, Buffer const & buf) const
438 {
439         ParConstIterator pit = par_const_iterator_begin(*this);
440         ParConstIterator end = par_const_iterator_end(*this);
441
442         // Find a caption layout in one of the (child inset's) pars
443         for (; pit != end; ++pit) {
444                 if (pit->layout()->name() == caplayout) {
445                         string const name = floatname(params_.type, buf.params());
446                         string const str =
447                                 tostr(toclist[name].size() + 1)
448                                 + ". " + pit->asString(buf, false);
449                         lyx::toc::TocItem const item(pit->id(), 0 , str);
450                         toclist[name].push_back(item);
451                 }
452         }
453 }
454
455
456 string const InsetFloatMailer::name_("float");
457
458 InsetFloatMailer::InsetFloatMailer(InsetFloat & inset)
459         : inset_(inset)
460 {}
461
462
463 string const InsetFloatMailer::inset2string(Buffer const &) const
464 {
465         return params2string(inset_.params());
466 }
467
468
469 void InsetFloatMailer::string2params(string const & in,
470                                      InsetFloatParams & params)
471 {
472         params = InsetFloatParams();
473         if (in.empty())
474                 return;
475
476         istringstream data(in);
477         LyXLex lex(0,0);
478         lex.setStream(data);
479
480         string name;
481         lex >> name;
482         if (!lex || name != name_)
483                 return print_mailer_error("InsetFloatMailer", in, 1, name_);
484
485         // This is part of the inset proper that is usually swallowed
486         // by LyXText::readInset
487         string id;
488         lex >> id;
489         if (!lex || id != "Float")
490                 return print_mailer_error("InsetBoxMailer", in, 2, "Float");
491
492         params.read(lex);
493 }
494
495
496 string const InsetFloatMailer::params2string(InsetFloatParams const & params)
497 {
498         ostringstream data;
499         data << name_ << ' ';
500         params.write(data);
501         return data.str();
502 }