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