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