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