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