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