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