]> git.lyx.org Git - features.git/blob - src/frontends/xforms/xforms_helpers.C
Herbert's latest "graphic5" patch (with the zippedFile stuff commented out),
[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 #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         // or with the char '%'
216         string const tmp = lowercase(strip(frontStrip(str)));
217
218         string::const_iterator p = tmp.begin();
219         for (; p != tmp.end(); ++p) {
220                 if ((*p >= 'a' && *p <= 'z') || *p == '%')
221                         break;
222         }
223
224         string len = "0";
225         int unitpos = 1; // xforms has Fortran-style indexing
226
227         if (p == tmp.end()) {
228                 if (isStrDbl(tmp))
229                         len = tmp;
230
231         } else {
232                 string tmplen = string(tmp.begin(), p);
233                 if (isStrDbl(tmplen))
234                         len = tmplen;
235                 string unit = string(p, tmp.end());
236                 unit = subst(unit, "%", "%%");
237
238                 for(int i = 0; i < fl_get_choice_maxitems(choice); ++i) {
239                         string const text = fl_get_choice_item_text(choice,i+1);
240                         if (unit == lowercase(strip(frontStrip(text)))) {
241                                 unitpos = i+1;
242                                 break;
243                         }
244                 }
245         }
246         
247         fl_set_input(input,   len.c_str());
248         fl_set_choice(choice, unitpos);
249 }
250 #else
251 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
252                                    string const & str,
253                                    string const & default_unit)
254 {
255         updateWidgetsFromLength(input, choice,
256                                 LyXLength(str), default_unit);
257 }
258
259
260 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
261                              LyXLength const & len,
262                              string const & default_unit)
263 {
264         // Paranoia check
265         lyx::Assert(input  && input->objclass  == FL_INPUT &&
266                     choice && choice->objclass == FL_CHOICE);
267
268         if (len.zero()) {
269                 fl_set_input(input, "");
270                 fl_set_choice_text(choice, default_unit.c_str());
271         } else {
272                 ostringstream buffer;
273                 buffer << len.value();
274                 fl_set_input(input, buffer.str().c_str());
275                 fl_set_choice_text(choice, stringFromUnit(len.unit()));
276         }
277 }
278 #endif
279
280
281 // Take a string and add breaks so that it fits into a desired label width, w
282 string formatted(string const & sin, int w, int size, int style)
283 {
284         // FIX: Q: Why cant this be done by a one pass algo? (Lgb)
285
286         string sout;
287         if (sin.empty()) return sout;
288
289         // breaks in up into a vector of individual words
290         vector<string> sentence;
291         string word;
292         for (string::const_iterator sit = sin.begin();
293              sit != sin.end(); ++sit) {
294                 if ((*sit) == ' ' || (*sit) == '\n') {
295                         if (!word.empty()) {
296                                 sentence.push_back(word);
297                                 word.erase();
298                         }
299                         if ((*sit) == '\n') word += '\n';
300                         
301                 } else {
302                         word += (*sit);
303                 }
304         }
305
306         // Flush remaining contents of word
307         if (!word.empty() ) sentence.push_back(word);
308
309         string line;
310         string line_plus_word;
311         for (vector<string>::const_iterator vit = sentence.begin();
312              vit != sentence.end(); ++vit) {
313                 string word(*vit);
314
315                 char c = word[0];
316                 if (c == '\n') {
317                         sout += line + '\n';
318                         word.erase(0,1);
319                         line_plus_word.erase();
320                         line.erase();
321                 }
322
323                 if (!line_plus_word.empty() ) line_plus_word += ' ';
324                 line_plus_word += word;
325
326                 int const length = fl_get_string_width(style, size,
327                                                        line_plus_word.c_str(),
328                                                        int(line_plus_word.length()));
329                 if (length >= w) {
330                         sout += line + '\n';
331                         line_plus_word = word;
332                 }
333
334                 line = line_plus_word;
335         }
336         // Flush remaining contents of line
337         if (!line.empty()) {
338                 sout += line;
339         }
340
341         if (sout[sout.length() - 1] == '\n')
342                 sout.erase(sout.length() - 1);
343
344         return sout;
345 }
346
347
348 namespace {
349
350 // sorted by hand to prevent LyXLex from complaining on read().
351 keyword_item xformTags[] = {
352         { "\\gui_background", FL_COL1 },
353         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
354         { "\\gui_buttonleft", FL_LEFT_BCOL },
355         { "\\gui_buttonright", FL_RIGHT_BCOL },
356         { "\\gui_buttontop", FL_TOP_BCOL },
357         { "\\gui_inactive", FL_INACTIVE },
358         { "\\gui_push_button", FL_YELLOW },
359         { "\\gui_selected", FL_MCOL },  
360         { "\\gui_text", FL_BLACK }
361 };
362
363
364 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
365
366 } // namespace anon
367
368
369 bool XformsColor::read(string const & filename)
370 {
371         LyXLex lexrc(xformTags, xformCount);
372         if (!lexrc.setFile(filename))
373                 return false;
374
375         while (lexrc.isOK()) {
376                 int const le = lexrc.lex();
377
378                 switch (le) {
379                 case LyXLex::LEX_UNDEF:
380                         lexrc.printError("Unknown tag `$$Token'");
381                         continue; 
382                 case LyXLex::LEX_FEOF:
383                         continue;
384                 default: break;
385                 }
386
387                 RGBColor col;
388
389                 if (!lexrc.next()) break;
390                 col.r = lexrc.getInteger();
391
392                 if (!lexrc.next()) break;
393                 col.g = lexrc.getInteger();
394
395                 if (!lexrc.next()) break;
396                 col.b = lexrc.getInteger();
397
398                 fl_mapcolor(le, col.r, col.g, col.b);
399         }
400                 
401         return true;
402 }
403
404
405 bool XformsColor::write(string const & filename)
406 {
407         ofstream os(filename.c_str());
408         if (!os)
409                 return false;
410
411         os << "### This file is part of\n"
412            << "### ========================================================\n"
413            << "###          LyX, The Document Processor\n"
414            << "###\n"
415            << "###          Copyright 1995 Matthias Ettrich\n"
416            << "###          Copyright 1995-2001 The LyX Team.\n"
417            << "###\n"
418            << "### ========================================================\n"
419            << "\n"
420            << "# This file is written by LyX, if you want to make your own\n"
421            << "# modifications you should do them from inside LyX and save\n"
422            << "\n";
423
424         for (int i = 0; i < xformCount; ++i) {
425                 string const tag  = xformTags[i].tag;
426                 int const colorID = xformTags[i].code;
427                 RGBColor color;
428
429                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
430
431                 os << tag << " "
432                    << color.r << " " << color.g << " " << color.b << "\n";
433         }
434
435         return true;
436 }
437
438
439 string  RWInfo::error_message;
440
441 bool RWInfo::WriteableDir(string const & name)
442 {
443         error_message.erase();
444
445         if (!AbsolutePath(name)) {
446                 error_message = N_("The absolute path is required.");
447                 return false;
448         }
449
450         FileInfo const tp(name);
451         if (!tp.isOK() || !tp.isDir()) {
452                 error_message = N_("Directory does not exist.");
453                 return false;
454         }
455
456         if (!tp.writable()) {
457                 error_message = N_("Cannot write to this directory.");
458                 return false;
459         }
460
461         return true;
462 }
463
464
465 bool RWInfo::ReadableDir(string const & name)
466 {
467         error_message.erase();
468
469         if (!AbsolutePath(name)) {
470                 error_message = N_("The absolute path is required.");
471                 return false;
472         }
473
474         FileInfo const tp(name);
475         if (!tp.isOK() || !tp.isDir()) {
476                 error_message = N_("Directory does not exist.");
477                 return false;
478         }
479
480         if (!tp.readable()) {
481                 error_message = N_("Cannot read this directory.");
482                 return false;
483         }
484
485         return true;
486 }
487
488
489 bool RWInfo::WriteableFile(string const & name)
490 {
491         // A writeable file is either:
492         // * An existing file to which we have write access, or
493         // * A file that doesn't yet exist but that would exist in a writeable
494         //   directory.
495
496         error_message.erase();
497
498         if (name.empty()) {
499                 error_message = N_("No file input.");
500                 return false;
501         }
502
503         string const dir = OnlyPath(name);
504         if (!AbsolutePath(dir)) {
505                 error_message = N_("The absolute path is required.");
506                 return false;
507         }
508
509         FileInfo d(name);
510
511         if (!d.isOK() || !d.isDir()) {
512                 d.newFile(dir);
513         }
514
515         if (!d.isOK() || !d.isDir()) {
516                 error_message = N_("Directory does not exist.");
517                 return false;
518         }
519         
520         if (!d.writable()) {
521                 error_message = N_("Cannot write to this directory.");
522                 return false;
523         }
524
525         FileInfo f(name);
526         if (dir == name || (f.isOK() && f.isDir())) {
527                 error_message = N_("A file is required, not a directory.");
528                 return false;
529         }
530
531         if (f.isOK() && f.exist() && !f.writable()) {
532                 error_message = N_("Cannot write to this file.");
533                 return false;
534         }
535         
536         return true;
537 }
538
539
540 bool RWInfo::ReadableFile(string const & name)
541 {
542         error_message.erase();
543
544         if (name.empty()) {
545                 error_message = N_("No file input.");
546                 return false;
547         }
548
549         string const dir = OnlyPath(name);
550         if (!AbsolutePath(dir)) {
551                 error_message = N_("The absolute path is required.");
552                 return false;
553         }
554
555         FileInfo d(name);
556
557         if (!d.isOK() && !d.isDir()) {
558                 d.newFile(dir);
559         }
560
561         if (!d.isOK() || !d.isDir()) {
562                 error_message = N_("Directory does not exist.");
563                 return false;
564         }
565         
566         if (!d.readable()) {
567                 error_message = N_("Cannot read from this directory.");
568                 return false;
569         }
570
571         FileInfo f(name);
572         if (dir == name || (f.isOK() && f.isDir())) {
573                 error_message = N_("A file is required, not a directory.");
574                 return false;
575         }
576
577         if (!f.exist()) {
578                 error_message = N_("File does not exist.");
579                 return false;
580         }
581         
582         if (!f.readable()) {
583                 error_message = N_("Cannot read from this file.");
584                 return false;
585         }
586
587         return true;
588 }