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