]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/xforms_helpers.C
The std::string mammoth path.
[lyx.git] / src / frontends / xforms / xforms_helpers.C
1 /**
2  * \file xforms_helpers.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "xforms_helpers.h"
14
15 #include "gettext.h"
16 #include "lyxgluelength.h"
17 #include "lyxlex.h"
18
19 #include "support/FileInfo.h"
20 #include "support/filetools.h"
21 #include "support/lstrings.h" // frontStrip, strip
22 #include "support/tostr.h"
23
24 #include "lyx_forms.h"
25 #include "combox.h"
26
27 #include <boost/assert.hpp>
28
29 #include <fstream>
30
31 using lyx::support::AbsolutePath;
32 using lyx::support::FileInfo;
33 using lyx::support::isStrDbl;
34 using lyx::support::OnlyPath;
35 using lyx::support::subst;
36 using lyx::support::trim;
37
38 using std::make_pair;
39
40 using std::ofstream;
41 using std::vector;
42 using std::string;
43
44
45 bool isActive(FL_OBJECT * ob)
46 {
47         return ob && ob->active > 0;
48 }
49
50
51 std::pair<string, string> parse_shortcut(string const & str)
52 {
53         string::size_type i = str.find_first_of("&");
54         if (i == string::npos || i == str.length() - 1)
55                 return make_pair(str, string());
56
57         // FIXME: handle &&
58
59         string::value_type c = str[i + 1];
60         return make_pair(str.substr(0, i) + str.substr(i + 1),
61                          string("#") + c);
62 }
63
64
65 // A wrapper for the xforms routine, but this one accepts uint args
66 unsigned long fl_getmcolor(int i,
67                            unsigned int * r, unsigned int * g, unsigned int * b)
68 {
69         int r2, g2, b2;
70         unsigned long ret_val = ::fl_getmcolor(i, &r2, &g2, &b2);
71         *r = r2;
72         *g = g2;
73         *b = b2;
74         return ret_val;
75 }
76
77
78 // Set an FL_OBJECT to activated or deactivated
79 void setEnabled(FL_OBJECT * ob, bool enable)
80 {
81         if (enable) {
82                 fl_activate_object(ob);
83                 fl_set_object_lcol(ob, FL_LCOL);
84         } else {
85                 fl_deactivate_object(ob);
86                 fl_set_object_lcol(ob, FL_INACTIVE);
87         }
88 }
89
90
91 // Given an fl_choice or an fl_browser, create a vector of its entries
92 vector<string> const getVector(FL_OBJECT * ob)
93 {
94         vector <string> vec;
95
96         switch (ob->objclass) {
97         case FL_CHOICE:
98                 for(int i = 0; i < fl_get_choice_maxitems(ob); ++i) {
99                         string const text = fl_get_choice_item_text(ob, i+1);
100                         vec.push_back(trim(text));
101                 }
102                 break;
103         case FL_BROWSER:
104                 for(int i = 0; i < fl_get_browser_maxline(ob); ++i) {
105                         string const text = fl_get_browser_line(ob, i+1);
106                         vec.push_back(trim(text));
107                 }
108                 break;
109         default:
110                 BOOST_ASSERT(false);
111         }
112
113         return vec;
114 }
115
116
117 ///
118 string const getString(FL_OBJECT * ob, int line)
119 {
120         // Negative line value does not make sense.
121         BOOST_ASSERT(line >= 0);
122
123         char const * tmp = 0;
124         switch (ob->objclass) {
125         case FL_INPUT:
126                 tmp = fl_get_input(ob);
127                 break;
128
129         case FL_BROWSER:
130                 if (line == 0)
131                         line = fl_get_browser(ob);
132
133                 if (line >= 1 && line <= fl_get_browser_maxline(ob))
134                         tmp = fl_get_browser_line(ob, line);
135                 break;
136
137         case FL_CHOICE:
138                 if (line == 0)
139                         line = fl_get_choice(ob);
140
141                 if (line >= 1 && line <= fl_get_choice_maxitems(ob))
142                         tmp = fl_get_choice_item_text(ob, line);
143                 break;
144
145         case FL_COMBOX:
146                 tmp = fl_get_combox_text(ob);
147                 break;
148
149         default:
150                 BOOST_ASSERT(false);
151         }
152
153         return tmp ? trim(tmp) : string();
154 }
155
156 string getLengthFromWidgets(FL_OBJECT * input, FL_OBJECT * choice)
157 {
158         // Paranoia check
159         BOOST_ASSERT(input  && input->objclass  == FL_INPUT &&
160                     choice && choice->objclass == FL_CHOICE);
161
162         string const length = trim(fl_get_input(input));
163         if (length.empty())
164                 return string();
165
166         // don't return unit-from-choice if the input(field) contains a unit
167         if (isValidGlueLength(length))
168                 return length;
169
170         string unit = trim(fl_get_choice_text(choice));
171         unit = subst(unit, "%%", "%");
172
173         return length + unit;
174 }
175
176
177 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
178                                    string const & str,
179                                    string const & default_unit)
180 {
181         // use input field only for gluelengths
182         if (!isValidLength(str) && !isStrDbl(str)) {
183                 fl_set_input(input, str.c_str());
184                 // we assume that "default_unit" is in the choice as "we"
185                 // have control over that!
186                 // No need to check for its presence in the choice, therefore.
187                 fl_set_choice_text(choice, default_unit.c_str());
188         } else {
189                 updateWidgetsFromLength(input, choice,
190                                         LyXLength(str), default_unit);
191         }
192 }
193
194
195 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
196                              LyXLength const & len,
197                              string const & default_unit)
198 {
199         // Paranoia check
200         BOOST_ASSERT(input  && input->objclass  == FL_INPUT &&
201                     choice && choice->objclass == FL_CHOICE);
202
203         if (len.empty()) {
204                 fl_set_input(input, "");
205                 fl_set_choice_text(choice, default_unit.c_str());
206         } else {
207                 fl_set_input(input, tostr(len.value()).c_str());
208
209                 // Set the choice to the desired unit, if present in the choice.
210                 // Else set the choice to the default unit.
211                 string const unit = subst(stringFromUnit(len.unit()),"%","%%");
212
213                 vector<string> const vec = getVector(choice);
214                 vector<string>::const_iterator it =
215                         std::find(vec.begin(), vec.end(), unit);
216                 if (it != vec.end()) {
217                         fl_set_choice_text(choice, unit.c_str());
218                 } else {
219                         fl_set_choice_text(choice, default_unit.c_str());
220                 }
221         }
222 }
223
224
225 // Take a string and add breaks so that it fits into a desired label width, w
226 string formatted(string const & sin, int w, int size, int style)
227 {
228         string sout;
229         if (sin.empty())
230                 return sout;
231
232         string::size_type curpos = 0;
233         string line;
234         for(;;) {
235                 string::size_type const nxtpos1 = sin.find(' ',  curpos);
236                 string::size_type const nxtpos2 = sin.find('\n', curpos);
237                 string::size_type const nxtpos = std::min(nxtpos1, nxtpos2);
238
239                 string const word = nxtpos == string::npos ?
240                         sin.substr(curpos) : sin.substr(curpos, nxtpos-curpos);
241
242                 bool const newline = (nxtpos2 != string::npos &&
243                                       nxtpos2 < nxtpos1);
244
245                 string const line_plus_word =
246                         line.empty() ? word : line + ' ' + word;
247
248                 int const length =
249                         fl_get_string_width(style, size,
250                                             line_plus_word.c_str(),
251                                             int(line_plus_word.length()));
252
253                 if (length >= w) {
254                         sout += line + '\n';
255                         if (newline) {
256                                 sout += word + '\n';
257                                 line.erase();
258                         } else {
259                                 line = word;
260                         }
261
262                 } else if (newline) {
263                         sout += line_plus_word + '\n';
264                         line.erase();
265
266                 } else {
267                         if (!line.empty())
268                                 line += ' ';
269                         line += word;
270                 }
271
272                 if (nxtpos == string::npos) {
273                         if (!line.empty())
274                                 sout += line;
275                         break;
276                 }
277
278                 curpos = nxtpos+1;
279         }
280
281         return sout;
282 }
283
284
285 void setCursorColor(int color)
286 {
287         fl_set_cursor_color(FL_DEFAULT_CURSOR, color, FL_WHITE);
288         fl_set_cursor_color(XC_xterm,          color, FL_WHITE);
289         fl_set_cursor_color(XC_watch,          color, FL_WHITE);
290         fl_set_cursor_color(XC_sb_right_arrow, color, FL_WHITE);
291 }
292
293
294 namespace {
295
296 // sorted by hand to prevent LyXLex from complaining on read().
297 keyword_item xformTags[] = {
298         { "\\gui_background",   FL_COL1 },
299         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
300         { "\\gui_buttonleft",   FL_LEFT_BCOL },
301         { "\\gui_buttonright",  FL_RIGHT_BCOL },
302         { "\\gui_buttontop",    FL_TOP_BCOL },
303         { "\\gui_inactive",     FL_INACTIVE },
304         { "\\gui_pointer",      FL_FREE_COL16 },
305         { "\\gui_push_button",  FL_YELLOW },
306         { "\\gui_selected",     FL_MCOL },
307         { "\\gui_text",         FL_BLACK }
308 };
309
310
311 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
312
313 } // namespace anon
314
315
316 bool XformsColor::read(string const & filename)
317 {
318         LyXLex lexrc(xformTags, xformCount);
319         if (!lexrc.setFile(filename))
320                 return false;
321
322         while (lexrc.isOK()) {
323                 int const le = lexrc.lex();
324
325                 switch (le) {
326                 case LyXLex::LEX_UNDEF:
327                         lexrc.printError("Unknown tag `$$Token'");
328                         continue;
329                 case LyXLex::LEX_FEOF:
330                         continue;
331                 default: break;
332                 }
333
334                 string const tag = lexrc.getString();
335
336                 RGBColor col;
337
338                 if (!lexrc.next()) break;
339                 col.r = lexrc.getInteger();
340
341                 if (!lexrc.next()) break;
342                 col.g = lexrc.getInteger();
343
344                 if (!lexrc.next()) break;
345                 col.b = lexrc.getInteger();
346
347                 fl_mapcolor(le, col.r, col.g, col.b);
348
349                 if (tag == "\\gui_pointer") {
350                         setCursorColor(FL_FREE_COL16);
351                 }
352         }
353
354         return true;
355 }
356
357
358 bool XformsColor::write(string const & filename)
359 {
360         ofstream os(filename.c_str());
361         if (!os)
362                 return false;
363
364         os << "###"
365            << "### file " << filename << "\n\n"
366            << "### This file is written by LyX, if you want to make your own\n"
367            << "### modifications you should do them from inside LyX and save\n"
368            << '\n';
369
370         for (int i = 0; i < xformCount; ++i) {
371                 string const tag  = xformTags[i].tag;
372                 int const colorID = xformTags[i].code;
373                 RGBColor color;
374
375                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
376
377                 os << tag << ' '
378                    << color.r << ' ' << color.g << ' ' << color.b << '\n';
379         }
380
381         return true;
382 }
383
384
385 string  RWInfo::error_message;
386
387 bool RWInfo::WriteableDir(string const & name)
388 {
389         error_message.erase();
390
391         if (!AbsolutePath(name)) {
392                 error_message = _("The absolute path is required.");
393                 return false;
394         }
395
396         FileInfo const tp(name);
397         if (!tp.isOK() || !tp.isDir()) {
398                 error_message = _("Directory does not exist.");
399                 return false;
400         }
401
402         if (!tp.writable()) {
403                 error_message = _("Cannot write to this directory.");
404                 return false;
405         }
406
407         return true;
408 }
409
410
411 bool RWInfo::ReadableDir(string const & name)
412 {
413         error_message.erase();
414
415         if (!AbsolutePath(name)) {
416                 error_message = _("The absolute path is required.");
417                 return false;
418         }
419
420         FileInfo const tp(name);
421         if (!tp.isOK() || !tp.isDir()) {
422                 error_message = _("Directory does not exist.");
423                 return false;
424         }
425
426         if (!tp.readable()) {
427                 error_message = _("Cannot read this directory.");
428                 return false;
429         }
430
431         return true;
432 }
433
434
435 bool RWInfo::WriteableFile(string const & name)
436 {
437         // A writeable file is either:
438         // * An existing file to which we have write access, or
439         // * A file that doesn't yet exist but that would exist in a writeable
440         //   directory.
441
442         error_message.erase();
443
444         if (name.empty()) {
445                 error_message = _("No file input.");
446                 return false;
447         }
448
449         string const dir = OnlyPath(name);
450         if (!AbsolutePath(dir)) {
451                 error_message = _("The absolute path is required.");
452                 return false;
453         }
454
455         FileInfo d(name);
456
457         if (!d.isOK() || !d.isDir()) {
458                 d.newFile(dir);
459         }
460
461         if (!d.isOK() || !d.isDir()) {
462                 error_message = _("Directory does not exist.");
463                 return false;
464         }
465
466         if (!d.writable()) {
467                 error_message = _("Cannot write to this directory.");
468                 return false;
469         }
470
471         FileInfo f(name);
472         if (dir == name || (f.isOK() && f.isDir())) {
473                 error_message = _("A file is required, not a directory.");
474                 return false;
475         }
476
477         if (f.isOK() && f.exist() && !f.writable()) {
478                 error_message = _("Cannot write to this file.");
479                 return false;
480         }
481
482         return true;
483 }
484
485
486 bool RWInfo::ReadableFile(string const & name)
487 {
488         error_message.erase();
489
490         if (name.empty()) {
491                 error_message = _("No file input.");
492                 return false;
493         }
494
495         string const dir = OnlyPath(name);
496         if (!AbsolutePath(dir)) {
497                 error_message = _("The absolute path is required.");
498                 return false;
499         }
500
501         FileInfo d(name);
502
503         if (!d.isOK() && !d.isDir()) {
504                 d.newFile(dir);
505         }
506
507         if (!d.isOK() || !d.isDir()) {
508                 error_message = _("Directory does not exist.");
509                 return false;
510         }
511
512         if (!d.readable()) {
513                 error_message = _("Cannot read from this directory.");
514                 return false;
515         }
516
517         FileInfo f(name);
518         if (dir == name || (f.isOK() && f.isDir())) {
519                 error_message = _("A file is required, not a directory.");
520                 return false;
521         }
522
523         if (!f.exist()) {
524                 error_message = _("File does not exist.");
525                 return false;
526         }
527
528         if (!f.readable()) {
529                 error_message = _("Cannot read from this file.");
530                 return false;
531         }
532
533         return true;
534 }