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