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