]> git.lyx.org Git - lyx.git/blob - src/frontends/xforms/xforms_helpers.C
fbf3287c47afce9b7fac95c550081882be4d52f5
[lyx.git] / src / frontends / xforms / xforms_helpers.C
1 /**
2  * \file xforms_helpers.C
3  * Copyright 2000-2002 The LyX Team.
4  * See the file COPYING.
5  *
6  * \author Angus Leeming, a.leeming@ic.ac.uk
7  */
8
9 #include <config.h>
10
11 #include FORMS_H_LOCATION
12
13 #include <fstream> // ofstream
14 #include <vector>
15
16 #ifdef __GNUG_
17 #pragma implementation
18 #endif
19  
20 #include "xforms_helpers.h"
21 #include "lyxlex.h"
22 #include "gettext.h"
23 #include "lyxlength.h"
24 #include "lyxgluelength.h"
25 #include "support/LAssert.h"
26 #include "support/FileInfo.h"
27 #include "support/filetools.h"
28 #include "support/lstrings.h" // frontStrip, strip
29
30 using std::ofstream;
31 using std::pair;
32 using std::vector;
33
34 // Extract shortcut from <ident>|<shortcut> string
35 char const * flyx_shortcut_extract(char const * sc)
36 {
37         // Find '|' in the sc and return the string after that.
38         register char const * sd = sc;
39         while (sd[0]!= 0 && sd[0] != '|') ++sd;
40
41         if (sd[0] == '|') {
42                 ++sd;
43                 return sd;
44         }
45         return "";
46 }
47
48
49 // Extract identifier from <ident>|<shortcut> string
50 char const * flyx_ident_extract(char const * sc)
51 {
52         register char const * se = sc;
53         while (se[0]!= 0 && se[0] != '|') ++se;
54
55         if (se[0] == 0) return sc;
56         
57         char * sb = new char[se - sc + 1];
58         int index = 0;
59         register char const * sd = sc;
60         while (sd != se) {
61                 sb[index] = sd[0];
62                 ++index; ++sd;
63         }
64         sb[index] = 0;
65         return sb;
66 }
67
68
69 // Set an FL_OBJECT to activated or deactivated
70 void setEnabled(FL_OBJECT * ob, bool enable)
71 {
72         if (enable) {
73                 fl_activate_object(ob);
74                 fl_set_object_lcol(ob, FL_BLACK);
75         } else {
76                 fl_deactivate_object(ob);
77                 fl_set_object_lcol(ob, FL_INACTIVE);
78         }
79 }
80
81         
82 // Given an fl_choice, create a vector of its entries
83 vector<string> const getVectorFromChoice(FL_OBJECT * ob)
84 {
85         vector<string> vec;
86         if (!ob || ob->objclass != FL_CHOICE)
87                 return vec;
88
89         for(int i = 0; i < fl_get_choice_maxitems(ob); ++i) {
90                 string const text = fl_get_choice_item_text(ob, i+1);
91                 vec.push_back(strip(frontStrip(text)));
92         }
93
94         return vec;
95 }
96
97
98 /// Given an fl_input, return its contents.
99 string const getStringFromInput(FL_OBJECT * ob)
100 {
101         if (!ob || ob->objclass != FL_INPUT)
102                 return string();
103
104         char const * tmp = fl_get_input(ob);
105         return (tmp) ? tmp : string();
106 }
107
108
109 // Given an fl_browser, return the contents of line
110 string const getStringFromBrowser(FL_OBJECT * ob, int line)
111 {
112         if (!ob || ob->objclass != FL_BROWSER || 
113             line < 1 || line > fl_get_browser_maxline(ob))
114                 return string();
115
116         char const * tmp = fl_get_browser_line(ob, line);
117         return (tmp) ? tmp : string();
118 }
119
120 // Given an fl_browser, return the contents of the currently
121 // highlighted line.
122 // If nothing is selected, return an empty string
123 string const getSelectedStringFromBrowser(FL_OBJECT * ob)
124 {
125         if (!ob || ob->objclass != FL_BROWSER)
126                 return string();
127
128         int const line = fl_get_browser(ob);
129         if (line < 1 || line > fl_get_browser_maxline(ob))
130                 return string();
131
132         if (!fl_isselected_browser_line(ob, line))
133                 return string();
134
135         char const * tmp = fl_get_browser_line(ob, line);
136         return (tmp) ? tmp : string();
137 }
138
139
140 // Given an fl_browser, create a vector of its entries
141 vector<string> const getVectorFromBrowser(FL_OBJECT * ob)
142 {
143         vector<string> vec;
144         if (!ob || ob->objclass != FL_BROWSER)
145                 return vec;
146
147         for(int i = 0; i < fl_get_browser_maxline(ob); ++i) {
148                 string const text = fl_get_browser_line(ob, i+1);
149                 vec.push_back(strip(frontStrip(text)));
150         }
151
152         return vec;
153 }
154
155
156 string getLengthFromWidgets(FL_OBJECT * input, FL_OBJECT * choice)
157 {
158         // Paranoia check
159         lyx::Assert(input  && input->objclass  == FL_INPUT &&
160                     choice && choice->objclass == FL_CHOICE);
161
162         string const length = strip(frontStrip(fl_get_input(input)));
163         if (length.empty())
164                 return string();
165
166         //don't return unit-from-choice if the input(field) contains a unit
167         if (isValidGlueLength(length))
168                 return length;
169
170         string unit = strip(frontStrip(fl_get_choice_text(choice)));
171         unit = subst(unit, "%%", "%");
172
173         return length + unit;
174 }
175         
176
177 #if 0
178 // old code which can be deleted if the new one, now enabled,
179 // works satisfyingly (JSpitzm, 11/02/2002)
180 // this should definitely be the other way around!!!
181 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
182                              LyXLength const & len,
183                              string const & default_unit)
184 {
185         if (len.zero())
186                 updateWidgetsFromLengthString(input, choice,
187                                               string(), default_unit);
188         // use input field only for gluelengths
189         else if (!isValidLength(len) && !isStrDbl(len)) {
190                 fl_set_input(input, len.c_str());
191                 fl_set_choice_text(choice, default_unit.c_str());
192         }
193         else
194                 updateWidgetsFromLengthString(input, choice,
195                                               len.asString(), default_unit);
196
197 }
198
199
200 // Most of the code here is a poor duplication of the parser code
201 // which is in LyXLength. Use that instead
202 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
203                                    string const & str,
204                                    string const & default_unit)
205 {
206         // Paranoia check
207         lyx::Assert(input  && input->objclass  == FL_INPUT &&
208                     choice && choice->objclass == FL_CHOICE);
209
210         if (str.empty()) {
211                 fl_set_input(input, "");
212                 int unitpos = 1; // xforms has Fortran-style indexing
213                 for(int i = 0; i < fl_get_choice_maxitems(choice); ++i) {
214                         string const text = fl_get_choice_item_text(choice,i+1);
215                         if (default_unit ==
216                             lowercase(strip(frontStrip(text)))) {
217                                 unitpos = i+1;
218                                 break;
219                         }
220                 }
221                 fl_set_choice(choice, unitpos);
222                 return;
223         }
224
225         // The unit is presumed to begin at the first char a-z
226         // or with the char '%'
227         string const tmp = lowercase(strip(frontStrip(str)));
228
229         string::const_iterator p = tmp.begin();
230         for (; p != tmp.end(); ++p) {
231                 if ((*p >= 'a' && *p <= 'z') || *p == '%')
232                         break;
233         }
234
235         string len = "0";
236         int unitpos = 1; // xforms has Fortran-style indexing
237
238         if (p == tmp.end()) {
239                 if (isStrDbl(tmp))
240                         len = tmp;
241
242         } else {
243                 string tmplen = string(tmp.begin(), p);
244                 if (isStrDbl(tmplen))
245                         len = tmplen;
246                 string unit = string(p, tmp.end());
247                 unit = subst(unit, "%", "%%");
248
249                 for(int i = 0; i < fl_get_choice_maxitems(choice); ++i) {
250                         string const text = fl_get_choice_item_text(choice,i+1);
251                         if (unit == lowercase(strip(frontStrip(text)))) {
252                                 unitpos = i+1;
253                                 break;
254                         }
255                 }
256         }
257         
258         fl_set_input(input,   len.c_str());
259         fl_set_choice(choice, unitpos);
260 }
261 #else
262 void updateWidgetsFromLengthString(FL_OBJECT * input, FL_OBJECT * choice,
263                                    string const & str,
264                                    string const & default_unit)
265 {
266         // use input field only for gluelengths
267         if (!isValidLength(str) && !isStrDbl(str)) {
268                 fl_set_input(input, str.c_str());
269                 fl_set_choice_text(choice, default_unit.c_str());
270         } else {
271                 updateWidgetsFromLength(input, choice,
272                                 LyXLength(str), default_unit);
273         }
274 }
275
276
277 void updateWidgetsFromLength(FL_OBJECT * input, FL_OBJECT * choice,
278                              LyXLength const & len,
279                              string const & default_unit)
280 {
281         // Paranoia check
282         lyx::Assert(input  && input->objclass  == FL_INPUT &&
283                     choice && choice->objclass == FL_CHOICE);
284
285         if (len.zero()) {
286                 fl_set_input(input, "");
287                 fl_set_choice_text(choice, default_unit.c_str());
288         } else {
289                 ostringstream buffer;
290                 buffer << len.value();
291                 fl_set_input(input, buffer.str().c_str());
292                 fl_set_choice_text(choice, 
293                     subst(stringFromUnit(len.unit()),"%","%%").c_str());
294         }
295 }
296 #endif
297
298
299 // Take a string and add breaks so that it fits into a desired label width, w
300 string formatted(string const & sin, int w, int size, int style)
301 {
302         string sout;
303         if (sin.empty()) return sout;
304
305 #if 0
306         // FIX: Q: Why cant this be done by a one pass algo? (Lgb)
307
308         // breaks in up into a vector of individual words
309         vector<string> sentence;
310         string word;
311         for (string::const_iterator sit = sin.begin();
312              sit != sin.end(); ++sit) {
313                 if ((*sit) == ' ' || (*sit) == '\n') {
314                         if (!word.empty()) {
315                                 sentence.push_back(word);
316                                 word.erase();
317                         }
318                         if ((*sit) == '\n') word += '\n';
319                         
320                 } else {
321                         word += (*sit);
322                 }
323         }
324
325         // Flush remaining contents of word
326         if (!word.empty()) sentence.push_back(word);
327
328         string line;
329         string line_plus_word;
330         for (vector<string>::const_iterator vit = sentence.begin();
331              vit != sentence.end(); ++vit) {
332                 string word(*vit);
333
334                 char c = word[0];
335                 if (c == '\n') {
336                         sout += line + '\n';
337                         word.erase(0,1);
338                         line_plus_word.erase();
339                         line.erase();
340                 }
341
342                 if (!line_plus_word.empty()) line_plus_word += ' ';
343                 line_plus_word += word;
344
345                 int const length = fl_get_string_width(style, size,
346                                                        line_plus_word.c_str(),
347                                                        int(line_plus_word.length()));
348                 if (length >= w) {
349                         sout += line + '\n';
350                         line_plus_word = word;
351                 }
352
353                 line = line_plus_word;
354         }
355         // Flush remaining contents of line
356         if (!line.empty()) {
357                 sout += line;
358         }
359
360         if (sout[sout.length() - 1] == '\n')
361                 sout.erase(sout.length() - 1);
362
363 #else
364         string::size_type curpos = 0;
365         string line;
366         for(;;) {
367                 string::size_type const nxtpos1 = sin.find(' ',  curpos);
368                 string::size_type const nxtpos2 = sin.find('\n', curpos);
369                 string::size_type const nxtpos = std::min(nxtpos1, nxtpos1);
370
371                 string const word = nxtpos == string::npos ?
372                         sin.substr(curpos) : sin.substr(curpos, nxtpos-curpos);
373
374                 bool const newline = (nxtpos2 != string::npos &&
375                                       nxtpos2 < nxtpos1);
376
377                 string const line_plus_word =
378                         line.empty() ? word : line + ' ' + word;
379
380                 int const length =
381                         fl_get_string_width(style, size,
382                                             line_plus_word.c_str(),
383                                             int(line_plus_word.length()));
384
385                 if (length >= w) {
386                         sout += line + '\n';
387                         if (newline) {
388                                 sout += word + '\n';
389                                 line.erase();
390                         } else {
391                                 line = word;
392                         }
393
394                 } else if (newline) {
395                         sout += line_plus_word + '\n';
396                         line.erase();
397
398                 } else {
399                         if (!line.empty())
400                                 line += ' ';
401                         line += word;
402                 }
403                 
404                 if (nxtpos == string::npos) {
405                         if (!line.empty())
406                                 sout += line;
407                         break;
408                 }
409
410                 curpos = nxtpos+1;
411         }
412 #endif
413         
414         return sout;
415 }
416
417
418 void setCursorColor(int color)
419 {
420         fl_set_cursor_color(FL_DEFAULT_CURSOR, color, FL_WHITE);
421         fl_set_cursor_color(XC_xterm,          color, FL_WHITE);
422         fl_set_cursor_color(XC_watch,          color, FL_WHITE);
423         fl_set_cursor_color(XC_sb_right_arrow, color, FL_WHITE);
424 }
425
426
427 namespace {
428
429 // sorted by hand to prevent LyXLex from complaining on read().
430 keyword_item xformTags[] = {
431         { "\\gui_background",   FL_COL1 },
432         { "\\gui_buttonbottom", FL_BOTTOM_BCOL },
433         { "\\gui_buttonleft",   FL_LEFT_BCOL },
434         { "\\gui_buttonright",  FL_RIGHT_BCOL },
435         { "\\gui_buttontop",    FL_TOP_BCOL },
436         { "\\gui_inactive",     FL_INACTIVE },
437         { "\\gui_pointer",      FL_FREE_COL16 },
438         { "\\gui_push_button",  FL_YELLOW },
439         { "\\gui_selected",     FL_MCOL },      
440         { "\\gui_text",         FL_BLACK }
441 };
442
443
444 const int xformCount = sizeof(xformTags) / sizeof(keyword_item);
445
446 } // namespace anon
447
448
449 bool XformsColor::read(string const & filename)
450 {
451         LyXLex lexrc(xformTags, xformCount);
452         if (!lexrc.setFile(filename))
453                 return false;
454
455         while (lexrc.isOK()) {
456                 int const le = lexrc.lex();
457
458                 switch (le) {
459                 case LyXLex::LEX_UNDEF:
460                         lexrc.printError("Unknown tag `$$Token'");
461                         continue; 
462                 case LyXLex::LEX_FEOF:
463                         continue;
464                 default: break;
465                 }
466
467                 string const tag = lexrc.getString();
468
469                 RGBColor col;
470
471                 if (!lexrc.next()) break;
472                 col.r = lexrc.getInteger();
473
474                 if (!lexrc.next()) break;
475                 col.g = lexrc.getInteger();
476
477                 if (!lexrc.next()) break;
478                 col.b = lexrc.getInteger();
479
480                 fl_mapcolor(le, col.r, col.g, col.b);
481
482                 if (tag == "\\gui_pointer") {
483                         setCursorColor(FL_FREE_COL16);
484                 }
485         }
486
487         return true;
488 }
489
490
491 bool XformsColor::write(string const & filename)
492 {
493         ofstream os(filename.c_str());
494         if (!os)
495                 return false;
496
497         os << "### This file is part of\n"
498            << "### ========================================================\n"
499            << "###          LyX, The Document Processor\n"
500            << "###\n"
501            << "###          Copyright 1995 Matthias Ettrich\n"
502            << "###          Copyright 1995-2002 The LyX Team.\n"
503            << "###\n"
504            << "### ========================================================\n"
505            << "\n"
506            << "# This file is written by LyX, if you want to make your own\n"
507            << "# modifications you should do them from inside LyX and save\n"
508            << "\n";
509
510         for (int i = 0; i < xformCount; ++i) {
511                 string const tag  = xformTags[i].tag;
512                 int const colorID = xformTags[i].code;
513                 RGBColor color;
514
515                 fl_getmcolor(colorID, &color.r, &color.g, &color.b);
516
517                 os << tag << " "
518                    << color.r << " " << color.g << " " << color.b << "\n";
519         }
520
521         return true;
522 }
523
524
525 string  RWInfo::error_message;
526
527 bool RWInfo::WriteableDir(string const & name)
528 {
529         error_message.erase();
530
531         if (!AbsolutePath(name)) {
532                 error_message = N_("The absolute path is required.");
533                 return false;
534         }
535
536         FileInfo const tp(name);
537         if (!tp.isOK() || !tp.isDir()) {
538                 error_message = N_("Directory does not exist.");
539                 return false;
540         }
541
542         if (!tp.writable()) {
543                 error_message = N_("Cannot write to this directory.");
544                 return false;
545         }
546
547         return true;
548 }
549
550
551 bool RWInfo::ReadableDir(string const & name)
552 {
553         error_message.erase();
554
555         if (!AbsolutePath(name)) {
556                 error_message = N_("The absolute path is required.");
557                 return false;
558         }
559
560         FileInfo const tp(name);
561         if (!tp.isOK() || !tp.isDir()) {
562                 error_message = N_("Directory does not exist.");
563                 return false;
564         }
565
566         if (!tp.readable()) {
567                 error_message = N_("Cannot read this directory.");
568                 return false;
569         }
570
571         return true;
572 }
573
574
575 bool RWInfo::WriteableFile(string const & name)
576 {
577         // A writeable file is either:
578         // * An existing file to which we have write access, or
579         // * A file that doesn't yet exist but that would exist in a writeable
580         //   directory.
581
582         error_message.erase();
583
584         if (name.empty()) {
585                 error_message = N_("No file input.");
586                 return false;
587         }
588
589         string const dir = OnlyPath(name);
590         if (!AbsolutePath(dir)) {
591                 error_message = N_("The absolute path is required.");
592                 return false;
593         }
594
595         FileInfo d(name);
596
597         if (!d.isOK() || !d.isDir()) {
598                 d.newFile(dir);
599         }
600
601         if (!d.isOK() || !d.isDir()) {
602                 error_message = N_("Directory does not exist.");
603                 return false;
604         }
605         
606         if (!d.writable()) {
607                 error_message = N_("Cannot write to this directory.");
608                 return false;
609         }
610
611         FileInfo f(name);
612         if (dir == name || (f.isOK() && f.isDir())) {
613                 error_message = N_("A file is required, not a directory.");
614                 return false;
615         }
616
617         if (f.isOK() && f.exist() && !f.writable()) {
618                 error_message = N_("Cannot write to this file.");
619                 return false;
620         }
621         
622         return true;
623 }
624
625
626 bool RWInfo::ReadableFile(string const & name)
627 {
628         error_message.erase();
629
630         if (name.empty()) {
631                 error_message = N_("No file input.");
632                 return false;
633         }
634
635         string const dir = OnlyPath(name);
636         if (!AbsolutePath(dir)) {
637                 error_message = N_("The absolute path is required.");
638                 return false;
639         }
640
641         FileInfo d(name);
642
643         if (!d.isOK() && !d.isDir()) {
644                 d.newFile(dir);
645         }
646
647         if (!d.isOK() || !d.isDir()) {
648                 error_message = N_("Directory does not exist.");
649                 return false;
650         }
651         
652         if (!d.readable()) {
653                 error_message = N_("Cannot read from this directory.");
654                 return false;
655         }
656
657         FileInfo f(name);
658         if (dir == name || (f.isOK() && f.isDir())) {
659                 error_message = N_("A file is required, not a directory.");
660                 return false;
661         }
662
663         if (!f.exist()) {
664                 error_message = N_("File does not exist.");
665                 return false;
666         }
667         
668         if (!f.readable()) {
669                 error_message = N_("Cannot read from this file.");
670                 return false;
671         }
672
673         return true;
674 }