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