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