]> git.lyx.org Git - lyx.git/blob - src/vspace.C
dfb2c3b3886df71361dcdd348f69549e92f3f7cb
[lyx.git] / src / vspace.C
1 // -*- C++ -*-
2 /* This file is part of
3  * ======================================================
4  * 
5  *           LyX, The Document Processor
6  *       
7  *          Copyright 1995 Matthias Ettrich
8  *          Copyright 1995-1999 The LyX Team.
9  *
10  * ======================================================*/
11
12 #include <config.h>
13
14 #ifdef __GNUG__
15 #pragma implementation "vspace.h"
16 #endif
17
18 #include "lyx_main.h"
19 #include "buffer.h"
20 #include "vspace.h"
21 #include "lyxrc.h"
22 #include "lyxtext.h"
23 #include <cstdio>
24 #include <cstring>
25 #include "BufferView.h"
26 #include "support/lstrings.h"
27
28 extern LyXRC * lyxrc;
29 extern BufferView *current_view;
30
31 /*  length units
32  */
33
34 static const int   num_units            = LyXLength::UNIT_NONE;
35
36 // I am not sure if "mu" should be possible to select (Lgb)
37 static char const * unit_name[num_units] = { "sp", "pt", "bp", "dd",
38                                             "mm", "pc", "cc", "cm",
39                                             "in", "ex", "em", "mu" }; 
40
41
42 LyXLength::UNIT unitFromString (string const & data)
43 {
44         int i=0;
45         while ((i<num_units) && (data != unit_name[i])) ++i;
46         return (LyXLength::UNIT)i;
47 }
48
49 /*  The following static items form a simple scanner for
50  *  length strings, used by isValid[Glue]Length.  See comments there.
51  */
52 static float           number[4] = { 0, 0, 0, 0 };
53 static LyXLength::UNIT unit[4]   = { LyXLength::UNIT_NONE,
54                                      LyXLength::UNIT_NONE,
55                                      LyXLength::UNIT_NONE,
56                                      LyXLength::UNIT_NONE };
57 //static int number_index, unit_index;
58 int number_index, unit_index;
59
60 static inline void advance (string & data, unsigned int n)
61 {
62         data.erase(0, n);
63 }
64
65 static inline bool isEndOfData (string const & data)
66 {
67         return frontStrip (data).empty();
68 }
69
70 static char nextToken (string & data)
71 {
72         data = frontStrip(data);
73         if (data.empty())
74                 return '\0';
75         else if (data[0] == '+') {
76                 advance (data, 1);
77                 return '+';
78         }
79         else if (prefixIs(data, "plus")) {
80                 advance (data, 4);
81                 return '+';
82         }
83         else if (data[0] == '-') {
84                 advance (data, 1);
85                 return '-';
86         }
87         else if (prefixIs(data, "minus")) {
88                 advance (data, 5);
89                 return '-';
90         }
91         else {
92                 string::size_type i;
93
94                 // I really mean assignment ("=") below, not equality!
95                 if ((i = data.find_last_of("0123456789.")) != string::npos) {
96                         if (number_index > 3) return 'E';  // Error
97                         string buffer = data.substr(0, i + 1);
98                         if (sscanf (buffer.c_str(),
99                                     "%f", &number[number_index]) == 1) {
100                                 advance (data, i + 1);
101                                 ++number_index;
102                                 return 'n';
103                         } else 
104                                 return 'E';  // Error
105                 } else if ((i=data.find_last_of("abcdefghijklmnopqrstuvwxyz"))
106                            != string::npos) {
107                         if (unit_index > 3) return 'E';  // Error
108                         string buffer = data.substr(0, i + 1);
109                         unit[unit_index] = unitFromString (buffer);
110                         if (unit[unit_index] != LyXLength::UNIT_NONE) {
111                                 advance (data, i + 1);
112                                 ++unit_index;
113                                 return 'u';
114                         } else
115                                 return 'E';  // Error
116                 } else
117                         return 'E';  // Error
118         }
119 }
120
121 static struct {
122         char const * pattern;
123         int   plus_val_index, minus_val_index,
124               plus_uni_index, minus_uni_index;
125 } table[] = { { "nu",       0, 0, 0, 0 },
126               { "nu+nu",    2, 0, 2, 0 },
127               { "nu+nu-nu", 2, 3, 2, 3 },
128               { "nu+-nu",   2, 2, 2, 2 },
129               { "nu-nu",    0, 2, 0, 2 },
130               { "nu-nu+nu", 3, 2, 3, 2 },
131               { "nu-+nu",   2, 2, 2, 2 },
132               { "n+nu",     2, 0, 1, 0 },
133               { "n+n-nu",   2, 3, 1, 1 },
134               { "n+-nu",    2, 2, 1, 1 },
135               { "n-nu",     0, 2, 0, 1 },
136               { "n-n+nu",   3, 2, 1, 1 },
137               { "n-+nu",    2, 2, 1, 1 },
138               { "",         0, 0, 0, 0 }   // sentinel, must be empty
139 };
140
141 bool isValidGlueLength (string const & data, LyXGlueLength * result)
142 {
143         // This parser is table-driven.  First, it constructs a "pattern"
144         // that describes the sequence of tokens in "data".  For example,
145         // "n-nu" means: number, minus sign, number, unit.  As we go along,
146         // numbers and units are stored into static arrays.  Then, "pattern"
147         // is searched in the "table".  If it is found, the associated
148         // table entries tell us which number and unit should go where
149         // in the LyXLength structure.  Example: if "data" has the "pattern"
150         // "nu+nu-nu", the associated table entries are "2, 3, 2, 3".  
151         // That means, "plus_val" is the second number that was seen
152         // in the input, "minus_val" is the third number, and "plus_uni"
153         // and "minus_uni" are the second and third units, respectively.
154         // ("val" and "uni" are always the first items seen in "data".)
155         //     This is the most elegant solution I could find -- a straight-
156         // forward approach leads to very long, tedious code that would be
157         // much harder to understand and maintain. (AS)
158
159         if (data.empty())
160                 return true;
161         string buffer = frontStrip(data);
162
163         // To make isValidGlueLength recognize negative values as
164         // the first number this little hack is needed:
165         short val_sign = 1; // positive as default
166         switch(buffer[0]) {
167         case '-':
168                 advance(buffer, 1);
169                 val_sign = -1;
170                 break;
171         case '+':
172                 advance(buffer, 1);
173                 // fall through
174         default:
175                 // no action
176                 break;
177         }
178         // end of hack
179         
180         int       pattern_index = 0, table_index = 0;
181         char      pattern[20];
182
183         number_index = unit_index = 1;  // entries at index 0 are sentinels
184
185         // construct "pattern" from "data"
186         while (!isEndOfData (buffer)) {
187                 if (pattern_index > 20) return false;
188                 pattern[pattern_index] = nextToken (buffer);
189                 if (pattern[pattern_index] == 'E') return false;
190                 ++pattern_index;
191         }
192         pattern[pattern_index] = '\0';
193
194         // search "pattern" in "table"
195         table_index = 0;
196         while (compare(pattern, table[table_index].pattern)) {
197                 ++table_index;
198                 if (!*table[table_index].pattern) return false;
199         }
200         
201         // Get the values from the appropriate places.  If an index
202         // is zero, the corresponding array value is zero or UNIT_NONE,
203         // so we needn't check this.
204         if (result) {
205             result->val = number[1] * val_sign;
206             result->uni = unit[1];
207             result->plus_val  = number[table[table_index].plus_val_index];
208             result->minus_val = number[table[table_index].minus_val_index];
209             result->plus_uni  = unit  [table[table_index].plus_uni_index];
210             result->minus_uni = unit  [table[table_index].minus_uni_index];
211         }
212         return true;
213 }
214
215
216 bool isValidLength(string const & data, LyXLength * result)
217 {
218         /// This is a trimmed down version of isValidGlueLength.
219         /// The parser may seem overkill for lengths without 
220         /// glue, but since we already have it, using it is
221         /// easier than writing something from scratch.
222
223         string   buffer = data;
224         int       pattern_index = 0;
225         char      pattern[3];
226
227         // To make isValidLength recognize negative values
228         // this little hack is needed:
229         short val_sign = 1; // positive as default
230         switch(buffer[0]) {
231         case '-':
232                 advance(buffer, 1);
233                 val_sign = -1;
234                 break;
235         case '+':
236                 advance(buffer, 1);
237                 // fall through
238         default:
239                 // no action
240                 break;
241         }
242         // end of hack
243         
244         number_index = unit_index = 1;  // entries at index 0 are sentinels
245
246         // construct "pattern" from "data"
247         while (!isEndOfData (buffer)) {
248                 if (pattern_index > 2) return false;
249                 pattern[pattern_index] = nextToken (buffer);
250                 if (pattern[pattern_index] == 'E') return false;
251                 ++pattern_index;
252         }
253         pattern[pattern_index] = '\0';
254
255         // only the most basic pattern is accepted here
256         if (compare(pattern, "nu") != 0) return false;          
257         
258         // It _was_ a correct length string.  
259         // Store away the values we found.
260         if (result) {
261             result->val = number[1]*val_sign;
262             result->uni = unit[1];
263         }
264         return true;
265 }
266
267 /// LyXLength class
268
269 LyXLength::LyXLength(string const & data)
270 {
271         LyXLength tmp;
272         
273         if (!isValidLength (data, &tmp))
274                 return; // should raise an exception
275         else {
276                 val = tmp.val;
277                 uni = tmp.uni;
278         }
279 }
280
281 bool LyXLength::operator== (LyXLength const & other) const
282 {
283         return (val == other.val &&
284                 uni == other.uni);
285 }
286
287 string LyXLength::asString() const
288 {
289         char buffer[20];
290
291         sprintf (buffer, "%g%s", val, unit_name[uni]);
292         return string (buffer);
293 }
294
295
296 /*  LyXGlueLength class
297  */
298
299 LyXGlueLength::LyXGlueLength (string const & data)
300 {
301         LyXGlueLength tmp(0.0, PT);
302
303         if (!isValidGlueLength (data, &tmp))
304                 return; // should raise an exception
305         else {
306                 val=tmp.val;
307                 uni=tmp.uni;
308                 plus_val =tmp.plus_val;
309                 plus_uni =tmp.plus_uni;
310                 minus_val=tmp.minus_val;
311                 minus_uni=tmp.minus_uni;
312         }
313 }
314
315
316 bool LyXGlueLength::operator== (LyXGlueLength const & other) const
317 {
318         return (val == other.val && 
319                 uni == other.uni &&
320                 plus_val  == other.plus_val &&
321                 plus_uni  == other.plus_uni &&
322                 minus_val == other.minus_val &&
323                 minus_uni == other.minus_uni);
324 }
325
326
327 string LyXGlueLength::asString() const
328 {
329         char buffer[20];
330         
331         if (plus_val != 0.0)
332                 if (minus_val != 0.0)
333                         if ((uni == plus_uni) && (uni == minus_uni))
334                                 if (plus_val == minus_val)
335                                         sprintf (buffer, "%g+-%g%s",
336                                                  val, plus_val, unit_name[uni]);
337                                 else
338                                         sprintf (buffer, "%g+%g-%g%s",
339                                                  val, plus_val, minus_val, 
340                                                  unit_name[uni]);
341                         else
342                                 if ((plus_uni == minus_uni) && (plus_val == minus_val))
343                                         sprintf (buffer, "%g%s+-%g%s",
344                                                  val, unit_name[uni],
345                                                  plus_val, unit_name[plus_uni]);
346                                 else
347                                         sprintf (buffer, "%g%s+%g%s-%g%s",
348                                                  val,       unit_name[uni],
349                                                  plus_val,  unit_name[plus_uni],
350                                                  minus_val, unit_name[minus_uni]);
351                 else 
352                         if (uni == plus_uni)
353                                 sprintf (buffer, "%g+%g%s",
354                                          val, plus_val, unit_name[uni]);
355                         else
356                                 sprintf (buffer, "%g%s+%g%s",
357                                          val,      unit_name[uni],
358                                          plus_val, unit_name[plus_uni]);
359         else
360                 if (minus_val != 0.0)
361                         if (uni == minus_uni)
362                                 sprintf (buffer, "%g-%g%s",
363                                          val, minus_val, unit_name[uni]);
364                         else
365                                 sprintf (buffer, "%g%s-%g%s",
366                                          val,       unit_name[uni],
367                                          minus_val, unit_name[minus_uni]);
368                 else
369                         sprintf (buffer, "%g%s", val, unit_name[uni]);
370         return string (buffer);
371 }
372
373
374 string LyXGlueLength::asLatexString() const
375 {
376         char buffer[40];
377
378         if (plus_val != 0.0)
379                 if (minus_val != 0.0)
380                         sprintf (buffer, "%g%s plus %g%s minus %g%s",
381                                  val, unit_name[uni],
382                                  plus_val,  unit_name[plus_uni],
383                                  minus_val, unit_name[minus_uni]);
384                 else
385                         sprintf (buffer, "%g%s plus %g%s",
386                                  val,      unit_name[uni],
387                                  plus_val, unit_name[plus_uni]);
388         else
389                 if (minus_val != 0.0)
390                         sprintf (buffer, "%g%s minus %g%s",
391                                  val,       unit_name[uni],
392                                  minus_val, unit_name[minus_uni]);
393                 else
394                         sprintf (buffer, "%g%s",
395                                  val, unit_name[uni]);
396         return string (buffer);
397 }
398
399
400 /*  VSpace class
401  */
402
403 VSpace::VSpace (string const & data)
404         : kin (NONE), len (0.0, LyXLength::PT) 
405 {
406         kp = false;
407         if (data.empty())
408                 return;
409         float   value;
410         string input  = strip(data);
411
412         int length = input.length();
413
414         if (length > 1 && input[length-1] == '*') {
415                 kp = true;
416                 input.erase(length - 1);
417         }
418
419         if      (prefixIs (input, "defskip"))   kin = DEFSKIP;
420         else if (prefixIs (input, "smallskip")) kin = SMALLSKIP;
421         else if (prefixIs (input, "medskip"))   kin = MEDSKIP;
422         else if (prefixIs (input, "bigskip"))   kin = BIGSKIP;
423         else if (prefixIs (input, "vfill"))     kin = VFILL;
424         else if (isValidGlueLength (input, &len))
425                 kin = LENGTH;
426         else if (sscanf (input.c_str(), "%f", &value) == 1) {
427                 // This last one is for reading old .lyx files
428                 // without units in added_space_top/bottom.
429                 // Let unit default to centimeters here.
430                 kin = LENGTH;
431                 len = LyXGlueLength (value, LyXLength::CM);
432         }
433 }
434
435
436 bool VSpace::operator== (VSpace const & other) const
437 {
438         if (this->kin == other.kin) 
439                 if (this->kin == LENGTH)
440                         if (this->len == other.len)
441                                 return this->kp == other.kp;
442                         else
443                                 return false;
444                 else
445                         return this->kp == other.kp;
446         else
447                 return false;
448 }
449
450
451 string VSpace::asLyXCommand() const
452 {
453         string result;
454
455         switch (kin) {
456         case NONE:      break;
457         case DEFSKIP:   result = "defskip";      break;
458         case SMALLSKIP: result = "smallskip";    break;
459         case MEDSKIP:   result = "medskip";      break;
460         case BIGSKIP:   result = "bigskip";      break;
461         case VFILL:     result = "vfill";        break;
462         case LENGTH:    result = len.asString(); break;
463         }
464         if (kp && (kin != NONE) && (kin != DEFSKIP))
465                 return result += '*';
466         else
467                 return result;
468 }
469
470
471 string VSpace::asLatexCommand() const
472 {
473         switch (kin) {
474         case NONE:      return string();
475         case DEFSKIP:   
476           return current_view->currentBuffer()->params.getDefSkip().asLatexCommand();
477         case SMALLSKIP: return kp ? "\\vspace*{\\smallskipamount}"
478                                   : "\\smallskip{}";
479         case MEDSKIP:   return kp ? "\\vspace*{\\medskipamount}"
480                                   : "\\medskip{}";
481         case BIGSKIP:   return kp ? "\\vspace*{\\bigskipamount}"
482                                   : "\\bigskip{}";
483         case VFILL:     return kp ? "\\vspace*{\\fill}"
484                                   : "\\vfill{}";
485         case LENGTH:    return kp ? "\\vspace*{" + len.asLatexString() + '}'
486                                   : "\\vspace{" + len.asLatexString() + '}';
487         }
488         return string();  // should never be reached
489 }
490
491
492 int VSpace::inPixels() const
493 {
494         // Height of a normal line in pixels (zoom factor considered)
495         int height = current_view->currentBuffer()->text->DefaultHeight(); // [pixels]
496
497         // Zoom factor specified by user in percent
498         float const zoom = lyxrc->zoom / 100.0; // [percent]
499
500         // DPI setting for monitor: pixels/inch
501         float const dpi = lyxrc->dpi; // screen resolution [pixels/inch]
502
503         // We want the result in pixels
504         float result, value;
505
506         switch (kin) {
507         case NONE: return 0;
508
509         case DEFSKIP:
510           return current_view->currentBuffer()->params.getDefSkip().inPixels();
511
512         // This is how the skips are normally defined by
513         // LateX.  But there should be some way to change
514         // this per document.
515         case SMALLSKIP: return height/4;
516         case MEDSKIP:   return height/2;
517         case BIGSKIP:   return height;
518         case VFILL:     return 3*height;
519                         // leave space for the vfill symbol
520         case LENGTH:
521                 // Pixel values are scaled so that the ratio
522                 // between lengths and font sizes on the screen
523                 // is the same as on paper.
524
525                 // we don't care about sign of value, we
526                 // can't display negative anyway
527                 result = 0.0;
528                 value = len.value();
529                 short val_sign = value < 0.0 ? -1 : 1;
530                 
531                 switch (len.unit()) {
532                 case LyXLength::SP:
533                         // Scaled point: sp = 1/65536 pt
534                         result = zoom * dpi * value
535                                 / (72.27 * 65536); // 4736286.7
536                         break;
537                 case LyXLength::PT:
538                         // Point: 1 pt = 1/72.27 inch
539                         result = zoom * dpi * value
540                                 / 72.27; // 72.27
541                         break;
542                 case LyXLength::BP:
543                         // Big point: 1 bp = 1/72 inch
544                         result = zoom * dpi * value
545                                 / 72; // 72
546                         break;
547                 case LyXLength::DD:
548                         // Didot: 1157dd = 1238 pt?
549                         result = zoom * dpi * value
550                                 / (72.27/(0.376 * 2.845)); // 67.559735
551                         break;
552                 case LyXLength::MM:
553                         // Millimeter: 1 mm = 1/25.4 inch
554                         result = zoom * dpi * value
555                                 / 25.4; // 25.4
556                         break;
557                 case LyXLength::PC:
558                         // Pica: 1 pc = 12 pt
559                         result = zoom * dpi * value
560                                 / (72.27/12); // 6.0225
561                         break;
562                 case LyXLength::CC:
563                         // Cicero: 1 cc = 12 dd
564                         result = zoom * dpi * value
565                                 / (72.27/ (12*0.376*2.845)); // 5.6299779
566                         break;
567                 case LyXLength::CM:
568                         // Centimeter: 1 cm = 1/2.54 inch
569                         result = zoom * dpi * value
570                                 / 2.54; // 2.54
571                         break;
572                 case LyXLength::IN:
573                         // Inch
574                         result = zoom * dpi * value;
575                         break;
576                 case LyXLength::EX:
577                         // Ex: The height of an "x"
578                         result = zoom * value * height / 2; // what to / width?
579                         break;
580                 case LyXLength::EM: // what to / width?
581                         // Em: The width of an "m"
582                         result = zoom * value * height / 2; // Why 2?
583                         break;
584                 case LyXLength::MU: // This is probably only allowed in
585                                     // math mode
586                         result = zoom * value * height;
587                         break;
588                 case LyXLength::UNIT_NONE:
589                         result = 0;  // this cannot happen
590                         break;  
591                 }
592                 return int (result * val_sign + 0.5);
593         }
594         return 0; // never reached
595 }