]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/xforms_helpers.C
Bugfixes: checkboxes to radiobuttons (from J�rgen S) and remove a little
[lyx.git] / src / frontends / xforms / xforms_helpers.C
1 /** Collection of some useful xform helper functions
2  */
3
4 #include <config.h>
5
6 #include FORMS_H_LOCATION
7
8 #include <fstream> // ofstream
9 #include <vector>
10
11 #ifdef __GNUG_
12 #pragma implementation
13 #endif
14  
15 #include "xforms_helpers.h"
16 #include "lyxlex.h"
17 #include "support/FileInfo.h"
18 #include "support/filetools.h"
19 #include "support/lstrings.h" // frontStrip, strip
20 #include "gettext.h"
21 #include "support/LAssert.h"
22 #include "lyxlength.h"
23 #include "lyxgluelength.h"
24
25 using std::ofstream;
26 using std::pair;
27 using std::vector;
28
29 // Extract shortcut from <ident>|<shortcut> string
30 char const * flyx_shortcut_extract(char const * sc)
31 {
32         // Find '|' in the sc and return the string after that.
33         register char const * sd = sc;
34         while (sd[0]!= 0 && sd[0] != '|') ++sd;
35
36         if (sd[0] == '|') {
37                 ++sd;
38                 //lyxerr << sd << endl;
39                 return sd;
40         }
41         return "";
42 }
43
44
45 // Extract identifier from <ident>|<shortcut> string
46 char const * flyx_ident_extract(char const * sc)
47 {
48         register char const * se = sc;
49         while (se[0]!= 0 && se[0] != '|') ++se;
50
51         if (se[0] == 0) return sc;
52         
53         char * sb = new char[se - sc + 1];
54         int index = 0;
55         register char const * sd = sc;
56         while (sd != se) {
57                 sb[index] = sd[0];
58                 ++index; ++sd;
59         }
60         sb[index] = 0;
61         return sb;
62 }
63
64
65 // Set an FL_OBJECT to activated or deactivated
66 void setEnabled(FL_OBJECT * ob, bool enable)
67 {
68         if (enable) {
69                 fl_activate_object(ob);
70                 fl_set_object_lcol(ob, FL_BLACK);
71         } else {
72                 fl_deactivate_object(ob);
73                 fl_set_object_lcol(ob, FL_INACTIVE);
74         }
75 }
76
77         
78 // Given an fl_choice, create a vector of its entries
79 vector<string> const getVectorFromChoice(FL_OBJECT * ob)
80 {
81         vector<string> vec;
82         if (!ob || ob->objclass != FL_CHOICE)
83                 return vec;
84
85         for(int i = 0; i < fl_get_choice_maxitems(ob); ++i) {
86                 string const text = fl_get_choice_item_text(ob, i+1);
87                 vec.push_back(strip(frontStrip(text)));
88         }
89
90         return vec;
91 }
92
93
94 /// Given an fl_input, return its contents.
95 string const getStringFromInput(FL_OBJECT * ob)
96 {
97         if (!ob || ob->objclass != FL_INPUT)
98                 return string();
99
100         char const * tmp = fl_get_input(ob);
101         return (tmp) ? tmp : string();
102 }
103
104
105 // Given an fl_browser, return the contents of line
106 string const getStringFromBrowser(FL_OBJECT * ob, int line)
107 {
108         if (!ob || ob->objclass != FL_BROWSER || 
109             line < 1 || line > fl_get_browser_maxline(ob))
110                 return string();
111
112         char const * tmp = fl_get_browser_line(ob, line);
113         return (tmp) ? tmp : string();
114 }
115
116 // Given an fl_browser, return the contents of the currently
117 // highlighted line.
118 // If nothing is selected, return an empty string
119 string const getSelectedStringFromBrowser(FL_OBJECT * ob)
120 {
121         if (!ob || ob->objclass != FL_BROWSER)
122                 return string();
123
124         int const line = fl_get_browser(ob);
125         if (line < 1 || line > fl_get_browser_maxline(ob))
126                 return string();
127
128         if (!fl_isselected_browser_line(ob, line))
129                 return string();
130
131         char const * tmp = fl_get_browser_line(ob, line);
132         return (tmp) ? tmp : string();
133 }
134
135
136 // Given an fl_browser, create a vector of its entries
137 vector<string> const getVectorFromBrowser(FL_OBJECT * ob)
138 {
139         vector<string> vec;
140         if (!ob || ob->objclass != FL_BROWSER)
141                 return vec;
142
143         for(int i = 0; i < fl_get_browser_maxline(ob); ++i) {
144                 string const text = fl_get_browser_line(ob, i+1);
145                 vec.push_back(strip(frontStrip(text)));
146         }
147
148         return vec;
149 }
150
151
152 string getLengthFromWidgets(FL_OBJECT * input, FL_OBJECT * choice)
153 {
154         // Paranoia check
155         lyx::Assert(input  && input->objclass  == FL_INPUT &&
156                     choice && choice->objclass == FL_CHOICE);
157
158         string const length = strip(frontStrip(fl_get_input(input)));
159         if (length.empty())
160                 return string();
161
162         //don't return unit-from-choice if the input(field) contains a unit
163         if (isValidGlueLength(length))
164                 return length;
165
166         string unit = strip(frontStrip(fl_get_choice_text(choice)));
167         unit = subst(unit, "%%", "%");
168
169         return length + unit;
170 }
171         
172
173 #if 1
174 // this should definitely be the other way around!!!
175 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
176                              LyXLength const & len,
177                              string const & default_unit)
178 {
179         if (len.zero())
180                 updateWidgetsFromLengthString(input, choice,
181                                               string(), default_unit);
182         else
183                 updateWidgetsFromLengthString(input, choice,
184                                               len.asString(), default_unit);
185
186 }
187
188
189 // Most of the code here is a poor duplication of the parser code
190 // which is in LyXLength. Use that instead
191 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
192                                    string const & str,
193                                    string const & default_unit)
194 {
195         // Paranoia check
196         lyx::Assert(input  && input->objclass  == FL_INPUT &&
197                     choice && choice->objclass == FL_CHOICE);
198
199         if (str.empty()) {
200                 fl_set_input(input, "");
201                 int unitpos = 1; // xforms has Fortran-style indexing
202                 for(int i = 0; i < fl_get_choice_maxitems(choice); ++i) {
203                         string const text = fl_get_choice_item_text(choice,i+1);
204                         if (default_unit ==
205                             lowercase(strip(frontStrip(text)))) {
206                                 unitpos = i+1;
207                                 break;
208                         }
209                 }
210                 fl_set_choice(choice, unitpos);
211                 return;
212         }
213
214         // The unit is presumed to begin at the first char a-z
215         string const tmp = lowercase(strip(frontStrip(str)));
216
217         string::const_iterator p = tmp.begin();
218         for (; p != tmp.end(); ++p) {
219                 if (*p >= 'a' && *p <= 'z')
220                         break;
221         }
222
223         string len = "0";
224         int unitpos = 1; // xforms has Fortran-style indexing
225
226         if (p == tmp.end()) {
227                 if (isStrDbl(tmp))
228                         len = tmp;
229
230         } else {
231                 string tmplen = string(tmp.begin(), p);
232                 if (isStrDbl(tmplen))
233                         len = tmplen;
234                 string unit = string(p, tmp.end());
235                 unit = subst(unit, "%", "%%");
236
237                 for(int i = 0; i < fl_get_choice_maxitems(choice); ++i) {
238                         string const text = fl_get_choice_item_text(choice,i+1);
239                         if (unit == lowercase(strip(frontStrip(text)))) {
240                                 unitpos = i+1;
241                                 break;
242                         }
243                 }
244         }
245         
246         fl_set_input(input,   len.c_str());
247         fl_set_choice(choice, unitpos);
248 }
249 #else
250 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
251                                    string const & str,
252                                    string const & default_unit)
253 {
254         updateWidgetsFromLength(input, choice,
255                                 LyXLength(str), default_unit);
256 }
257
258
259 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
260                              LyXLength const & len,
261                              string const & default_unit)
262 {
263         // Paranoia check
264         lyx::Assert(input  && input->objclass  == FL_INPUT &&
265                     choice && choice->objclass == FL_CHOICE);
266
267         if (len.zero()) {
268                 fl_set_input(input, "");
269                 fl_set_choice_text(choice, default_unit.c_str());
270         } else {
271                 ostringstream buffer;
272                 buffer << len.value();
273                 fl_set_input(input, buffer.str().c_str());
274                 fl_set_choice_text(choice, stringFromUnit(len.unit()));
275         }
276 }
277 #endif
278
279
280 // Take a string and add breaks so that it fits into a desired label width, w
281 string formatted(string const & sin, int w, int size, int style)
282 {
283         // FIX: Q: Why cant this be done by a one pass algo? (Lgb)
284
285         string sout;
286         if (sin.empty()) return sout;
287
288         // breaks in up into a vector of individual words
289         vector<string> sentence;
290         string word;
291         for (string::const_iterator sit = sin.begin();
292              sit != sin.end(); ++sit) {
293                 if ((*sit) == ' ' || (*sit) == '\n') {
294                         if (!word.empty()) {
295                                 sentence.push_back(word);
296                                 word.erase();
297                         }
298                         if ((*sit) == '\n') word += '\n';
299                         
300                 } else {
301                         word += (*sit);
302                 }
303         }
304
305         // Flush remaining contents of word
306         if (!word.empty() ) sentence.push_back(word);
307
308         string line;
309         string line_plus_word;
310         for (vector<string>::const_iterator vit = sentence.begin();
311              vit != sentence.end(); ++vit) {
312                 string word(*vit);
313
314                 char c = word[0];
315                 if (c == '\n') {
316                         sout += line + '\n';
317                         word.erase(0,1);
318                         line_plus_word.erase();
319                         line.erase();
320                 }
321
322                 if (!line_plus_word.empty() ) line_plus_word += ' ';
323                 line_plus_word += word;
324
325                 int const length = fl_get_string_width(style, size,
326                                                        line_plus_word.c_str(),
327                                                        int(line_plus_word.length()));
328                 if (length >= w) {
329                         sout += line + '\n';
330                         line_plus_word = word;
331                 }
332
333                 line = line_plus_word;
334         }
335         // Flush remaining contents of line
336         if (!line.empty()) {
337                 sout += line;
338         }
339
340         if (sout[sout.length() - 1] == '\n')
341                 sout.erase(sout.length() - 1);
342
343         return sout;
344 }
345
346
347 namespace {
348
349 // sorted by hand to prevent LyXLex from complaining on read().
350 keyword_item xformTags[] = {
351         { "\\gui_background", FL_COL1 },
352         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
353         { "\\gui_buttonleft", FL_LEFT_BCOL },
354         { "\\gui_buttonright", FL_RIGHT_BCOL },
355         { "\\gui_buttontop", FL_TOP_BCOL },
356         { "\\gui_inactive", FL_INACTIVE },
357         { "\\gui_push_button", FL_YELLOW },
358         { "\\gui_selected", FL_MCOL },  
359         { "\\gui_text", FL_BLACK }
360 };
361
362
363 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
364
365 } // namespace anon
366
367
368 bool XformsColor::read(string const & filename)
369 {
370         LyXLex lexrc(xformTags, xformCount);
371         if (!lexrc.setFile(filename))
372                 return false;
373
374         while (lexrc.isOK()) {
375                 int const le = lexrc.lex();
376
377                 switch (le) {
378                 case LyXLex::LEX_UNDEF:
379                         lexrc.printError("Unknown tag `$$Token'");
380                         continue; 
381                 case LyXLex::LEX_FEOF:
382                         continue;
383                 default: break;
384                 }
385
386                 RGBColor col;
387
388                 if (!lexrc.next()) break;
389                 col.r = lexrc.getInteger();
390
391                 if (!lexrc.next()) break;
392                 col.g = lexrc.getInteger();
393
394                 if (!lexrc.next()) break;
395                 col.b = lexrc.getInteger();
396
397                 fl_mapcolor(le, col.r, col.g, col.b);
398         }
399                 
400         return true;
401 }
402
403
404 bool XformsColor::write(string const & filename)
405 {
406         ofstream os(filename.c_str());
407         if (!os)
408                 return false;
409
410         os << "### This file is part of\n"
411            << "### ========================================================\n"
412            << "###          LyX, The Document Processor\n"
413            << "###\n"
414            << "###          Copyright 1995 Matthias Ettrich\n"
415            << "###          Copyright 1995-2001 The LyX Team.\n"
416            << "###\n"
417            << "### ========================================================\n"
418            << "\n"
419            << "# This file is written by LyX, if you want to make your own\n"
420            << "# modifications you should do them from inside LyX and save\n"
421            << "\n";
422
423         for (int i = 0; i < xformCount; ++i) {
424                 string const tag  = xformTags[i].tag;
425                 int const colorID = xformTags[i].code;
426                 RGBColor color;
427
428                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
429
430                 os << tag << " "
431                    << color.r << " " << color.g << " " << color.b << "\n";
432         }
433
434         return true;
435 }
436
437
438 string  RWInfo::error_message;
439
440 bool RWInfo::WriteableDir(string const & name)
441 {
442         error_message.erase();
443
444         if (!AbsolutePath(name)) {
445                 error_message = N_("The absolute path is required.");
446                 return false;
447         }
448
449         FileInfo const tp(name);
450         if (!tp.isOK() || !tp.isDir()) {
451                 error_message = N_("Directory does not exist.");
452                 return false;
453         }
454
455         if (!tp.writable()) {
456                 error_message = N_("Cannot write to this directory.");
457                 return false;
458         }
459
460         return true;
461 }
462
463
464 bool RWInfo::ReadableDir(string const & name)
465 {
466         error_message.erase();
467
468         if (!AbsolutePath(name)) {
469                 error_message = N_("The absolute path is required.");
470                 return false;
471         }
472
473         FileInfo const tp(name);
474         if (!tp.isOK() || !tp.isDir()) {
475                 error_message = N_("Directory does not exist.");
476                 return false;
477         }
478
479         if (!tp.readable()) {
480                 error_message = N_("Cannot read this directory.");
481                 return false;
482         }
483
484         return true;
485 }
486
487
488 bool RWInfo::WriteableFile(string const & name)
489 {
490         // A writeable file is either:
491         // * An existing file to which we have write access, or
492         // * A file that doesn't yet exist but that would exist in a writeable
493         //   directory.
494
495         error_message.erase();
496
497         if (name.empty()) {
498                 error_message = N_("No file input.");
499                 return false;
500         }
501
502         string const dir = OnlyPath(name);
503         if (!AbsolutePath(dir)) {
504                 error_message = N_("The absolute path is required.");
505                 return false;
506         }
507
508         FileInfo d(name);
509
510         if (!d.isOK() || !d.isDir()) {
511                 d.newFile(dir);
512         }
513
514         if (!d.isOK() || !d.isDir()) {
515                 error_message = N_("Directory does not exist.");
516                 return false;
517         }
518         
519         if (!d.writable()) {
520                 error_message = N_("Cannot write to this directory.");
521                 return false;
522         }
523
524         FileInfo f(name);
525         if (dir == name || (f.isOK() && f.isDir())) {
526                 error_message = N_("A file is required, not a directory.");
527                 return false;
528         }
529
530         if (f.isOK() && f.exist() && !f.writable()) {
531                 error_message = N_("Cannot write to this file.");
532                 return false;
533         }
534         
535         return true;
536 }
537
538
539 bool RWInfo::ReadableFile(string const & name)
540 {
541         error_message.erase();
542
543         if (name.empty()) {
544                 error_message = N_("No file input.");
545                 return false;
546         }
547
548         string const dir = OnlyPath(name);
549         if (!AbsolutePath(dir)) {
550                 error_message = N_("The absolute path is required.");
551                 return false;
552         }
553
554         FileInfo d(name);
555
556         if (!d.isOK() && !d.isDir()) {
557                 d.newFile(dir);
558         }
559
560         if (!d.isOK() || !d.isDir()) {
561                 error_message = N_("Directory does not exist.");
562                 return false;
563         }
564         
565         if (!d.readable()) {
566                 error_message = N_("Cannot read from this directory.");
567                 return false;
568         }
569
570         FileInfo f(name);
571         if (dir == name || (f.isOK() && f.isDir())) {
572                 error_message = N_("A file is required, not a directory.");
573                 return false;
574         }
575
576         if (!f.exist()) {
577                 error_message = N_("File does not exist.");
578                 return false;
579         }
580         
581         if (!f.readable()) {
582                 error_message = N_("Cannot read from this file.");
583                 return false;
584         }
585
586         return true;
587 }