]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/xforms_helpers.C
Tiny clean-ups.
[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         // Paranoia check
182         BOOST_ASSERT(input  && input->objclass  == FL_INPUT &&
183                      choice && choice->objclass == FL_CHOICE);
184
185         // use input field only for gluelengths
186         if (!isValidLength(str) && !isStrDbl(str)) {
187                 fl_set_input(input, str.c_str());
188                 // we assume that "default_unit" is in the choice as "we"
189                 // have control over that!
190                 // No need to check for its presence in the choice, therefore.
191                 fl_set_choice_text(choice, default_unit.c_str());
192         } else {
193                 updateWidgetsFromLength(input, choice,
194                                         LyXLength(str), default_unit);
195         }
196 }
197
198
199 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
200                              LyXLength const & len,
201                              string const & default_unit)
202 {
203         // Paranoia check
204         BOOST_ASSERT(input  && input->objclass  == FL_INPUT &&
205                      choice && choice->objclass == FL_CHOICE);
206
207         if (len.empty()) {
208                 fl_set_input(input, "");
209                 fl_set_choice_text(choice, default_unit.c_str());
210         } else {
211                 fl_set_input(input, tostr(len.value()).c_str());
212
213                 // Set the choice to the desired unit, if present in the choice.
214                 // Else set the choice to the default unit.
215                 string const unit = subst(stringFromUnit(len.unit()),"%","%%");
216
217                 vector<string> const vec = getVector(choice);
218                 vector<string>::const_iterator it =
219                         std::find(vec.begin(), vec.end(), unit);
220                 if (it != vec.end()) {
221                         fl_set_choice_text(choice, unit.c_str());
222                 } else {
223                         fl_set_choice_text(choice, default_unit.c_str());
224                 }
225         }
226 }
227
228
229 // Take a string and add breaks so that it fits into a desired label width, w
230 string formatted(string const & sin, int w, int size, int style)
231 {
232         string sout;
233         if (sin.empty())
234                 return sout;
235
236         string::size_type curpos = 0;
237         string line;
238         for(;;) {
239                 string::size_type const nxtpos1 = sin.find(' ',  curpos);
240                 string::size_type const nxtpos2 = sin.find('\n', curpos);
241                 string::size_type const nxtpos = std::min(nxtpos1, nxtpos2);
242
243                 string const word = nxtpos == string::npos ?
244                         sin.substr(curpos) : sin.substr(curpos, nxtpos-curpos);
245
246                 bool const newline = (nxtpos2 != string::npos &&
247                                       nxtpos2 < nxtpos1);
248
249                 string const line_plus_word =
250                         line.empty() ? word : line + ' ' + word;
251
252                 int const length =
253                         fl_get_string_width(style, size,
254                                             line_plus_word.c_str(),
255                                             int(line_plus_word.length()));
256
257                 if (length >= w) {
258                         sout += line + '\n';
259                         if (newline) {
260                                 sout += word + '\n';
261                                 line.erase();
262                         } else {
263                                 line = word;
264                         }
265
266                 } else if (newline) {
267                         sout += line_plus_word + '\n';
268                         line.erase();
269
270                 } else {
271                         if (!line.empty())
272                                 line += ' ';
273                         line += word;
274                 }
275
276                 if (nxtpos == string::npos) {
277                         if (!line.empty())
278                                 sout += line;
279                         break;
280                 }
281
282                 curpos = nxtpos+1;
283         }
284
285         return sout;
286 }
287
288
289 void setCursorColor(int color)
290 {
291         fl_set_cursor_color(FL_DEFAULT_CURSOR, color, FL_WHITE);
292         fl_set_cursor_color(XC_xterm,          color, FL_WHITE);
293         fl_set_cursor_color(XC_watch,          color, FL_WHITE);
294         fl_set_cursor_color(XC_sb_right_arrow, color, FL_WHITE);
295 }
296
297
298 namespace {
299
300 // sorted by hand to prevent LyXLex from complaining on read().
301 keyword_item xformTags[] = {
302         { "\\gui_background",   FL_COL1 },
303         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
304         { "\\gui_buttonleft",   FL_LEFT_BCOL },
305         { "\\gui_buttonright",  FL_RIGHT_BCOL },
306         { "\\gui_buttontop",    FL_TOP_BCOL },
307         { "\\gui_inactive",     FL_INACTIVE },
308         { "\\gui_pointer",      FL_FREE_COL16 },
309         { "\\gui_push_button",  FL_YELLOW },
310         { "\\gui_selected",     FL_MCOL },
311         { "\\gui_text",         FL_BLACK }
312 };
313
314
315 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
316
317 } // namespace anon
318
319
320 bool XformsColor::read(string const & filename)
321 {
322         LyXLex lexrc(xformTags, xformCount);
323         if (!lexrc.setFile(filename))
324                 return false;
325
326         while (lexrc.isOK()) {
327                 int const le = lexrc.lex();
328
329                 switch (le) {
330                 case LyXLex::LEX_UNDEF:
331                         lexrc.printError("Unknown tag `$$Token'");
332                         continue;
333                 case LyXLex::LEX_FEOF:
334                         continue;
335                 default: break;
336                 }
337
338                 string const tag = lexrc.getString();
339
340                 RGBColor col;
341
342                 if (!lexrc.next()) break;
343                 col.r = lexrc.getInteger();
344
345                 if (!lexrc.next()) break;
346                 col.g = lexrc.getInteger();
347
348                 if (!lexrc.next()) break;
349                 col.b = lexrc.getInteger();
350
351                 fl_mapcolor(le, col.r, col.g, col.b);
352
353                 if (tag == "\\gui_pointer") {
354                         setCursorColor(FL_FREE_COL16);
355                 }
356         }
357
358         return true;
359 }
360
361
362 bool XformsColor::write(string const & filename)
363 {
364         ofstream os(filename.c_str());
365         if (!os)
366                 return false;
367
368         os << "###"
369            << "### file " << filename << "\n\n"
370            << "### This file is written by LyX, if you want to make your own\n"
371            << "### modifications you should do them from inside LyX and save\n"
372            << '\n';
373
374         for (int i = 0; i < xformCount; ++i) {
375                 string const tag  = xformTags[i].tag;
376                 int const colorID = xformTags[i].code;
377                 RGBColor color;
378
379                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
380
381                 os << tag << ' '
382                    << color.r << ' ' << color.g << ' ' << color.b << '\n';
383         }
384
385         return true;
386 }
387
388
389 string  RWInfo::error_message;
390
391 bool RWInfo::WriteableDir(string const & name)
392 {
393         error_message.erase();
394
395         if (!AbsolutePath(name)) {
396                 error_message = _("The absolute path is required.");
397                 return false;
398         }
399
400         FileInfo const tp(name);
401         if (!tp.isOK() || !tp.isDir()) {
402                 error_message = _("Directory does not exist.");
403                 return false;
404         }
405
406         if (!tp.writable()) {
407                 error_message = _("Cannot write to this directory.");
408                 return false;
409         }
410
411         return true;
412 }
413
414
415 bool RWInfo::ReadableDir(string const & name)
416 {
417         error_message.erase();
418
419         if (!AbsolutePath(name)) {
420                 error_message = _("The absolute path is required.");
421                 return false;
422         }
423
424         FileInfo const tp(name);
425         if (!tp.isOK() || !tp.isDir()) {
426                 error_message = _("Directory does not exist.");
427                 return false;
428         }
429
430         if (!tp.readable()) {
431                 error_message = _("Cannot read this directory.");
432                 return false;
433         }
434
435         return true;
436 }
437
438
439 bool RWInfo::WriteableFile(string const & name)
440 {
441         // A writeable file is either:
442         // * An existing file to which we have write access, or
443         // * A file that doesn't yet exist but that would exist in a writeable
444         //   directory.
445
446         error_message.erase();
447
448         if (name.empty()) {
449                 error_message = _("No file input.");
450                 return false;
451         }
452
453         string const dir = OnlyPath(name);
454         if (!AbsolutePath(dir)) {
455                 error_message = _("The absolute path is required.");
456                 return false;
457         }
458
459         FileInfo d(name);
460
461         if (!d.isOK() || !d.isDir()) {
462                 d.newFile(dir);
463         }
464
465         if (!d.isOK() || !d.isDir()) {
466                 error_message = _("Directory does not exist.");
467                 return false;
468         }
469
470         if (!d.writable()) {
471                 error_message = _("Cannot write to this directory.");
472                 return false;
473         }
474
475         FileInfo f(name);
476         if (dir == name || (f.isOK() && f.isDir())) {
477                 error_message = _("A file is required, not a directory.");
478                 return false;
479         }
480
481         if (f.isOK() && f.exist() && !f.writable()) {
482                 error_message = _("Cannot write to this file.");
483                 return false;
484         }
485
486         return true;
487 }
488
489
490 bool RWInfo::ReadableFile(string const & name)
491 {
492         error_message.erase();
493
494         if (name.empty()) {
495                 error_message = _("No file input.");
496                 return false;
497         }
498
499         string const dir = OnlyPath(name);
500         if (!AbsolutePath(dir)) {
501                 error_message = _("The absolute path is required.");
502                 return false;
503         }
504
505         FileInfo d(name);
506
507         if (!d.isOK() && !d.isDir()) {
508                 d.newFile(dir);
509         }
510
511         if (!d.isOK() || !d.isDir()) {
512                 error_message = _("Directory does not exist.");
513                 return false;
514         }
515
516         if (!d.readable()) {
517                 error_message = _("Cannot read from this directory.");
518                 return false;
519         }
520
521         FileInfo f(name);
522         if (dir == name || (f.isOK() && f.isDir())) {
523                 error_message = _("A file is required, not a directory.");
524                 return false;
525         }
526
527         if (!f.exist()) {
528                 error_message = _("File does not exist.");
529                 return false;
530         }
531
532         if (!f.readable()) {
533                 error_message = _("Cannot read from this file.");
534                 return false;
535         }
536
537         return true;
538 }