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